M7-S2 — Readings in, work orders out
Section titled “M7-S2 — Readings in, work orders out”| Module | M7 — Extend through documented extension points (extension strand) |
| After this session you can | Connect an outside data feed through the API with a least-privilege credential and safe retries, and send the result outward through an authenticated webhook. |
| Time | 58 min with a facilitator · about 58 min on your own |
| Before you start | M7-S1 (readings get a level). Larkspur Dev, Rami Aziz signed in; your terminal with Node.js 20+; BASE set to your Larkspur Dev address, as in the workbench; the CMMS stub’s address and receiver key from your enrolment message. Keep M5-S1 and M6-S1 at hand. |
| Go deeper | Writing data · Errors and retries · Choosing a credential · Webhooks and integrations |
◆ Orientation (1 min) — Both ends of the capability
Section titled “◆ Orientation (1 min) — Both ends of the capability”The evaluator decides; now the capability needs its two ends. Readings must arrive from the plant without a person typing them, and an alarm must reach the people and systems that act on it. Both ends are documented extension points you already understand from the inside: the API with an application user, and reactions with an outbound call. What is new is doing them as a master would ship them: a credential that can do one thing, writes that are safe to repeat, and a receiver that can tell a real call from a forged one.
▤ Concept (6 min) — Least privilege, safe retries, an authenticated call
Section titled “▤ Concept (6 min) — Least privilege, safe retries, an authenticated call”The feed’s credential
Section titled “The feed’s credential”The plant’s gateway runs a small feed adapter that posts readings. It authenticates as the application user Larkspur Telemetry, whose token is the feed’s only secret. Design its access from what the feed must do, nothing more:
| The feed must | So Larkspur Telemetry gets |
|---|---|
| Create readings | Access to one view, Telemetry intake (API), on Meter Readings, which exposes only the fields a reading needs |
| Find the rule that applies to a reading | Read access to one view, Active rules (API), on Threshold Rules |
| Know each asset’s class | Read access to one view, Monitored assets (API) |
| Nothing else | System level Restricted, no module or entity grant, membership of the Larkspur space only, an expiry date, a named owner |
Writing through a view (POST /api/v1/v/<view id>/v1/entities/meter_readings/entries) is the narrow
door you used in ACE: the view’s own access settings decide, and the call reaches only the fields the
view exposes. A token that leaks can then create readings and read rules, and nothing else. The
M5-S1 revocation window applies: a deactivated token keeps working
for up to five minutes.
Writes that are safe to retry
Section titled “Writes that are safe to retry”Networks fail in the middle. The hardest case is a timeout after sending: the adapter does not know
whether the reading was stored. Retrying blindly would store it twice and, worse, raise a second work
order. Reading back before every retry is slow. The platform gives a better tool: a unique field.
Each reading carries Reading key, <sensor id>@<taken at>, and the field is unique. A repeated create
is refused with 400 UNIQUE_VALUE, which the adapter treats as “already stored”. The retry policy then
fits on one line per answer:
| Answer | Meaning | The adapter does |
|---|---|---|
2xx | Stored | Next reading |
400 UNIQUE_VALUE on Reading key | Stored earlier | Count it as stored |
Other 400, 422 | The reading is wrong | Log it with the trace id and skip it |
401, or the API-token refusal | The credential is refused | Stop and alert; never retry |
403 | The view’s access changed | Stop and alert |
429, 502, 503, 504, a timeout | Transient | Back off with jitter, at most five times, then park the reading |
Out through an authenticated call
Section titled “Out through an authenticated call”When a reading’s Level becomes Alarm, a reaction raises a work order in Asset Maintenance, and a
second reaction, chained on its success, tells the CMMS with Call API. The platform does not sign
outbound calls (M6-S1), so the call authenticates itself instead: the CMMS issues a receiver key, the
reaction sends it in an X-Api-Key header marked Redact in history, and the CMMS checks it on every
call. The body carries the work order’s number and the reading’s key, which the CMMS uses as an
idempotency key: the chained reaction may run twice on the recovery path (M4-S2), and the CMMS must
then ignore the second call.
flowchart LR G["Plant gateway: feed adapter<br/>(Larkspur Telemetry)"] -->|"POST through the intake view,<br/>unique Reading key"| R["Meter Readings"] R --> E["Evaluate and store level (M7-S1)"] E -->|"Level is Alarm"| W["Reaction: raise a work order"] W -->|"on success"| C["Reaction: Call API to the CMMS,<br/>key header redacted, idempotency key"] C --> X["CMMS checks the key,<br/>ignores a repeat"]
What to notice: there is one secret at each end, the feed’s token and the CMMS key, and neither ever appears in a record, a run history or the Function.
A body signature, an HMAC over the payload, would be stronger than a shared key, but it needs code that holds the key; on the 1.10 line a Function has no secret store, so a signature would put the key in the source. The shared key, redacted in history and rotated with the CMMS team, is the honest choice here.
⛏ Lab (41 min) — Connect the feed and close the loop
Section titled “⛏ Lab (41 min) — Connect the feed and close the loop”Goal. Readings posted by your adapter get evaluated; an alarm raises one work order and one call to the CMMS stub; a repeated post stores nothing twice; and the feed’s token can do nothing else.
Before you start. Larkspur Dev with M7-S1’s reactions. The CMMS stub shows the requests it receives.
The credential and its doors
- On Meter Readings, add a unique Short Text field Reading key. Save with Save Changes.
- Create the view Telemetry intake (API) on Meter Readings exposing Asset, Measure, Value, Unit, Taken at, Source, Rule and Reading key, allowing creation. Create Active rules (API) on Threshold Rules (active rules only) and Monitored assets (API) on Monitored Assets, both read-only.
- In Administration › Organization › Users, add the application user Larkspur Telemetry, email
telemetry@example.com, expiry date one year ahead, system level Restricted, member of the Larkspur space. Copy its token from the mail you receive:export TEL="<the token>". - Give Larkspur Telemetry access to the three views in their access settings, and nothing else.
- Set
export INTAKE=<intake view id> RULES=<rules view id> ASSETS=<assets view id>.
The adapter
-
Create
feed.mjs:const { BASE, TEL, INTAKE, RULES, ASSETS } = process.env;const h = { 'x-app-token': TEL, 'Content-Type': 'application/json' };const sleep = (ms) => new Promise((r) => setTimeout(r, ms));const get = async (view, entity, criteria) => {const q = encodeURIComponent(JSON.stringify({ limit: 50, criteria }));const r = await fetch(`${BASE}/api/v1/v/${view}/v3/entities/${entity}/entries?filterCriteria=${q}`, { headers: h });if (!r.ok) throw new Error(`lookup ${r.status}`);return (await r.json()).entries; // v3 reads answer {entries, tags}, without the envelope};const ruleFor = async (assetId, measure) => {const [asset] = await get(ASSETS, 'monitored_assets', { id: assetId });const rules = await get(RULES, 'threshold_rules', { 'value.asset_class.dataEntry': asset.value.asset_class.dataEntry, 'value.measure.id': measure });return rules[0] ?? null;};export async function post(reading) {const rule = await ruleFor(reading.asset.dataEntry, reading.measure);const value = { ...reading, measure: { id: reading.measure }, rule: rule && { dataEntity: rule.dataEntity, dataEntry: rule.id },reading_key: `${reading.source}@${reading.taken_at}` };for (let attempt = 0; attempt < 5; attempt++) {const r = await fetch(`${BASE}/api/v1/v/${INTAKE}/v1/entities/meter_readings/entries`, { method: 'POST', headers: h, body: JSON.stringify({ value }) });if (r.ok) return 'stored';const body = await r.json().catch(() => ({}));if (r.status === 400 && body.error?.code === 'UNIQUE_VALUE') return 'already stored';if ([429, 502, 503, 504].includes(r.status)) { await sleep(Math.random() * Math.min(60000, 1000 * 2 ** attempt)); continue; }if ([400, 422].includes(r.status)) return `rejected ${body.error?.code} ${body.error?.traceId}`;throw new Error(`stop: ${r.status} ${body.error?.code}`); // 401, 403 and anything unexpected}return 'parked';} -
Create
run.mjswith five readings, using the ids of P-104 and C-220 from Monitored assets (API):import { post } from './feed.mjs';const A = (id) => ({ dataEntity: process.env.MON_ASSETS_ENTITY, dataEntry: id });const now = new Date().toISOString().slice(0, 16);const readings = [{ asset: A(process.env.P104), measure: 'pressure', value: 8.4, unit: 'bar', source: 'PT-104-1', taken_at: `${now}:00Z` },{ asset: A(process.env.P104), measure: 'pressure', value: 9.6, unit: 'bar', source: 'PT-104-1', taken_at: `${now}:10Z` },{ asset: A(process.env.C220), measure: 'vibration', value: 7.9, unit: 'mm/s', source: 'VT-220-2', taken_at: `${now}:10Z` },{ asset: A(process.env.P104), measure: 'temperature', value: 71, unit: '°C', source: 'TT-104-1', taken_at: `${now}:20Z` },];for (const r of readings) console.log(r.source, r.taken_at, await post(r));console.log('repeat', await post(readings[2])); // as after a timeout: must not store twice -
Set
P104,C220andMON_ASSETS_ENTITY(and keepBASEexported), then runnode run.mjs. Four lines saystored; the last saysalready stored.
Screenshot pending The terminal output of the feed run, four readings stored and the repeated one reported as already stored What to notice: the repeat is refused by the platform’s unique key and counted as stored, so a retry after a timeout cannot duplicate an alarm.
Close the loop
-
On Meter Readings, add Raise alarm work order: On Entry Updated, watching Level, criteria Level is Alarm; Event Executor Type System; Create Data Entry in Work Orders with Title “Alarm: {Asset} {Measure} {Value} {Unit}”, Asset from the reading’s Asset, Priority High, Source “Condition Monitoring”. Save.
-
Add Tell the CMMS of alarm: Reaction Succeeded of Raise alarm work order, Triggering Space, Call API
POSTto the stub’s/alarms, headerX-Api-Keywith the receiver key, marked Redact in history, and a payload with the work order’s number and the reading’s Reading key. Save. -
Run
node run.mjsagain (new timestamps). The readings are evaluated as before. -
In Work Orders, one new work order “Alarm: C-220 Vibration 7.9 mm/s”, priority High.
-
In the CMMS stub, one
POST /alarmswith the work order number, the reading key and your key header. Screenshot pending The CMMS stub's request list with one POST to /alarms carrying the work order number, the reading key and the X-Api-Key header What to notice: the receiver sees the key, the run history does not; and the reading key is what lets the CMMS ignore a repeat. -
In Reaction Logs, the Tell the CMMS of alarm run shows
X-Api-Key: ****. -
The repeated reading from step 7 raised no second work order: count the alarm work orders for that reading key.
Prove least privilege
- With
$TEL, try to read suppliers through any view or directly by id:curl -s -o /dev/null -w '%{http_code}\n' "$BASE/api/v2/entities/suppliers/entries/<a supplier id>" -H "x-app-token: $TEL". It is refused. - With
$TEL, try to update a reading through the intake view (PATCH). It is refused: the view allows creation only. - Record the token’s owner and expiry in the program’s integration register.
Check.
- Reading key is unique and every stored reading has one.
- Larkspur Telemetry is Restricted with access to three views only, an expiry date and an owner.
- Four readings stored; the repeat answered “already stored” and stored nothing.
- Exactly one alarm work order and one CMMS call per alarm reading.
- The CMMS call carried the key, and the run history shows it as
****. - The telemetry token was refused for suppliers and for an update.
- The integration register names the token’s owner and expiry.
Pass condition. A fresh run of run.mjs produces, for the alarm reading only, one work order and one
CMMS call, the repeat stores nothing, and both negative tests are refused.
If something goes wrong
| What you see | What to do |
|---|---|
stop: 403 on the first post | The intake view’s access settings do not include Larkspur Telemetry, or the view does not allow creation. |
lookup 403 | The rules or assets view is not shared with the telemetry user. |
rejected ENTRY_VALIDATION_ERROR | Read the error’s details: usually a field the view does not expose, or a category given as text instead of {id}. |
The repeat says stored | Reading key is not unique, or the key is built differently on the two posts. |
| Two work orders for one alarm | Raise alarm work order watches more than Level, or a second update re-set Level to Alarm; watch Level only. |
| The CMMS call fails with a blocked destination | The stub address is private; use the public address from your enrolment message. |
Model answer
The adapter writes only through the intake view, so the token can create readings and nothing else; it
reads rules and assets through two read-only views to attach the right rule. Each reading’s Reading key
is unique, so the repeated post, which simulates a retry after a timeout, is refused with UNIQUE_VALUE
and counted as already stored: no second reading, no second evaluation, no second work order. The
evaluator and Store level set Alarm on the vibration reading; Raise alarm work order, watching
Level only, raised one work order as System across modules; its success started the Call API, which
sent the receiver key in a redacted header and the reading key for the CMMS to deduplicate. The negative
tests show the token’s blast radius: one create door and two read doors.
◇ Worked scenario (3 min) — The alarm storm
Section titled “◇ Worked scenario (3 min) — The alarm storm”At 02:10 a vibration sensor on C-220 fails and reports 12 mm/s every ten seconds. By 02:40 there are 180 alarm readings, 180 work orders and 180 CMMS calls, and the CMMS team pages Larkspur’s on-call engineer. Decide at each step before you read on.
Step 1. Which part behaved wrongly? None, by its own contract: each reading was a real alarm by its rule, each work order followed from a reading, each call from a work order. The design is missing a rule: one open alarm per asset and measure.
Step 2. Where does that rule belong? Not in the Function: it would need to read work orders, which needs a credential, and it would hide a business rule in code. Not in the adapter: the plant should report what it measures. It belongs in configuration, where a planner can see and change it.
Step 3. The configuration. You add a reference field Open alarm work order on Monitored Assets’ source, written by a chained reaction when an alarm work order is raised and cleared by a reaction in Asset Maintenance when that work order is completed. Raise alarm work order gains a criterion: the asset’s Open alarm work order is empty. The second to 180th alarms are still stored and evaluated, so the evidence is complete, but they raise nothing.
Step 4. The faulty sensor. A reading the machine cannot produce (12 mm/s on a pump that never exceeds
8) should not be an alarm at all. You add an optional Plausible maximum to Threshold Rules, mapped onto
the reading, and the evaluator gains one parameter, plausible_max: a value above it returns
success: false with the message “implausible reading”, so no level is stored and Flag evaluation
problem writes the note. No new level word is invented, and the planners own both limits.
The lesson: an extension that is correct reading by reading can still be wrong in bulk. Put the cross-record rules in configuration, where the people who own the process can see them.
✓ Practice (6 min) — Check your understanding
Section titled “✓ Practice (6 min) — Check your understanding”The feed adapter times out after posting a reading. What should it do next?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A colleague proposes giving Larkspur Telemetry Edit on the Condition Monitoring module “so it can fix readings later”. What do you answer?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
The CMMS receives the same alarm twice, a second apart, after a reaction-service pod was replaced. What in this design keeps the CMMS correct?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
Why does Raise alarm work order watch only the field Level?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
The CMMS team asks for an HMAC signature of each body instead of a shared key. On the 1.10 line, what do you explain?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
↺ Recap (1 min) — Both ends, safely
Section titled “↺ Recap (1 min) — Both ends, safely”The capability now runs end to end: readings in through one narrow door, evaluated, alarms turned into work orders and authenticated calls, every write safe to repeat. Next, M7-S3: the test that matters most. You hand the capability to Omar Haddad, a planner who writes no code, and he extends it on the web and on the phone.