@marinoscar/platform-db 0.0.0-stage → 0.1.0-next.3

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.
Files changed (208) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/LICENSE +21 -0
  3. package/README.md +382 -2
  4. package/bin/platform.js +28 -0
  5. package/dist/baseline/deps.d.ts +32 -0
  6. package/dist/baseline/deps.d.ts.map +1 -0
  7. package/dist/baseline/deps.js +64 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +34 -0
  10. package/dist/baseline/errors.d.ts.map +1 -0
  11. package/dist/baseline/errors.js +23 -0
  12. package/dist/baseline/errors.js.map +1 -0
  13. package/dist/baseline/fs.d.ts +9 -0
  14. package/dist/baseline/fs.d.ts.map +1 -0
  15. package/dist/baseline/fs.js +39 -0
  16. package/dist/baseline/fs.js.map +1 -0
  17. package/dist/baseline/index.d.ts +8 -0
  18. package/dist/baseline/index.d.ts.map +1 -0
  19. package/dist/baseline/index.js +24 -0
  20. package/dist/baseline/index.js.map +1 -0
  21. package/dist/baseline/mapping.d.ts +43 -0
  22. package/dist/baseline/mapping.d.ts.map +1 -0
  23. package/dist/baseline/mapping.js +80 -0
  24. package/dist/baseline/mapping.js.map +1 -0
  25. package/dist/baseline/normalise.d.ts +42 -0
  26. package/dist/baseline/normalise.d.ts.map +1 -0
  27. package/dist/baseline/normalise.js +133 -0
  28. package/dist/baseline/normalise.js.map +1 -0
  29. package/dist/baseline/plan.d.ts +66 -0
  30. package/dist/baseline/plan.d.ts.map +1 -0
  31. package/dist/baseline/plan.js +105 -0
  32. package/dist/baseline/plan.js.map +1 -0
  33. package/dist/baseline/report.d.ts +125 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +85 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +106 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +339 -0
  40. package/dist/baseline/run.js.map +1 -0
  41. package/dist/bin/db-commands.d.ts +31 -0
  42. package/dist/bin/db-commands.d.ts.map +1 -0
  43. package/dist/bin/db-commands.js +276 -0
  44. package/dist/bin/db-commands.js.map +1 -0
  45. package/dist/bin/fs-io.d.ts +7 -0
  46. package/dist/bin/fs-io.d.ts.map +1 -0
  47. package/dist/bin/fs-io.js +45 -0
  48. package/dist/bin/fs-io.js.map +1 -0
  49. package/dist/bin/platform.d.ts +21 -0
  50. package/dist/bin/platform.d.ts.map +1 -0
  51. package/dist/bin/platform.js +99 -0
  52. package/dist/bin/platform.js.map +1 -0
  53. package/dist/compose/api.d.ts +84 -0
  54. package/dist/compose/api.d.ts.map +1 -0
  55. package/dist/compose/api.js +101 -0
  56. package/dist/compose/api.js.map +1 -0
  57. package/dist/compose/compose.d.ts +51 -0
  58. package/dist/compose/compose.d.ts.map +1 -0
  59. package/dist/compose/compose.js +177 -0
  60. package/dist/compose/compose.js.map +1 -0
  61. package/dist/compose/diff.d.ts +7 -0
  62. package/dist/compose/diff.d.ts.map +1 -0
  63. package/dist/compose/diff.js +68 -0
  64. package/dist/compose/diff.js.map +1 -0
  65. package/dist/compose/errors.d.ts +31 -0
  66. package/dist/compose/errors.d.ts.map +1 -0
  67. package/dist/compose/errors.js +35 -0
  68. package/dist/compose/errors.js.map +1 -0
  69. package/dist/compose/index.d.ts +3 -0
  70. package/dist/compose/index.d.ts.map +1 -0
  71. package/dist/compose/index.js +11 -0
  72. package/dist/compose/index.js.map +1 -0
  73. package/dist/compose/parse.d.ts +65 -0
  74. package/dist/compose/parse.d.ts.map +1 -0
  75. package/dist/compose/parse.js +122 -0
  76. package/dist/compose/parse.js.map +1 -0
  77. package/dist/drift/db-conformance.d.ts +49 -0
  78. package/dist/drift/db-conformance.d.ts.map +1 -0
  79. package/dist/drift/db-conformance.js +65 -0
  80. package/dist/drift/db-conformance.js.map +1 -0
  81. package/dist/drift/index.d.ts +5 -0
  82. package/dist/drift/index.d.ts.map +1 -0
  83. package/dist/drift/index.js +26 -0
  84. package/dist/drift/index.js.map +1 -0
  85. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  86. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  87. package/dist/drift/raw-sql-indexes.js +113 -0
  88. package/dist/drift/raw-sql-indexes.js.map +1 -0
  89. package/dist/drift/raw-sql-tripwire.d.ts +150 -0
  90. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-tripwire.js +394 -0
  92. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  93. package/dist/drift/run.d.ts +128 -0
  94. package/dist/drift/run.d.ts.map +1 -0
  95. package/dist/drift/run.js +201 -0
  96. package/dist/drift/run.js.map +1 -0
  97. package/dist/index.d.ts +16 -0
  98. package/dist/index.d.ts.map +1 -0
  99. package/dist/index.js +33 -0
  100. package/dist/index.js.map +1 -0
  101. package/dist/lock/hash.d.ts +13 -0
  102. package/dist/lock/hash.d.ts.map +1 -0
  103. package/dist/lock/hash.js +19 -0
  104. package/dist/lock/hash.js.map +1 -0
  105. package/dist/lock/index.d.ts +5 -0
  106. package/dist/lock/index.d.ts.map +1 -0
  107. package/dist/lock/index.js +20 -0
  108. package/dist/lock/index.js.map +1 -0
  109. package/dist/lock/lock.d.ts +117 -0
  110. package/dist/lock/lock.d.ts.map +1 -0
  111. package/dist/lock/lock.js +140 -0
  112. package/dist/lock/lock.js.map +1 -0
  113. package/dist/lock/manifest.d.ts +60 -0
  114. package/dist/lock/manifest.d.ts.map +1 -0
  115. package/dist/lock/manifest.js +95 -0
  116. package/dist/lock/manifest.js.map +1 -0
  117. package/dist/lock/semver.d.ts +10 -0
  118. package/dist/lock/semver.d.ts.map +1 -0
  119. package/dist/lock/semver.js +13 -0
  120. package/dist/lock/semver.js.map +1 -0
  121. package/dist/seed/index.d.ts +4 -0
  122. package/dist/seed/index.d.ts.map +1 -0
  123. package/dist/seed/index.js +10 -0
  124. package/dist/seed/index.js.map +1 -0
  125. package/dist/seed/input.d.ts +52 -0
  126. package/dist/seed/input.d.ts.map +1 -0
  127. package/dist/seed/input.js +77 -0
  128. package/dist/seed/input.js.map +1 -0
  129. package/dist/seed/seed-platform.d.ts +28 -0
  130. package/dist/seed/seed-platform.d.ts.map +1 -0
  131. package/dist/seed/seed-platform.js +133 -0
  132. package/dist/seed/seed-platform.js.map +1 -0
  133. package/dist/seed/types.d.ts +277 -0
  134. package/dist/seed/types.d.ts.map +1 -0
  135. package/dist/seed/types.js +5 -0
  136. package/dist/seed/types.js.map +1 -0
  137. package/dist/sync/apply.d.ts +29 -0
  138. package/dist/sync/apply.d.ts.map +1 -0
  139. package/dist/sync/apply.js +37 -0
  140. package/dist/sync/apply.js.map +1 -0
  141. package/dist/sync/check.d.ts +56 -0
  142. package/dist/sync/check.d.ts.map +1 -0
  143. package/dist/sync/check.js +108 -0
  144. package/dist/sync/check.js.map +1 -0
  145. package/dist/sync/errors.d.ts +31 -0
  146. package/dist/sync/errors.d.ts.map +1 -0
  147. package/dist/sync/errors.js +23 -0
  148. package/dist/sync/errors.js.map +1 -0
  149. package/dist/sync/index.d.ts +9 -0
  150. package/dist/sync/index.d.ts.map +1 -0
  151. package/dist/sync/index.js +25 -0
  152. package/dist/sync/index.js.map +1 -0
  153. package/dist/sync/ledger.d.ts +65 -0
  154. package/dist/sync/ledger.d.ts.map +1 -0
  155. package/dist/sync/ledger.js +49 -0
  156. package/dist/sync/ledger.js.map +1 -0
  157. package/dist/sync/plan.d.ts +61 -0
  158. package/dist/sync/plan.d.ts.map +1 -0
  159. package/dist/sync/plan.js +79 -0
  160. package/dist/sync/plan.js.map +1 -0
  161. package/dist/sync/promote.d.ts +58 -0
  162. package/dist/sync/promote.d.ts.map +1 -0
  163. package/dist/sync/promote.js +93 -0
  164. package/dist/sync/promote.js.map +1 -0
  165. package/dist/sync/timestamps.d.ts +41 -0
  166. package/dist/sync/timestamps.d.ts.map +1 -0
  167. package/dist/sync/timestamps.js +68 -0
  168. package/dist/sync/timestamps.js.map +1 -0
  169. package/dist/sync/version.d.ts +28 -0
  170. package/dist/sync/version.d.ts.map +1 -0
  171. package/dist/sync/version.js +66 -0
  172. package/dist/sync/version.js.map +1 -0
  173. package/migrations/0001_initial/migration.sql +297 -0
  174. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  175. package/migrations/0003_add_credentials/migration.sql +20 -0
  176. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  177. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  178. package/migrations/0006_add_notifications/migration.sql +22 -0
  179. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  180. package/migrations/0008_add_jobs/migration.sql +110 -0
  181. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  182. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  183. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  184. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  185. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  186. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  187. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  188. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  189. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  190. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  191. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  192. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  193. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  194. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  195. package/migrations/0023_add_organizations/migration.sql +142 -0
  196. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  197. package/migrations/manifest.json +240 -0
  198. package/package.json +75 -4
  199. package/raw-sql-indexes.json +49 -0
  200. package/schema/ai.prisma +387 -0
  201. package/schema/base.prisma +11 -0
  202. package/schema/credentials.prisma +108 -0
  203. package/schema/db-backup.prisma +376 -0
  204. package/schema/identity.prisma +407 -0
  205. package/schema/jobs.prisma +731 -0
  206. package/schema/notifications.prisma +610 -0
  207. package/schema/settings.prisma +35 -0
  208. package/schema/storage.prisma +57 -0
@@ -0,0 +1,731 @@
1
+ // =============================================================================
2
+ // Jobs (issue #255, epic #254)
3
+ // =============================================================================
4
+ //
5
+ // A generic background-job queue table: one row per unit of work a worker
6
+ // node claims, runs, and reports the outcome of. This issue adds only the
7
+ // schema — the enqueue path, the claim query, and the node plane that
8
+ // actually pulls jobs off this table all arrive in later issues of #254
9
+ // (the claim query's `RETURNING` aliases land in #260, the `WorkerNode` model
10
+ // that `claimedByNodeId` will finally point at lands with the node plane).
11
+ // What is here is deliberately complete on its own: every column and index a
12
+ // worker needs to claim, execute, retry, and rate-limit a job, so nothing
13
+ // downstream requires a follow-up migration to `jobs` itself.
14
+ //
15
+ // -----------------------------------------------------------------------------
16
+ // subjectType / subjectId — plain nullable TEXT, not typed or FK'd columns
17
+ // -----------------------------------------------------------------------------
18
+ // REJECTED: a column per subject shape (`mediaItemId`, `circleId`, ...). This
19
+ // table is generic across every handler `type` this app will ever register,
20
+ // present and future. A typed column per subject means every new job kind
21
+ // that targets a new kind of thing is a migration to this table, which is
22
+ // exactly the coupling a job queue must not have to its callers — the whole
23
+ // point of `type` being a free-form handler key is that new handlers cost
24
+ // zero schema changes. `subjectType` (a short discriminator string the
25
+ // handler itself defines, e.g. `'media_item'`) plus `subjectId` (that
26
+ // subject's id, stored as text specifically so it is not assumed to be a
27
+ // UUID — some future subject might key by something else) covers every shape
28
+ // with two columns, forever.
29
+ //
30
+ // REJECTED: payload-only, with no subject columns at all (dig the subject id
31
+ // out of the JSONB `payload` when you need it). This is what `[subjectType,
32
+ // subjectId]` below exists to make wrong: "cancel every pending job for this
33
+ // media item" and "is there already an active job for this exact subject"
34
+ // (the dedup index just below) are both real, known queries (not
35
+ // speculative), and neither is expressible as an index over JSONB without a
36
+ // GIN index and a much more awkward query. Two plain columns, indexed
37
+ // normally, are simpler and cheaper than making Postgres reach into JSON for
38
+ // a value that is known and named at enqueue time regardless.
39
+ //
40
+ // Both nullable, and BOTH null together is the documented spelling of "this
41
+ // is a global/system job" (a nightly sweep, a cache warm) that is not about
42
+ // any one row elsewhere in the database — there is no sentinel subjectType
43
+ // like `'system'` to keep in sync with anything.
44
+ //
45
+ // -----------------------------------------------------------------------------
46
+ // dedupKey / the active-dedup unique index — enforced by a hand-written
47
+ // partial index, NOT `findFirst` then `create` in the enqueue service
48
+ // -----------------------------------------------------------------------------
49
+ // REJECTED: "check whether an active job with this key already exists, and
50
+ // only insert if not" as application logic. That is a check-then-act race:
51
+ // two concurrent enqueue calls can both see "no active duplicate" and both
52
+ // insert, which is precisely the failure a dedup key exists to prevent, and
53
+ // under real concurrent load (a webhook retried while the first delivery is
54
+ // still being handled, two nodes reacting to the same event) it is not a
55
+ // rare edge case. Only the database can make "is there already an active job
56
+ // with this key" atomic with the insert that would violate it, which is what
57
+ // `jobs_active_dedup_uniq_idx` below is for: a partial UNIQUE index on
58
+ // `dedup_key` filtered to `status IN ('pending','running')`. The enqueue path
59
+ // (arriving with #260) inserts optimistically and treats the resulting
60
+ // unique-violation as "a duplicate is already in flight", not as an error —
61
+ // no pre-check query, no race window.
62
+ //
63
+ // The partial filter is exactly what makes the key reusable: once a job
64
+ // reaches `succeeded` (or `failed`) it drops out of the index's predicate, so
65
+ // the same `dedup_key` is free again for a new active job — retrying or
66
+ // re-triggering the same logical work later is not permanently blocked by
67
+ // its own history. `dedup_key IS NOT NULL` in the predicate is what lets
68
+ // jobs that opt out of dedup (most ad-hoc jobs) insert freely with a NULL key
69
+ // — Postgres does not consider NULLs equal for uniqueness, but the explicit
70
+ // clause documents that this is relied upon, not incidental.
71
+ //
72
+ // The key's actual format (`type:subjectType:subjectId`) is defined ONCE, in
73
+ // `buildDedupKey()` (`src/jobs/job-keys.ts`), which this comment and the
74
+ // migration's raw SQL both point back to rather than restating it — see that
75
+ // file for why the format is what it is.
76
+ //
77
+ // -----------------------------------------------------------------------------
78
+ // priority — ASCENDING is more urgent
79
+ // -----------------------------------------------------------------------------
80
+ // Chosen so `ORDER BY priority ASC, created_at ASC` is both "most urgent
81
+ // first" and "oldest first within a priority", the same direction Postgres
82
+ // already walks a plain ascending b-tree index in — no `DESC` index variant
83
+ // needed for the hot claim-query ordering that `[status, priority,
84
+ // createdAt]` and `[status, scheduledFor, priority, createdAt]` below exist
85
+ // to serve. `0` is the default (normal) priority; more urgent work is a
86
+ // smaller (including negative) number, not a larger one.
87
+ //
88
+ // -----------------------------------------------------------------------------
89
+ // attempts vs rateLimitedAt/rateLimitHits — two counters for two different
90
+ // reasons a job didn't finish, deliberately not merged into one
91
+ // -----------------------------------------------------------------------------
92
+ // `attempts` is charged AT CLAIM TIME (incremented when a worker takes the
93
+ // job, not when it fails) and is what a max-retry policy reads. Being rate
94
+ // limited by a downstream provider is not the job's fault and is not a
95
+ // retry in that sense — charging it against `attempts` would make a job that
96
+ // is simply waiting its turn look like a job that keeps failing, and could
97
+ // exhaust its retry budget for a reason that has nothing to do with the
98
+ // job's own correctness. `rateLimitedAt` / `rateLimitHits` track that
99
+ // separately: `scheduledFor` is pushed out to defer the job, `rateLimitHits`
100
+ // records how often this has happened (for observability/alerting on a
101
+ // provider that is persistently saturated), and neither touches `attempts`.
102
+ //
103
+ // -----------------------------------------------------------------------------
104
+ // providerKey / modelVersion — audit of WHAT ran the job, not inputs to it
105
+ // -----------------------------------------------------------------------------
106
+ // Both nullable and both write-once-at-completion-time metadata: which
107
+ // downstream provider handled this job and which model/version it ran
108
+ // against, for after-the-fact questions ("did the incident affect jobs that
109
+ // ran on provider X" / "which jobs ran before the model version bump").
110
+ // Neither is read back by the claim query — they exist for audit, not for
111
+ // scheduling.
112
+ //
113
+ // -----------------------------------------------------------------------------
114
+ // claimedByNodeId — a real relation as of issue #267, epic #254
115
+ // -----------------------------------------------------------------------------
116
+ // This column existed unconstrained (`String? @db.Uuid`) from #255 onward, so
117
+ // the claim query and its indexes ([status, leaseExpiresAt],
118
+ // [claimedByNodeId]) could be built against their final shape before the
119
+ // `WorkerNode` table it references existed. #267 adds that table and wires
120
+ // the FK on top of this already-populated column: `onDelete: SetNull`, so a
121
+ // node's disappearance (deregistered, pruned, or manually deleted by an
122
+ // admin) frees the jobs it was holding — via `leaseExpiresAt` already having
123
+ // them look abandoned to the reaper — rather than deleting job history. See
124
+ // the block comment above the `WorkerNode` model for the corresponding
125
+ // `onDelete` decision on `WorkerNode.createdBy`, which is a different
126
+ // question (what happens to the NODE when its owning USER is deleted, not
127
+ // what happens to a JOB when its claiming NODE is deleted).
128
+ //
129
+ // -----------------------------------------------------------------------------
130
+ // claimToken — per-claim identity, closing the two-replica lease hole
131
+ // (issue #361)
132
+ // -----------------------------------------------------------------------------
133
+ // `claimedByNodeId` distinguishes a node's claim from the server's, but every
134
+ // API replica claims with `claimedByNodeId: null` — so two different server
135
+ // replicas produce an IDENTICAL `heldLeaseWhere` predicate for the same job,
136
+ // and one replica's renewal cannot be told apart from another's. `claimToken`
137
+ // is minted fresh per claim (not per process, not per batch — see the field
138
+ // comment below for why that distinction matters) and is the extra predicate
139
+ // that makes a specific claim, not just a specific kind of claimant,
140
+ // checkable. Nullable with no default, same as `claimedByNodeId` and
141
+ // `leaseExpiresAt`: `NULL` iff not currently claimed, no backfill, no index —
142
+ // see the migration header (`20260908120000_add_job_claim_token`) for the
143
+ // full argument, which this comment does not restate.
144
+ //
145
+ // -----------------------------------------------------------------------------
146
+ // sumDurationMs on JobStatsRollup — Float (double precision), NOT BigInt
147
+ // -----------------------------------------------------------------------------
148
+ // REJECTED: BigInt. Prisma maps a BigInt column to the JS `bigint` primitive,
149
+ // which `JSON.stringify` refuses outright ("Do not know how to serialize a
150
+ // BigInt") — the not-yet-built insights endpoint that reads this rollup would
151
+ // crash on its very first response, not degrade gracefully. A running sum of
152
+ // per-job durations in milliseconds, even at very high job volume, never
153
+ // approaches the ~2^53 safe-integer boundary where `Float` would start
154
+ // losing precision that matters for an aggregate (an average duration off by
155
+ // fractions of a millisecond at that scale is not a real-world concern);
156
+ // BigInt's exactness buys nothing here and costs a runtime crash.
157
+ //
158
+ // -----------------------------------------------------------------------------
159
+ // Prisma-expressible indexes vs the three below written directly in the
160
+ // migration (INTENTIONAL SCHEMA DRIFT — see migration.sql in
161
+ // 20260906120000_add_jobs)
162
+ // -----------------------------------------------------------------------------
163
+ // Everything Prisma's index DSL can express is declared with `@@index` below.
164
+ // Three more indexes exist ONLY in `migration.sql` because the Prisma schema
165
+ // language has no syntax for a partial index (a `WHERE` clause on the index
166
+ // itself) — `@@index` always builds a full index over every row:
167
+ //
168
+ // - "jobs_active_dedup_uniq_idx": the partial UNIQUE index described above
169
+ // that actually enforces the active-dedup constraint (`dedup_key` where
170
+ // `status IN ('pending','running') AND dedup_key IS NOT NULL`).
171
+ // - "jobs_attempts_gt1_idx": a partial index on `attempts` where
172
+ // `attempts > 1`, sized to the small minority of jobs that have ever
173
+ // been retried, for "show me flaky jobs" without indexing the (large)
174
+ // majority that succeeded on the first attempt.
175
+ // - "jobs_succeeded_duration_idx": a partial index on
176
+ // `(finished_at, started_at, type)` where `status = 'succeeded' AND
177
+ // started_at IS NOT NULL AND finished_at IS NOT NULL`, for computing
178
+ // per-type duration stats (what feeds `JobStatsRollup`) without scanning
179
+ // jobs that were never actually timed.
180
+ //
181
+ // Because `prisma migrate dev`/`diff` cannot regenerate these from the
182
+ // schema file, they will show up as "drift" if anyone ever diffs this schema
183
+ // against the live database with a tool that expects `@@index` to be the
184
+ // full story. That drift is intentional and this comment (plus the ones in
185
+ // the migration itself) is the record of why — do not "fix" it by dropping
186
+ // these three indexes, and do not try to force them into `@@index` syntax
187
+ // that does not exist.
188
+ // @extensible — back-relations only, added with "extend model Job { ... }" in a fragment
189
+ model Job {
190
+ id String @id @default(uuid()) @db.Uuid
191
+
192
+ // The handler key a worker dispatches on (e.g. `'email.send'`,
193
+ // `'export.csv'`). A small, code-owned, growing set — deliberately a plain
194
+ // string and not a Prisma enum, for the same reason `NotificationDelivery
195
+ // .channel` and `.eventKey` are plain strings: new handlers must cost zero
196
+ // migrations, and a row must be able to outlive the handler that produced
197
+ // it (a removed/renamed handler's historical jobs stay queryable).
198
+ type String
199
+
200
+ // See the block comment above for why these are plain nullable TEXT rather
201
+ // than typed/FK'd columns, and why both null together means a
202
+ // global/system job.
203
+ subjectType String? @map("subject_type")
204
+ subjectId String? @map("subject_id")
205
+
206
+ // See the block comment above ("dedupKey / the active-dedup unique index")
207
+ // for the full mechanism. Built by `buildDedupKey()`
208
+ // (`src/jobs/job-keys.ts`); nullable because most jobs opt out of dedup
209
+ // entirely.
210
+ dedupKey String? @map("dedup_key")
211
+
212
+ status JobStatus @default(pending)
213
+ reason JobReason
214
+
215
+ // Ascending = more urgent. See the block comment above.
216
+ priority Int @default(0)
217
+
218
+ // Audit of what actually ran this job — see the block comment above.
219
+ // Written once, at completion; never read by the claim query.
220
+ providerKey String? @map("provider_key")
221
+ modelVersion String? @map("model_version")
222
+
223
+ // Handler-defined input, opaque to this table.
224
+ payload Json? @db.JsonB
225
+
226
+ // Charged AT CLAIM TIME (see the block comment above for why this is kept
227
+ // separate from rateLimitHits).
228
+ attempts Int @default(0)
229
+
230
+ lastError String? @map("last_error")
231
+
232
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
233
+ startedAt DateTime? @map("started_at") @db.Timestamptz
234
+ finishedAt DateTime? @map("finished_at") @db.Timestamptz
235
+
236
+ // NULL means eligible now. A non-null value in the future is what makes a
237
+ // job invisible to the claim query until then (deferred rate-limit retries,
238
+ // deliberately scheduled work).
239
+ scheduledFor DateTime? @map("scheduled_for") @db.Timestamptz
240
+
241
+ // Deferral bookkeeping, deliberately separate from `attempts` — see the
242
+ // block comment above.
243
+ rateLimitedAt DateTime? @map("rate_limited_at") @db.Timestamptz
244
+ rateLimitHits Int @default(0) @map("rate_limit_hits")
245
+
246
+ // Node claiming. See the block comment above ("claimedByNodeId") for why
247
+ // this relation arrived a migration after the column did, and why
248
+ // `onDelete: SetNull` is correct here specifically.
249
+ claimedByNodeId String? @map("claimed_by_node_id") @db.Uuid
250
+ claimedByNode WorkerNode? @relation("NodeClaimedJobs", fields: [claimedByNodeId], references: [id], onDelete: SetNull)
251
+ leaseExpiresAt DateTime? @map("lease_expires_at") @db.Timestamptz
252
+ // 'server' | 'node' — which side actually executed the job. A plain
253
+ // string, not an enum, for the same "small closed set, but code-owned and
254
+ // not this table's own state machine" reasoning as
255
+ // NotificationDelivery.channel above.
256
+ executor String?
257
+
258
+ // The identity of ONE CLAIM, not one KIND of claimant (issue #361). Minted
259
+ // fresh by the claim statement itself (`gen_random_uuid()` in
260
+ // `job-claim.service.ts`) every time a job is claimed, so "do I still hold
261
+ // this row" is answerable without reference to who is asking —
262
+ // `claimedByNodeId` distinguishes a node's claim from the server's, but
263
+ // every server replica claims with `claimedByNodeId: null`, which makes
264
+ // two different replicas holding the SAME job at different times
265
+ // indistinguishable from each other. A token minted per row closes that:
266
+ // it must be minted PER CLAIM, not once per claiming process or per batch,
267
+ // because a process-level token has the identical defect one level up — it
268
+ // cannot tell one process apart from itself across two separate claims of
269
+ // the same job (claim, lose it to the reaper, claim it again).
270
+ //
271
+ // Non-null exactly while the row is claimed — the same "non-null iff held"
272
+ // invariant `claimedByNodeId`/`leaseExpiresAt` already carry. The claim
273
+ // writes it alongside them; every un-claim path (settle, the lease reaper,
274
+ // a retry reset) clears it in the same statement that clears them, never
275
+ // on its own.
276
+ //
277
+ // Deliberately NOT exposed by the admin API — `JOB_LIST_SELECT`
278
+ // (`job-admin.service.ts`) omits it. It is internal ownership machinery
279
+ // with no operator-facing meaning; an admin reading the job list cares
280
+ // which node holds a job, not which of that node's (or the server's)
281
+ // claims it currently is.
282
+ claimToken String? @map("claim_token") @db.Uuid
283
+
284
+ // The W3C `traceparent` of the span that was active when this job was
285
+ // ENQUEUED (issue #607), or NULL when nothing was being traced (OTel off, a
286
+ // cron tick with no active span, a row written before this column existed).
287
+ // Written once, by `JobsService` at insert time (`job-trace-context.ts`
288
+ // validates the format and bounds it at 256 characters); never updated.
289
+ // The server worker starts the job's span as a CHILD of it, and the node
290
+ // claim hands it to the node, so queued work stays connected to the request
291
+ // that queued it. Plain nullable TEXT: it is an opaque correlation handle,
292
+ // never a key, never indexed, never read by the claim query's WHERE.
293
+ traceContext String? @map("trace_context")
294
+
295
+ // See the block comment above ("Prisma-expressible indexes...") for why
296
+ // these eight are declared here and three more exist only in
297
+ // migration.sql.
298
+ //
299
+ // The hot claim-query orderings:
300
+ @@index([status, priority, createdAt])
301
+ @@index([status, scheduledFor, priority, createdAt])
302
+ // "Every job for this subject" / "is there already a job for this exact
303
+ // subject":
304
+ @@index([subjectType, subjectId])
305
+ // "How is this handler doing" (per-type status breakdown):
306
+ @@index([type, status])
307
+ // Lease expiry sweep (finding jobs whose claiming node went away):
308
+ @@index([status, leaseExpiresAt])
309
+ // "What is this node holding right now" — also backs the FK added by #267:
310
+ @@index([claimedByNodeId])
311
+ // Recency listings (admin job list, "what just happened"):
312
+ @@index([createdAt(sort: Desc)])
313
+ // Covering index: the two unconditional admin groupBy counts
314
+ // (`groupBy({ by: ['status'] })`-shaped queries) are answered entirely from
315
+ // this index — status, type and id are all it needs to project — so
316
+ // Postgres never has to visit the heap for them (index-only scan).
317
+ @@index([status, type, id])
318
+ @@map("jobs")
319
+ }
320
+
321
+ enum JobStatus {
322
+ pending
323
+ running
324
+ succeeded
325
+ failed
326
+ }
327
+
328
+ enum JobReason {
329
+ upload
330
+ rerun
331
+ backfill
332
+ }
333
+
334
+ // =============================================================================
335
+ // Job Stats Rollup (issue #255, epic #254)
336
+ // =============================================================================
337
+ //
338
+ // One row per `type` (Job.type), maintained incrementally as jobs finish
339
+ // rather than computed by aggregating the full `jobs` table on every read —
340
+ // `jobs` is expected to grow without bound (or be pruned independently of
341
+ // this rollup's needs), so a per-type COUNT/AVG over it is not something the
342
+ // not-yet-built insights endpoint should be doing on every request.
343
+ //
344
+ // `sumDurationMs` is `Float`, deliberately not `BigInt` — see the block
345
+ // comment above the `Job` model ("sumDurationMs on JobStatsRollup") for why
346
+ // BigInt would crash `JSON.stringify` at the exact place this rollup is
347
+ // meant to be read from. Average duration for a type is
348
+ // `sumDurationMs / durationSamples`, computed by the reader; this table
349
+ // stores the two accumulators, not the derived average, so re-deriving after
350
+ // a correction never requires touching historical precision.
351
+ model JobStatsRollup {
352
+ type String @id
353
+
354
+ succeededCount Int @default(0) @map("succeeded_count")
355
+ failedCount Int @default(0) @map("failed_count")
356
+
357
+ // See the block comment above for why Float, not BigInt.
358
+ sumDurationMs Float @default(0) @map("sum_duration_ms")
359
+ durationSamples Int @default(0) @map("duration_samples")
360
+
361
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
362
+
363
+ @@map("job_stats_rollup")
364
+ }
365
+
366
+ // =============================================================================
367
+ // Worker Nodes (issue #267, epic #254)
368
+ // =============================================================================
369
+ //
370
+ // This issue adds only the schema half of the node plane: `WorkerNode`
371
+ // itself, `NodeCredential` (the `nod_` bearer credential a node authenticates
372
+ // with), and the `Job.claimedByNode` relation deferred by #255 (see the
373
+ // block comment above the `Job` model, "claimedByNodeId"). The service that
374
+ // mints/validates `NodeCredential` tokens, the `/api/node-credentials`
375
+ // endpoints, and the `Bearer nod_` branch in `jwt-auth.guard.ts` all arrive
376
+ // in the same issue's backend half; the register/heartbeat/claim control
377
+ // plane that actually populates and mutates `WorkerNode` rows is #268. What
378
+ // is here is deliberately complete on its own for that later work: every
379
+ // column and index the control plane needs already exists, so #268 requires
380
+ // no follow-up migration to either table.
381
+ //
382
+ // -----------------------------------------------------------------------------
383
+ // Why a `NodeCredential` distinct from `PersonalAccessToken`, not a reused PAT
384
+ // -----------------------------------------------------------------------------
385
+ // A worker node runs unattended for months on a machine its operator may not
386
+ // tightly control. A leaked PAT carries its owning user's FULL authority —
387
+ // admin routes included, if the owner is an admin. A node only ever needs to
388
+ // talk to `/api/nodes/*` (enforced by a route allowlist in the guard, not by
389
+ // this schema), so its credential is a distinct token family precisely so a
390
+ // leak's blast radius is confined to that allowlist even for an admin owner.
391
+ // `NodeCredential` mirrors `PersonalAccessToken`'s shape — same hash/prefix
392
+ // pattern, same show-once-in-full contract — MINUS the duration bookkeeping;
393
+ // see the block comment on `NodeCredential.expiresAt` below for why that one
394
+ // column is deliberately not carried over.
395
+ model WorkerNode {
396
+ id String @id @default(uuid()) @db.Uuid
397
+
398
+ name String
399
+
400
+ // Self-reported identity, refreshed on every successful register/reattach
401
+ // and heartbeat (#268) — none of these three are queried on individually,
402
+ // they exist for the fleet page and for operators diagnosing "which
403
+ // process is this row". Not part of any uniqueness: a node can rename its
404
+ // hostname or upgrade its CLI without becoming a different node, because
405
+ // identity is `(createdById, name)`, not any of these.
406
+ hostname String
407
+ platform String
408
+ cliVersion String @map("cli_version")
409
+
410
+ // The handler `type` keys (see `Job.type`'s own comment for why that column
411
+ // is a plain string, not an enum) this node is willing to claim. #268's
412
+ // claim endpoint INTERSECTS a request's requested types with this list — a
413
+ // node can only ever narrow what it claims, never broaden it beyond what it
414
+ // last declared itself capable of running.
415
+ eligibleTypes String[] @map("eligible_types")
416
+
417
+ // The node's own claimed concurrency ceiling, read LIVE by #268's claim
418
+ // endpoint (not cached at claim time) so a runtime `appctl node
419
+ // set-concurrency` takes effect on the very next claim without a
420
+ // re-register.
421
+ concurrency Int
422
+
423
+ // Operator/administrative state, NOT liveness — a node can be `online` and
424
+ // still be silently dead; that question is answered by comparing
425
+ // `lastHeartbeatAt` against the heartbeat interval, elsewhere (#270's fleet
426
+ // cron), not by this column. `disabled` is the operator-driven kill switch
427
+ // (refuse this node's claims regardless of what it reports); `draining` is
428
+ // "finish what you're holding, claim nothing new" — both are decisions a
429
+ // human or #270's lifecycle cron makes, not facts the node reports about
430
+ // itself.
431
+ status NodeStatus @default(offline)
432
+
433
+ // The node's last self-reported capability summary (CPU/RAM, GPU
434
+ // presence, disk headroom, ... — the exact shape is #268/#276's to define,
435
+ // not this schema's) from register or heartbeat. JSONB, not typed columns,
436
+ // for the same reason `Job.payload` is JSONB: this is opaque, evolving,
437
+ // node-supplied data that no query here needs to filter or index on —
438
+ // it exists for the fleet page to display, not for this table to reason
439
+ // about. Nullable: a node that has never heartbeated has reported nothing
440
+ // yet.
441
+ capabilities Json? @db.JsonB
442
+
443
+ // When this row was first created (register), vs. `lastHeartbeatAt` below
444
+ // which moves on every liveness ping. Distinct on purpose: "how long has
445
+ // this node existed" and "is it still alive" are different questions, and
446
+ // collapsing them into one timestamp would lose the first once the second
447
+ // starts moving.
448
+ registeredAt DateTime @default(now()) @map("registered_at") @db.Timestamptz
449
+
450
+ // NULL until the first heartbeat. #270's liveness/prune cron reads this to
451
+ // decide a node has gone dark; #268's lease reaper reads `Job
452
+ // .leaseExpiresAt` for the same question about an individual claim — the
453
+ // two are deliberately independent so a node with no jobs currently
454
+ // claimed still shows up as stale when it stops heartbeating.
455
+ lastHeartbeatAt DateTime? @map("last_heartbeat_at") @db.Timestamptz
456
+
457
+ // The node's last self-reported vitals snapshot (load, memory, disk, ...)
458
+ // carried on the heartbeat (#604). Opaque JSONB like `capabilities`: it is
459
+ // displayed, never filtered or indexed. `lastVitalsAt` is when the API
460
+ // stored it, so a stale snapshot is distinguishable from a fresh one.
461
+ // Both NULL until a heartbeat carries vitals.
462
+ lastVitals Json? @map("last_vitals") @db.JsonB
463
+ lastVitalsAt DateTime? @map("last_vitals_at") @db.Timestamptz
464
+
465
+ // The user who registered this node — see the long comment below for why
466
+ // this is required (not nullable) and `onDelete: Cascade`.
467
+ createdById String @map("created_by_id") @db.Uuid
468
+
469
+ // Relations
470
+ //
471
+ // -----------------------------------------------------------------------------
472
+ // createdBy — onDelete: Cascade, and `createdById` stays required
473
+ // -----------------------------------------------------------------------------
474
+ // This is NOT the audit-trail pattern this schema uses elsewhere
475
+ // (`AuditEvent.actorUserId`, `Credential.updatedByUser`,
476
+ // `NotificationDelivery.user` — all `SetNull`, all deliberately preserving a
477
+ // history record after its actor is gone). A `WorkerNode` is closer to
478
+ // `PushSubscription`: a LIVE registration with no standalone value once its
479
+ // owner is gone, not a record of a past event. Concretely:
480
+ //
481
+ // 1. `NodeCredential.user` is `onDelete: Cascade` (mirroring
482
+ // `PersonalAccessToken`, per this table's own design above) — so
483
+ // deleting the owning user ALREADY destroys every credential that
484
+ // could ever authenticate as this node. A `WorkerNode` row surviving
485
+ // its owner would be permanently unauthenticatable inventory: no
486
+ // token can ever heartbeat, claim, or deregister it again.
487
+ // 2. `assertOwnership` (#268) is `node.createdById === callerId` with no
488
+ // concept of "unowned" — a `SetNull`'d, ownerless node could not be
489
+ // managed (deregistered, disabled, viewed via `GET /nodes`) by
490
+ // anyone, ever, through the API this issue's sibling adds. It would
491
+ // sit as a permanently orphaned row no admin surface reaches.
492
+ // 3. `@@unique([createdById, name])` below is #268's register-or-reattach
493
+ // anchor. Keeping `createdById` NOT NULL keeps that constraint doing
494
+ // real work: two different (deleted-owner) nodes could otherwise both
495
+ // carry `createdById: null` with the same `name` and NOT collide
496
+ // (Postgres does not treat two NULLs as equal for uniqueness) — a
497
+ // silent hole in the exact invariant #268 depends on "existing
498
+ // exactly this way" for.
499
+ //
500
+ // Cascade does not touch job HISTORY: `Job.claimedByNode` is its own
501
+ // separate `onDelete: SetNull` (see the block comment above the `Job`
502
+ // model), so a cascaded `WorkerNode` deletion still only nulls out
503
+ // `claimedByNodeId` on whatever it was holding — it never deletes a `Job`
504
+ // row. Losing the fleet-inventory row (hostname, platform, capabilities
505
+ // history) when its owner's account is gone is an acceptable, even
506
+ // correct, cleanup; losing job history is not, and nothing here does that.
507
+ createdBy User @relation("UserWorkerNodes", fields: [createdById], references: [id], onDelete: Cascade)
508
+
509
+ // The jobs this node currently holds or has ever held. See `Job
510
+ // .claimedByNode`'s own comment for the `onDelete: SetNull` that keeps
511
+ // this list from ever forcing a `Job` deletion.
512
+ claimedJobs Job[] @relation("NodeClaimedJobs")
513
+
514
+ // THE register-or-reattach anchor (#268's own words: "existing exactly
515
+ // this way"). A node identifies itself to `/nodes/register` by
516
+ // `(callerId, name)`; this is what lets that endpoint find-or-create
517
+ // instead of always inserting, so a restarted container reattaches to its
518
+ // existing row (refreshing hostname/platform/cliVersion/eligibleTypes/
519
+ // concurrency and flipping back to `online`) rather than leaking a new
520
+ // node row on every restart. `name` is caller-chosen precisely so one
521
+ // user can register many distinctly-named nodes while each individual
522
+ // name stays idempotent for them.
523
+ @@unique([createdById, name])
524
+ // "Every online/draining/offline/disabled node" — the fleet page's own
525
+ // primary filter, and what #270's lifecycle cron scans to find nodes to
526
+ // act on.
527
+ @@index([status])
528
+ // "This user's own nodes" — backs `GET /nodes` (#268: "the caller's own
529
+ // nodes") and the ownership check inside `assertOwnership`, in addition to
530
+ // already being the left half of the composite unique index above.
531
+ @@index([createdById])
532
+ @@map("worker_nodes")
533
+ }
534
+
535
+ enum NodeStatus {
536
+ online
537
+ draining
538
+ offline
539
+ disabled
540
+ }
541
+
542
+ // -----------------------------------------------------------------------------
543
+ // NodeCredential — mirrors PersonalAccessToken minus the duration bookkeeping
544
+ // -----------------------------------------------------------------------------
545
+ // Same token lifecycle as `PersonalAccessToken` (`pat.service.ts` is the
546
+ // documented model for `NodeCredentialService`): a `nod_`-prefixed token is
547
+ // minted, hashed with sha256 into `tokenHash`, a short `tokenPrefix` is kept
548
+ // for display, and the raw value is shown exactly once. `validateToken`
549
+ // rejects an unknown hash, a `revokedAt`, an expired `expiresAt`, or an
550
+ // inactive owning user, then stamps `lastUsedAt` fire-and-forget — all of
551
+ // that is `NodeCredentialService`'s job (#267's backend half), not this
552
+ // schema's; this model exists to make those checks possible.
553
+ //
554
+ // -----------------------------------------------------------------------------
555
+ // expiresAt — nullable here, REQUIRED on PersonalAccessToken. This is the one
556
+ // deliberate divergence from the PAT shape, and it is worth writing out why.
557
+ // -----------------------------------------------------------------------------
558
+ // A PAT is typically minted for a person's own convenience (the CLI, a
559
+ // script they wrote) and a forced expiry is a reasonable default nudge
560
+ // toward rotation — a human is around to notice it expired and mint a new
561
+ // one. A `NodeCredential` authenticates a worker node that is expected to
562
+ // run UNATTENDED FOR MONTHS: a spare box, a container in someone else's
563
+ // cluster, a machine nobody is watching a dashboard for. If that credential
564
+ // had a mandatory expiry the way a PAT does, the failure mode is an entire
565
+ // fleet going dark at 3am because a timer nobody scheduled fired — the
566
+ // worker can't heartbeat, can't claim, can't report results, and the first
567
+ // anyone learns of it is jobs silently piling up unclaimed. That is a WORSE
568
+ // failure than a long-lived credential, because the credential's blast
569
+ // radius is already confined to `/api/nodes/*` by the guard's route
570
+ // allowlist (issue #267) even if it leaks — the thing a mandatory expiry on
571
+ // a PAT protects against (a leaked token with the owner's full authority)
572
+ // simply does not apply here to the same degree. So `expiresAt` is nullable
573
+ // and NULL is a real, supported, expected value meaning "never expires,
574
+ // authenticate indefinitely until revoked" — not "not yet set". Revocation
575
+ // (`revokedAt`) is the actual control for a node credential, and it is
576
+ // immediate: an operator who needs to cut a node off does so by revoking,
577
+ // not by waiting for a clock. An operator who DOES want an expiring node
578
+ // credential can still set one; the column supports it, it is just not
579
+ // forced.
580
+ model NodeCredential {
581
+ id String @id @default(uuid()) @db.Uuid
582
+
583
+ userId String @map("user_id") @db.Uuid
584
+
585
+ // Operator-chosen label ("prod-worker-1", "gpu-box-3"), shown alongside
586
+ // `tokenPrefix` in list views — same role as `PersonalAccessToken.name`.
587
+ name String
588
+
589
+ // sha256 hash of the full `nod_...` token; the only form of the token this
590
+ // table ever stores. Never the plaintext — see `NodeCredentialService
591
+ // .validateToken`'s own documentation for the lookup this backs.
592
+ tokenHash String @unique @map("token_hash")
593
+
594
+ // Short, non-secret display fragment (e.g. the first several characters
595
+ // after `nod_`) so an operator can tell two credentials apart in a list
596
+ // without either one's full value ever being shown again after creation.
597
+ tokenPrefix String @map("token_prefix")
598
+
599
+ // See the block comment above for why this is nullable, unlike
600
+ // `PersonalAccessToken.expiresAt` which is required. NULL = never expires.
601
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
602
+
603
+ // Stamped fire-and-forget by `validateToken` on each successful
604
+ // authentication — the operator-facing answer to "is this node actually
605
+ // still using this credential, or is it dead and safe to revoke".
606
+ lastUsedAt DateTime? @map("last_used_at") @db.Timestamptz
607
+
608
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
609
+
610
+ // NULL means active. Set once, never cleared — revocation is a one-way
611
+ // door, matching `PersonalAccessToken.revokedAt` and `RefreshToken
612
+ // .revokedAt` elsewhere in this schema. Revocation is immediate: the
613
+ // block comment above explains why this, not a clock, is the real control
614
+ // for a node credential.
615
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
616
+
617
+ // Relations
618
+ //
619
+ // onDelete: Cascade, matching `PersonalAccessToken.user` exactly (per
620
+ // issue #267's own instruction) and for the identical reason: a node
621
+ // credential is a live, personal authentication artifact with no
622
+ // standalone value once its owning account is gone — there is no one left
623
+ // to authorize a node acting on this user's behalf, and no audit value in
624
+ // keeping hashed token material around for an account that no longer
625
+ // exists. See `WorkerNode.createdBy`'s own comment above for how this
626
+ // Cascade is part of the same reasoning that made `WorkerNode.createdBy`
627
+ // Cascade too: the two tables are designed to disappear together.
628
+ user User @relation("UserNodeCredentials", fields: [userId], references: [id], onDelete: Cascade)
629
+
630
+ // "This user's own credentials" — backs `GET /api/node-credentials`
631
+ // (#267's list endpoint), matching `PersonalAccessToken`'s own
632
+ // `@@index([userId])` for the identical query shape.
633
+ @@index([userId])
634
+ @@map("node_credentials")
635
+ }
636
+
637
+ // =============================================================================
638
+ // Job Node Secrets (issue #349, epic #345)
639
+ // =============================================================================
640
+ //
641
+ // THE AUDIT RECORD OF A CREDENTIAL A WORKER NODE ONCE HELD — and, precisely,
642
+ // NOT the credential. A node has no database access and no storage credentials
643
+ // by design (`docs/specs/worker-nodes.md` §8); epic #345 needs it to run work
644
+ // that genuinely requires one (a `pg_dump` needs a connection), so the server
645
+ // mints one per job, hands it over once, and destroys it on settlement. This
646
+ // table exists so that "which node held a credential to this deployment's
647
+ // database, of what kind, from when until when, and was it revoked" is a
648
+ // question with an answer.
649
+ //
650
+ // -----------------------------------------------------------------------------
651
+ // ⚠ THERE IS NO COLUMN HERE CAPABLE OF HOLDING SECRET MATERIAL, AND THERE MUST
652
+ // NEVER BE — NOT PLAINTEXT, NOT ENCRYPTED
653
+ // -----------------------------------------------------------------------------
654
+ //
655
+ // `handle` is an IDENTIFIER for the grant — a role name, a token id — and it is
656
+ // what `JobSecretBroker.revoke(handle)` takes. It is never the password. The
657
+ // material itself is serialised into exactly one HTTP response
658
+ // (`POST /api/nodes/:id/jobs/:jobId/secret`) and then dropped; nothing in this
659
+ // process, this database, or any backup of it retains a copy.
660
+ //
661
+ // REJECTED: an `encryptedMaterial` column, reusing `SECRETS_ENCRYPTION_KEY` the
662
+ // way the `credentials` table does. A credential that can be re-read is a
663
+ // credential that can be STOLEN TWICE, and nothing needs to re-read this one:
664
+ // the node received it once, and revocation is by handle rather than by
665
+ // presenting the secret back. `credentials` stores material because an SMTP
666
+ // password must be replayed on every send; a job credential must not be
667
+ // replayed at all. Storing it — even encrypted — would buy nothing and would
668
+ // put a live database password into this table, into every `pg_dump` of it,
669
+ // and into every copy of that dump, protected by a key that lives in the same
670
+ // deployment. That is the owner's rule for epic #345 expressed in schema rather
671
+ // than in a convention somebody can forget.
672
+ //
673
+ // -----------------------------------------------------------------------------
674
+ // `@@unique([jobId, kind])` — ONE CREDENTIAL PER JOB, EVER
675
+ // -----------------------------------------------------------------------------
676
+ //
677
+ // A node asks for its secret more than once as a matter of course: a process
678
+ // restarted while holding the lease, a response lost on the way back, a retry
679
+ // of the same job. Every one of those calls must land on the SAME grant,
680
+ // extended — never on a second one, because the revocation paths know exactly
681
+ // one handle per (job, kind) and a sibling grant would be one nothing ever
682
+ // destroys. The unique index makes the second row unrepresentable; the broker's
683
+ // own `issue` idempotence (see `job-secret-broker.ts`) is the other half.
684
+ //
685
+ // `@@index([expiresAt])` backs the sweeper, which scans unrevoked grants whose
686
+ // own clock has lapsed. See `NodeSecretBrokerService.sweep` for why the sweeper
687
+ // is NOT redundant with the settle-event revoker: three real cases emit no
688
+ // event at all.
689
+ //
690
+ // NO RELATIONS, DELIBERATELY. `jobId` and `nodeId` are plain UUID columns with
691
+ // no foreign key either way, for two reasons. `jobs` rows are deleted on a
692
+ // retention schedule (`job.history.purge`) that has nothing to do with a
693
+ // grant's lifetime, and a cascade from that purge would silently erase the
694
+ // audit record of a credential — which is the one thing this table is for. And
695
+ // a grant must stay revocable by handle after its job row is gone, which is
696
+ // why the sweeper resolves a broker by `kind` rather than by the job's `type`.
697
+ model JobNodeSecret {
698
+ id String @id @default(uuid()) @db.Uuid
699
+
700
+ jobId String @map("job_id") @db.Uuid
701
+ nodeId String @map("node_id") @db.Uuid
702
+
703
+ // Which broker minted this — `JobSecretBroker.kind`, e.g.
704
+ // `'postgres.readonly'`. Also how the revocation paths find their way back
705
+ // to the broker that can destroy the grant. A plain string, not an enum, for
706
+ // the same reason `Job.type` is: a fork's broker must cost zero migrations.
707
+ kind String
708
+
709
+ // The grant's identifier. ⚠ THE ROLE NAME. NEVER THE PASSWORD. See the block
710
+ // comment above.
711
+ handle String
712
+
713
+ issuedAt DateTime @default(now()) @map("issued_at") @db.Timestamptz
714
+ // The credential's own backstop, bounded by the job's lease (never a second
715
+ // clock of its own — see `JobSecretBroker.issue`). It is what makes a grant
716
+ // worthless if BOTH revocation paths somehow miss it.
717
+ expiresAt DateTime @map("expires_at") @db.Timestamptz
718
+ // NULL means the grant is still live as far as this server knows. Set by
719
+ // whichever revocation path got there first; both tolerate the other having
720
+ // won.
721
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
722
+
723
+ @@unique([jobId, kind])
724
+ @@index([expiresAt])
725
+ @@map("job_node_secrets")
726
+ }
727
+
728
+ extend model User {
729
+ workerNodes WorkerNode[] @relation("UserWorkerNodes")
730
+ nodeCredentials NodeCredential[] @relation("UserNodeCredentials")
731
+ }