Live job updates for field devices
A driver’s phone shows a list of jobs. Dispatch assigns a new one. Without push, the phone finds out at the next poll. With push, the backend sends a small signal over a server-sent-events (SSE) stream and the phone reads the list again. This guide wires that up for field devices. How push works in general is in Push to clients; publishing and listening in other client types is in Push from a use case and listen in the browser.
The shape of it
Section titled “The shape of it”sequenceDiagram
participant Disp as Dispatcher
participant API as Your backend
participant Dev as Field device (PushStream)
Dev->>API: POST /push/subscriptions (DPoP-signed, worker's field token)
API-->>Dev: stream token, granted topics
Dev->>API: GET /push/stream?st=... (SSE)
Disp->>API: assign job (one transaction: change + push)
API-->>Dev: event: order.assigned data: {"jobId":"..."}
Dev->>API: GET /api/jobs (the real state, with the worker's normal access checks)
Two rules shape everything:
- A push is a signal, not state. It says “your jobs changed”. The device then reads the jobs through your API, which applies the worker’s normal checks. This also makes a duplicate or late push harmless: it costs one extra read.
- A push is written in the same transaction as the change. It is sent only if the change commits.
The topic
Section titled “The topic”A worker’s jobs arrive on the topic
{app}:field-worker:{principal}:jobswhere {app} is your application code and {principal} is the worker’s id (fwu_..., the sub of
the field token). The rule {principal} lets the signed-in worker subscribe to a topic carrying their
own id, and only theirs. The topic must start with your application code. The platform’s own naming
is up to you beyond that; this is the convention the field libraries’ examples use.
Publish from the backend
Section titled “Publish from the backend”Push is written by a use case, in the same transaction as the work it announces. With the Go framework, from a use case:
// a plan step in the use case that assigns the job; written in the same transaction, in plan orderreturn usecase.NewPlan(assigned, usecase.Insert(usecase.NewFresh(cx, job), jobRepo{}), usecase.Push("yard-gate:field-worker:"+workerID+":jobs", "job.assigned", map[string]any{"jobId": jobID})), niland in Java:
plan.andPush(Push.of("yard-gate:field-worker:" + workerId + ":jobs", "job.assigned", Map.of("jobId", jobId)));The Java push module that serves the streams declares the rule once (the Go module has the same rule declaration):
builder.authenticate(PushAuth.authModule()); // accepts bearer, session cookie or a field token + proofbuilder.topic("yard-gate:field-worker:{principal}:jobs"); // rule: {principal} must be the caller's principalPushAuth.authModule() authenticates a subscribe with the auth module, so a field token with its DPoP
proof works as is. See Verify field tokens in your backend for turning on
field workers in the framework, which push needs. Keep payloads small and put an id in them, not the
record: the default data limit is 16 KiB.
If you do not host push in your application, the platform can: set FC_PUSH_ENABLED on the platform
and publish through its outbox. The platform’s gateway grants a field worker only the topics of the
application their token was issued for, so another application’s rules and tickets are ignored. The
readers below work against it by changing baseUrl to {platform}/api. The gateway is opt-in; see
Push to clients.
Listen on the device
Section titled “Listen on the device”PushStream is in both @flowcatalyst/field-js (browsers and WebViews) and
@flowcatalyst/field-react-native (React Native, running on Hermes). They share one source file
and behave the same; only the event API differs (addEventListener versus addListener).
Browser or WebView
Section titled “Browser or WebView”import { FieldAuth, PushStream } from "@flowcatalyst/field-js";
const principal = auth.session!.worker.id; // the same id your rule usesconst topic = `yard-gate:field-worker:${principal}:jobs`;
const stream = new PushStream({ baseUrl: "https://app.example.com/api", topics: [topic], fetch: auth.fetch.bind(auth), // signs the subscribe call: DPoP and token refresh lastEventId: await loadSavedId(), // optional: resume after an app restart});
stream.on(topic, (push) => refreshJobs()); // push = { id, topic, type, data }stream.addEventListener("reset", () => refreshJobs()); // away too long: reload statestream.addEventListener("denied", (e) => console.warn((e as CustomEvent).detail));stream.addEventListener("error", (e) => console.warn((e as CustomEvent).detail));stream.start();React Native
Section titled “React Native”import { PushStream } from "@flowcatalyst/field-react-native";import { fetch as streamFetch } from "expo/fetch"; // streams response bodies; RN's built-in fetch does not
const stream = new PushStream({ baseUrl: "https://app.example.com/api", topics: [topic], fetch: field.fetch.bind(field), // signs the subscribe call streamFetch, // the stream GET carries its token in the URL, so it needs no signature lastEventId: await loadSavedId(),});
stream.on(topic, () => refreshJobs());stream.addListener("reset", () => refreshJobs());stream.addListener("denied", (topics) => console.warn(topics));stream.addListener("error", (err) => console.warn(err.code));stream.start();
// The OS drops the connection in the background: end it and start it again.AppState.addEventListener("change", (s) => { if (s === "active") { stream.stop(); stream.start(); } else stream.stop();});After stop(); start() the reader resumes from the last id; stop() alone does not forget it.
What the reader does for you
Section titled “What the reader does for you”- Subscribes, then listens. It POSTs the topics with the credentials you give, gets a stream token, and reads the SSE stream. The subscribe call is the one that is signed; the stream request carries its token in the URL, and the access log never records query strings.
- Delivers once, in order. Ids are 64-bit and arrive as strings. A push with an id at or below the last delivered one is dropped (resume overlap).
- Reconnects and resumes. It remembers the last id and sends it as
Last-Event-ID. After a drop it reconnects after the server’sretry(3 s) with jitter, backing off up to 60 s on repeated failures. - Handles expiry. When the server ends the stream with
auth-expired, or answers 401, it subscribes again (refreshing the field token through yourfetch) and resumes. - Handles
403 NO_TOPICS. It stops the stream and reports anerror. - Handles long absences. A client that was away longer than the retention window (24 hours at most)
gets a
reset: reload your state.
Events and handlers
Section titled “Events and handlers”| Event | Detail | Meaning |
|---|---|---|
subscribed |
{ granted, latest } |
Stream open; the topics granted. |
reset |
{ reason, latest } |
History is gone (away too long, or an unknown id). Reload from the API. |
denied |
[{ topic, code }] |
Topics the server refused. |
error |
a PushError |
A failure the reader reports. |
state |
connecting, open, reconnecting, stopped |
Connection state. |
on(pattern, handler) takes a topic or a pattern where * is one segment and a final ** is the rest;
onAny(handler) takes every push. Both return a function that removes the handler. stream.setTopics([...])
subscribes again with a new set, and stream.stop() ends it.
Save stream.lastEventId (for example on each push) and pass it back as lastEventId next start.
Where bodies are not streamable
Section titled “Where bodies are not streamable”The reader streams with fetch. React Native’s built-in fetch cannot, so the reader falls back to
EventSource if one exists; then give eventTypes (your push types), because EventSource only hears
event types it is told about. Or pass a streaming streamFetch as above. On a web page, pass
fetch: globalThis.fetch.bind(globalThis) for cookie sessions.
Do not miss a change between load and listen
Section titled “Do not miss a change between load and listen”If the device loads the jobs and then subscribes, a change committed between the two is missed. Return a cursor with the state and start the stream from it:
- On the server, take
pushes.cursor()(GoCursor()) before you read the jobs, and return it with the list. - On the device, pass it as
lastEventIdfor the first listen.
A cursor that lags the log only causes more pushes to be replayed, never a missed one. Through the
platform gateway there is no cursor (Cursor() is empty): the first listen is live, so read the
state once more when the stream reports subscribed.
Tickets
Section titled “Tickets”A worker’s own topics need no ticket because the {principal} rule grants them. A topic that rules cannot
express (for example “any worker at this depot”) is granted by a ticket, minted by your own endpoint
after your own access check. Pass getTickets(topics) to PushStream to fetch them from that endpoint; they
are fetched again on every subscribe. A ticket can be bound to the device’s key, in which case the subscribe
must come from a field token bound to that same key. See
Topics, rules and tickets.
When a worker is revoked
Section titled “When a worker is revoked”Suspending a worker or revoking a device ends their sessions; their next token refresh fails. Streams
are ended too, if your backend does it: handle the revocation event and call endStreams (Java
pushes.endStreams(PushHolders.of(event)), Go pushes.EndStreams(ctx, flowcatalyst.PushHolder(e))).
The client sees auth-expired, tries to subscribe again, and fails because the token no longer
refreshes. In the platform gateway a database trigger on field sessions does this for you.
Limits to design for
Section titled “Limits to design for”- Push is not a mobile notification. A device that is not listening gets nothing until it reconnects and resumes (or resets).
- There are no client-to-server messages and no presence.
- Ordering is the log order of one host. Through the platform gateway, pushes of one message group of an application arrive in their outbox order.