Skip to content

7. Cloud Fleet Control Plane, Provisioning, Remote Policy, Alerts & PostgreSQL Schema

Repository: Converters (planovi-converter) • Rule Prefix: BR-CLOUD • Documented Rules: 8 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

Provides the central operational REST API, PostgreSQL schema (000–019), and background monitoring services for managing the Planovi Edge Converter fleet: manufacturing serial reservation and Device CA mTLS certificate issuance, organization/building assignment and converter order fulfillment against the shared Supabase schema, time-series monitoring & receipt diagnostics, remote command queuing, firmware release hosting, global/per-device telemetry policy, infrastructure health caching, and Google Chat incident alerting.

  • Actors: Flutter Fleet Admin Panel (admin/), USB Provisioning CLI (tools/provision_device.py), VPS Health Cron (deploy/check-health.sh), Admin mTLS Operators (/api/v1/admin/*), Autonomous AlertDispatcher background loop, Shared Supabase Trigger (fn_sync_edge_converter_to_converters).

2. All Features & End-to-End Flows

  • Fleet CRUD, Serial Allocation & USB mTLS Provisioning (cloud/api/converters.py):
    • GET /api/v1/converters-next-serial: Computes next PLN-EC-XXXXXXXX (floor 130, ignoring suffixes > 8 digits, peeking public.edge_converter_serial_seq).
    • POST /api/v1/converters/prepare-usb-provisioning: Upserts EdgeConverter (OFFLINE), mints an ECDSA P-256 keypair + 10-year X.509 leaf certificate (BasicConstraints(ca=False), EKU=CLIENT_AUTH, signed by Device CA if present on disk else self-signed), 20-char setup password, and 32 B aes_key_hex; advances edge_converter_serial_seq.
    • POST /api/v1/converters/{id}/confirm-flash: Marks OFFLINE and records USB_FLASH_CONFIRMED (3004).
    • GET/POST/PUT/DELETE /api/v1/converters, POST /api/v1/converters/provision (legacy mTLS upsert as ONLINE with default IP "10.20.4.10").
    • GET /api/v1/facilities, GET /api/v1/organizations (reads public.companies + public.buildings), GET/PATCH /api/v1/converter-orders (reads/updates public.converter_orders; Note: PATCH currently crashes with AttributeError — see §7).
  • Live Telemetry Monitor, Diagnostics & Remote Commands (cloud/api/converters.py):
    • GET /api/v1/converters/{id}/monitor: Aggregates Europe/Warsaw windowed buckets (4h/today/7d/1m, downsampled to 48/42 points), KPIs, 3-phase table, and per-parameter series.
    • GET /api/v1/converters/{id}/telemetry-diagnostics: Paginated (limit 1..100) receipts outer-joined with telemetry_data, plus active meters.
    • GET /api/v1/converters/stats/overview: Fleet status totals (computed dynamically via compute_dynamic_status), 24 h receipts, active alerts, active meters.
    • POST /api/v1/converters/{id}/desired-config: Sets desired_cloud_host, desired_cloud_port, desired_telemetry_interval_sec and records DESIRED_CONFIG_UPDATED (3005).
    • POST/GET/DELETE /api/v1/converters/{id}/commands: Queues validated remote commands (reboot, sync_time, clear_queue, reset_sd, trigger_telemetry, replay_from_seq, ota_update, reconnect_wifi, update_wifi_credentials, reset_wifi_ap), lists last 20 with redacted wifi_password, and cancels PENDING commands (409 if already SENT/APPLIED/FAILED).
  • Firmware Artifacts & OTA Release Hosting (cloud/api/converters.py, cloud/api/firmware.py):
    • GET /api/v1/converters/firmware/{info,history,latest-uf2,download/{filename},releases}: Serves compiled .uf2/.bin/.manifest.json from disk (PLANOVI_FIRMWARE_DIR candidates) with strict regex + realpath traversal guard.
    • GET /api/v1/firmware/releases, POST /api/v1/firmware/upload, GET /api/v1/firmware/{version}/{metadata,chunk}: Hosts DB-backed OTA releases, computes SHA-256 + ECDSA P-256 signature (PLANOVI_OTA_SIGNING_KEY_PATH -> Device CA fallback -> auto-generated .dev_ota_key.pem), streams 1..8192 B chunks.
  • Admin mTLS Telemetry Policy (cloud/api/admin_telemetry_settings.py, cloud/services/telemetry_policy.py):
    • PUT /api/v1/admin/converters/{converter_id}/telemetry-policy and PUT /api/v1/admin/telemetry-policy: Authenticated via verify_admin_mtls (trusted proxy + verified cert CN in PLANOVI_ADMIN_MTLS_CNS), updates telemetry_interval_sec (5..86400), telemetry_enabled, increments remote_config_version (1..0xFFFFFFFF, skipping 0), and publishes retained QoS 1 MQTT command (202 "queued"/"retry_required"/"partial", or 503 if MQTT bridge is disabled).
  • Activity Logs, System Settings & Infrastructure Health (activity_logs.py, settings.py, status.py):
    • GET /api/v1/activity-logs & /export-csv (1000-row cap): Joins device_events + edge_converters + facilities; promotes "info" rows matching _SUCCESS_KEYWORDS to UI severity "SUCCESS".
    • GET/PUT /api/v1/settings: Reads/writes SystemSetting (edge_system_settings, falling back to in-memory _GLOBAL_SETTINGS on DB error).
    • POST /api/v1/infra/report-status & GET /api/v1/status (and app alias GET /status): Token-authenticated container health reporting into in-memory COMPONENTS_CACHE (supabase-db, vps-proxy, vps-deployer, converters-prod, php-app-prod, webpage-prod) + SELECT 1 DB probe.
  • Alert Outbox & Offline Reconciliation (cloud/services/alert_dispatcher.py):
    • Background loop (1 s tick; 30 s availability sweep) marks converters with last_seen < now - offline_after_seconds (max(60, env or 300)) as OFFLINE, enqueues CONVERTER_OFFLINE (ACTIVE/RESOLVED) and severe device events into alert_notifications (ON CONFLICT (dedupe_key) DO NOTHING), and delivers via Google Chat webhook (10 s timeout, retry schedule 5, 15, 60, 300, 900, 3600 s indefinitely). No email/SMTP/Resend sender exists (email-templates/*.html are unreferenced static mockups).
  • Shared-Supabase Sync Trigger (cloud/migrations/019_fix_converter_sync_and_telemetry_rpc.sql):
    • public.fn_sync_edge_converter_to_converters() mirrors edge_converters writes into public.converters, public.gateway_registry, primary public.logical_points, updates existing public.counters/public.buildings.main_counter_id (Option 2: never synthesizes fake counters), and inserts 'system_alert' rows into public.system_notifications for owner/admin company members.

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

  • BR-CLOUD-01 (PostgreSQL Schema 000–019 Referential Integrity): Migration 008 and 012 hardened historical FKs to ON DELETE RESTRICT on energy_meters.converter_id, telemetry_data.{converter_id,meter_id}, telemetry_ingest_receipts.converter_id, device_events.converter_id, meter_configuration_history.meter_id, alert_notifications.converter_id, and storage_streams.facility_id. Deleting a converter with history via DELETE /api/v1/converters/{id} fails with FK violation (HTTP 500) rather than cascading data loss.
  • BR-CLOUD-02 (Active Meter Partial Uniqueness): Migration 011 enforces idx_converter_modbus_active UNIQUE (converter_id, modbus_address) WHERE is_active and idx_converter_logical_meter_active UNIQUE (converter_id, logical_id) WHERE is_active, permitting retired historical meters to retain old addresses/IDs while keeping active maps conflict-free.
  • BR-CLOUD-03 (Serial Number Generation Floor & Collision Avoidance): public.next_edge_converter_serial() (018) checks both PLN-EC-XXXXXXXX and legacy ASL-EC-XXXXXXXX against public.edge_converters.serial_number and public.converters.hardware_id. cloud/api/converters.py:316,918 enforces floor max_num = 130 and ignores numeric suffixes > 8 digits.
  • BR-CLOUD-04 (Dynamic Online/Offline/Warning Status vs Alert Thresholds): Three distinct thresholds exist across the backend:
    • UI dynamic status (converters.py:329, compute_dynamic_status): offline after max(2 * telemetry_interval_sec, 180) s.
    • Alert dispatcher (alert_dispatcher.py:207): CONVERTER_OFFLINE after max(60, PLANOVI_OFFLINE_ALERT_SECONDS or 300) s.
    • Sync recovery log (telemetry_ingress.py:303): emits CONNECTION_RECOVERED (3011) if previously offline, never seen, or gap > 900 s.
  • BR-CLOUD-05 (Remote Command Validation): POST /api/v1/converters/{id}/commands allows strictly 10 command types; update_wifi_credentials enforces wifi_ssid 1..32 chars and wifi_password empty or 8..63 chars (default save_as_fallback = True updates fallback_wifi_ssid); sync_time auto-injects server_time_utc. Cancellation (DELETE .../commands/{cmd_id}) returns 409 unless status == PENDING.
  • BR-CLOUD-06 (Alert Outbox Deduplication & Delivery Policy): alert_dispatcher.py enqueues device_events when severity in {"error","critical"} OR code in {"CLOUD_DELIVERY_UNAVAILABLE","SD_WRITE_FAILED","SD_WRITE_RETRY_EXCESSIVE"}. SD_WRITE_FAILED deduplicates per incident (event-incident:{stream}:{code}:{state}:{first_ts}); all others deduplicate per (stream, seq). Webhook URL must be https://chat.googleapis.com/v1/spaces/....
  • BR-CLOUD-07 (Firmware Download Traversal Protection): GET /api/v1/converters/firmware/download/{filename} restricts names to ^(?:planovi|aslandi)_[A-Za-z0-9._-]+\.(?:uf2|bin|manifest\.json)$ (400) and verifies resolved realpath stays inside the firmware directory.
  • BR-CLOUD-08 (Global Validation Error Sanitizer): cloud/app.py:126-138 overrides RequestValidationError (422) to strip raw input payloads so rejected NaN/Infinity floats never crash JSON serialization.

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> PENDING: enqueue_device_event_notification / offline sweep
    PENDING --> SENDING: Worker claims via FOR UPDATE SKIP LOCKED
    SENDING --> SENT: Google Chat HTTP 2xx -> sent_at set
    SENDING --> FAILED: Network / HTTP non-2xx -> attempt_count++, next_attempt_at += backoff(5s..3600s)
    FAILED --> SENDING: next_attempt_at elapsed (up to DB check attempt_count <= 100)
  • Converter Status (devicestatusenum): OFFLINE (initial) <-> ONLINE (telemetry/event/sync) | MAINTENANCE (card adoption or manual) | ERROR.
  • Converter Orders (public.converter_orders): new -> in_progress -> ready -> completed | cancelled.

5. Technical Contract (Inputs -> Processing -> Side Effects)

  • Routes (42 across app.py & 6 routers): app.py (5: /favicon.svg, /favicon.ico, /docs, /redoc, /status), converters.py (25 under /api/v1), admin_telemetry_settings.py (2 under /api/v1/admin), firmware.py (4 under /api/v1/firmware), settings.py (2 under /api/v1/settings), activity_logs.py (2 under /api/v1/activity-logs), status.py (2 under /api/v1/status & /api/v1/infra/report-status).
  • Database Tables (12 in 000–019): facilities, edge_converters, energy_meters, telemetry_data, firmware_releases, telemetry_ingest_receipts, device_events, storage_streams, meter_configuration_history, alert_notifications, edge_device_commands, system_settings (vs ORM edge_system_settings).
  • PostgreSQL Functions (3 in 018–019): public.next_edge_converter_serial(), public.fn_sync_edge_converter_to_converters(), public.ingest_telemetry_record(text, jsonb, text).
  • External Side Effects: Google Chat webhook HTTP POSTs, Device CA X.509 cert signing, disk writes in PLANOVI_FIRMWARE_STORAGE_DIR, MQTT retained command publishes.

6. Cross-Repository Dependencies

  • cloud/api/converters.py & 018–019 -> Shared Supabase planovi-backend schema | Direct PostgreSQL SQL / Trigger / FK | Reads/writes public.companies, public.buildings, public.converters, public.converter_orders, public.gateway_registry, public.logical_points, public.counters, public.devices, public.raw_telemetry, public.company_members, public.system_notifications, public.meter_model, public.fn_aggregate_hourly_telemetry.
  • deploy/check-health.sh -> cloud/api/status.py | HTTP + X-Status-Auth-Token | POST /api/v1/infra/report-status.
  • admin/ -> cloud/api/{converters,firmware,settings,activity_logs,status} | HTTP/HTTPS (unauthenticated at FastAPI layer) | /api/v1/*.

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • Option 2 Counter Sync in Migration 019: Intentionally stops synthesizing placeholder MAIN counters on edge_converters insert so unassigned warehouse converters (company_id IS NULL) never violate public.counters.company_id NOT NULL; real counters are created lazily upon first assigned Schema 3 telemetry.
  • Confirmed Critical Bugs & Discrepancies:
    1. Guaranteed 500 crash on PATCH /api/v1/converter-orders/{order_id} (cloud/api/converters.py:126-130, 635-648): Pydantic ConverterOrderUpdateRequest defines status, admin_notes, fulfilled_edge_converter_id, but handler accesses payload.converter_serial and payload.notes -> AttributeError.
    2. AlertDispatcher ignores PLANOVI_GOOGLE_CHAT_WEBHOOK_URL (alert_dispatcher.py:203): Reads only legacy ASLANDI_GOOGLE_CHAT_WEBHOOK_URL; when unset, start() returns early and offline detection (reconcile_converter_availability) never runs.
    3. Breaking ORM-vs-Migration mismatches (db_models.py vs 000–019):
      • SystemSetting maps to edge_system_settings (UUID PK + created_at + created_by), while migration 016 creates system_settings (INT PK = 1, no created_at). No migration creates edge_system_settings!
      • TelemetryIngestReceipt maps 4 columns (id, created_at, updated_at, created_by) that do NOT exist in any migration 000–019.
      • Migration 018 adds soft-delete/audit columns to storage_streams, edge_device_commands, and energy_meters that are absent from db_models.py.
      • telemetry_data.source_sequence lost IS NOT NULL in migration 008 while ORM marks nullable=False.
      • storage_streams.facility_id is ON DELETE RESTRICT in SQL vs ondelete="SET NULL" in ORM.
    4. Zero authentication on 35 management routes: All routes in converters.py (including Device CA cert minting!), settings.py, activity_logs.py, and firmware.py (POST /upload) have zero FastAPI auth checks.
    5. Path traversal on POST /api/v1/firmware/upload (firmware.py:268-271): f"{version}_{filename}" does not sanitize directory separators (../) in filename.
    6. Sticky offline DB status (status.py:133-140) & broken /status alias (app.py:150-154): COMPONENTS_CACHE["supabase-db"] never resets to "online" after transient failure; GET /status invokes get_status() directly without DI so session is a Depends object.
    7. Always-zero duplicate_count (converters.py:2046,2060,2798): Queries outcome == 'DUPLICATE' on telemetry_ingest_receipts, which only permits 'PENDING' | 'PROCESSED' | 'REJECTED'.
    8. Hardcoded UTC+2 offset (converters.py:1598), unstripped cert CN (converters.py:1301), missing bounds on desired-config (converters.py), status.py non-constant-time token compare + hardcoded DEFAULT_TOKEN fallback, database.py missing pool/PgBouncer tuning.
    9. Dead code: cloud/services/device_provisioning.py, email-templates/*.html (all 4 files), ConverterUpdateRequest.clear_company/clear_building, status._check_tcp_port, alert_notifications DB check attempt_count <= 100 (dispatcher retries forever without checking cap, so attempt 101 will fail with DB CheckViolation!).
  • [TEAM_WHY_NEEDED: Why are all 25 routes in converters.py (including Device CA signing in prepare-usb-provisioning), settings.py, activity_logs.py, and firmware.py unauthenticated in FastAPI? Is network/Nginx IP allowlisting the sole intended boundary, or is Supabase JWT auth pending?]
  • [TEAM_WHY_NEEDED: Were edge_system_settings and the 4 UUID/audit columns on telemetry_ingest_receipts created manually in Supabase outside cloud/migrations/000..019? Should a reconciliation migration 020 be added?]
  • [TEAM_WHY_NEEDED: Why does get_next_converter_serial() enforce floor max_num = 130, why does prepare-usb-provisioning return synthetic Slot B metadata (total_blocks=512, payload_size_bytes=196608), and why do offline thresholds diverge across 180s / 300s / 900s?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact CommandFix
500 Internal Server Error (AttributeError: 'ConverterOrderUpdateRequest' object has no attribute 'converter_serial')Schema/handler mismatch in PATCH /api/v1/converter-orders/{order_id} (converters.py:126-130, 635-648)pytest cloud/tests/ or inspect FastAPI traceback on order status changeAlign ConverterOrderUpdateRequest fields with handler (converter_serial/notes vs admin_notes/fulfilled_edge_converter_id)
Converters stay ONLINE forever / Google Chat alerts never fireAlertDispatcher only reads ASLANDI_GOOGLE_CHAT_WEBHOOK_URL (alert_dispatcher.py:203); if unset, worker exits immediatelyCheck env vars on backend container and query SELECT * FROM alert_notifications ORDER BY id DESC LIMIT 20Set ASLANDI_GOOGLE_CHAT_WEBHOOK_URL or patch alert_dispatcher.py to read PLANOVI_GOOGLE_CHAT_WEBHOOK_URL first
UndefinedTableError: relation "edge_system_settings" does not exist or UndefinedColumnError on telemetry_ingest_receipts.idFresh DB built only from 000–019 lacks manual Supabase table/columns expected by db_models.pyRun psql \dt and \d telemetry_ingest_receiptsAdd migration reconciling edge_system_settings and telemetry_ingest_receipts columns
500 on DELETE /api/v1/converters/{id}ON DELETE RESTRICT FKs from energy_meters/telemetry_data/device_events/alert_notifications (008, 012, 014)Check PostgreSQL ForeignKeyViolation logUse soft-delete (deleted_at) instead of physical DELETE for converters with telemetry history