@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,376 @@
1
+ // =============================================================================
2
+ // Database Backup Runs (issue #281, epic #254)
3
+ // =============================================================================
4
+ //
5
+ // One row per attempt to dump this deployment's PostgreSQL database into
6
+ // object storage — and, from Phase 7 onwards, per attempt to restore FROM one.
7
+ // `DatabaseBackupRunnerService` (`src/db-backup/db-backup-runner.service.ts`)
8
+ // is the only writer of the backup half; the columns in the restore-audit
9
+ // group are declared here now and written by #285.
10
+ //
11
+ // -----------------------------------------------------------------------------
12
+ // ### Why this WAS not a queue job, and why it now is (issue #351, epic #345)
13
+ // -----------------------------------------------------------------------------
14
+ //
15
+ // ⚠ THIS SECTION USED TO SAY "DO NOT MIGRATE THIS ONTO THE QUEUE". It has
16
+ // been migrated, deliberately, and the history is kept because the three
17
+ // objections were correct and a reader needs to know WHERE EACH IS NOW
18
+ // ANSWERED rather than assume they were waved away.
19
+ //
20
+ // 1. `jobs.stuckThresholdMinutes` DEFAULTS TO 30 MINUTES. A dump of a real
21
+ // production database routinely runs longer than that. The lease reaper
22
+ // (`JobStuckResetTask`) would see a `running` job whose lease had
23
+ // expired, conclude its executor had died, and RESET IT TO `pending` —
24
+ // while `pg_dump` was still streaming. The next claim starts a SECOND
25
+ // `pg_dump`, writing to the SAME derived storage key as the first, and
26
+ // two processes interleave their output into one object.
27
+ // → ANSWERED BY #346's PER-TYPE PROFILES. `db.backup.run` declares
28
+ // `maxRuntimeMs: 6h`, and the claim's lease is DERIVED from that ceiling
29
+ // (`resolveJobLeaseMs`), never declared beside it — so a lease shorter
30
+ // than the permitted runtime is unrepresentable rather than merely
31
+ // avoided.
32
+ // 2. THE IN-PROCESS WORKER HAS NO LEASE-RENEWAL PATH. `JobWorker` claimed
33
+ // with a lease and never extended it, so the reaper's verdict above was
34
+ // not a rare race but unconditional for any long job.
35
+ // → ANSWERED BY #347. The worker renews on a ticker (lease ÷ 3) for
36
+ // exactly as long as `process()` runs.
37
+ // 3. A JOB HAS `attempts` AND A RETRY BUDGET. Automatically re-running a
38
+ // failed multi-gigabyte dump is exactly the wrong behaviour: it burns
39
+ // hours of I/O on a database that is probably already unwell, and the
40
+ // correct retry for a backup is "the next scheduled one", tomorrow.
41
+ // → ANSWERED BY `maxAttempts: 1` on the same profile. The policy did not
42
+ // change; what changed is that `JobStuckService`'s give-up phase now
43
+ // ENFORCES it, instead of it holding by the accident of there being no
44
+ // queue to disagree.
45
+ //
46
+ // This table still has its OWN heartbeat (`lastHeartbeatAt`, written every
47
+ // ~20s with live `bytesWritten`), its OWN staleness policy
48
+ // (`databaseBackup.runStaleMinutes`) and its OWN terminal states, and all
49
+ // three are still load-bearing — but their jobs have narrowed. The heartbeat
50
+ // is now PROGRESS REPORTING for the UI (the lease is the liveness signal),
51
+ // and the stale sweep is the backstop for the one path that still has no job:
52
+ // the `pre_restore` safety dump, which `DatabaseRestoreService` takes through
53
+ // `startBackup` because a restore must not wait on a worker slot.
54
+ //
55
+ // ⚠ THE TWO ROWS ARE NOT REDUNDANT. The `jobs` row answers who asked, when,
56
+ // which executor, which attempt and what error; this row answers what was
57
+ // PRODUCED — key, bucket, bytes, checksum, `verifiedAt`, the db/app/migration
58
+ // audit and the restore audit. They also have independent lifetimes: a job is
59
+ // purged by `job.history.purge` on a retention schedule that has nothing to do
60
+ // with how long the archive is kept, which is exactly why `jobId` is
61
+ // `onDelete: SetNull` and not `Cascade`.
62
+ //
63
+ // -----------------------------------------------------------------------------
64
+ // THE SINGLE-ACTIVE-RUN GUARD IS A PARTIAL UNIQUE INDEX, NOT APPLICATION CODE
65
+ // -----------------------------------------------------------------------------
66
+ //
67
+ // `database_backup_runs_active_uniq_idx` (hand-written in
68
+ // `prisma/migrations/20260907120000_add_database_backup_runs/migration.sql`,
69
+ // TIGHTENED by
70
+ // `prisma/migrations/<add_backup_run_job_link>/migration.sql`, epic #345,
71
+ // issue #351 — see that migration's own header for why) is a UNIQUE index on
72
+ // the CONSTANT EXPRESSION `(true)` restricted to `status IN
73
+ // ('pending','running')`. It is what makes "at most one backup at a time"
74
+ // true ACROSS REPLICAS.
75
+ //
76
+ // REJECTED: a `findFirst({ where: { status: 'running' } })` before the insert.
77
+ // It is a check-then-act race, and it is racy exactly when it matters — a
78
+ // scheduled tick on replica A and an admin's manual click on replica B, in
79
+ // the same second. Both would see no active run, both would insert, and two
80
+ // `pg_dump` processes would stream into two objects while the settings say
81
+ // one backup a night. Only the database can make "is one already active"
82
+ // atomic with the insert that would violate it.
83
+ //
84
+ // The loser's Prisma `P2002` becomes a typed `DatabaseBackupAlreadyRunningError`
85
+ // carrying the winner's run id, which #282/#283 turn into a 409.
86
+ //
87
+ // ⚠ PRISMA CANNOT EXPRESS THIS INDEX — INTENTIONAL SCHEMA DRIFT. The schema
88
+ // language has no syntax for a partial index OR an expression index, exactly
89
+ // as recorded above the `Job` model for `jobs_active_dedup_uniq_idx` and its
90
+ // two siblings. So `prisma migrate dev`/`diff` will not regenerate it and, if
91
+ // anyone diffs this schema against a live database, will want to DROP it.
92
+ // That drift is deliberate and permanent: do not "fix" it, and do not try to
93
+ // force it into `@@unique` syntax that does not exist. The migration file
94
+ // carries the same warning next to the statement itself.
95
+ //
96
+ // ⚠ WHAT THE INDEX ADMITS, PRECISELY, AND WHY THAT CHANGED. The ORIGINAL index
97
+ // keyed on the `status` COLUMN, filtered to two values — that admits at most
98
+ // one `pending` row AND at most one `running` row AT THE SAME TIME, i.e. TWO
99
+ // active runs, not one. That was harmless only as long as
100
+ // `DatabaseBackupRunnerService` inserted its claim directly as `running` and
101
+ // never wrote `pending`. #351 makes the backup a queue job: `POST
102
+ // /api/admin/db-backup/runs` now enqueues the job and creates the run row in
103
+ // `pending` BEFORE any worker has claimed it (so the endpoint can return a run
104
+ // id immediately and `GET /runs/{id}` keeps working), and the handler flips it
105
+ // to `running` once claimed. The moment `pending` rows are real, the
106
+ // column-keyed index stops meaning "at most one active run" and starts
107
+ // meaning "at most two". Keying on `(true)` instead makes every active row —
108
+ // whichever of the two statuses it holds — index to the SAME key, so at most
109
+ // one can exist across both statuses COMBINED. This is the exact tightening
110
+ // this comment always said a future path needing both states populated at
111
+ // once would require ("tighten this index to a constant expression, never
112
+ // move the guard into a service") — it has now happened.
113
+ //
114
+ // -----------------------------------------------------------------------------
115
+ // WHY THE RESTORE AUDIT LIVES ON THE BACKUP'S OWN ROW
116
+ // -----------------------------------------------------------------------------
117
+ //
118
+ // `restoreStatus`, `restoreError`, `restoredAt`, `restoredById`,
119
+ // `restoreScratchDb`, `restoreOldDb`, `swappedAt` and `preRestoreBackupId` are
120
+ // all nullable and all belong to Phase 7. They are columns on THIS table
121
+ // rather than a `database_restore_runs` table because A RESTORE IS ALWAYS
122
+ // DEFINED IN TERMS OF EXACTLY ONE BACKUP: there is no restore without an
123
+ // archive to restore, no archive is restored twice concurrently, and every
124
+ // question anyone asks about a restore ("which dump was this?", "how big was
125
+ // it?", "what migration was the schema on?") is answered by the backup's own
126
+ // columns. A separate table would buy a join on a strict 1:1 relationship and
127
+ // would let the two rows disagree about which archive was replayed.
128
+ //
129
+ // The cost is honest: a backup restored twice (a restore that failed, then
130
+ // retried) overwrites the first attempt's audit fields. That is the correct
131
+ // trade — the interesting record is the state of the LAST restore, and the
132
+ // full history of attempts is in `audit_events`.
133
+ //
134
+ // `preRestoreBackupId` is a SELF-FK: before a restore swaps a database away,
135
+ // #285 takes a `pre_restore` backup, and this column points the restore at the
136
+ // safety net it took. `onDelete: SetNull`, so pruning that safety backup by
137
+ // retention never deletes the restore record that referenced it.
138
+ model DatabaseBackupRun {
139
+ id String @id @default(uuid()) @db.Uuid
140
+
141
+ // The `jobs` row that drove this run, once the dump became a queue job
142
+ // (`db.backup.run`, epic #345, issue #351). Three properties, each
143
+ // load-bearing:
144
+ //
145
+ // 1. `@unique` is what makes a SECOND run row for one job
146
+ // UNREPRESENTABLE. #348 lets a handler derive its own node upload
147
+ // key, and a node may legitimately ask for that key twice (a
148
+ // timed-out transfer, a lost response, a restarted process still
149
+ // holding the lease). The backup's `deriveOutputKey` re-reads by
150
+ // `jobId` and returns the existing key; the unique index is what
151
+ // GUARANTEES there is at most one to find, rather than that being a
152
+ // convention the service has to remember.
153
+ //
154
+ // 2. Nullable, ON PURPOSE. Not every run has a job: the `pre_restore`
155
+ // dump `DatabaseRestoreService` takes goes through the runner
156
+ // directly, with no job in between, and rows predating this
157
+ // migration have no job at all. A required column would either break
158
+ // the restore path or need a backfill that invents job rows for
159
+ // history.
160
+ //
161
+ // 3. `onDelete: SetNull`, NOT `Cascade`. `job.history.purge` deletes
162
+ // `jobs` rows on a retention schedule that is completely independent
163
+ // of the archive retention. Cascade would let a routine history purge
164
+ // delete the record of a backup whose archive is still in the bucket
165
+ // and still restorable — the exact "deleting history must not delete
166
+ // history" hazard `JobStatsRollup` already exists to avoid on the
167
+ // stats side. Losing the LINK is acceptable; losing the RUN ROW is
168
+ // not.
169
+ jobId String? @unique @map("job_id") @db.Uuid
170
+ job Job? @relation(fields: [jobId], references: [id], onDelete: SetNull)
171
+
172
+ // `pending` = claimed, dump not yet spawned. `running` = a `pg_dump` is
173
+ // streaming. `completed` = uploaded AND verified (see `verifiedAt`).
174
+ // `failed` = terminal, `lastError` says why. `stale` = the run's heartbeat
175
+ // stopped for longer than `databaseBackup.runStaleMinutes` and #282's sweep
176
+ // gave up on it — DISTINCT from `failed` on purpose, because nothing
177
+ // observed this run fail; the process holding it disappeared, and an
178
+ // operator reading the list needs to be able to tell "the dump errored"
179
+ // from "the container went away mid-dump".
180
+ status DatabaseBackupStatus @default(pending)
181
+
182
+ // `manual` = an administrator clicked. `scheduled` = #282's cron.
183
+ // `pre_restore` = the safety backup #285 takes immediately before swapping
184
+ // a restored database into place. No default: a run with no known origin is
185
+ // a run nobody can attribute, and every caller knows which it is.
186
+ trigger DatabaseBackupTrigger
187
+
188
+ // NULL until the dump is claimed / until it settles. `lastHeartbeatAt` is
189
+ // now PROGRESS REPORTING for the UI rather than this table's liveness
190
+ // signal — the job's LEASE is the liveness signal since #351/#352 — see the
191
+ // "Why this WAS not a queue job, and why it now is" block above.
192
+ startedAt DateTime? @map("started_at") @db.Timestamptz
193
+ finishedAt DateTime? @map("finished_at") @db.Timestamptz
194
+ lastHeartbeatAt DateTime? @map("last_heartbeat_at") @db.Timestamptz
195
+
196
+ // BigInt, both of them, and NOT `Int`. A PostgreSQL dump crossing 2 GiB is
197
+ // ordinary, and `Int` is a signed 32-bit column that overflows at 2147483647
198
+ // bytes — the failure would be a write error on the LARGEST backups, i.e.
199
+ // exactly the deployments this feature exists for, and it would surface as
200
+ // a failed run rather than as a wrong number.
201
+ //
202
+ // ⚠ A `BigInt` field is the JS `bigint` primitive, which `JSON.stringify`
203
+ // REFUSES to serialise. #283's response DTO must convert these two to
204
+ // `string` (or `Number`) explicitly — see the note above `JobStatsRollup`
205
+ // for the same hazard, decided the other way there because that column is a
206
+ // running average and this one is a byte count that must stay exact.
207
+ //
208
+ // `bytesWritten` is LIVE PROGRESS, rewritten by the heartbeat while the dump
209
+ // streams; `sizeBytes` is the final size, written once at completion. They
210
+ // converge on success and deliberately do not on a failure, where the
211
+ // difference is "how far did it get".
212
+ bytesWritten BigInt @default(0) @map("bytes_written")
213
+ sizeBytes BigInt @default(0) @map("size_bytes")
214
+
215
+ // The storage triple: WHICH provider, WHICH key, WHICH bucket. All three
216
+ // are recorded rather than derived on read, because all three can change
217
+ // under a deployment (a bucket rename, a provider swap) and a backup that
218
+ // cannot say where it was written is a backup nobody can restore. The key
219
+ // is chosen by the SERVER (`buildBackupStorageKey`), never by a caller.
220
+ storageProvider String @map("storage_provider")
221
+ storageKey String @map("storage_key")
222
+ bucket String
223
+
224
+ // `pg_dump`'s archive format — `custom` (`-Fc`) for everything this
225
+ // repository writes. Stored so a future format change does not make old
226
+ // archives unreadable-by-inspection: `pg_restore` needs to know, and
227
+ // guessing from the key's extension is not knowing.
228
+ format String
229
+
230
+ // sha256 of the archive, computed IN THE SAME SINGLE PASS as `sizeBytes`
231
+ // while the bytes stream past on their way to storage — the archive is
232
+ // never buffered and never read twice. NULL until the upload completes.
233
+ checksumSha256 String? @map("checksum_sha256")
234
+
235
+ // The audit quartet: what produced this archive. All four nullable because
236
+ // each is read best-effort and NONE of them may fail a backup — a run that
237
+ // could not read the server version is still a valid backup.
238
+ //
239
+ // `dbVersion` — the PostgreSQL server version this was dumped from.
240
+ // A restore onto an older major will not work, and this
241
+ // is the only place that fact is recorded.
242
+ // `appVersion` — the application build (`resolveApiVersion()`).
243
+ // `migrationName` — the newest applied `_prisma_migrations` row. THE most
244
+ // important of the four for a restore: it says which
245
+ // schema the archive contains, so an operator can tell
246
+ // before replaying it whether the running code will
247
+ // understand what comes back.
248
+ // `pgDumpVersion` — the `pg_dump` client that WROTE the archive (#352,
249
+ // epic #345). It was a trio until the dump could run on
250
+ // a worker node: on that path the client is a binary on
251
+ // a machine this deployment may not own and cannot
252
+ // inspect, so unless the node reports it, nothing
253
+ // anywhere records which `pg_dump` produced the file —
254
+ // and a `pg_restore` older than the `pg_dump` that wrote
255
+ // an archive simply cannot read it. The server path
256
+ // fills the same column from its own image's client, so
257
+ // the row means one thing whichever executor ran.
258
+ dbVersion String? @map("db_version")
259
+ appVersion String? @map("app_version")
260
+ migrationName String? @map("migration_name")
261
+ pgDumpVersion String? @map("pg_dump_version")
262
+
263
+ // Set when the UPLOADED OBJECT was streamed back out of storage and read by
264
+ // `pg_restore --list` with a non-empty table of contents. A run is never
265
+ // `completed` without it: the checksum proves what we sent, this proves what
266
+ // arrived is a readable archive.
267
+ verifiedAt DateTime? @map("verified_at") @db.Timestamptz
268
+
269
+ lastError String? @map("last_error")
270
+
271
+ // NULL for a `scheduled` run — nobody asked for it, a timer did. `SetNull`
272
+ // rather than `Cascade`, matching `AuditEvent.actorUserId` and
273
+ // `Credential.updatedByUser`: this is a HISTORY RECORD, and deleting an
274
+ // administrator's account must never delete the record that a backup was
275
+ // taken. Contrast `WorkerNode.createdBy`, which cascades because a node is
276
+ // live inventory rather than history.
277
+ createdById String? @map("created_by_id") @db.Uuid
278
+ createdBy User? @relation("UserDatabaseBackupRuns", fields: [createdById], references: [id], onDelete: SetNull)
279
+
280
+ // ---------------------------------------------------------------------------
281
+ // Restore audit (Phase 7). Declared by #281, written by #285's
282
+ // `DatabaseRestoreService`. See the "WHY THE RESTORE AUDIT LIVES ON THE
283
+ // BACKUP'S OWN ROW" block above.
284
+ // ---------------------------------------------------------------------------
285
+
286
+ // A plain string, not an enum, for the same reason `Job.executor` is one: a
287
+ // small closed set owned by code rather than by this table's own state
288
+ // machine, and adding a state to it must not cost a migration. NULL means
289
+ // "this backup has never been restored".
290
+ //
291
+ // `restoring` -> `verifying` -> `swapping` -> `completed` | `failed`, plus
292
+ // `rolled_back` for a restore that was swapped in and then undone. That last
293
+ // one is the argument for the column being a string: it was added by #285
294
+ // without a migration. The set lives in `RESTORE_STATUSES`
295
+ // (`src/db-backup/database-restore.service.ts`).
296
+ restoreStatus String? @map("restore_status")
297
+ restoreError String? @map("restore_error")
298
+
299
+ restoredAt DateTime? @map("restored_at") @db.Timestamptz
300
+ restoredById String? @map("restored_by_id") @db.Uuid
301
+ restoredBy User? @relation("UserDatabaseRestores", fields: [restoredById], references: [id], onDelete: SetNull)
302
+
303
+ // The names of the two databases a swap-style restore creates and displaces:
304
+ // the scratch database the archive was replayed into, and the original that
305
+ // was renamed out of the way. Recorded as NAMES because after the swap they
306
+ // are the only handle an operator has on either — `databaseBackup
307
+ // .restoreRollbackMode` decides whether the displaced one survives, and
308
+ // `oldDatabaseRetentionHours` decides for how long.
309
+ restoreScratchDb String? @map("restore_scratch_db")
310
+ restoreOldDb String? @map("restore_old_db")
311
+ swappedAt DateTime? @map("swapped_at") @db.Timestamptz
312
+
313
+ // The `pre_restore` backup taken immediately before this row's archive was
314
+ // swapped in — the way back. `SetNull` so retention pruning that safety
315
+ // backup never deletes the restore record pointing at it.
316
+ preRestoreBackupId String? @map("pre_restore_backup_id") @db.Uuid
317
+ preRestoreBackup DatabaseBackupRun? @relation("PreRestoreBackup", fields: [preRestoreBackupId], references: [id], onDelete: SetNull)
318
+ // The back-reference Prisma requires for the self-relation above. Nothing
319
+ // reads it today; it exists because a named relation needs both sides.
320
+ restoresUsingThis DatabaseBackupRun[] @relation("PreRestoreBackup")
321
+
322
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
323
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
324
+
325
+ // The queries #282 and #283 issue, and nothing speculative:
326
+ //
327
+ // - the admin list and the retention sweep are both "newest first", which
328
+ // is `createdAt DESC`;
329
+ // - `startedAt DESC` answers "when did backups actually run", which is a
330
+ // different question from "when were they requested" for any run that
331
+ // waited or never started at all;
332
+ // - `[status]` backs the stale sweep (`status = 'running'`) and the
333
+ // active-run lookup that turns a P2002 into an id;
334
+ // - `[status, createdAt DESC]` is the retention query — "the completed
335
+ // runs, newest first, keep N" — which neither single-column index
336
+ // answers without a sort.
337
+ @@index([createdAt(sort: Desc)])
338
+ @@index([startedAt(sort: Desc)])
339
+ @@index([status])
340
+ @@index([status, createdAt(sort: Desc)])
341
+ @@map("database_backup_runs")
342
+ }
343
+
344
+ enum DatabaseBackupStatus {
345
+ pending
346
+ running
347
+ completed
348
+ failed
349
+ stale
350
+ }
351
+
352
+ enum DatabaseBackupTrigger {
353
+ manual
354
+ scheduled
355
+ pre_restore
356
+ }
357
+
358
+ extend model User {
359
+ // Two relations to ONE table, deliberately (#281, epic #254): a
360
+ // `database_backup_runs` row records both "who asked for this backup" and,
361
+ // once Phase 7 restores from it, "who restored it". They are different acts
362
+ // by (usually) different people at different times, so they are different
363
+ // columns and therefore different relation names. See the block comment
364
+ // above `DatabaseBackupRun` for why the restore audit lives on the backup's
365
+ // own row rather than in a second table.
366
+ databaseBackupRuns DatabaseBackupRun[] @relation("UserDatabaseBackupRuns")
367
+ databaseRestores DatabaseBackupRun[] @relation("UserDatabaseRestores")
368
+ }
369
+
370
+ extend model Job {
371
+ // The `database_backup_runs` row this job produced, when `type` is
372
+ // `'db.backup.run'` (epic #345, issue #351). See `DatabaseBackupRun.jobId`
373
+ // for the full reasoning behind `@unique`/nullable/`SetNull` — this is
374
+ // just the required other half of that one-to-one relation.
375
+ backupRun DatabaseBackupRun?
376
+ }