Skip to content

M4-S1 — Write, deploy and call a Function

Section titled “M4-S1 — Write, deploy and call a Function”
ModuleM4 — Functions: code where the designer stops
After this session you canTurn a rule the designer cannot hold into a tested Function, deploy it, and use its result in the suite.
TimeFacilitated: 70 min · On your own: 70 min
Before you startM3-S4. Ziad Karam waits at Job offer. Your terminal with Node.js 20+, npm, curl, jq and zip (M0-S1). Signed in as yourself, a system Admin of your practice space; Samir Khoury in a private window.
Go deeperFunctions: run your own code · Call another system, or your own code · Functions in a multi-tenant deployment

◆ Orientation (1 min) — The first rung of deep-code

Section titled “◆ Orientation (1 min) — The first rung of deep-code”

Finance’s grade policy (R-09) sets each offer’s housing and transport allowances by grade, caps them, and rounds the package to the nearest 50. The table changes every January. In M1-S1 you decided that this belongs in code: a long formula nobody can read or test would hold it badly. In this session you write that code as a Function, test it on your own computer, deploy it to the platform, and let a reaction fill each offer’s gross package from it.

▤ Concept (4 min) — What a Function is, and how the platform runs it

Section titled “▤ Concept (4 min) — What a Function is, and how the platform runs it”

A small service the platform builds for you

Section titled “A small service the platform builds for you”

A Function is a small TypeScript project you upload as a ZIP file in Administration › Applications › Functions. When you save it, the platform builds your source and deploys it as a small serverless service inside the cluster that runs the platform (a Kubernetes cluster; you never see or manage it). The function is private to that cluster: only the platform calls it, over HTTP, sending a CloudEvent and reading the JSON you return.

stateDiagram-v2
  [*] --> Provisioning: save with a ZIP
  Provisioning --> Provisioned: build and deploy succeeded
  Provisioning --> BuildFailed: build failed
  BuildFailed --> Provisioning: upload a fixed ZIP
  Provisioned --> Provisioning: upload new source
  Provisioned --> [*]: archive (deployment removed)

What to notice: a function can be called only while it is Provisioned; uploading new source is the only thing that rebuilds it.

On screen the states read Provisioning, Provisioned and Build failed; when it is provisioned a Function URL appears, and a failed build shows its Provisioning Error. Managing functions needs the system Admin level.

TypeCalledReceivesReturns
Reaction Custom ActionBy a reaction’s Execute Function action{ context, parameters }Any JSON object; later reactions can use it
Standalone ValidatorWhen a record is saved, edited or archived{ dataEntry, existingEntry }{ success, errors }
Value ValidatorWhen a field value is saved{ value }{ success, errors }
InterceptorBefore a matching incoming requestThe requestA rewritten request, or an answer

This session builds the first; M4-S2 the others.

offer-package/
├── func.yaml required: the runtime and how to build
├── params.yaml the parameters a reaction maps
├── package.json the build and start scripts
├── tsconfig.json compiles src/ into build/
└── src/index.ts exports handle()

Only TypeScript and ZIP uploads are deployed. The platform derives the deployed name from the function record, so the name in func.yaml does not matter. params.yaml lists the inputs a builder maps in the reaction; it names them, it does not validate them, so your code must.

The platform sends a CloudEvent; depending on its mode, your input is the body itself or its data property, so read body.data ?? body. Your answer must be a JSON object: plain text is treated as an error. Return success, a message, and your values under result. Reactions chained after the one that called you can use success, message and any key under result, for example result.gross, so keep the shape stable: renaming a key breaks every binding. The action counts as run whenever your function answers, so report a failure in the body with success: false.

Build and run the function on your own computer first: npm start serves it on port 8080, and curl sends it the same JSON a reaction would. Every bug you find there costs seconds; every bug you find after upload costs a rebuild.

⛏ Lab (27 min) — Write and test the offer package on your computer

Section titled “⛏ Lab (27 min) — Write and test the offer package on your computer”

Goal. A function that turns a grade and a base salary into Meridian’s offer package, tested with three cases, packaged as a ZIP.

Before you start. A terminal in an empty working folder.

  1. Create the folder and its source folder: mkdir -p offer-package/src && cd offer-package.

  2. Create func.yaml:

    specVersion: 0.36.0
    name: offer-package
    runtime: typescript
    build:
    builder: pack
    buildEnvs:
    - name: BP_NODE_RUN_SCRIPTS
    value: build
  3. Create params.yaml:

    version: "1"
    parameters:
    - name: grade
    - name: base_salary
  4. Create package.json:

    {
    "name": "offer-package",
    "version": "1.0.0",
    "scripts": {
    "build": "npx -p typescript tsc",
    "start": "faas-js-runtime ./build/index.js"
    },
    "dependencies": {
    "cloudevents": "^9.0.0",
    "faas-js-runtime": "^2.4.0"
    },
    "devDependencies": {
    "typescript": "^5.5.2"
    }
    }
  5. Create tsconfig.json:

    {
    "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "rootDir": "src",
    "outDir": "build",
    "strict": true,
    "esModuleInterop": true
    }
    }
  6. Create src/index.ts. The policy table is the only part finance will ever change:

    import { Context } from 'faas-js-runtime';
    interface Input {
    context?: unknown; // the event that triggered the reaction
    parameters?: { grade?: string | number; base_salary?: string | number };
    }
    // Meridian's grade policy. Finance revises it every January.
    const POLICY: Record<number, { housingRate: number; transport: number }> = {
    1: { housingRate: 0.25, transport: 600 },
    2: { housingRate: 0.25, transport: 700 },
    3: { housingRate: 0.25, transport: 800 },
    4: { housingRate: 0.3, transport: 1000 },
    5: { housingRate: 0.3, transport: 1200 },
    6: { housingRate: 0.35, transport: 1500 },
    7: { housingRate: 0.35, transport: 2000 },
    };
    const ALLOWANCE_CAP = 20000;
    const roundTo50 = (n: number) => Math.round(n / 50) * 50;
    export function offerPackage(grade: number, base: number) {
    const rule = POLICY[grade];
    if (!rule) throw new Error(`unknown grade ${grade}`);
    const housing = base * rule.housingRate;
    const allowances = Math.min(housing + rule.transport, ALLOWANCE_CAP);
    return {
    grade,
    base,
    housing: roundTo50(housing),
    transport: rule.transport,
    gross: roundTo50(base + allowances),
    };
    }
    const handle = async (context: Context) => {
    const body = (context.body ?? {}) as { data?: Input } & Input;
    const input: Input = body.data ?? body;
    const grade = Number(input.parameters?.grade);
    const base = Number(input.parameters?.base_salary);
    if (!Number.isInteger(grade) || !Number.isFinite(base) || base <= 0) {
    return { success: false, message: 'grade must be 1 to 7 and base_salary a positive number' };
    }
    try {
    return { success: true, message: 'Offer package calculated', result: offerPackage(grade, base) };
    } catch (e) {
    return { success: false, message: (e as Error).message };
    }
    };
    export { handle };
  7. Install, build and start it: npm install, then npm run build, then npm start. It listens on port 8080. Leave it running and open a second terminal in the same folder.

  8. Send the three test cases, exactly as a reaction would:

    Terminal window
    curl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \
    -d '{"parameters": {"grade": 4, "base_salary": 12000}}' | jq
    curl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \
    -d '{"parameters": {"grade": 7, "base_salary": 60000}}' | jq '.result.gross'
    curl -s -X POST http://localhost:8080 -H 'Content-Type: application/json' \
    -d '{"parameters": {"grade": 9, "base_salary": 5000}}' | jq
  9. Stop the function (Ctrl+C) and package it, without node_modules and build: zip -r ../offer-package.zip . -x 'node_modules/*' 'build/*'.

Check.

  • Grade 4 on 12,000 returns success: true with housing 3600, transport 1000 and gross 16600.
  • Grade 7 on 60,000 returns gross 80000: the allowances were capped at 20,000.
  • Grade 9 returns success: false with the message unknown grade 9, not a crash.
  • offer-package.zip has func.yaml at its root and no node_modules or build folder.

Pass condition. The three cases give exactly these answers on your computer, and the ZIP holds the five files and no build output.

If something goes wrong

What you seeWhat to do
npm run build reports a type errorCompare src/index.ts with step 6 character by character; a missing bracket shows as an error on a later line.
curl says connection refusedThe function is not running: start it again with npm start in the first terminal.
The answer is {"success": false, ...} for grade 4The JSON in -d is malformed, so the parameters were empty: check the quotes.
zip included node_modulesDelete the ZIP and run step 9 from inside offer-package.
Model answer

The first case gives {"success": true, "message": "Offer package calculated", "result": {"grade": 4, "base": 12000, "housing": 3600, "transport": 1000, "gross": 16600}}: housing is 30 % of 12,000, allowances 4,600, gross 16,600. The second gives 80000: allowances would be 23,000 and the cap holds them at 20,000. The third gives {"success": false, "message": "unknown grade 9"}. Keep the three curl lines: they are your regression test whenever finance changes the table.

⛏ Lab (30 min) — Deploy it and fill each offer’s gross package

Section titled “⛏ Lab (30 min) — Deploy it and fill each offer’s gross package”

Goal. offer-package is provisioned in your practice space, and when HR enters a grade and a base salary at Job offer, the application’s Offered gross fills itself.

Before you start. offer-package.zip from the first lab.

Add the function

  1. Open Administration › Applications › Functions and select Add Function.
  2. Name offer-package. Type Reaction Custom Action. Function Scope Module, Recruitment System. Keep Provisioning Type Internal, and upload the ZIP in Function Zip File. Save.
  3. Wait until Status reads Provisioned and a Function URL appears (usually a minute or two; reload the page).

Screenshot pending The offer-package function record with Status Provisioned and a Function URL filled in What to notice: the URL belongs to the cluster, not the internet; only the platform can call it, which is why there is nothing to secure on the function itself.

The fields and the two reactions

  1. Edit Job Application. In the Job offer details block, add Number fields Grade and Base salary, and a Number field Offered gross. Save with Save Changes.
  2. In Workflows › Job offer › Requirements, set Grade and Base salary to Mandatory and Offered gross to Locked. Save.
  3. Add a reaction Calculate offer package: Event On Entry Updated, watching Grade and Base salary. Action Type Execute Function; Function offer-package; map grade to the field Grade and base_salary to Base salary. Confirm.
  4. Add a reaction Store offered gross: Event Reaction Succeeded of Calculate offer package; Triggering Space; Action Type Update Data Entry, Self: set Offered gross from the function’s output result.gross. Confirm.

Prove it

  1. As Samir Khoury, open Ziad Karam at Job offer. Enter Grade 2 and Base salary 12345, and save.
  2. Reload after a moment: Offered gross reads 16150.
  3. As yourself, open Administration › Monitoring › Reaction Logs: the run of Calculate offer package shows the parameters it sent and the JSON it got back.

Check.

  • offer-package is Provisioned, type Reaction Custom Action, scoped to Recruitment System.
  • Calculate offer package watches only Grade and Base salary.
  • Store offered gross writes result.gross after a success.
  • Ziad Karam’s Offered gross reads 16150.
  • Reaction Logs shows the function’s input and output.

Pass condition. Entering a grade and a base salary on an application at Job offer fills its Offered gross from your deployed function, and the run is visible in Reaction Logs.

If something goes wrong

What you seeWhat to do
Status stays Provisioning for many minutesYour practice space may have no function builder set up; saving then does nothing. Ask your operator. Your first lab still stands as evidence of the code.
Build failedRead Provisioning Error. Usually func.yaml is not at the ZIP’s root, or the build failed: rebuild locally first.
offer-package is not offered in Execute FunctionIt is not Provisioned yet, or its scope is another module.
Offered gross stays emptyCheck the run in Reaction Logs: a success: false answer, an unbound parameter, or a refused write to a locked field.
The reactions run again and againCalculate offer package must watch only Grade and Base salary, not Offered gross.
Model answer

The function record is Provisioned with a cluster-internal Function URL. Two reactions use it: the first calls it whenever Grade or Base salary changes, mapping the two parameters declared in params.yaml; the second, chained on success, writes result.gross into Offered gross. Watching only the two inputs keeps the write from setting the first reaction off again. Grade 2 on 12,345 gives housing 3,086.25 and transport 700, gross 16,131.25, rounded to 16,150.

◇ Worked scenario (1 min) — Finance’s January change

Section titled “◇ Worked scenario (1 min) — Finance’s January change”

In January finance raises grade 4’s transport allowance to 1,100 and the cap to 22,000. Follow the change before reading the steps.

Where the change goes. Two numbers in POLICY and ALLOWANCE_CAP. Nothing in the designer changes: the reaction, the parameters and the field stay as they are.

How it is proved. The three curl cases are run again. The first now gives 16,700. The second gives 82,000, because its 23,000 of allowances is now capped at 22,000 instead of 20,000: its expected answer must be updated, which is exactly what a written test makes visible.

How it ships. A new ZIP is uploaded to the same function record. Uploading new source is the only thing that rebuilds it, and its name and URL stay the same, so no reaction needs touching. Offers already calculated keep their old figure; only applications whose grade or salary is entered after the upload use the new table.

The lesson: when the rule lives in one tested place, a policy change is a two-line edit, a test run and an upload.

✓ Practice (6 min) — Check your understanding

Section titled “✓ Practice (6 min) — Check your understanding”
PracticeChoose one answer.

A function answers Done as plain text. What does the reaction see?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the platform parses the answer as JSON, and text is not JSON. See the contract with the reaction.

  2. Explanation for B

    ✓ Correct

    Correct: an answer sent as plain text is treated as an error. See the contract with the reaction.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the function runs; it is its answer that is refused. See the contract with the reaction.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A developer renames result.gross to result.grossPackage in a new version. What breaks?

  1. Explanation for A

    ✗ Incorrect

    Not this one: the output keys are a contract too, and chained reactions bind to them by name. See the contract with the reaction.

  2. Explanation for B

    ✓ Correct

    Correct: later reactions bind keys under result by name, so a rename leaves them empty. See the contract with the reaction.

  3. Explanation for C

    ✗ Incorrect

    Not this one: the platform builds whatever valid source you upload; the break happens in the reactions. See what a Function is.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A builder edits the function record’s name and description and saves. Is the new code from yesterday’s ZIP running?

  1. Explanation for A

    ✗ Incorrect

    Not this one: only uploading new source rebuilds it. See what a Function is.

  2. Explanation for B

    ✓ Correct

    Correct: the code runs as of the last upload, whatever else is edited. See what a Function is.

  3. Explanation for C

    ✗ Incorrect

    Not this one: archiving removes the deployment; renaming keeps the deployed name. See what a Function is.

Check your answer

The correct answer is B. Open the explanation under each option to see why.

PracticeChoose one answer.

A function receives {"parameters": {"amount": "250"}} from a reaction and multiplies amount by 1.05 directly. What should it do instead?

  1. Explanation for A

    ✓ Correct

    Correct: params.yaml names inputs but does not validate them, and a reaction may pass a string. See the project.

  2. Explanation for B

    ✗ Incorrect

    Not this one: params.yaml lists names only; it does not type or validate them. See the project.

  3. Explanation for C

    ✗ Incorrect

    Not this one: a value can arrive as text, and “250” * 1.05 only works by accident. See the project.

Check your answer

The correct answer is A. Open the explanation under each option to see why.

PracticePut the items in the right order.

Put the steps of shipping a change to a function in the right order.

  1. Explanation for A

    Belongs in position 5 of 5

    Last, because the function can be called only once it is Provisioned, and only a real run proves the deployed version. See what a Function is.

  2. Explanation for B

    Belongs in position 4 of 5

    Fourth: uploading new source is the only thing that rebuilds the function, and the same record keeps its name. See what a Function is.

  3. Explanation for C

    Belongs in position 1 of 5

    First, because the expected answers change with the rule, and a test must say so before anything runs. See Finance’s January change.

  4. Explanation for D

    Belongs in position 3 of 5

    Third: the platform installs and builds itself, so the ZIP carries source only. See the project.

  5. Explanation for E

    Belongs in position 2 of 5

    Second, because a bug found locally costs seconds instead of a rebuild. See before you upload.

Check your answer

The correct order is C → E → D → B → A. Open the explanation under each item to see why it sits where it does.

You wrote, tested, packaged and deployed a Function, and the suite now uses its result through a reaction and a chained update. You know its contract: JSON in, a stable JSON shape out, failures in the body.

Next. In M4-S2 the same skill guards data on the way in: validators that refuse a bad application, interceptors that see a request first, and a rule for choosing among a Function, an expression and a reaction.