6. Cloud Ingestion Pipeline (mTLS Gateway, Supabase Edge Function, FastAPI Ingress, MQTT Bridge & Virtual Meter Semantics)
Repository:
Converters (planovi-converter)• Rule Prefix:BR-INGEST• Documented Rules: 8 • Open[TEAM_WHY_NEEDED]Questions: 2
1. Business Purpose & Actors
Authenticates every incoming device connection via mutual TLS, enforces certificate and payload integrity at the public perimeter, bridges telemetry through the Supabase Edge Function while routing control-plane (event, storage, sync) and optional dual-write traffic to the FastAPI backend, persists idempotent sequence-tracked telemetry and events, maintains monotonic virtual meter energy totals (NUMERIC(20, 3)), escrows portable SD card keys across hardware swaps, and prunes expired history.
- Actors: RP2350 Edge Converters (
telemetry,event,storage,sync), Public Nginx mTLS Proxy,cloud/mtls_gateway.py, Supabase Edge Functioningest-telemetry, FastAPIcloud/api/telemetry_ingress.py, Optional Mosquitto MQTT Broker +cloud/mqtt_ingress.py, BackgroundRetentionService.
2. All Features & End-to-End Flows
- Public mTLS Edge Hop (
deploy/nginx.api.planovi.conf->cloud/mtls_gateway.py->supabase/functions/ingest-telemetry/index.ts->cloud/api/telemetry_ingress.py):- Nginx (
:443): Terminates TLS 1.2/1.3 withssl_verify_client onagainstplanovi-device-ca.pem, enforcesPOST-only andclient_max_body_size 4k, strips any client-spoofedX-Planovi-Client-CN/X-Planovi-Gateway-*headers, and forwardsX-SSL-Client-Verify,X-SSL-Client-CN,X-SSL-Client-Cert,X-Real-IP,X-Device-Serial,X-Planovi-Record-Typetomtls-gateway:8001. - mTLS Gateway (
cloud/mtls_gateway.py): Verifies caller IP inPLANOVI_TRUSTED_PROXY_CIDRS,X-SSL-Client-Verify == "SUCCESS", leaf cert (BasicConstraints.ca == False,EKU == CLIENT_AUTH,not_valid_before <= now <= not_valid_after, singleCN == X-SSL-Client-CN), constant-timeX-Device-Serial == X-SSL-Client-CN, validrecord_type, and body2..4096 B.- For
telemetry: signs canonicaltimestamp\ncn\nserial\nrecord_type\nsha256(body)withPLANOVI_GATEWAY_HMAC_SECRETand forwards toPLANOVI_SUPABASE_INGEST_URL(20 stimeout). IfPLANOVI_GATEWAY_DUAL_WRITE_TELEMETRYis enabled, also mirrors toCONVERTERS_API_URL(X-Planovi-Edge-Token) and injects"sync_required": trueinto the Supabase JSON reply if FastAPI indicates pending sync/commands. - For
event,storage,sync: forwards directly toCONVERTERS_API_URL(/api/v1/telemetry/edge-record) withX-Planovi-Edge-Token.
- For
- Supabase Edge Function (
supabase/functions/ingest-telemetry/index.ts):verify_jwt = false,POST-only (405), body2..2048 B(413), verifies HMAC-SHA256 within±300 sreplay window (401), runsvalidateTelemetryRecord()(schema3_adapter.ts,422) fortelemetry, then proxies raw bytes (withX-Planovi-Edge-Token,20 stimeout) toPLANOVI_INGEST_ORIGIN_URL(FastAPI/api/v1/telemetry/edge-record). Does not touch PostgreSQL directly. - FastAPI Ingress (
cloud/api/telemetry_ingress.py):/record,/storage,/sync,/ingressauthenticate viaverify_mtls_client(direct behind staging/trusted Nginx)./edge-record,/edge-storage,/edge-syncauthenticate viaverify_edge_client(X-Planovi-Edge-Token >= 32chars constant-time +X-Planovi-Client-CN)._process_single_record()enforces<= 4096 B(413), dispatchestelemetry/event/storage/sync, commits transaction, appends"sync_required": trueifPENDINGcommands exist ordesired_cloud_host/desired_telemetry_interval_secdiffer from reported values.
- Nginx (
- Telemetry Ingestion & Virtual Meter Calculation (
cloud/services/telemetry_ingestion.py,virtual_meter_service.py):- Deduplicates/sorts batch deterministically by
(stream_id, seq)(conflicting duplicates raiseValueError->403). Locksedge_convertersrowFOR UPDATE, updateslast_seen/ip_address/status=ONLINE(unlessMAINTENANCE/ERROR). - Auto-creates placeholder
StorageStream(key_nonce = 12×0x00) on first HTTPS record if missing; enforcesstream.active_converter_id == converter.idand matchingcompany_id/facility_id. - Inserts
TelemetryIngestReceipt(outcome="PENDING")viaON CONFLICT (storage_stream_id, source_sequence) DO NOTHING. Retries existing receipts only iftelemetry_id IS NULLand outcome isPENDINGorREJECTEDwith a retryable reason (METER_ADDRESS_CONFLICT,INVALID_METER_PARENT,UNKNOWN_METER). - For Schema 3: advances meter semantics only if
!record.replayand sequence/timestamp advances (_may_advance_semantics()), auto-createsEnergyMeter, validatesSUBMETER -> MAINparent in samemeasurement_point, writes immutableMeterConfigurationHistorysnapshot on change, and auto-resolves activeRS485events on valid live telemetry. - Inserts
TelemetryData; if valid and not a historical replay, callsVirtualMeterService.calculate_energy_delta()(NUMERIC(20, 3),ROUND_HALF_UP): rejects counter decreases (ValueError— no automatic rollover) and implausible jumps> 1,000,000 kW * dt_h + 1 kWh(settingis_valid = False,reject_reason = "ENERGY_STATE_REJECTED"while retaining thetelemetry_id).
- Deduplicates/sorts batch deterministically by
- Sync, Command Dispatch & Reboot Auto-Finalization (
_process_sync_record,cloud/api/telemetry_ingress.py:257-538):- Updates firmware/uptime/heap/cloud/Wi-Fi diagnostics, logs
WIFI_SELF_HEALED(3012) andCONNECTION_RECOVERED(3011when previously offline/never seen/gap > 900 s), recordslast_command_ack(COMMAND_APPLIED3013/COMMAND_FAILED3014, redactingwifi_password). - Commit
2bdc8a6Reboot Auto-Finalization: Queries all lingeringSENTrebootcommands for that converter and marks themAPPLIED("Konwerter zrestartowany i ponownie połączony z Chmurą") + logsCOMMAND_APPLIED(3013). - Pops oldest
PENDINGcommand -> marksSENT(redactingwifi_passwordin DBparametersJSONB after preparing response), flattens convenience keys (url,sha256,version,wifi_ssid,wifi_password,save_as_fallback), returnsserver_time_utc+desired_config+pending_command.
- Updates firmware/uptime/heap/cloud/Wi-Fi diagnostics, logs
- Portable Storage Escrow (
cloud/services/storage_transfer.py):register: encrypts 32 Bdata_keyvia AES-256-GCM underPLANOVI_CARD_MASTER_KEY_B64(12 B nonce, AAD =card_id), storesSHA-256(claim_token). Upgrades HTTPS auto-bootstrap placeholder streams in-place; idempotent for same owner/converter/key/claim; rejects foreign owners.adopt: verifies replacement converter hascompany_id/facility_id, matches owner &claim_token_hash, rejects if replacement converter already has activeEnergyMeterrows, reassigns all activeEnergyMeterrows from old converter to new converter, marks old converterMAINTENANCE, incrementsadoption_count, and returns decrypteddata_key.
- Legacy/Optional MQTT Ingress (
cloud/mqtt_ingress.py) & Retention (cloud/services/retention_service.py):- Disabled by default (
PLANOVI_MQTT_INGRESS_ENABLED=0). When enabled, connects withclean_session=False,manual_ack=True,max_inflight=1, subscribes QoS 1 tov1/devices/+/{telemetry,alerts,attributes,storage}, retries DB failures with1 s..30 sbackoff before manualack(), and serves MQTT time-sync viacloud/services/time_sync.py. RetentionServiceruns every3600 s(initial 15 s delay), parsesSystemSetting.keep_history(clamped1..3650days, default30), and deletes expired rows fromtelemetry_ingest_receipts,telemetry_data,device_events, and optionaltelemetry_quarantine.
- Disabled by default (
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-INGEST-01(Payload Size Caps Across Hops): Nginxclient_max_body_size 4k(deploy/nginx.api.planovi.conf),mtls_gateway.py2..4096 B(413), FastAPI_process_single_record1..4096 B(413), FastAPI batch/ingress1..500records, Supabase Edge Functionindex.ts:49,70strictly2..2048 B(413).BR-INGEST-02(HMAC Replay Window & Edge Token Floor):mtls_gateway.pyandsupabase/functions/ingest-telemetry/index.tsrequirelen(PLANOVI_GATEWAY_HMAC_SECRET) >= 32and±300 stimestamp tolerance (401 "expired_gateway_signature"). FastAPIverify_edge_clientrequireslen(PLANOVI_EDGE_SHARED_TOKEN) >= 32withsecrets.compare_digest.BR-INGEST-03(Telemetry Schema v1–v3 Validation):TelemetryRecordSchema(cloud/telemetry_schemas.py,extra="forbid",allow_inf_nan=False) enforcesseq ∈ [1, 2^63-1],stream_id^[0-9a-f]{32}$,ts ∈ [946684800, 4102444800]ANDts <= now + 600(max +10 min future skew),meter_addr ∈ [1, 247],v ∈ [0, 1000],i ∈ [0, 100000],p/q ∈ [-1e9, 1e9],s ∈ [0, 1e9],pf ∈ [-1, 1],hz ∈ [0, 1000], energies∈ [0, 1e12]. Schema 3 mandates all 8 metadata fields (mt,mr,mp,pa,md,bc==0,br ∈ [1200, 115200],pc^[A-Z0-9_-]{1,15}$) andSUBMETER => pa != 0 && pa != meter_idelsepa == 0.BR-INGEST-04(Strict Event Schema Validation & RS-485 Auto-Resolution):DeviceEventSchema(cloud/event_schemas.py) requiresschema == 1,ACTIVE => duration_s == 0,RESOLVED => duration_s == ts - first_ts, pairedmeter_id/meter_addr, andstorage_*fields exclusively onSD_RECORD_QUARANTINED(code_num == 2008). Receiving either aRESOLVEDevent withmeter_idor a valid live (!replay) telemetry packet bulk-resolves allACTIVERS485events on(storage_stream_id, meter_logical_id)withevent_timestamp <= recovered_at.BR-INGEST-05(Virtual Meter Monotonicity & 1 GW Plausibility Bound):VirtualMeterService.calculate_energy_delta()(cloud/services/virtual_meter_service.py) locksEnergyMeter FOR UPDATE, quantizes to0.001 kWh(ROUND_HALF_UP), rejects negative readings, duplicatesource_sequence, out-of-ordertimestamp < last_energy_timestamp, any counter decrease (current < previous), and deltas exceeding1_000_000 * max(elapsed_s, 0) / 3600 + 1kWh.BR-INGEST-06(Anti-Rollback Meter Semantics):_may_advance_semantics()(telemetry_ingestion.py) never updatesEnergyMetermetadata fromreplay=Truepackets, requires strictly higherseqon the same stream, or strictly newerrecord_timeon a new stream.BR-INGEST-07(Shared Supabase RPCingest_telemetry_recordRules — Migration019): When invoked in the shared Supabase DB, rejects unknown (UNKNOWN_DEVICE, 403) or non-active/standby(DISABLED_DEVICE, 403) converters; short-circuits warehouse unassigned converters (company_id IS NULL) withPROCESSED(200) without writingraw_telemetry/counters; maps Schema 3mr in (2,3) -> SUBMETER,mp == 2 -> PV, elseMAIN; mapsmt == 2 -> chint_dtsu666elsezamel_lem60; deduplicates on(logical_point_id, source_sequence, batch_id); and triggersfn_aggregate_hourly_telemetry()for replays or prior-hour packets on non-submeters.BR-INGEST-08(Credential Redaction in Sync & Commands):wifi_passwordis redacted ("***") inedge_device_commands.parametersonce popped toSENTand inCOMMAND_APPLIED/COMMAND_FAILEDevent details (cloud/api/telemetry_ingress.py).
4. State Machines & Data Lifecycle
stateDiagram-v2
[*] --> PENDING: INSERT telemetry_ingest_receipts ON CONFLICT DO NOTHING
PENDING --> PROCESSED: Valid telemetry stored + virtual energy updated (or replay)
PENDING --> REJECTED_RETRYABLE: METER_ADDRESS_CONFLICT / INVALID_METER_PARENT / UNKNOWN_METER (telemetry_id=NULL)
PENDING --> REJECTED_TERMINAL: ENERGY_STATE_REJECTED (telemetry_id!=NULL, auditable)
REJECTED_RETRYABLE --> PROCESSED: Subsequent retry after meter map fixed
PROCESSED --> [*]: Duplicate (stream_id, seq) skipped idempotently
- Device Command Lifecycle (
edge_device_commands.status):PENDING->SENT(popped on/sync) ->APPLIED(vialast_command_ackor auto-finalizedrebooton next/sync) orFAILED(vialast_command_ackor manualDELETE /commands/{cmd_id}whilePENDING).
5. Technical Contract (Inputs -> Processing -> Side Effects)
- Endpoints (
cloud/mtls_gateway.py+supabase/+cloud/api/telemetry_ingress.py):GET /healthz,POST /functions/v1/ingest-telemetry(mtls_gateway.py)POST /functions/v1/ingest-telemetry(supabase/functions/ingest-telemetry/index.ts)POST /api/v1/telemetry/{record,edge-record,ingress,storage,edge-storage,sync,edge-sync}(cloud/api/telemetry_ingress.py)
- DB Tables Touched:
edge_converters,storage_streams,energy_meters,meter_configuration_history,telemetry_data,telemetry_ingest_receipts,device_events,edge_device_commands,alert_notifications,edge_system_settings(retention), optionaltelemetry_quarantine. - External Calls:
mtls_gateway-> Supabase Edge HTTPS (20 s); Supabase Edge -> FastAPI/edge-recordHTTPS (20 s);mtls_gateway-> FastAPI/edge-record(control plane & dual-write).
6. Cross-Repository Dependencies
cloud/mtls_gateway.py->supabase/functions/ingest-telemetry| HTTPS + HMAC-SHA256 (PLANOVI_GATEWAY_HMAC_SECRET, ±300 s) |POST /functions/v1/ingest-telemetry.supabase/functions/ingest-telemetry->cloud/api/telemetry_ingress.py| HTTPS + Shared Token (X-Planovi-Edge-Token) |POST /api/v1/telemetry/edge-record.cloud/migrations/019ingest_telemetry_record-> Externalplanovi-backendSupabase tables (public.converters,public.gateway_registry,public.logical_points,public.counters,public.buildings,public.raw_telemetry,public.devices,public.fn_aggregate_hourly_telemetry).
7. Why It Works This Way (Decisions, Trade-offs & Workarounds)
- HTTPS Auto-Bootstrap of
StorageStream: Allows HTTPS converters to ingest telemetry immediately without stalling on an initial out-of-bandregisterround-trip; when the device later sendsoperation="register", the zero-nonce placeholder is upgraded in-place. - Confirmed Bugs & Discrepancies:
cloud/api/telemetry_ingress.py:49-85(verify_forwarded_client_certificate) does NOT check certificate expiration (not_valid_before_utc/not_valid_after_utc), unlikemtls_gateway.py:_verify_certificate.cloud/api/telemetry_ingress.py:246-254(_check_sync_required) checksdesired_cloud_hostanddesired_telemetry_interval_sec, omittingdesired_cloud_port.cloud/services/event_ingestion.py(resolve_active_rs485_events) overwritesdetails = {"resolution_source": ...}, wiping the original Polishdetails["message"].cloud/services/retention_service.py:31-32(parse_retention_days) maps any string containing"year"/"rok"to365, ignoring multipliers like"2 years".cloud/mqtt_ingress.py:107reads only legacyASLANDI_MQTT_INGRESS_CLIENT_ID, ignoringPLANOVI_MQTT_INGRESS_CLIENT_ID.supabase/functions/ingest-telemetry/schema3_adapter.ts:152-230:mapSchema3ToRawTelemetryis dead code (never imported byindex.ts), has a falsy-zero bug (vL2 && vL3), and its comments at lines 19–20 contradict019_fix_converter_sync_and_telemetry_rpc.sql(mt1/2 = LEM60/CHINT666, not 1-phase/3-phase;mr3 = TECHNICAL, not generation).cloud/mtls_gateway.py:40contains a hardcoded 64-character dev fallback forEDGE_SHARED_TOKEN.supabase/functions/ingest-telemetry/index.tsenforces max2048 Bwhilemtls_gateway.pyand FastAPI enforce4096 B(and firmware enforces1400 Btotal /768 Bbody).
[TEAM_WHY_NEEDED: Why does supabase/functions/ingest-telemetry/index.ts exist as a validating pass-through proxy to FastAPI /edge-record while migration 019 also defines public.ingest_telemetry_record() in Supabase? Is direct Supabase RPC ingestion the planned future path or used by a separate Supabase function in planovi-backend?][TEAM_WHY_NEEDED: VirtualMeterService.register_point_zero() and handle_meter_replacement() exist in cloud/services/virtual_meter_service.py with full validation logic, yet zero API endpoints expose them. How do operators currently recover a meter after physical replacement when counter decreases are rejected?]
8. Debugging, Logs & Common Failure Modes
| Symptom / Error Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
401 "expired_gateway_signature" or "invalid_gateway_signature" | Clock skew > 300 s between VPS and Supabase, or PLANOVI_GATEWAY_HMAC_SECRET mismatch | Check docker logs mtls-gateway and Supabase Edge Function logs | Synchronize VPS NTP (chronyc tracking) and verify secret parity |
403 "The storage stream is not assigned to this converter" | StorageStream.active_converter_id != converter.id or company_id/facility_id mismatch (telemetry_ingestion.py) | Query SELECT id, active_converter_id, company_id, facility_id FROM storage_streams WHERE id = '<stream_id>' | Ensure converter is assigned to same company/facility and perform SD adoption |
413 "record_too_large" at Supabase Edge | Payload > 2048 B (supabase/functions/ingest-telemetry/index.ts:49,70) | Inspect Content-Length in Nginx mtls_diag log | Keep single-record JSON <= 2048 B (firmware cap is 768 B) |
503 "Telemetry storage is temporarily unavailable." | SQLAlchemyError inside _process_single_record() (e.g. broken trigger/enum before migration 019, or missing columns) | Check FastAPI logs & run SELECT * FROM planovi_schema_migrations ORDER BY filename | Apply migration 019_fix_converter_sync_and_telemetry_rpc.sql and verify schema parity |