M4-S1 — Write, deploy and call a Function
Section titled “M4-S1 — Write, deploy and call a Function”| Module | M4 — Functions: code where the designer stops |
| After this session you can | Turn a rule the designer cannot hold into a tested Function, deploy it, and use its result in the suite. |
| Time | Facilitated: 70 min · On your own: 70 min |
| Before you start | M3-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 deeper | Functions: 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.
Four types, four callers
Section titled “Four types, four callers”| Type | Called | Receives | Returns |
|---|---|---|---|
| Reaction Custom Action | By a reaction’s Execute Function action | { context, parameters } | Any JSON object; later reactions can use it |
| Standalone Validator | When a record is saved, edited or archived | { dataEntry, existingEntry } | { success, errors } |
| Value Validator | When a field value is saved | { value } | { success, errors } |
| Interceptor | Before a matching incoming request | The request | A rewritten request, or an answer |
This session builds the first; M4-S2 the others.
The project
Section titled “The project”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 contract with the reaction
Section titled “The contract with the reaction”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.
Before you upload
Section titled “Before you upload”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.
-
Create the folder and its source folder:
mkdir -p offer-package/src && cd offer-package. -
Create
func.yaml:specVersion: 0.36.0name: offer-packageruntime: typescriptbuild:builder: packbuildEnvs:- name: BP_NODE_RUN_SCRIPTSvalue: build -
Create
params.yaml:version: "1"parameters:- name: grade- name: base_salary -
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"}} -
Create
tsconfig.json:{"compilerOptions": {"target": "ES2020","module": "commonjs","rootDir": "src","outDir": "build","strict": true,"esModuleInterop": true}} -
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 reactionparameters?: { 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 }; -
Install, build and start it:
npm install, thennpm run build, thennpm start. It listens on port 8080. Leave it running and open a second terminal in the same folder. -
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}}' | jqcurl -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 -
Stop the function (Ctrl+C) and package it, without
node_modulesandbuild:zip -r ../offer-package.zip . -x 'node_modules/*' 'build/*'.
Check.
- Grade 4 on 12,000 returns
success: truewithhousing3600,transport1000 andgross16600. - Grade 7 on 60,000 returns
gross80000: the allowances were capped at 20,000. - Grade 9 returns
success: falsewith the message unknown grade 9, not a crash. -
offer-package.ziphasfunc.yamlat its root and nonode_modulesorbuildfolder.
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 see | What to do |
|---|---|
npm run build reports a type error | Compare src/index.ts with step 6 character by character; a missing bracket shows as an error on a later line. |
curl says connection refused | The function is not running: start it again with npm start in the first terminal. |
The answer is {"success": false, ...} for grade 4 | The JSON in -d is malformed, so the parameters were empty: check the quotes. |
zip included node_modules | Delete 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
- Open Administration › Applications › Functions and select Add Function.
- 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.
- 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
- 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.
- In Workflows › Job offer › Requirements, set Grade and Base salary to Mandatory and Offered gross to Locked. Save.
- 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.
- 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
- As Samir Khoury, open Ziad Karam at Job offer. Enter Grade 2 and Base salary 12345, and save.
- Reload after a moment: Offered gross reads 16150.
- 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.grossafter 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 see | What to do |
|---|---|
| Status stays Provisioning for many minutes | Your 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 failed | Read 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 Function | It is not Provisioned yet, or its scope is another module. |
| Offered gross stays empty | Check 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 again | Calculate 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”A function answers Done as plain text. What does the reaction see?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A developer renames result.gross to result.grossPackage in a new version. What breaks?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A builder edits the function record’s name and description and saves. Is the new code from yesterday’s ZIP running?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A function receives {"parameters": {"amount": "250"}} from a reaction and multiplies amount by
1.05 directly. What should it do instead?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
Put the steps of shipping a change to a function in the right order.
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.
↺ Recap (1 min) — Code with a home
Section titled “↺ Recap (1 min) — Code with a home”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.