Skip to main content

Target architecture

:::caution Planned — not implemented This page describes the proposed target architecture from the cse-http-be blueprint (docs/blueprint/05-integration.md) and ADRs 0003, 0005–0009. None of the resources, queues, topics, events or routes below exist yet. The current, deployed architecture is in Architecture overview. Items tagged TCP-REQ-nn are work in cse_tcp_be that this plan depends on and does not implement — see TCP dependencies. :::

Target picture​

Web console (HTTPS) ─┐ ┌──────── cse-http-be ──────────────────────────┐
Flutter app (HTTPS) ─┼─▶ CloudFront+WAF ─▶ HTTP API v2 ─▶ λ (core/api) ─▶ DynamoDB (+GSI2/3, stream)
│ Cognito LITE (mobile + web clients) │ S3 (attachments, firmware, reports)
│ KMS (ticket signing) │ stream-router λ ─▶ SNS FIFO ──┐
│ tcp-events λ / notifier λ ◀─ SQS ◀┐ │
│ SES / SNS mobile push │ │
│ └────────────────────────────────────────────────────────────┼───┼─┘
│ │ ▼
└─ WSS (ticket) ─▶ cse_tcp_be ws-gateway ◀─ NATS ◀─ tcpserver ◀─ devices (Modbus) │ SQS FIFO (TCP-owned)
TimescaleDB · alerts · analytics · renderer ─▶ SNS (TCP-owned) ─────┘

New pieces on the HTTP side: a public web-console Cognito client (SRP, no secret, 24 h refresh, no Hosted UI — stays on LITE), CloudFront + WAF in front of the HTTP API with a security-headers policy, a per-stage CORS allow-list (no wildcard), two new generic GSIs, S3 buckets, a KMS asymmetric signing key, and three new Lambdas (stream-router, tcp-events, notifier) plus scheduled sweeps (ADR 0009, ADR 0005).

Invariants carried forward​

ADR 0001, as amended by ADR 0005:

  1. HTTP Lambdas never open a connection to the TCP server, NATS, the telemetry Postgres or the TCP VPC, and never join a VPC.
  2. HTTP ↔ TCP exchange happens only through AWS-managed, IAM-authenticated services: SNS topics, SQS queues, S3 presigned URLs and a published KMS public key. The producer owns the topic; the consumer owns its queue.
  3. Clients talk to both backends directly: HTTPS to this API, WSS to the TCP gateway. HTTP issues the ticket that authorizes the WS session.
  4. No telemetry value, aggregate or KPI is stored in or served by HTTP, in any form.

Responsibility matrix (HTTP ↔ TCP ↔ client)​

CapabilitySource of truthHTTP serverTCP serverClientChannel
Sign-in, tokens, MFACognitoTriggers, IdentityProvider, MFA policy check—Cognito SDK directHTTPS (Cognito)
Organisations, members, roles, scopes, sharesHTTPOwns, authorizes, auditsConsumes ticket grantsTeam & Access screensHTTPS
Realtime session authHTTP (policy)Issues signed ticketsVerifies tickets, enforces grants (TCP-REQ-01/02)Fetches ticket, connects WSSHTTPS + WSS
Plant metadata & settingsHTTPCRUD, publishes plant.*Projection for day boundaries, analytics, alert rules (TCP-REQ-04)Plant screensHTTPS; SNS→SQS
Device registry / bindingHTTP (DEC-4)CRUD, import, transfer, publishes device.*Binds physical connection to the registry entry; reports device.observed (TCP-REQ-05/13)Inventory screensHTTPS; SNS↔SQS
Device presence, live status, live readingsTCP—watch / telemetry / presenceMerges with registry rows by id/serialWSS
Fleet / plant status summaries (status strips, comm age, power columns)TCP—Plant-summary query API (TCP-REQ-07)Joins onto HTTP plant pages by plantIdWSS
History, charts, analytics KPIs, compareTCP (DEC-5)Publishes metadata TCP needs (capacity, expected yield, tariff, timezone, tags)History/analytics query API (TCP-REQ-08)Energy / Analytics / device history tabsWSS
Alerts: detection, instances, catalog, ack/assign/resolve, timelineTCP (DEC-3)Stores only alertId links on work orders and deliveriesScope-based queries, workflow ops, CROWN catalog (TCP-REQ-09)Alert Center, workspace alert tabWSS
Alert → work orderHTTP (WO) + TCP (alert)Creates WO with alertId; publishes workorder.linked / workorder.completedShows the link on the alert timeline; resolves the alert on WO completion only if the condition cleared"Create work order" from an alertHTTPS; SNS→SQS
Notification rules, channels, recipientsHTTP (DEC-6)CRUD; evaluates rules; delivers push/emailPublishes alert.changedSettings screens; receives push/emailHTTPS; SNS→SQS; SES; SNS mobile push
Commands, approvals, bulk tasks, rollouts, operation logHTTP intent (DEC-2)Validates, authorizes, approves, records, enqueues; projects statusExecutes, enforces deadlines/preconditions, reports status (TCP-REQ-06)Engineering + device screensHTTPS; SNS FIFO→SQS FIFO; SNS→SQS
Command progress while runningTCP → HTTP projectionGET /v1/commands/{id} (history + fallback)Pushes command_status to the requester's WS connectionsProgress UIWSS primary, HTTPS fallback
Register catalog / read configurationTCPCommand definitions reference register groups by keyget_registers / read_registersParameters tabWSS (read-only; writes go through commands)
Firmware packagesHTTPS3 + metadata; presigned GET in the command messageDownloads, verifies SHA-256, flashes (TCP-REQ-06)EngineeringHTTPS; S3
ReportsHTTP records + TCP renderingRecords, schedules, S3, deliveryRenders on report.render.requested (TCP-REQ-11)Reports moduleHTTPS; SNS↔SQS; S3
Work orders, plans, attachmentsHTTPEverything—Service moduleHTTPS; S3 presigned
Plant archive / delete, device removalHTTP starts; TCP completesSaga ownerMutes / erases on events (TCP-REQ-12)Confirm flowsHTTPS; SNS↔SQS
Preferences, favourites, saved viewsHTTPCRUD——HTTPS

Integration bus​

(HTTP-owned) (TCP-owned)
DynamoDB ─stream─▶ stream-router λ ─▶ SNS FIFO cse-http-be-<stage>-to-tcp.fifo ─▶ SQS FIFO cse-tcp-be-<stage>-from-http.fifo ─▶ TCP consumers
▲ (outbox items written in the (MessageGroupId = aggregate id; dedup id = event id)
│ same transaction as the change)
│
HTTP λs ◀─ SQS cse-http-be-<stage>-from-tcp ◀─┐
notifier λ ◀─ SQS cse-http-be-<stage>-alert-events ◀─┤ SNS cse-tcp-be-<stage>-events ◀─ TCP publishers
(HTTP-owned queues, filter policies) └─ (TCP-owned topic)
ResourceOwnerTypeNotes
cse-http-be-<stage>-to-tcp.fifoHTTPSNS FIFOProducer stream-router; dedup id = event id; group id device/<id> for commands, plant/<id> etc. for metadata
cse-tcp-be-<stage>-from-http.fifoTCPSQS FIFOTCP subscribes it to the HTTP topic; TCP-owned DLQ
cse-tcp-be-<stage>-eventsTCPSNS standardHTTP subscribes two queues with filter policies
cse-http-be-<stage>-from-tcpHTTPSQS + DLQtcp-events λ, maximumConcurrency: 2 — command/device/report/erasure events
cse-http-be-<stage>-alert-eventsHTTPSQS + DLQnotifier λ, maximumConcurrency: 2 — alert.changed only

Transactional outbox. Every state change another system must learn about writes an OUTBOX# item in the same DynamoDB transaction; the stream-router Lambda publishes it from the table stream. A DB write can therefore never succeed while its event is lost; failed publishes retry, then land in a DLQ with an alarm.

Concurrency. The account's Lambda quota is 1000 (raised from 10; B-01 closed), shared with live TCP ingest. Every new consumer is capped with SQS maximumConcurrency, not reservedConcurrentExecutions.

Envelope​

CloudEvents-shaped JSON — illustrative example:

{
"specversion": "1.0",
"id": "01JABCDEF...",
"type": "command.requested.v1",
"source": "cse-http-be/dev",
"time": "2026-09-28T10:15:00.000Z",
"subject": "device/01J...",
"correlationId": "req-...",
"causationId": "01J...",
"seq": 7,
"data": {}
}

id is a ULID consumers dedupe on; seq is a per-aggregate monotonic version (the entity version for HTTP events). Rules: additive changes only within a vN; a breaking change publishes v(N+1) alongside vN until the consumer migrates; consumers ignore unknown fields and types, are idempotent on id, and apply state only if seq is newer than what they hold.

Event catalog (summary)​

HTTP → TCP

TypePayload summaryTCP use
org.upserted.v1orgId, kind, name, timezone, statusTenancy / timezone projection
plant.upserted.v1plantId, code, operator/customer/installer org ids, tagIds, regionTagId, timezone, pvCapacityKwp, expected yield, grid, battery, tariff, lifecycle, versionDay boundaries, analytics inputs, alert scoping, ticket selector matching
plant.alert-rules.updated.v1rule toggles and thresholdsPlant-level alert evaluation
plant.archived.v1 / plant.restored.v1plantId, atMute alerts, stop scheduled jobs
plant.deletion.requested.v1plantId, deviceIds, deadlineErase telemetry/alerts/activity for those devices
device.upserted.v1deviceId, serialNorm, loggerKey?, type, modelId, ownerOrgId, plantId?, parentDeviceId?, registration/binding state, versionBind physical connections; replaces WS register
device.removed.v1deviceId, loggerKey, eraseRevoke / erase
command.requested.v1 / command.cancelled.v1see Command lifecycleExecute / drop if not yet sent
workorder.linked.v1 / workorder.completed.v1alertIds, workOrderId, code, completedAt, resolutionAlert timeline; resolve-if-cleared
report.render.requested.v1reportId, template, audience, resolved plantIds, period, timezone, format, presigned upload URLs, deadlineRender
access.revoked.v1sub, orgId?, plantIds?, reasonDrop WS subscriptions now

TCP → HTTP (TCP-owned topic, HTTP filter policies)

TypeQueueHTTP use
device.observed.v1from-tcpInventory snapshot, firmware-eligibility pre-check, "never reported" state
device.binding.result.v1from-tcpBinding state BLOCKED + reason (logger moved, inverter taken)
command.status.v1from-tcpStatus projection, operation log, bulk-task progress
report.render.status.v1from-tcpReport library status
plant.erasure.completed.v1 / device.erasure.completed.v1from-tcpSaga completion
alert.changed.v1alert-eventsNotification rules and delivery

Realtime tickets (ADR 0003)​

Today the TCP ws-gateway has no authentication and trusts a userId field in each message. Authorization policy (orgs, roles, scopes, shares) will live in this service's DynamoDB. ADR 0003 chooses HTTP-issued signed tickets over TCP reading DynamoDB (duplicates security-critical logic in Go and couples TCP to this key schema) or TCP calling an HTTP authz endpoint per subscription (puts every WS subscribe on a Lambda path limited by the shared account concurrency quota).

  • POST /v1/realtime/tickets evaluates the caller's access and returns an ES256 JWT signed by an asymmetric KMS key — TTL 10 min, audience cse-tcp-be-ws, claims sub, org, grants[{sel, ids, lv}], jti.
  • GET /v1/realtime/jwks (public route) publishes the verification keys. TCP verifies offline — no shared secret, no DynamoDB reads.
  • Grants carry selectors (org / tag / customer / plants) plus per-category levels (alerts, devices, commands), not device lists, so a Crown HQ ticket stays small. TCP matches each device's plant against the selector using the plant projection it receives from plant.upserted.v1 (TCP-REQ-04).
  • Refresh: the client sends a new ticket in an auth message before expiry.
  • Revocation lag is ≤ ticket TTL (10 min) unless TCP consumes access.revoked.v1 (TCP-REQ-03), which lets it drop subscriptions immediately.
  • Cost: ~$1/month per KMS key + $0.03 per 10k sign requests; clients cache a ticket until ~1 min before expiry.

ADR 0003 supersedes the earlier idea (mentioned in Architecture → Database interactions) of a read-only DynamoDB grant to the TCP side.

Realtime surfaces (who serves what)​

UI surfaceServed byReconnect behaviour
Live power, today totals, SOC, energy flowTCP watch / telemetryRe-send watch; show "Last data X ago" from presence until fresh data
Freshness ("Live · updated 22 s ago")TCP presenceThresholds to be agreed (OQ-12)
Plant list / fleet status stripTCP plant-summary query (TCP-REQ-07)Re-query on reconnect
Alerts pill, bell, Alert CenterTCP alert queries + push (TCP-REQ-09)Re-subscribe and re-fetch; no replay today (TCP-REQ-16 asks for a since cursor)
Command progressTCP command_status push; HTTP recordAfter reconnect GET /v1/commands/{id} is authoritative
Report generation progressHTTP recordClient polls GET /v1/reports/{id} with backoff (low-volume exception)
Work orders, inventory, team changesHTTPRefetch on focus; conflicts surface as 409 VERSION_CONFLICT

The wss:// blocker​

The TCP gateway is served today as plain ws://<ip>:8090 with no TLS or DNS. A console served over HTTPS cannot open a ws:// socket (browser mixed-content rule). TCP-REQ-14 (TLS + DNS, wss://) is a P0 blocker (B-05): no web realtime feature can be verified until it ships. For the current TCP WebSocket protocol, see the TCP Server's WebSocket integration page.