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/*), AutonomousAlertDispatcherbackground 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 nextPLN-EC-XXXXXXXX(floor130, ignoring suffixes> 8digits, peekingpublic.edge_converter_serial_seq).POST /api/v1/converters/prepare-usb-provisioning: UpsertsEdgeConverter(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 Baes_key_hex; advancesedge_converter_serial_seq.POST /api/v1/converters/{id}/confirm-flash: MarksOFFLINEand recordsUSB_FLASH_CONFIRMED(3004).GET/POST/PUT/DELETE /api/v1/converters,POST /api/v1/converters/provision(legacy mTLS upsert asONLINEwith default IP"10.20.4.10").GET /api/v1/facilities,GET /api/v1/organizations(readspublic.companies+public.buildings),GET/PATCH /api/v1/converter-orders(reads/updatespublic.converter_orders; Note:PATCHcurrently crashes withAttributeError— see §7).
- Live Telemetry Monitor, Diagnostics & Remote Commands (
cloud/api/converters.py):GET /api/v1/converters/{id}/monitor: AggregatesEurope/Warsawwindowed buckets (4h/today/7d/1m, downsampled to48/42points), KPIs, 3-phase table, and per-parameter series.GET /api/v1/converters/{id}/telemetry-diagnostics: Paginated (limit1..100) receipts outer-joined withtelemetry_data, plus active meters.GET /api/v1/converters/stats/overview: Fleet status totals (computed dynamically viacompute_dynamic_status), 24 h receipts, active alerts, active meters.POST /api/v1/converters/{id}/desired-config: Setsdesired_cloud_host,desired_cloud_port,desired_telemetry_interval_secand recordsDESIRED_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 redactedwifi_password, and cancelsPENDINGcommands (409if alreadySENT/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.jsonfrom disk (PLANOVI_FIRMWARE_DIRcandidates) with strict regex +realpathtraversal 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), streams1..8192 Bchunks.
- Admin mTLS Telemetry Policy (
cloud/api/admin_telemetry_settings.py,cloud/services/telemetry_policy.py):PUT /api/v1/admin/converters/{converter_id}/telemetry-policyandPUT /api/v1/admin/telemetry-policy: Authenticated viaverify_admin_mtls(trusted proxy + verified cert CN inPLANOVI_ADMIN_MTLS_CNS), updatestelemetry_interval_sec(5..86400),telemetry_enabled, incrementsremote_config_version(1..0xFFFFFFFF, skipping0), and publishes retained QoS 1 MQTT command (202"queued"/"retry_required"/"partial", or503if 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): Joinsdevice_events+edge_converters+facilities; promotes"info"rows matching_SUCCESS_KEYWORDSto UI severity"SUCCESS".GET/PUT /api/v1/settings: Reads/writesSystemSetting(edge_system_settings, falling back to in-memory_GLOBAL_SETTINGSon DB error).POST /api/v1/infra/report-status&GET /api/v1/status(and app aliasGET /status): Token-authenticated container health reporting into in-memoryCOMPONENTS_CACHE(supabase-db,vps-proxy,vps-deployer,converters-prod,php-app-prod,webpage-prod) +SELECT 1DB probe.
- Alert Outbox & Offline Reconciliation (
cloud/services/alert_dispatcher.py):- Background loop (
1 stick;30 savailability sweep) marks converters withlast_seen < now - offline_after_seconds(max(60, env or 300)) asOFFLINE, enqueuesCONVERTER_OFFLINE(ACTIVE/RESOLVED) and severe device events intoalert_notifications(ON CONFLICT (dedupe_key) DO NOTHING), and delivers via Google Chat webhook (10 stimeout, retry schedule5, 15, 60, 300, 900, 3600 sindefinitely). No email/SMTP/Resend sender exists (email-templates/*.htmlare unreferenced static mockups).
- Background loop (
- Shared-Supabase Sync Trigger (
cloud/migrations/019_fix_converter_sync_and_telemetry_rpc.sql):public.fn_sync_edge_converter_to_converters()mirrorsedge_converterswrites intopublic.converters,public.gateway_registry, primarypublic.logical_points, updates existingpublic.counters/public.buildings.main_counter_id(Option 2: never synthesizes fake counters), and inserts'system_alert'rows intopublic.system_notificationsforowner/admincompany members.
3. Hard Business Rules, Validations, Calculations & Edge Cases
BR-CLOUD-01(PostgreSQL Schema000–019Referential Integrity): Migration008and012hardened historical FKs toON DELETE RESTRICTonenergy_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, andstorage_streams.facility_id. Deleting a converter with history viaDELETE /api/v1/converters/{id}fails with FK violation (HTTP 500) rather than cascading data loss.BR-CLOUD-02(Active Meter Partial Uniqueness): Migration011enforcesidx_converter_modbus_active UNIQUE (converter_id, modbus_address) WHERE is_activeandidx_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 bothPLN-EC-XXXXXXXXand legacyASL-EC-XXXXXXXXagainstpublic.edge_converters.serial_numberandpublic.converters.hardware_id.cloud/api/converters.py:316,918enforces floormax_num = 130and ignores numeric suffixes> 8digits.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 aftermax(2 * telemetry_interval_sec, 180)s. - Alert dispatcher (
alert_dispatcher.py:207):CONVERTER_OFFLINEaftermax(60, PLANOVI_OFFLINE_ALERT_SECONDS or 300)s. - Sync recovery log (
telemetry_ingress.py:303): emitsCONNECTION_RECOVERED(3011) if previously offline, never seen, or gap> 900 s.
- UI dynamic status (
BR-CLOUD-05(Remote Command Validation):POST /api/v1/converters/{id}/commandsallows strictly 10 command types;update_wifi_credentialsenforceswifi_ssid1..32chars andwifi_passwordempty or8..63chars (defaultsave_as_fallback = Trueupdatesfallback_wifi_ssid);sync_timeauto-injectsserver_time_utc. Cancellation (DELETE .../commands/{cmd_id}) returns409unlessstatus == PENDING.BR-CLOUD-06(Alert Outbox Deduplication & Delivery Policy):alert_dispatcher.pyenqueuesdevice_eventswhenseverity in {"error","critical"}ORcode in {"CLOUD_DELIVERY_UNAVAILABLE","SD_WRITE_FAILED","SD_WRITE_RETRY_EXCESSIVE"}.SD_WRITE_FAILEDdeduplicates per incident (event-incident:{stream}:{code}:{state}:{first_ts}); all others deduplicate per(stream, seq). Webhook URL must behttps://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 resolvedrealpathstays inside the firmware directory.BR-CLOUD-08(Global Validation Error Sanitizer):cloud/app.py:126-138overridesRequestValidationError(422) to strip raw input payloads so rejectedNaN/Infinityfloats 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 ORMedge_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 Supabaseplanovi-backendschema | Direct PostgreSQL SQL / Trigger / FK | Reads/writespublic.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 placeholderMAINcounters onedge_convertersinsert so unassigned warehouse converters (company_id IS NULL) never violatepublic.counters.company_id NOT NULL; real counters are created lazily upon first assigned Schema 3 telemetry. - Confirmed Critical Bugs & Discrepancies:
- Guaranteed 500 crash on
PATCH /api/v1/converter-orders/{order_id}(cloud/api/converters.py:126-130, 635-648): PydanticConverterOrderUpdateRequestdefinesstatus,admin_notes,fulfilled_edge_converter_id, but handler accessespayload.converter_serialandpayload.notes->AttributeError. AlertDispatcherignoresPLANOVI_GOOGLE_CHAT_WEBHOOK_URL(alert_dispatcher.py:203): Reads only legacyASLANDI_GOOGLE_CHAT_WEBHOOK_URL; when unset,start()returns early and offline detection (reconcile_converter_availability) never runs.- Breaking ORM-vs-Migration mismatches (
db_models.pyvs000–019):SystemSettingmaps toedge_system_settings(UUID PK +created_at+created_by), while migration016createssystem_settings(INT PK= 1, nocreated_at). No migration createsedge_system_settings!TelemetryIngestReceiptmaps 4 columns (id,created_at,updated_at,created_by) that do NOT exist in any migration000–019.- Migration
018adds soft-delete/audit columns tostorage_streams,edge_device_commands, andenergy_metersthat are absent fromdb_models.py. telemetry_data.source_sequencelostIS NOT NULLin migration008while ORM marksnullable=False.storage_streams.facility_idisON DELETE RESTRICTin SQL vsondelete="SET NULL"in ORM.
- Zero authentication on 35 management routes: All routes in
converters.py(including Device CA cert minting!),settings.py,activity_logs.py, andfirmware.py(POST /upload) have zero FastAPI auth checks. - Path traversal on
POST /api/v1/firmware/upload(firmware.py:268-271):f"{version}_{filename}"does not sanitize directory separators (../) infilename. - Sticky offline DB status (
status.py:133-140) & broken/statusalias (app.py:150-154):COMPONENTS_CACHE["supabase-db"]never resets to"online"after transient failure;GET /statusinvokesget_status()directly without DI sosessionis aDependsobject. - Always-zero
duplicate_count(converters.py:2046,2060,2798): Queriesoutcome == 'DUPLICATE'ontelemetry_ingest_receipts, which only permits'PENDING' | 'PROCESSED' | 'REJECTED'. - Hardcoded UTC+2 offset (
converters.py:1598), unstripped cert CN (converters.py:1301), missing bounds ondesired-config(converters.py),status.pynon-constant-time token compare + hardcodedDEFAULT_TOKENfallback,database.pymissing pool/PgBouncer tuning. - Dead code:
cloud/services/device_provisioning.py,email-templates/*.html(all 4 files),ConverterUpdateRequest.clear_company/clear_building,status._check_tcp_port,alert_notificationsDB checkattempt_count <= 100(dispatcher retries forever without checking cap, so attempt 101 will fail with DBCheckViolation!).
- Guaranteed 500 crash on
[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 Message | Root Cause in Code | How to Verify / Exact Command | Fix |
|---|---|---|---|
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 change | Align ConverterOrderUpdateRequest fields with handler (converter_serial/notes vs admin_notes/fulfilled_edge_converter_id) |
Converters stay ONLINE forever / Google Chat alerts never fire | AlertDispatcher only reads ASLANDI_GOOGLE_CHAT_WEBHOOK_URL (alert_dispatcher.py:203); if unset, worker exits immediately | Check env vars on backend container and query SELECT * FROM alert_notifications ORDER BY id DESC LIMIT 20 | Set 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.id | Fresh DB built only from 000–019 lacks manual Supabase table/columns expected by db_models.py | Run psql \dt and \d telemetry_ingest_receipts | Add 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 log | Use soft-delete (deleted_at) instead of physical DELETE for converters with telemetry history |