@marinoscar/platform-db 0.1.0-next.19 → 0.1.0-next.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # @marinoscar/platform-db
2
2
 
3
+ ## 0.1.0-next.20
4
+
5
+ ### Minor Changes
6
+
7
+ - 7b5796f: Add the `alerts` slice (#1047). `@marinoscar/platform-contract/alerts` carries the wire shapes (rules, the configs of the built-in kinds, incidents, the dry-run response, the kind catalog, the summary). `@marinoscar/platform-api/alerts` adds `AlertsModule.forRoot`, the open rule-kind registry (`registerAlertRuleKind`) with the `metric_threshold`, `node_event`, `verdict`, `node_offline` and `telemetry_unavailable` kinds, the pending/firing/resolved state machine, the `alerts.evaluate`, `alerts.evaluate_event` and `alerts.incidents_purge` server-only jobs, notifications on a transition with an optional webhook port (`ALERTS_WEBHOOK_EMITTER`), eight disabled starter rules, the `/api/admin/alerts` routes behind the new `alerts:read` and `alerts:write` permissions, and the `alerts` conformance suite (`@marinoscar/platform-api/alerts/testing`). The telemetry slice now exports `TelemetryDashboardService` and `createQueryFacade`, accepts a `null` (system) user and an `alert` query source, and the nodes slice exports `deriveNodeHealth`. `@marinoscar/platform-db` adds migration `0040_add_alerts` (`alert_rules`, `alert_incidents` and the raw-SQL partial unique index `alert_incidents_open_uniq_idx`).
8
+ - ad3f525: Add the `webhooks` slice schema (#1046): `WebhookEndpoint` (`webhook_endpoints`) and `WebhookDelivery` (`webhook_deliveries`), with the `WebhookScope` and `WebhookDeliveryStatus` enums and back-relations on `User` and `Organization`. Both tables are org-owned with a nullable `org_id` (NULL only for a system-scope endpoint) under FORCEd `webhook_endpoints_org_isolation` and `webhook_deliveries_org_isolation` policies (listed in `RLS_POLICIES`). Endpoints cascade with their owning user and organization, deliveries with their endpoint. Migration `0039_add_webhooks`.
9
+
10
+ ### Patch Changes
11
+
12
+ - f4ce36e: Add the `worker_node_events` table (`WorkerNodeEvent`, jobs/nodes slice, #1045): events a worker node reports about itself, with an open `type`, a `severity`, optional JSON `attrs`, the node's `occurred_at` and the server's `received_at`. Cascades with `worker_nodes`; no row-level security. Migration `0038_add_worker_node_events`; apply it with `npm run db:sync`, then `prisma:migrate`.
13
+
3
14
  ## 0.1.0-next.19
4
15
 
5
16
  ## 0.1.0-next.18
package/README.md CHANGED
@@ -185,6 +185,7 @@ The migration tooling adds no row to the catalog. How an app extends the migrati
185
185
  | `db-backup.prisma` | `DatabaseBackupRun` |
186
186
  | `ai.prisma` | `AiModel`, `UserAiKey`, `AiRun`, `AiUsageEvent` |
187
187
  | `sharing.prisma` | `Group` (`@extensible`), `GroupMember`, `GroupInvite` |
188
+ | `webhooks.prisma` | `WebhookEndpoint`, `WebhookDelivery` (#1046: outbound webhook destinations and delivery attempts; nullable `org_id` under forced row-level security, NULL only for system scope; no secret column, the signing secret is in `credentials`) |
188
189
  | `android-app.prisma` | `AndroidAppRelease` (#746: the hosted Android APKs; `sizeBytes` BigInt; at most one current release through the raw-SQL index `android_app_releases_one_current_uniq_idx`) |
189
190
 
190
191
  A slice declares the back-relations that point **into** another slice as `extend model` blocks in its own fragment (the 17 `User` fields that leave identity, and `Job.backupRun` in `db-backup.prisma`). Every block comment of the original schema is kept verbatim: they are the design documentation.
@@ -0,0 +1,21 @@
1
+ -- CreateTable
2
+ CREATE TABLE "worker_node_events" (
3
+ "id" UUID NOT NULL,
4
+ "node_id" UUID NOT NULL,
5
+ "type" VARCHAR(64) NOT NULL,
6
+ "severity" VARCHAR(16) NOT NULL,
7
+ "attrs" JSONB,
8
+ "occurred_at" TIMESTAMPTZ NOT NULL,
9
+ "received_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
10
+
11
+ CONSTRAINT "worker_node_events_pkey" PRIMARY KEY ("id")
12
+ );
13
+
14
+ -- CreateIndex
15
+ CREATE INDEX "worker_node_events_node_id_received_at_idx" ON "worker_node_events"("node_id", "received_at" DESC);
16
+
17
+ -- CreateIndex
18
+ CREATE INDEX "worker_node_events_received_at_idx" ON "worker_node_events"("received_at");
19
+
20
+ -- AddForeignKey
21
+ ALTER TABLE "worker_node_events" ADD CONSTRAINT "worker_node_events_node_id_fkey" FOREIGN KEY ("node_id") REFERENCES "worker_nodes"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,125 @@
1
+ -- =============================================================================
2
+ -- Outbound webhooks: webhook_endpoints and webhook_deliveries (#1046)
3
+ -- =============================================================================
4
+ --
5
+ -- Two new org-owned tables. org_id is NULLABLE on both: NULL only for a
6
+ -- system-scope endpoint and its deliveries, visible to the bypass (system)
7
+ -- client only, as for ai_usage_events in 0025_org_scoped_rls. A delivery carries
8
+ -- its endpoint's org_id because a policy cannot join through its parent; the
9
+ -- endpoint link is a simple FK (a composite FK on a nullable org_id is not
10
+ -- enforced by MATCH SIMPLE and would add no isolation). The signing secret is
11
+ -- never a column: it lives in the encrypted credentials store.
12
+ --
13
+ -- No raw-SQL partial index: the (endpoint_id, event_id) uniqueness is a plain
14
+ -- composite UNIQUE. No backfill: the tables are new, so RLS is enabled at once.
15
+ -- =============================================================================
16
+
17
+ BEGIN;
18
+ SELECT set_config('app.rls_bypass', 'on', true);
19
+
20
+ -- CreateEnum
21
+ CREATE TYPE "WebhookScope" AS ENUM ('user', 'org', 'system');
22
+
23
+ -- CreateEnum
24
+ CREATE TYPE "WebhookDeliveryStatus" AS ENUM ('pending', 'delivering', 'succeeded', 'failed', 'dead');
25
+
26
+ -- CreateTable
27
+ CREATE TABLE "webhook_endpoints" (
28
+ "id" UUID NOT NULL,
29
+ "org_id" UUID,
30
+ "scope" "WebhookScope" NOT NULL,
31
+ "owner_user_id" UUID,
32
+ "created_by_id" UUID,
33
+ "name" VARCHAR(120) NOT NULL,
34
+ "description" VARCHAR(500),
35
+ "url" VARCHAR(2048) NOT NULL,
36
+ "event_keys" TEXT[],
37
+ "enabled" BOOLEAN NOT NULL DEFAULT true,
38
+ "secret_version" INTEGER NOT NULL DEFAULT 1,
39
+ "previous_secret_until" TIMESTAMPTZ,
40
+ "consecutive_failures" INTEGER NOT NULL DEFAULT 0,
41
+ "disabled_reason" VARCHAR(64),
42
+ "last_delivery_at" TIMESTAMPTZ,
43
+ "last_success_at" TIMESTAMPTZ,
44
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
45
+ "updated_at" TIMESTAMPTZ NOT NULL,
46
+
47
+ CONSTRAINT "webhook_endpoints_pkey" PRIMARY KEY ("id")
48
+ );
49
+
50
+ -- CreateTable
51
+ CREATE TABLE "webhook_deliveries" (
52
+ "id" UUID NOT NULL,
53
+ "org_id" UUID,
54
+ "endpoint_id" UUID NOT NULL,
55
+ "event_key" VARCHAR(128) NOT NULL,
56
+ "event_id" UUID NOT NULL,
57
+ "payload" JSONB NOT NULL,
58
+ "status" "WebhookDeliveryStatus" NOT NULL DEFAULT 'pending',
59
+ "attempt" INTEGER NOT NULL DEFAULT 0,
60
+ "response_status" INTEGER,
61
+ "response_snippet" VARCHAR(1024),
62
+ "error_code" VARCHAR(64),
63
+ "duration_ms" INTEGER,
64
+ "next_attempt_at" TIMESTAMPTZ,
65
+ "delivered_at" TIMESTAMPTZ,
66
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
67
+
68
+ CONSTRAINT "webhook_deliveries_pkey" PRIMARY KEY ("id")
69
+ );
70
+
71
+ -- CreateIndex
72
+ CREATE INDEX "webhook_endpoints_org_id_scope_enabled_idx" ON "webhook_endpoints"("org_id", "scope", "enabled");
73
+
74
+ -- CreateIndex
75
+ CREATE INDEX "webhook_endpoints_owner_user_id_idx" ON "webhook_endpoints"("owner_user_id");
76
+
77
+ -- CreateIndex
78
+ CREATE INDEX "webhook_deliveries_endpoint_id_created_at_idx" ON "webhook_deliveries"("endpoint_id", "created_at" DESC);
79
+
80
+ -- CreateIndex
81
+ CREATE INDEX "webhook_deliveries_org_id_created_at_idx" ON "webhook_deliveries"("org_id", "created_at");
82
+
83
+ -- CreateIndex
84
+ CREATE INDEX "webhook_deliveries_event_id_idx" ON "webhook_deliveries"("event_id");
85
+
86
+ -- CreateIndex
87
+ CREATE INDEX "webhook_deliveries_created_at_idx" ON "webhook_deliveries"("created_at");
88
+
89
+ -- CreateIndex
90
+ CREATE UNIQUE INDEX "webhook_deliveries_endpoint_id_event_id_key" ON "webhook_deliveries"("endpoint_id", "event_id");
91
+
92
+ -- AddForeignKey
93
+ ALTER TABLE "webhook_endpoints" ADD CONSTRAINT "webhook_endpoints_owner_user_id_fkey" FOREIGN KEY ("owner_user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
94
+
95
+ -- AddForeignKey
96
+ ALTER TABLE "webhook_endpoints" ADD CONSTRAINT "webhook_endpoints_org_id_fkey" FOREIGN KEY ("org_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
97
+
98
+ -- AddForeignKey
99
+ ALTER TABLE "webhook_deliveries" ADD CONSTRAINT "webhook_deliveries_endpoint_id_fkey" FOREIGN KEY ("endpoint_id") REFERENCES "webhook_endpoints"("id") ON DELETE CASCADE ON UPDATE CASCADE;
100
+
101
+ -- =============================================================================
102
+ -- Row-level security, as in 0025_org_scoped_rls (ai_usage_events). The policy
103
+ -- names are listed in RLS_POLICIES (rls-policies.json) and asserted against
104
+ -- pg_policies by the drift test. NULLIF(..., '') because current_setting(name,
105
+ -- true) is the empty string on a connection that ever held a transaction-local
106
+ -- value. A NULL org_id never equals app.org_id, so those rows need the bypass.
107
+ -- =============================================================================
108
+
109
+ ALTER TABLE "webhook_endpoints" ENABLE ROW LEVEL SECURITY;
110
+ ALTER TABLE "webhook_endpoints" FORCE ROW LEVEL SECURITY;
111
+ CREATE POLICY "webhook_endpoints_org_isolation" ON "webhook_endpoints"
112
+ USING ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
113
+ OR current_setting('app.rls_bypass', true) = 'on')
114
+ WITH CHECK ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
115
+ OR current_setting('app.rls_bypass', true) = 'on');
116
+
117
+ ALTER TABLE "webhook_deliveries" ENABLE ROW LEVEL SECURITY;
118
+ ALTER TABLE "webhook_deliveries" FORCE ROW LEVEL SECURITY;
119
+ CREATE POLICY "webhook_deliveries_org_isolation" ON "webhook_deliveries"
120
+ USING ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
121
+ OR current_setting('app.rls_bypass', true) = 'on')
122
+ WITH CHECK ("org_id" = NULLIF(current_setting('app.org_id', true), '')::uuid
123
+ OR current_setting('app.rls_bypass', true) = 'on');
124
+
125
+ COMMIT;
@@ -0,0 +1,66 @@
1
+ -- CreateTable
2
+ CREATE TABLE "alert_rules" (
3
+ "id" UUID NOT NULL,
4
+ "org_id" UUID,
5
+ "key" VARCHAR(64),
6
+ "name" VARCHAR(120) NOT NULL,
7
+ "description" VARCHAR(500),
8
+ "enabled" BOOLEAN NOT NULL DEFAULT false,
9
+ "kind" VARCHAR(32) NOT NULL,
10
+ "severity" VARCHAR(16) NOT NULL,
11
+ "config" JSONB NOT NULL,
12
+ "for_seconds" INTEGER NOT NULL DEFAULT 0,
13
+ "cooldown_seconds" INTEGER NOT NULL DEFAULT 900,
14
+ "notify_channels" TEXT[] DEFAULT ARRAY[]::TEXT[],
15
+ "webhook" BOOLEAN NOT NULL DEFAULT true,
16
+ "created_by_id" UUID,
17
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
18
+ "updated_at" TIMESTAMPTZ NOT NULL,
19
+ "last_evaluated_at" TIMESTAMPTZ,
20
+ "last_error" VARCHAR(500),
21
+
22
+ CONSTRAINT "alert_rules_pkey" PRIMARY KEY ("id")
23
+ );
24
+
25
+ -- CreateTable
26
+ CREATE TABLE "alert_incidents" (
27
+ "id" UUID NOT NULL,
28
+ "rule_id" UUID NOT NULL,
29
+ "labels_key" VARCHAR(512) NOT NULL,
30
+ "labels" JSONB NOT NULL,
31
+ "state" VARCHAR(16) NOT NULL,
32
+ "severity" VARCHAR(16) NOT NULL,
33
+ "pending_since" TIMESTAMPTZ,
34
+ "fired_at" TIMESTAMPTZ,
35
+ "resolved_at" TIMESTAMPTZ,
36
+ "last_value" DOUBLE PRECISION,
37
+ "last_seen_at" TIMESTAMPTZ NOT NULL,
38
+ "summary" VARCHAR(500) NOT NULL,
39
+ "acknowledged_at" TIMESTAMPTZ,
40
+ "acknowledged_by_id" UUID,
41
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
42
+
43
+ CONSTRAINT "alert_incidents_pkey" PRIMARY KEY ("id")
44
+ );
45
+
46
+ -- CreateIndex
47
+ CREATE UNIQUE INDEX "alert_rules_key_key" ON "alert_rules"("key");
48
+
49
+ -- CreateIndex
50
+ CREATE INDEX "alert_rules_enabled_kind_idx" ON "alert_rules"("enabled", "kind");
51
+
52
+ -- CreateIndex
53
+ CREATE INDEX "alert_incidents_rule_id_state_idx" ON "alert_incidents"("rule_id", "state");
54
+
55
+ -- CreateIndex
56
+ CREATE INDEX "alert_incidents_state_fired_at_idx" ON "alert_incidents"("state", "fired_at");
57
+
58
+ -- CreateIndex
59
+ CREATE INDEX "alert_incidents_resolved_at_idx" ON "alert_incidents"("resolved_at");
60
+
61
+ -- AddForeignKey
62
+ ALTER TABLE "alert_incidents" ADD CONSTRAINT "alert_incidents_rule_id_fkey" FOREIGN KEY ("rule_id") REFERENCES "alert_rules"("id") ON DELETE CASCADE ON UPDATE CASCADE;
63
+
64
+ -- CreateIndex (raw SQL, intentional schema drift: Prisma cannot express a partial unique index)
65
+ -- One OPEN incident per rule and label set. The evaluator relies on it to stay idempotent.
66
+ CREATE UNIQUE INDEX "alert_incidents_open_uniq_idx" ON "alert_incidents"("rule_id", "labels_key") WHERE "state" IN ('pending', 'firing');
@@ -375,5 +375,32 @@
375
375
  "sha256": "4b7047703bacab08af629004ff569e250869355acd03795f17d1b1e5b277c5e6",
376
376
  "since": "1.0.0",
377
377
  "slice": "sharing"
378
+ },
379
+ {
380
+ "dir": "0038_add_worker_node_events",
381
+ "id": "0038_add_worker_node_events",
382
+ "requires": [],
383
+ "sha256": "5775b304027a1cb77b30707093fd6be26290fd49df695f4d850e149fe265b196",
384
+ "since": "1.0.0",
385
+ "slice": "jobs"
386
+ },
387
+ {
388
+ "dir": "0039_add_webhooks",
389
+ "id": "0039_add_webhooks",
390
+ "requires": [
391
+ "identity"
392
+ ],
393
+ "rls": true,
394
+ "sha256": "8f719dc380610f61133612a52921fa6d89ee21957635372c2bc4bdc69d4c0a92",
395
+ "since": "1.0.0",
396
+ "slice": "webhooks"
397
+ },
398
+ {
399
+ "dir": "0040_add_alerts",
400
+ "id": "0040_add_alerts",
401
+ "requires": [],
402
+ "sha256": "ec4af7e5123ecd8bb6faf3505893cb2efab4d793dae84a98d8b7f26f2dff3776",
403
+ "since": "1.0.0",
404
+ "slice": "alerts"
378
405
  }
379
406
  ]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marinoscar/platform-db",
3
- "version": "0.1.0-next.19",
3
+ "version": "0.1.0-next.20",
4
4
  "description": "Prisma schema fragments, SQL migrations and seed functions of the platform (CommonJS).",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
@@ -89,6 +89,15 @@
89
89
  "reason": "At most one current Android APK release deployment-wide: a constant-expression partial unique index Prisma cannot express. Make-current clears the old flag and sets the new one in one transaction; the index arbitrates concurrent calls (the loser gets 409), never a findFirst pre-check.",
90
90
  "doc": "docs/specs/native-companion-architecture.md",
91
91
  "createdIn": "0033_add_android_app"
92
+ },
93
+ {
94
+ "name": "alert_incidents_open_uniq_idx",
95
+ "table": "alert_incidents",
96
+ "unique": true,
97
+ "definition": "CREATE UNIQUE INDEX alert_incidents_open_uniq_idx ON public.alert_incidents USING btree (rule_id, labels_key) WHERE ((state)::text = ANY ((ARRAY['pending'::character varying, 'firing'::character varying])::text[]))",
98
+ "reason": "At most one OPEN (pending or firing) incident per alert rule and label set; a partial unique index Prisma cannot express. The evaluator creates incidents and treats the unique violation as 'already open', so two overlapping evaluations leave one incident.",
99
+ "doc": "docs/specs/platform-packages.md",
100
+ "createdIn": "0040_add_alerts"
92
101
  }
93
102
  ]
94
103
  }
package/rls-policies.json CHANGED
@@ -69,6 +69,20 @@
69
69
  "reason": "Organization isolation of organization-owned encrypted credentials (PP-8.8): an org's key is visible only inside that organization's scope.",
70
70
  "doc": "docs/SECURITY-ARCHITECTURE.md",
71
71
  "createdIn": "0029_add_org_credentials"
72
+ },
73
+ {
74
+ "name": "webhook_endpoints_org_isolation",
75
+ "table": "webhook_endpoints",
76
+ "reason": "Organization isolation of outbound webhook endpoints (#1046); a system-scope endpoint has a NULL org_id and is visible to the bypass (system) client only.",
77
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
78
+ "createdIn": "0039_add_webhooks"
79
+ },
80
+ {
81
+ "name": "webhook_deliveries_org_isolation",
82
+ "table": "webhook_deliveries",
83
+ "reason": "Organization isolation of webhook delivery attempts, whose payload is the event body sent; the row carries the endpoint's org_id because a policy cannot join through its parent.",
84
+ "doc": "docs/SECURITY-ARCHITECTURE.md",
85
+ "createdIn": "0039_add_webhooks"
72
86
  }
73
87
  ]
74
88
  }
@@ -0,0 +1,75 @@
1
+ // =============================================================================
2
+ // Alerts (issue #1047)
3
+ // =============================================================================
4
+ //
5
+ // DEPLOYMENT-LEVEL tables: a rule watches the deployment's telemetry and its
6
+ // worker-node fleet, which no organization owns, so there is NO row-level
7
+ // security on either table in v1. `org_id` is reserved on `alert_rules` for a
8
+ // later organization-scoped rule (NULL = a deployment rule, the only kind v1
9
+ // creates); it is not a foreign key yet, for the same reason.
10
+ //
11
+ // `created_by_id` and `acknowledged_by_id` are plain user ids with no relation:
12
+ // an incident outlives the administrator who acknowledged it, and deleting a
13
+ // user must not delete (or null) alert history through a cascade.
14
+ //
15
+ // ONE OPEN INCIDENT PER RULE AND LABEL SET is a raw-SQL partial unique index
16
+ // that exists only in the migration (listed in raw-sql-indexes.json):
17
+ // alert_incidents_open_uniq_idx ON alert_incidents (rule_id, labels_key)
18
+ // WHERE state IN ('pending', 'firing')
19
+ // Never "fix" it with @@unique or a findFirst pre-check.
20
+
21
+ /// An alert rule. `kind` is an open registry id (`registerAlertRuleKind`),
22
+ /// `config` is validated by that kind's schema in the API. `key` is the stable
23
+ /// key of a seeded starter rule (NULL for an administrator's own rule).
24
+ model AlertRule {
25
+ id String @id @default(uuid()) @db.Uuid
26
+ orgId String? @map("org_id") @db.Uuid
27
+ key String? @unique @db.VarChar(64)
28
+ name String @db.VarChar(120)
29
+ description String? @db.VarChar(500)
30
+ enabled Boolean @default(false)
31
+ kind String @db.VarChar(32)
32
+ severity String @db.VarChar(16)
33
+ config Json
34
+ forSeconds Int @default(0) @map("for_seconds")
35
+ cooldownSeconds Int @default(900) @map("cooldown_seconds")
36
+ notifyChannels String[] @default([]) @map("notify_channels")
37
+ webhook Boolean @default(true)
38
+ createdById String? @map("created_by_id") @db.Uuid
39
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
40
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
41
+ lastEvaluatedAt DateTime? @map("last_evaluated_at") @db.Timestamptz
42
+ lastError String? @map("last_error") @db.VarChar(500)
43
+
44
+ incidents AlertIncident[]
45
+
46
+ @@index([enabled, kind])
47
+ @@map("alert_rules")
48
+ }
49
+
50
+ /// One rule breached for one label set. `labels_key` is the canonical sorted
51
+ /// `k=v,k=v` of `labels` ('' when unlabelled), the identity within a rule.
52
+ model AlertIncident {
53
+ id String @id @default(uuid()) @db.Uuid
54
+ ruleId String @map("rule_id") @db.Uuid
55
+ labelsKey String @map("labels_key") @db.VarChar(512)
56
+ labels Json
57
+ state String @db.VarChar(16)
58
+ severity String @db.VarChar(16)
59
+ pendingSince DateTime? @map("pending_since") @db.Timestamptz
60
+ firedAt DateTime? @map("fired_at") @db.Timestamptz
61
+ resolvedAt DateTime? @map("resolved_at") @db.Timestamptz
62
+ lastValue Float? @map("last_value")
63
+ lastSeenAt DateTime @map("last_seen_at") @db.Timestamptz
64
+ summary String @db.VarChar(500)
65
+ acknowledgedAt DateTime? @map("acknowledged_at") @db.Timestamptz
66
+ acknowledgedById String? @map("acknowledged_by_id") @db.Uuid
67
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
68
+
69
+ rule AlertRule @relation(fields: [ruleId], references: [id], onDelete: Cascade)
70
+
71
+ @@index([ruleId, state])
72
+ @@index([state, firedAt])
73
+ @@index([resolvedAt])
74
+ @@map("alert_incidents")
75
+ }
@@ -535,6 +535,10 @@ model WorkerNode {
535
535
  // this list from ever forcing a `Job` deletion.
536
536
  claimedJobs Job[] @relation("NodeClaimedJobs")
537
537
 
538
+ // Events the node reported about itself (power source changes, ...). Cascades
539
+ // with the node: an event has no meaning once its node is gone.
540
+ events WorkerNodeEvent[]
541
+
538
542
  // THE register-or-reattach anchor (#268's own words: "existing exactly
539
543
  // this way"). A node identifies itself to `/nodes/register` by
540
544
  // `(callerId, name)`; this is what lets that endpoint find-or-create
@@ -556,6 +560,35 @@ model WorkerNode {
556
560
  @@map("worker_nodes")
557
561
  }
558
562
 
563
+ // -----------------------------------------------------------------------------
564
+ // WorkerNodeEvent — an event a worker node reported about itself (#1045)
565
+ // -----------------------------------------------------------------------------
566
+ // `type` is an open registry key (e.g. `power.source_changed`), a plain string
567
+ // for the same reason `Job.type` is: a new event type costs zero migrations.
568
+ // `severity` is `info | warning | critical`, validated in the API. `attrs` is
569
+ // opaque node-supplied JSON, displayed and never filtered. `occurredAt` is the
570
+ // node's clock; `receivedAt` is the server's, so skew is visible. Cascades with
571
+ // the node. No row-level security (worker_nodes has none).
572
+ model WorkerNodeEvent {
573
+ id String @id @default(uuid()) @db.Uuid
574
+
575
+ nodeId String @map("node_id") @db.Uuid
576
+ node WorkerNode @relation(fields: [nodeId], references: [id], onDelete: Cascade)
577
+
578
+ type String @db.VarChar(64)
579
+ severity String @db.VarChar(16)
580
+ attrs Json? @db.JsonB
581
+
582
+ occurredAt DateTime @map("occurred_at") @db.Timestamptz
583
+ receivedAt DateTime @default(now()) @map("received_at") @db.Timestamptz
584
+
585
+ // "This node's newest events" — the fleet page's timeline.
586
+ @@index([nodeId, receivedAt(sort: Desc)])
587
+ // Retention sweeps by age.
588
+ @@index([receivedAt])
589
+ @@map("worker_node_events")
590
+ }
591
+
559
592
  enum NodeStatus {
560
593
  online
561
594
  draining
@@ -0,0 +1,108 @@
1
+ // =============================================================================
2
+ // Outbound webhooks (issue #1046)
3
+ // =============================================================================
4
+ //
5
+ // Two org-owned tables under row-level security (policy `<table>_org_isolation`,
6
+ // raw SQL in the migration, listed in rls-policies.json).
7
+ //
8
+ // `org_id` is NULLABLE on both: NULL only for a `system`-scope endpoint (and the
9
+ // deliveries it produces), which is visible to the bypass (system) client only,
10
+ // exactly like `ai_usage_events`. An org row's `org_id` is never NULL.
11
+ //
12
+ // A delivery carries its endpoint's `org_id` (copied at fan-out) because a
13
+ // policy cannot join through its parent. The endpoint link is a simple FK on
14
+ // `endpoint_id` (ON DELETE CASCADE), not a composite `(endpoint_id, org_id)`:
15
+ // `org_id` is nullable here, and a composite foreign key with a NULL column is
16
+ // not enforced (MATCH SIMPLE), so it would add no isolation. The fan-out code
17
+ // is the only writer and copies `org_id` from the endpoint row it just read.
18
+ //
19
+ // The signing secret is never a column: it lives in the encrypted credentials
20
+ // store, versioned by `secretVersion`. These rows hold no secret material.
21
+
22
+ enum WebhookScope {
23
+ user
24
+ org
25
+ system
26
+ }
27
+
28
+ enum WebhookDeliveryStatus {
29
+ pending
30
+ delivering
31
+ succeeded
32
+ failed
33
+ dead
34
+ }
35
+
36
+ /// A destination URL subscribed to platform events. `scope` = user: owned by
37
+ /// `ownerUserId` (receives only events that user may see); org: an
38
+ /// organization's endpoint; system: a deployment-wide endpoint (`orgId` NULL).
39
+ /// `eventKeys` holds exact keys, a trailing wildcard (`nodes.*`) or `*`.
40
+ model WebhookEndpoint {
41
+ id String @id @default(uuid()) @db.Uuid
42
+ orgId String? @map("org_id") @db.Uuid
43
+ scope WebhookScope
44
+ ownerUserId String? @map("owner_user_id") @db.Uuid
45
+ createdById String? @map("created_by_id") @db.Uuid
46
+ name String @db.VarChar(120)
47
+ description String? @db.VarChar(500)
48
+ url String @db.VarChar(2048)
49
+ eventKeys String[] @map("event_keys")
50
+ enabled Boolean @default(true)
51
+ secretVersion Int @default(1) @map("secret_version")
52
+ previousSecretUntil DateTime? @map("previous_secret_until") @db.Timestamptz
53
+ consecutiveFailures Int @default(0) @map("consecutive_failures")
54
+ disabledReason String? @map("disabled_reason") @db.VarChar(64)
55
+ lastDeliveryAt DateTime? @map("last_delivery_at") @db.Timestamptz
56
+ lastSuccessAt DateTime? @map("last_success_at") @db.Timestamptz
57
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
58
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
59
+
60
+ // Deleting the owning user (or the organization) deletes the endpoint and,
61
+ // through it, its deliveries.
62
+ owner User? @relation("WebhookEndpointOwner", fields: [ownerUserId], references: [id], onDelete: Cascade)
63
+ organization Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
64
+ deliveries WebhookDelivery[]
65
+
66
+ @@index([orgId, scope, enabled])
67
+ @@index([ownerUserId])
68
+ @@map("webhook_endpoints")
69
+ }
70
+
71
+ /// One attempt chain of one event to one endpoint. `id` is also the
72
+ /// `webhook-id` header, stable across retries. `payload` is the exact JSON body
73
+ /// sent (already redacted). `@@unique([endpointId, eventId])` makes fan-out
74
+ /// idempotent per endpoint and event.
75
+ model WebhookDelivery {
76
+ id String @id @default(uuid()) @db.Uuid
77
+ orgId String? @map("org_id") @db.Uuid
78
+ endpointId String @map("endpoint_id") @db.Uuid
79
+ eventKey String @map("event_key") @db.VarChar(128)
80
+ eventId String @map("event_id") @db.Uuid
81
+ payload Json
82
+ status WebhookDeliveryStatus @default(pending)
83
+ attempt Int @default(0)
84
+ responseStatus Int? @map("response_status")
85
+ responseSnippet String? @map("response_snippet") @db.VarChar(1024)
86
+ errorCode String? @map("error_code") @db.VarChar(64)
87
+ durationMs Int? @map("duration_ms")
88
+ nextAttemptAt DateTime? @map("next_attempt_at") @db.Timestamptz
89
+ deliveredAt DateTime? @map("delivered_at") @db.Timestamptz
90
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
91
+
92
+ endpoint WebhookEndpoint @relation(fields: [endpointId], references: [id], onDelete: Cascade)
93
+
94
+ @@unique([endpointId, eventId])
95
+ @@index([endpointId, createdAt(sort: Desc)])
96
+ @@index([orgId, createdAt])
97
+ @@index([eventId])
98
+ @@index([createdAt])
99
+ @@map("webhook_deliveries")
100
+ }
101
+
102
+ extend model User {
103
+ webhookEndpoints WebhookEndpoint[] @relation("WebhookEndpointOwner")
104
+ }
105
+
106
+ extend model Organization {
107
+ webhookEndpoints WebhookEndpoint[]
108
+ }