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:
- HTTP Lambdas never open a connection to the TCP server, NATS, the telemetry Postgres or the TCP VPC, and never join a VPC.
- 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.
- Clients talk to both backends directly: HTTPS to this API, WSS to the TCP gateway. HTTP issues the ticket that authorizes the WS session.
- No telemetry value, aggregate or KPI is stored in or served by HTTP, in any form.
Responsibility matrix (HTTP ↔ TCP ↔ client)
| Capability | Source of truth | HTTP server | TCP server | Client | Channel |
|---|---|---|---|---|---|
| Sign-in, tokens, MFA | Cognito | Triggers, IdentityProvider, MFA policy check | — | Cognito SDK direct | HTTPS (Cognito) |
| Organisations, members, roles, scopes, shares | HTTP | Owns, authorizes, audits | Consumes ticket grants | Team & Access screens | HTTPS |
| Realtime session auth | HTTP (policy) | Issues signed tickets | Verifies tickets, enforces grants (TCP-REQ-01/02) | Fetches ticket, connects WSS | HTTPS + WSS |
| Plant metadata & settings | HTTP | CRUD, publishes plant.* | Projection for day boundaries, analytics, alert rules (TCP-REQ-04) | Plant screens | HTTPS; SNS→SQS |
| Device registry / binding | HTTP (DEC-4) | CRUD, import, transfer, publishes device.* | Binds physical connection to the registry entry; reports device.observed (TCP-REQ-05/13) | Inventory screens | HTTPS; SNS↔SQS |
| Device presence, live status, live readings | TCP | — | watch / telemetry / presence | Merges with registry rows by id/serial | WSS |
| Fleet / plant status summaries (status strips, comm age, power columns) | TCP | — | Plant-summary query API (TCP-REQ-07) | Joins onto HTTP plant pages by plantId | WSS |
| History, charts, analytics KPIs, compare | TCP (DEC-5) | Publishes metadata TCP needs (capacity, expected yield, tariff, timezone, tags) | History/analytics query API (TCP-REQ-08) | Energy / Analytics / device history tabs | WSS |
| Alerts: detection, instances, catalog, ack/assign/resolve, timeline | TCP (DEC-3) | Stores only alertId links on work orders and deliveries | Scope-based queries, workflow ops, CROWN catalog (TCP-REQ-09) | Alert Center, workspace alert tab | WSS |
| Alert → work order | HTTP (WO) + TCP (alert) | Creates WO with alertId; publishes workorder.linked / workorder.completed | Shows the link on the alert timeline; resolves the alert on WO completion only if the condition cleared | "Create work order" from an alert | HTTPS; SNS→SQS |
| Notification rules, channels, recipients | HTTP (DEC-6) | CRUD; evaluates rules; delivers push/email | Publishes alert.changed | Settings screens; receives push/email | HTTPS; SNS→SQS; SES; SNS mobile push |
| Commands, approvals, bulk tasks, rollouts, operation log | HTTP intent (DEC-2) | Validates, authorizes, approves, records, enqueues; projects status | Executes, enforces deadlines/preconditions, reports status (TCP-REQ-06) | Engineering + device screens | HTTPS; SNS FIFO→SQS FIFO; SNS→SQS |
| Command progress while running | TCP → HTTP projection | GET /v1/commands/{id} (history + fallback) | Pushes command_status to the requester's WS connections | Progress UI | WSS primary, HTTPS fallback |
| Register catalog / read configuration | TCP | Command definitions reference register groups by key | get_registers / read_registers | Parameters tab | WSS (read-only; writes go through commands) |
| Firmware packages | HTTP | S3 + metadata; presigned GET in the command message | Downloads, verifies SHA-256, flashes (TCP-REQ-06) | Engineering | HTTPS; S3 |
| Reports | HTTP records + TCP rendering | Records, schedules, S3, delivery | Renders on report.render.requested (TCP-REQ-11) | Reports module | HTTPS; SNS↔SQS; S3 |
| Work orders, plans, attachments | HTTP | Everything | — | Service module | HTTPS; S3 presigned |
| Plant archive / delete, device removal | HTTP starts; TCP completes | Saga owner | Mutes / erases on events (TCP-REQ-12) | Confirm flows | HTTPS; SNS↔SQS |
| Preferences, favourites, saved views | HTTP | CRUD | — | — | 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)
| Resource | Owner | Type | Notes |
|---|---|---|---|
cse-http-be-<stage>-to-tcp.fifo | HTTP | SNS FIFO | Producer stream-router; dedup id = event id; group id device/<id> for commands, plant/<id> etc. for metadata |
cse-tcp-be-<stage>-from-http.fifo | TCP | SQS FIFO | TCP subscribes it to the HTTP topic; TCP-owned DLQ |
cse-tcp-be-<stage>-events | TCP | SNS standard | HTTP subscribes two queues with filter policies |
cse-http-be-<stage>-from-tcp | HTTP | SQS + DLQ | tcp-events λ, maximumConcurrency: 2 — command/device/report/erasure events |
cse-http-be-<stage>-alert-events | HTTP | SQS + DLQ | notifier λ, 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
| Type | Payload summary | TCP use |
|---|---|---|
org.upserted.v1 | orgId, kind, name, timezone, status | Tenancy / timezone projection |
plant.upserted.v1 | plantId, code, operator/customer/installer org ids, tagIds, regionTagId, timezone, pvCapacityKwp, expected yield, grid, battery, tariff, lifecycle, version | Day boundaries, analytics inputs, alert scoping, ticket selector matching |
plant.alert-rules.updated.v1 | rule toggles and thresholds | Plant-level alert evaluation |
plant.archived.v1 / plant.restored.v1 | plantId, at | Mute alerts, stop scheduled jobs |
plant.deletion.requested.v1 | plantId, deviceIds, deadline | Erase telemetry/alerts/activity for those devices |
device.upserted.v1 | deviceId, serialNorm, loggerKey?, type, modelId, ownerOrgId, plantId?, parentDeviceId?, registration/binding state, version | Bind physical connections; replaces WS register |
device.removed.v1 | deviceId, loggerKey, erase | Revoke / erase |
command.requested.v1 / command.cancelled.v1 | see Command lifecycle | Execute / drop if not yet sent |
workorder.linked.v1 / workorder.completed.v1 | alertIds, workOrderId, code, completedAt, resolution | Alert timeline; resolve-if-cleared |
report.render.requested.v1 | reportId, template, audience, resolved plantIds, period, timezone, format, presigned upload URLs, deadline | Render |
access.revoked.v1 | sub, orgId?, plantIds?, reason | Drop WS subscriptions now |
TCP → HTTP (TCP-owned topic, HTTP filter policies)
| Type | Queue | HTTP use |
|---|---|---|
device.observed.v1 | from-tcp | Inventory snapshot, firmware-eligibility pre-check, "never reported" state |
device.binding.result.v1 | from-tcp | Binding state BLOCKED + reason (logger moved, inverter taken) |
command.status.v1 | from-tcp | Status projection, operation log, bulk-task progress |
report.render.status.v1 | from-tcp | Report library status |
plant.erasure.completed.v1 / device.erasure.completed.v1 | from-tcp | Saga completion |
alert.changed.v1 | alert-events | Notification 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/ticketsevaluates the caller's access and returns an ES256 JWT signed by an asymmetric KMS key — TTL 10 min, audiencecse-tcp-be-ws, claimssub,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 fromplant.upserted.v1(TCP-REQ-04). - Refresh: the client sends a new ticket in an
authmessage 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 surface | Served by | Reconnect behaviour |
|---|---|---|
| Live power, today totals, SOC, energy flow | TCP watch / telemetry | Re-send watch; show "Last data X ago" from presence until fresh data |
| Freshness ("Live · updated 22 s ago") | TCP presence | Thresholds to be agreed (OQ-12) |
| Plant list / fleet status strip | TCP plant-summary query (TCP-REQ-07) | Re-query on reconnect |
| Alerts pill, bell, Alert Center | TCP alert queries + push (TCP-REQ-09) | Re-subscribe and re-fetch; no replay today (TCP-REQ-16 asks for a since cursor) |
| Command progress | TCP command_status push; HTTP record | After reconnect GET /v1/commands/{id} is authoritative |
| Report generation progress | HTTP record | Client polls GET /v1/reports/{id} with backoff (low-volume exception) |
| Work orders, inventory, team changes | HTTP | Refetch 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.