Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Converters (IoT & Cloud) v1.0 (frozen on 2026-11-23, commit 71e82be). Switch to Latest →

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 Function ingest-telemetry, FastAPI cloud/api/telemetry_ingress.py, Optional Mosquitto MQTT Broker + cloud/mqtt_ingress.py, Background RetentionService.

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):
    1. Nginx (:443): Terminates TLS 1.2/1.3 with ssl_verify_client on against planovi-device-ca.pem, enforces POST-only and client_max_body_size 4k, strips any client-spoofed X-Planovi-Client-CN / X-Planovi-Gateway-* headers, and forwards X-SSL-Client-Verify, X-SSL-Client-CN, X-SSL-Client-Cert, X-Real-IP, X-Device-Serial, X-Planovi-Record-Type to mtls-gateway:8001.
    2. mTLS Gateway (cloud/mtls_gateway.py): Verifies caller IP in PLANOVI_TRUSTED_PROXY_CIDRS, X-SSL-Client-Verify == "SUCCESS", leaf cert (BasicConstraints.ca == False, EKU == CLIENT_AUTH, not_valid_before <= now <= not_valid_after, single CN == X-SSL-Client-CN), constant-time X-Device-Serial == X-SSL-Client-CN, valid record_type, and body 2..4096 B.
      • For telemetry: signs canonical timestamp\ncn\nserial\nrecord_type\nsha256(body) with PLANOVI_GATEWAY_HMAC_SECRET and forwards to PLANOVI_SUPABASE_INGEST_URL (20 s timeout). If PLANOVI_GATEWAY_DUAL_WRITE_TELEMETRY is enabled, also mirrors to CONVERTERS_API_URL (X-Planovi-Edge-Token) and injects "sync_required": true into the Supabase JSON reply if FastAPI indicates pending sync/commands.
      • For event, storage, sync: forwards directly to CONVERTERS_API_URL (/api/v1/telemetry/edge-record) with X-Planovi-Edge-Token.
    3. Supabase Edge Function (supabase/functions/ingest-telemetry/index.ts): verify_jwt = false, POST-only (405), body 2..2048 B (413), verifies HMAC-SHA256 within ±300 s replay window (401), runs validateTelemetryRecord() (schema3_adapter.ts, 422) for telemetry, then proxies raw bytes (with X-Planovi-Edge-Token, 20 s timeout) to PLANOVI_INGEST_ORIGIN_URL (FastAPI /api/v1/telemetry/edge-record). Does not touch PostgreSQL directly.
    4. FastAPI Ingress (cloud/api/telemetry_ingress.py):
      • /record, /storage, /sync, /ingress authenticate via verify_mtls_client (direct behind staging/trusted Nginx).
      • /edge-record, /edge-storage, /edge-sync authenticate via verify_edge_client (X-Planovi-Edge-Token >= 32 chars constant-time + X-Planovi-Client-CN).
      • _process_single_record() enforces <= 4096 B (413), dispatches telemetry / event / storage / sync, commits transaction, appends "sync_required": true if PENDING commands exist or desired_cloud_host/desired_telemetry_interval_sec differ from reported values.
  • Telemetry Ingestion & Virtual Meter Calculation (cloud/services/telemetry_ingestion.py, virtual_meter_service.py):
    • Deduplicates/sorts batch deterministically by (stream_id, seq) (conflicting duplicates raise ValueError -> 403). Locks edge_converters row FOR UPDATE, updates last_seen/ip_address/status=ONLINE (unless MAINTENANCE/ERROR).
    • Auto-creates placeholder StorageStream (key_nonce = 12×0x00) on first HTTPS record if missing; enforces stream.active_converter_id == converter.id and matching company_id/facility_id.
    • Inserts TelemetryIngestReceipt(outcome="PENDING") via ON CONFLICT (storage_stream_id, source_sequence) DO NOTHING. Retries existing receipts only if telemetry_id IS NULL and outcome is PENDING or REJECTED with a retryable reason (METER_ADDRESS_CONFLICT, INVALID_METER_PARENT, UNKNOWN_METER).
    • For Schema 3: advances meter semantics only if !record.replay and sequence/timestamp advances (_may_advance_semantics()), auto-creates EnergyMeter, validates SUBMETER -> MAIN parent in same measurement_point, writes immutable MeterConfigurationHistory snapshot on change, and auto-resolves active RS485 events on valid live telemetry.
    • Inserts TelemetryData; if valid and not a historical replay, calls VirtualMeterService.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 (setting is_valid = False, reject_reason = "ENERGY_STATE_REJECTED" while retaining the telemetry_id).
  • 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) and CONNECTION_RECOVERED (3011 when previously offline/never seen/gap > 900 s), records last_command_ack (COMMAND_APPLIED 3013 / COMMAND_FAILED 3014, redacting wifi_password).
    • Commit 2bdc8a6 Reboot Auto-Finalization: Queries all lingering SENT reboot commands for that converter and marks them APPLIED ("Konwerter zrestartowany i ponownie połączony z Chmurą") + logs COMMAND_APPLIED (3013).
    • Pops oldest PENDING command -> marks SENT (redacting wifi_password in DB parameters JSONB after preparing response), flattens convenience keys (url, sha256, version, wifi_ssid, wifi_password, save_as_fallback), returns server_time_utc + desired_config + pending_command.
  • Portable Storage Escrow (cloud/services/storage_transfer.py):
    • register: encrypts 32 B data_key via AES-256-GCM under PLANOVI_CARD_MASTER_KEY_B64 (12 B nonce, AAD = card_id), stores SHA-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 has company_id/facility_id, matches owner & claim_token_hash, rejects if replacement converter already has active EnergyMeter rows, reassigns all active EnergyMeter rows from old converter to new converter, marks old converter MAINTENANCE, increments adoption_count, and returns decrypted data_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 with clean_session=False, manual_ack=True, max_inflight=1, subscribes QoS 1 to v1/devices/+/{telemetry,alerts,attributes,storage}, retries DB failures with 1 s..30 s backoff before manual ack(), and serves MQTT time-sync via cloud/services/time_sync.py.
    • RetentionService runs every 3600 s (initial 15 s delay), parses SystemSetting.keep_history (clamped 1..3650 days, default 30), and deletes expired rows from telemetry_ingest_receipts, telemetry_data, device_events, and optional telemetry_quarantine.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-INGEST-01 (Payload Size Caps Across Hops): Nginx client_max_body_size 4k (deploy/nginx.api.planovi.conf), mtls_gateway.py 2..4096 B (413), FastAPI _process_single_record 1..4096 B (413), FastAPI batch /ingress 1..500 records, Supabase Edge Function index.ts:49,70 strictly 2..2048 B (413).
  • BR-INGEST-02 (HMAC Replay Window & Edge Token Floor): mtls_gateway.py and supabase/functions/ingest-telemetry/index.ts require len(PLANOVI_GATEWAY_HMAC_SECRET) >= 32 and ±300 s timestamp tolerance (401 "expired_gateway_signature"). FastAPI verify_edge_client requires len(PLANOVI_EDGE_SHARED_TOKEN) >= 32 with secrets.compare_digest.
  • BR-INGEST-03 (Telemetry Schema v1–v3 Validation): TelemetryRecordSchema (cloud/telemetry_schemas.py, extra="forbid", allow_inf_nan=False) enforces seq ∈ [1, 2^63-1], stream_id ^[0-9a-f]{32}$, ts ∈ [946684800, 4102444800] AND ts <= 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}$) and SUBMETER => pa != 0 && pa != meter_id else pa == 0.
  • BR-INGEST-04 (Strict Event Schema Validation & RS-485 Auto-Resolution): DeviceEventSchema (cloud/event_schemas.py) requires schema == 1, ACTIVE => duration_s == 0, RESOLVED => duration_s == ts - first_ts, paired meter_id/meter_addr, and storage_* fields exclusively on SD_RECORD_QUARANTINED (code_num == 2008). Receiving either a RESOLVED event with meter_id or a valid live (!replay) telemetry packet bulk-resolves all ACTIVE RS485 events on (storage_stream_id, meter_logical_id) with event_timestamp <= recovered_at.
  • BR-INGEST-05 (Virtual Meter Monotonicity & 1 GW Plausibility Bound): VirtualMeterService.calculate_energy_delta() (cloud/services/virtual_meter_service.py) locks EnergyMeter FOR UPDATE, quantizes to 0.001 kWh (ROUND_HALF_UP), rejects negative readings, duplicate source_sequence, out-of-order timestamp < last_energy_timestamp, any counter decrease (current < previous), and deltas exceeding 1_000_000 * max(elapsed_s, 0) / 3600 + 1 kWh.
  • BR-INGEST-06 (Anti-Rollback Meter Semantics): _may_advance_semantics() (telemetry_ingestion.py) never updates EnergyMeter metadata from replay=True packets, requires strictly higher seq on the same stream, or strictly newer record_time on a new stream.
  • BR-INGEST-07 (Shared Supabase RPC ingest_telemetry_record Rules — Migration 019): 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) with PROCESSED (200) without writing raw_telemetry/counters; maps Schema 3 mr in (2,3) -> SUBMETER, mp == 2 -> PV, else MAIN; maps mt == 2 -> chint_dtsu666 else zamel_lem60; deduplicates on (logical_point_id, source_sequence, batch_id); and triggers fn_aggregate_hourly_telemetry() for replays or prior-hour packets on non-submeters.
  • BR-INGEST-08 (Credential Redaction in Sync & Commands): wifi_password is redacted ("***") in edge_device_commands.parameters once popped to SENT and in COMMAND_APPLIED/COMMAND_FAILED event 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 (via last_command_ack or auto-finalized reboot on next /sync) or FAILED (via last_command_ack or manual DELETE /commands/{cmd_id} while PENDING).

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), optional telemetry_quarantine.
  • External Calls: mtls_gateway -> Supabase Edge HTTPS (20 s); Supabase Edge -> FastAPI /edge-record HTTPS (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/019 ingest_telemetry_record -> External planovi-backend Supabase 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-band register round-trip; when the device later sends operation="register", the zero-nonce placeholder is upgraded in-place.
  • Confirmed Bugs & Discrepancies:
    1. cloud/api/telemetry_ingress.py:49-85 (verify_forwarded_client_certificate) does NOT check certificate expiration (not_valid_before_utc/not_valid_after_utc), unlike mtls_gateway.py:_verify_certificate.
    2. cloud/api/telemetry_ingress.py:246-254 (_check_sync_required) checks desired_cloud_host and desired_telemetry_interval_sec, omitting desired_cloud_port.
    3. cloud/services/event_ingestion.py (resolve_active_rs485_events) overwrites details = {"resolution_source": ...}, wiping the original Polish details["message"].
    4. cloud/services/retention_service.py:31-32 (parse_retention_days) maps any string containing "year"/"rok" to 365, ignoring multipliers like "2 years".
    5. cloud/mqtt_ingress.py:107 reads only legacy ASLANDI_MQTT_INGRESS_CLIENT_ID, ignoring PLANOVI_MQTT_INGRESS_CLIENT_ID.
    6. supabase/functions/ingest-telemetry/schema3_adapter.ts:152-230: mapSchema3ToRawTelemetry is dead code (never imported by index.ts), has a falsy-zero bug (vL2 && vL3), and its comments at lines 19–20 contradict 019_fix_converter_sync_and_telemetry_rpc.sql (mt 1/2 = LEM60/CHINT666, not 1-phase/3-phase; mr 3 = TECHNICAL, not generation).
    7. cloud/mtls_gateway.py:40 contains a hardcoded 64-character dev fallback for EDGE_SHARED_TOKEN.
    8. supabase/functions/ingest-telemetry/index.ts enforces max 2048 B while mtls_gateway.py and FastAPI enforce 4096 B (and firmware enforces 1400 B total / 768 B body).
  • [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 MessageRoot Cause in CodeHow to Verify / Exact CommandFix
401 "expired_gateway_signature" or "invalid_gateway_signature"Clock skew > 300 s between VPS and Supabase, or PLANOVI_GATEWAY_HMAC_SECRET mismatchCheck docker logs mtls-gateway and Supabase Edge Function logsSynchronize 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 EdgePayload > 2048 B (supabase/functions/ingest-telemetry/index.ts:49,70)Inspect Content-Length in Nginx mtls_diag logKeep 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 filenameApply migration 019_fix_converter_sync_and_telemetry_rpc.sql and verify schema parity