Skip to main content

Integration bus (HTTP ↔ TCP)

ADR 0005 (cse-http-be); blueprint 05 §3; research R15/R16; FR-023–FR-029, FR-049. This is the one sanctioned channel between the two independently owned backends — see the hard invariant: this service never reads the TCP Server's PostgreSQL database directly, in either direction. Everything here is IntegrationStack (lib/integration-stack.ts, T002-085), which is authored but not deployed in every stage that exists today — see Infrastructure → IntegrationStack for the full resource/context-key reference and Architecture overview → Data flow for the request-level narrative this page doesn't repeat. This page is the reference for the bus itself: the envelope, the topics/queues, the ordering/dedup guarantees, what a TCP-side consumer is obligated to do with a message, and how to recover from a failure.

Envelope​

Every message on the bus, in both directions, is validated against IntegrationEnvelope (packages/core/src/schemas.ts) — a CloudEvents-influenced shape:

{
specversion: '1.0';
id: string; // ULID; consumers dedupe on it (= MessageDeduplicationId outbound)
type: string; // e.g. "plant.created.v1"
source: string; // "cse-http-be/<stage>" outbound; TCP's own source inbound
time: string; // ISO-8601 datetime
subject?: string;
correlationId: string; // outbound: always set, the originating API request's id.
// IntegrationEnvelope itself treats this as optional —
// see Types & schemas for the exact outbound/inbound diff
causationId?: string; // the event that caused this one, if any
seq: number; // per-aggregate monotonic version
data: unknown;
}

Full field-by-field optionality diff between the outbound Envelope TypeScript type (packages/core/src/outbox.ts) and the IntegrationEnvelope Zod schema: Types & schemas → IntegrationEnvelope.

Topics and queues​

ResourceDirectionDetail
SNS FIFO cse-http-be-<stage>-to-tcp.fifoHTTP → TCP (outbound)contentBasedDeduplication: false — envelope ids are already unique ULIDs. Topic policy allows sns:Subscribe only to the TCP account's principal, conditioned on an sqs endpoint matching cse-tcp-be-<stage>-*
SQS from-tcp + DLQTCP → HTTP (inbound)Device/binding/command/report/erasure events — the allowlisted types on this subscription's filter policy are in Infrastructure → IntegrationStack
SQS alert-events + DLQTCP → HTTP (inbound)alert.changed.v1 only. The queue/DLQ exist in this stack; the consumer logic (notifier) is a later feature (008)

Outbound publish rights are deliberately narrow: only stream-router has sns:Publish on the topic (research R15) — no handler, and no other function in IntegrationStack, can publish directly.

Every published message carries the SNS message attribute type (String, the envelope type, added 2026-11-02), so a TCP subscription can use an SNS filter policy on type instead of parsing the body.

plant.upserted.v1 carries optional latitude/longitude (2026-11-02, both or neither, only when the stored address has valid coordinates, rounded to 2 decimal places, about 1 km, so an exact home location never leaves this service); the report render manifest (since v3) passes the same values per plant. See Reports pipeline.

Ordering and dedup​

  • Outbound. MessageGroupId = <aggregateType>/<aggregateId> — SNS FIFO guarantees order only within a group, so events about the same aggregate (e.g. the same plant) stay ordered; different aggregates process independently and may interleave. MessageDeduplicationId = envelope.id gives SNS's own 5-minute dedup window as a second line of defence on top of content-based dedup being off.
  • The DynamoDB-stream side (stream-router) is "retry from the first failure." A TransactWriteItems guarded by a DEDUP#stream#<eventID> marker (attribute_not_exists(PK)) makes a redelivered stream record (Lambda's at-least-once stream processing) a no-op. When a batch has any failure, stream-router reports only the first failing record as the one batchItemFailures entry — the event-source mapping then retries from that record's sequence number onward, which is what preserves order for a DynamoDB stream (unlike the SQS side below).
  • Inbound (consume, packages/core/src/integration/consume.ts) is per-message, not per-batch. Each registered handler owns a DEDUP#tcp#<id> guard (7-day TTL) combined with its own projection's attribute_not_exists(lastSeq) OR lastSeq < :seq condition, in the same TransactWriteItems as the dedup put — so a redelivery (duplicate) and an out-of-order/superseded event (stale) are distinguished from the single transaction's CancellationReasons (index 0 = dedup, any later index = the handler's own condition), and either outcome acks the message rather than retrying it. SQS failures are reported back by the specific messages that were invalid or threw (by messageId), regardless of their position in the batch — unlike the stream side, a later message in the same batch can succeed even when an earlier one in it failed.

See Architecture overview → Outbound and → Inbound for the full step-by-step walkthrough of both directions, including the consume() outcome table (invalid/ignored/applied/duplicate/stale).

Consumer obligations (what the TCP side must do)​

  • Subscribe only with a filter policy, not a blanket subscription — this stack's own subscriptions (when tcpEventsTopicArn is set) use FilterPolicyScope: MessageBody filters on type, and the TCP side's subscription to to-tcp.fifo should do the same rather than receiving and discarding every envelope.
  • Dedupe on envelope.id. SNS FIFO's own dedup window is 5 minutes; anything beyond that is the consumer's responsibility, the same way this service's own DEDUP#tcp#<id> guard (7-day TTL) is its responsibility for the reverse direction.
  • Respect MessageGroupId ordering — process messages from the same group (<aggregateType>/<aggregateId>) in delivery order; different groups may be processed concurrently.
  • Treat data as the versioned payload for type. A type is a stable contract (same spirit as this API's error codes — see Types & schemas → Error codes); a breaking payload change needs a new type (e.g. ...v2), not a silent shape change under the same type.
  • The subscription only exists once tcpEventsTopicArn context is set on this side (see Infrastructure) — until TCP's own topic ARN is known and passed in, this stack creates the queues/DLQs but never subscribes them.

busEnabled gating (CR-21, blocker B-01)​

Every event-source mapping in IntegrationStack — stream-router's DynamoEventSource and both of tcp-events's SqsEventSources — is created with enabled: busEnabled, a CDK context flag (-c busEnabled=true) defaulting to false in every stage. With it false, IntegrationStack doesn't exist at all; true creates it with every Lambda, queue and topic fully IAM-wired and live-invoking, in the same deploy. Renamed, T002-148 (CR-26): this used to be two flags — withIntegration created the stack shell, and a separate busEnabled flipped the mappings on inside it — now the one busEnabled flag does both, so there's no intermediate "deployed but silent" state (see Infrastructure for the full context-key reference).

It was gated for capacity: this AWS account's Lambda concurrency quota was 10, shared with the live TCP Server's ingest functions (blocker B-01, quota L-B99A9384). B-01 closed on 2026-10-26 — the quota is now 1000, still shared. Every SQS mapping caps itself with maxConcurrency: 2 (tcp-events has two, so up to 4); stream-router's DynamoEventSource has no such cap. busEnabled still defaults to false; flipping it is a human decision made at deploy time, never something the code does on its own. The same flag also brings up the plant-jobs worker (the D14 device-import-jobs queue and worker were removed, ADR 0012).

While it is off, nothing derived from the stream updates (search tokens, counters, access-index copies, the HTTP inbox, outbox publishing). See KI-43 for the full list. After the first deploy with the bus on, run npm run resync:plants on that stage so the TCP Server's plant_projection includes plants written more than 7 days earlier. Then run npm run republish:orgs so its org_projection has the name of every existing org. The full order is in Device Inventory backfill order.

Stream and consumer hardening (Audit wave 1 (2026-10-27))​

  • Stream filter: the stream-router filter is built from packages/core/src/stream/filter-spec.ts. It covers 13 entity types (ORG, PLANT, ROLE#, MEMBER#, SHARE#, ACCESSREQ#, TAG#, DEVICE#, REL#CUSTOMER#, REL#PARTNER#, WORK_ORDER, REPORT, RSCH#). TTL deletes are excluded with exists:false. Before this change, most projections never ran with the bus on.
  • bisectBatchOnError is on. Projections write their dedup marker last.
  • from-tcp now delivers notify.endpoint.invalid.v1. alert-events is no longer subscribed to alert.changed.v1.
  • Timeouts: tcp-events 120 s. Batch size 1 for from-tcp and schedule-runner. Inbound queue visibility timeout 720 s.
  • Every inbound message is validated with Zod.
  • Schedule sync rethrows retryable errors. There is no reconcile sweep yet (known issue).
  • The org-settings walk continues by re-enqueueing itself.

Event catalog​

The envelope's data field (above) is unknown at the schema level — type determines its real shape, and each type has its own JSON Schema (draft 2020-12) under cse-http-be's docs/events/, generated from and kept in step with the handler/contract that emits it. Two HTTP→TCP event types exist so far:

TypeWhenPayload (summary)Schema (in cse-http-be)
org.upserted.v1An organisation is created or updated (feature 003: personal-org bootstrap on first GET /v1/me, or PATCH /v1/orgs/{orgId}; customer, partner and Business creates and renames). Re-emitted for every org, at its current version, by the human-run npm run republish:orgs{orgId, kind, personal, name, timezone, currency?, status, version} (currency optional, ISO 4217, added by 004); MessageGroupId = org/<orgId>; seq = org.versiondocs/events/org.upserted.v1.schema.json
tag.upserted.v1A tag is created (by hand, or as a system REGION tag on plant create / address change) or edited (rename, colour, note, appliesTo) — 2026-11-27, cse_tcp_be request for Plants-list tag labels; built, not deployed. Re-emitted for every ACTIVE tag, at its current version, by the human-run npm run republish:tags{tagId, orgId, label, group, system, regionKey?, version} (group = SEGMENT | REGION | SERVICE | COMMERCIAL | COMPLIANCE); MessageGroupId = TAG/<tagId>; seq = tag.version. A plant's plant.upserted.v1 tagIds already includes its regionTagIddocs/events/tag.upserted.v1.schema.json
customer.status.v1Bug fix 2026-12-02 (TCP's console "Needing attention" count). After a customer :close, an End User attach (plant transfer, joining with plants) or detach / removal, and an End User :suspend / :restore. A full snapshot read after the write commits; best effort (a failure is logged, never fails the request). Re-emitted for every Crown-wide list entry by the human-run npm run republish:customer-status. Built, not deployed{customerOrgId, operatorOrgId, status: ACTIVE | CHURNED, endUserSuspended} (a CLOSED personal row, Q3, is sent as CHURNED). operatorOrgId is the org listing the customer (the personal org itself for an Independent End User); endUserSuspended is the End User's membership there. MessageGroupId = CUSTOMER/<customerOrgId>; seq = epoch ms of the snapshot, newest wins. A customer TCP has no row for is ACTIVE, not suspendeddocs/events/customer.status.v1.schema.json
user.profile.v12026-12-02, agreed with cse_tcp_be (its BE-10 / BE-11: device owner and activity actor names, which TCP holds nowhere). When a user profile is created and when its display name changes; a full snapshot read after the write, best effort. Re-emitted for every user of the identity provider by the human-run npm run republish:user-profiles. Built, not deployed{sub, displayName: string | null, deleted}. displayName is the profile name, else the email's local part (never the email). MessageGroupId = USER/<sub>; seq = epoch ms, highest per sub wins; deleted: true clears the namedocs/events/user.profile.v1.schema.json
tag.deleted.v1DELETE /v1/orgs/{orgId}/tags/{tagId} marks the tag DELETING (2026-11-27). Its plant links are removed afterwards, each plant emitting plant.upserted.v1 without it{tagId, orgId, version}; MessageGroupId = TAG/<tagId>; seq = the DELETING versiondocs/events/tag.deleted.v1.schema.json
access.revoked.v1A member's or share grantee's effective access decreases (feature 003: role/scope narrowing, suspend/end-sessions/reset-mfa/remove, or a share revoked/suspended/narrowed){scope:"USER"|"ORG", sub?, orgId, plantIds?, selector?, originJtis?, reason, effectiveAt} — originJtis (2026-11-30, QA B5) only with USER + SESSIONS_ENDED: close only the listed sign-ins' sockets (ticket oj), emitted by the session-end routes and password:report-change; reason is one of SCOPE_NARROWED, ROLE_CHANGED, MEMBER_SUSPENDED, SESSIONS_ENDED, MFA_RESET, MEMBER_REMOVED, SHARE_REVOKED, SHARE_SUSPENDED, SHARE_NARROWED, and from feature 004 CUSTOMER_CLOSED, PORTAL_NARROWED, PARTNER_SUSPENDED; MessageGroupId = user/<sub> or org/<orgId>docs/events/access.revoked.v1.schema.json

Status (2026-10-01): schema-only. These two types are specified (specs/003-organizations-access/contracts/http-api.md §Integration events, FR-062/FR-063) and their JSON Schemas exist, but feature 003's handlers don't emit them yet — no code in cse-http-be currently publishes either type. access.revoked.v1 is the signal ws-gateway needs to drop a live subscription the moment a user's or org's access to a plant narrows, so the TCP side can treat its arrival as "re-check this subscription now" without waiting for a periodic re-poll. Both are ordinary envelope data payloads on the same to-tcp.fifo topic and from-tcp/alert-events consumer obligations above apply unchanged once they ship.

Inbound device events (TCP → HTTP, feature 005)​

Delivered on from-tcp and consumed by the 002 tcp-events dispatcher — this service never connects to the TCP server. Each is idempotent on the envelope id (DEDUP#tcp#<id> written in the same transaction); unknown types and unknown payload fields are ignored.

TypePayloadEffect
device.observed.v1 Removed (ADR 0012){loggerKey, inverterSn?, modelDetected?, firmware?, firstSeenAt?, lastSeenAt?}Logger resolved by logger key; unknown → dropped (anomaly). Newer snapshot replaces observed (out-of-order ignored). An unknown inverterSn under a REGISTERED, BOUND logger is discovered: created BOUND on the logger's plant with the logger as parent (entryMethod: DISCOVERED). Serial held by a device elsewhere → anomaly, logger snapshot only
device.binding.result.v1 Removed (ADR 0012){deviceId, version, result: bound|refused, reason?}Applied only when version equals the device's current version (else stale, ignored). bound → tcpBinding.status CONFIRMED; refused on a BOUND device → bindingState BLOCKED, blocked.reason LOGGER_MOVED / INVERTER_TAKEN / TCP_REFUSED_OTHER
device.erasure.completed.v1 Removed (ADR 0012){deviceId? | deviceIds[], counts?}Finishes removal of devices in REMOVING; others skipped

The three device rows above are removed (ADR 0012): they are no longer in the from-tcp filter or the tcp-events dispatch, and DeviceInboundAnomaly is gone. Historically, anomalies emitted the metric DeviceInboundAnomaly — see Operations.

Inbound binding events (TCP → HTTP, ADR 0018)​

Live on dev since 2026-11-04. Both servers are deployed, and the first sync completed at 08:06Z: 6 events applied, 2 stale, and the DLQ empty. tcpEventsTopicArn is in cdk.json context.stages.dev. Not deployed on staging or prod; there, TCP sends nothing until its deviceBindingEvents context is on for that stage.

TCP is the source of truth for which plant a device is on. This server's plant ↔ serial binding follows TCP's device.binding.changed.v1 (schema docs/events/device.binding.changed.v1.schema.json in cse-http-be). The consumer is packages/core/src/plants/binding-from-tcp.ts.

FieldMeaning
subjectdevice/<deviceId> (TCP's device uuid)
seq = data.versionTCP's per-device inventory_version. Only increases, may skip numbers; an event is applied only when seq is greater than the last applied
data.loggerId, data.inverterSnThe device's current serials, as TCP stores them. This server normalises them. inverterSn can be null (always present as a key): the mobile app may register a device without it, and TCP fills it from the hardware on first connection, so it can first appear in a later event
data.previousLoggerId, data.previousInverterSnThe serials before a logger swap (null when unchanged)
data.plantId, data.previousPlantIdnull = on no plant (unbound, deleted or erased)
data.reasonBIND, UNBIND, TRANSFER, REGISTER, LOGGER_SWAP, ERASE or SYNC. Informational only. A TRANSFER is immediate on TCP (issue #26), so it arrives as a single event with the final plantId; no pending state ever reaches this server
data.label, data.model, data.changedAtCopied onto the binding (label from TCP's display_name)
data.hasBatteryAdded 2026-11-18, optional. true when the device has at least one battery in TCP's batteries table. TCP sends it on every event and emits an event (higher seq) when the device's battery count goes 0 ↔ non-zero. Stored on the binding; an event without it keeps the binding's previous value. Plant hasBattery is derived from it (see below)
data.lifecycleAdded 2026-11-25, optional. TCP device lifecycle: in_service, revoked or deactivated, sent on every event. A revoke or restore now emits an event with reason: "LIFECYCLE", and a label or model change emits reason: "SYNC". HTTP accepts it but doesn't act on it: the binding follows plantId only. seq may skip numbers; HTTP applies an event only when seq is greater than the last applied one

Derived plant battery (2026-11-18). A stream pass (packages/core/src/projections/plant-battery.ts) runs when a binding with hasBattery: true is inserted or removed, or a binding's hasBattery flips. It recounts the plant's battery bindings and writes batteryDeviceCount on plant META (no version bump, no event). Every plant response returns hasBattery = batteryDeviceCount > 0. plant.upserted.v1 no longer carries hasBattery or batteryCapacityKwh.

Plant creation time (2026-11-25, console request P9). plant.upserted.v1 gains an optional createdAt (ISO-8601 UTC, the plant's stored creation time) on every event; absent when the plant stores none or an unparseable value. Additive, so the event stays v1. TCP projects it for the list_plants date-created filter (createdFrom / createdTo). A plant TCP already holds at its current version keeps no createdAt until its next edit, or until npm run resync:plants -- --stage dev --bump-version --apply (human-run) re-emits it at a new version. Run on dev 2026-11-25: 29 plants re-emitted with createdAt, 0 failed (Operations).

Create batteries removed (2026-11-20). Plant create takes no battery data any more (ADR 0029): plant.upserted.v1 no longer carries batteries; createdByUserSub stays. Batteries are added per device on TCP. The paragraph below describes the 2026-11-19 behaviour, kept for history.

Create batteries and creator (2026-11-19, batteries removed 2026-11-20). plant.upserted.v1 gains two optional fields: createdByUserSub (the plant's creator, on every event when stored) and batteries ([{batteryId, brand, capacityKwh}], one item per battery, only on the event of a POST /v1/plants that carried batteries; omitted when none). HTTP stores no battery. TCP stores one row per battery, waiting at the plant with no device; the first in-service device registered to the plant takes all of them (up to 16 per device), or, if the plant already has a device, its oldest in-service device does. That device's device.binding.changed.v1 then reports hasBattery: true. Each event is its own outbox item on the FIFO topic (group per plant), so a later PATCH event never replaces the create event. TCP gives the batteries to the plant's end user when there is one (so a Crown staff create for an end user gives them to the end user), else to createdByUserSub.

Plant end user and device owners (2026-11-19). TCP treats the plant's end user as ownerUserSub when non-null, else customerSub. When a newer plant.upserted.v1 changes it — a web PATCH of the customer to another user's personal org, or a plant transfer (POST /v1/orgs/{orgId}/plant-transfers, 2026-11-19) — TCP sets owner_user_id on every device and battery of the plant. A move between orgs with the same end user, or no end user at all, changes nothing. This server never reads device owners.

Stored owner (2026-11-19). A plant transfer stores the receiver on the plant META as ownerUserSub; when set it is sent on every later plant.upserted.v1, also for a plant whose operatorOrgId is a Business (before, a non-null ownerUserSub meant a personal customer org only). Without a stored owner the personal-customer-org rule applies. It is removed — the next event carries ownerUserSub: null — when the End User customer is detached or removed, or when a staff owner leaves the Business. The event shape is unchanged.

Owner on every plant (2026-11-20, ADR 0029). Every plant now stores its owner from create (the creator, or the end user the create assigns), so ownerUserSub is non-null on every plant.upserted.v1 of a plant with an owner. It changes on a share (the end user), an unshare / detach / removal of the End User (the caller who did it — no longer null), a staff owner leaving the Business (the Business owner — no longer null) and a web PATCH to an end user's personal customer org. Older plants get it from npm run migrate:plant-owners, which bumps their version so TCP applies the event. TCP re-owns the plant's devices and batteries on each change; the event shape is unchanged.

How it applies:

  • Transaction: one transaction writes the DEDUP#tcp#<id> marker, then the per-device marker TCPDEVICE#<deviceId>/BINDING (conditioned on lastSeq < seq), then the binding writes. A redelivery ends as duplicate, and an older event as stale.
  • Lookup: the consumer finds the device's bindings under every serial in the event (current and previous, plus the serials it applied last time). It keeps one binding on the target plant and deletes the rest with their guards.
  • Key (ADR 0020, 2026-11-05): a binding is keyed by TCP's stable device id, PLANT#<p>/DEVICE#TCP#<deviceId>, so a logger swap or a corrected inverter serial updates it in place. Its primary serial (inverter serial, else the logger id) is the GSI1 lookup key, and every current serial has its own guard. A serial-keyed binding on the target plant (from the deprecated POST route, or written before ADR 0020) is converted on TCP's next event.
  • Previous serials: a binding found only under a previous serial is removed only when it belongs to this device or to no TCP device yet, because a reused logger id can belong to another device.
  • Plant state: a missing or DELETING target plant is not bound to; ARCHIVED is.
  • Permissions: no caller-permission check runs. TCP has already authorized the action.
  • Bad payloads: an invalid payload is retried, then goes to the DLQ.
  • Device counts: deviceCount follows from the stream, as for the HTTP bind/unbind routes.

Throughput. The consumer handles one message at a time, two at once at most (about 10–20 events/s). TCP sends live changes first, and paces its one-time backfill (reason SYNC, one event per device) at 10/s, about 28 h for 1M devices.

Deploy order:

  1. This server, with the type in the from-tcp filter and tcpEventsTopicArn set.
  2. TCP, with deviceBindingEvents=true. Until then, TCP queues the events and loses none.

DLQ, replay and rebuild (FR-026, FR-049)​

Three separate, human-run recovery tools exist for this pipeline — full usage and output in Operations → Replay, rebuild and redrive:

  • scripts/redrive-dlq.sh moves messages from from-tcp-dlq or alert-events-dlq back to their source queue (aws sqs start-message-move-task), after printing the exact source/destination and requiring the operator to type the destination queue's name back as confirmation.
  • scripts/replay-outbox.ts re-queries the OUTBOX#<hour>#<shard> access pattern for an operator-given UTC hour range (10 shards/hour, never a Scan) and re-publishes what it finds — for when stream-router missed or mishandled a window of events. Outbox items carry a 7-day TTL, so this only has that long a window to work with.
  • scripts/rebuild-projections.ts re-derives the COUNT#/SRCH# projections for one org's collection from the live items on GSI2 (never a Scan) — for when stream-router missed events and a counter or search token drifted from, or was wiped relative to, the entities actually on the table.

All three default to a dry run (query/report only) and require an explicit flag to actually write or move anything; none is invoked by any Lambda, CI job, or agent.