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

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 (244) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +21 -0
  3. package/README.md +525 -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 +66 -0
  8. package/dist/baseline/deps.js.map +1 -0
  9. package/dist/baseline/errors.d.ts +36 -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 +127 -0
  34. package/dist/baseline/report.d.ts.map +1 -0
  35. package/dist/baseline/report.js +89 -0
  36. package/dist/baseline/report.js.map +1 -0
  37. package/dist/baseline/run.d.ts +117 -0
  38. package/dist/baseline/run.d.ts.map +1 -0
  39. package/dist/baseline/run.js +358 -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 +311 -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/app-objects.d.ts +107 -0
  78. package/dist/drift/app-objects.d.ts.map +1 -0
  79. package/dist/drift/app-objects.js +193 -0
  80. package/dist/drift/app-objects.js.map +1 -0
  81. package/dist/drift/db-conformance.d.ts +52 -0
  82. package/dist/drift/db-conformance.d.ts.map +1 -0
  83. package/dist/drift/db-conformance.js +89 -0
  84. package/dist/drift/db-conformance.js.map +1 -0
  85. package/dist/drift/index.d.ts +8 -0
  86. package/dist/drift/index.d.ts.map +1 -0
  87. package/dist/drift/index.js +43 -0
  88. package/dist/drift/index.js.map +1 -0
  89. package/dist/drift/raw-sql-indexes.d.ts +106 -0
  90. package/dist/drift/raw-sql-indexes.d.ts.map +1 -0
  91. package/dist/drift/raw-sql-indexes.js +113 -0
  92. package/dist/drift/raw-sql-indexes.js.map +1 -0
  93. package/dist/drift/raw-sql-tripwire.d.ts +191 -0
  94. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -0
  95. package/dist/drift/raw-sql-tripwire.js +422 -0
  96. package/dist/drift/raw-sql-tripwire.js.map +1 -0
  97. package/dist/drift/rls-policies.d.ts +226 -0
  98. package/dist/drift/rls-policies.d.ts.map +1 -0
  99. package/dist/drift/rls-policies.js +317 -0
  100. package/dist/drift/rls-policies.js.map +1 -0
  101. package/dist/drift/run.d.ts +152 -0
  102. package/dist/drift/run.d.ts.map +1 -0
  103. package/dist/drift/run.js +252 -0
  104. package/dist/drift/run.js.map +1 -0
  105. package/dist/drift/sql-expression.d.ts +27 -0
  106. package/dist/drift/sql-expression.d.ts.map +1 -0
  107. package/dist/drift/sql-expression.js +64 -0
  108. package/dist/drift/sql-expression.js.map +1 -0
  109. package/dist/index.d.ts +16 -0
  110. package/dist/index.d.ts.map +1 -0
  111. package/dist/index.js +33 -0
  112. package/dist/index.js.map +1 -0
  113. package/dist/lock/hash.d.ts +13 -0
  114. package/dist/lock/hash.d.ts.map +1 -0
  115. package/dist/lock/hash.js +19 -0
  116. package/dist/lock/hash.js.map +1 -0
  117. package/dist/lock/index.d.ts +5 -0
  118. package/dist/lock/index.d.ts.map +1 -0
  119. package/dist/lock/index.js +20 -0
  120. package/dist/lock/index.js.map +1 -0
  121. package/dist/lock/lock.d.ts +154 -0
  122. package/dist/lock/lock.d.ts.map +1 -0
  123. package/dist/lock/lock.js +151 -0
  124. package/dist/lock/lock.js.map +1 -0
  125. package/dist/lock/manifest.d.ts +68 -0
  126. package/dist/lock/manifest.d.ts.map +1 -0
  127. package/dist/lock/manifest.js +96 -0
  128. package/dist/lock/manifest.js.map +1 -0
  129. package/dist/lock/semver.d.ts +10 -0
  130. package/dist/lock/semver.d.ts.map +1 -0
  131. package/dist/lock/semver.js +13 -0
  132. package/dist/lock/semver.js.map +1 -0
  133. package/dist/seed/index.d.ts +5 -0
  134. package/dist/seed/index.d.ts.map +1 -0
  135. package/dist/seed/index.js +16 -0
  136. package/dist/seed/index.js.map +1 -0
  137. package/dist/seed/input.d.ts +52 -0
  138. package/dist/seed/input.d.ts.map +1 -0
  139. package/dist/seed/input.js +77 -0
  140. package/dist/seed/input.js.map +1 -0
  141. package/dist/seed/seed-platform.d.ts +41 -0
  142. package/dist/seed/seed-platform.d.ts.map +1 -0
  143. package/dist/seed/seed-platform.js +165 -0
  144. package/dist/seed/seed-platform.js.map +1 -0
  145. package/dist/seed/steps.d.ts +172 -0
  146. package/dist/seed/steps.d.ts.map +1 -0
  147. package/dist/seed/steps.js +136 -0
  148. package/dist/seed/steps.js.map +1 -0
  149. package/dist/seed/types.d.ts +287 -0
  150. package/dist/seed/types.d.ts.map +1 -0
  151. package/dist/seed/types.js +5 -0
  152. package/dist/seed/types.js.map +1 -0
  153. package/dist/sync/app-migrations.d.ts +52 -0
  154. package/dist/sync/app-migrations.d.ts.map +1 -0
  155. package/dist/sync/app-migrations.js +62 -0
  156. package/dist/sync/app-migrations.js.map +1 -0
  157. package/dist/sync/apply.d.ts +29 -0
  158. package/dist/sync/apply.d.ts.map +1 -0
  159. package/dist/sync/apply.js +38 -0
  160. package/dist/sync/apply.js.map +1 -0
  161. package/dist/sync/check.d.ts +59 -0
  162. package/dist/sync/check.d.ts.map +1 -0
  163. package/dist/sync/check.js +115 -0
  164. package/dist/sync/check.js.map +1 -0
  165. package/dist/sync/errors.d.ts +32 -0
  166. package/dist/sync/errors.d.ts.map +1 -0
  167. package/dist/sync/errors.js +23 -0
  168. package/dist/sync/errors.js.map +1 -0
  169. package/dist/sync/index.d.ts +10 -0
  170. package/dist/sync/index.d.ts.map +1 -0
  171. package/dist/sync/index.js +27 -0
  172. package/dist/sync/index.js.map +1 -0
  173. package/dist/sync/ledger.d.ts +65 -0
  174. package/dist/sync/ledger.d.ts.map +1 -0
  175. package/dist/sync/ledger.js +49 -0
  176. package/dist/sync/ledger.js.map +1 -0
  177. package/dist/sync/plan.d.ts +63 -0
  178. package/dist/sync/plan.d.ts.map +1 -0
  179. package/dist/sync/plan.js +86 -0
  180. package/dist/sync/plan.js.map +1 -0
  181. package/dist/sync/promote.d.ts +62 -0
  182. package/dist/sync/promote.d.ts.map +1 -0
  183. package/dist/sync/promote.js +95 -0
  184. package/dist/sync/promote.js.map +1 -0
  185. package/dist/sync/timestamps.d.ts +41 -0
  186. package/dist/sync/timestamps.d.ts.map +1 -0
  187. package/dist/sync/timestamps.js +68 -0
  188. package/dist/sync/timestamps.js.map +1 -0
  189. package/dist/sync/version.d.ts +28 -0
  190. package/dist/sync/version.d.ts.map +1 -0
  191. package/dist/sync/version.js +66 -0
  192. package/dist/sync/version.js.map +1 -0
  193. package/migrations/0001_initial/migration.sql +297 -0
  194. package/migrations/0002_add_personal_access_tokens/migration.sql +31 -0
  195. package/migrations/0003_add_credentials/migration.sql +20 -0
  196. package/migrations/0004_add_notification_deliveries/migration.sql +27 -0
  197. package/migrations/0005_drop_stale_uuid_defaults/migration.sql +35 -0
  198. package/migrations/0006_add_notifications/migration.sql +22 -0
  199. package/migrations/0007_add_push_subscriptions/migration.sql +25 -0
  200. package/migrations/0008_add_jobs/migration.sql +110 -0
  201. package/migrations/0009_add_worker_nodes/migration.sql +90 -0
  202. package/migrations/0010_add_database_backup_runs/migration.sql +104 -0
  203. package/migrations/0011_add_notification_broadcasts/migration.sql +57 -0
  204. package/migrations/0012_add_backup_run_job_link/migration.sql +87 -0
  205. package/migrations/0013_add_job_node_secrets/migration.sql +61 -0
  206. package/migrations/0014_add_backup_run_pg_dump_version/migration.sql +26 -0
  207. package/migrations/0015_add_job_claim_token/migration.sql +92 -0
  208. package/migrations/0016_add_ai_platform/migration.sql +108 -0
  209. package/migrations/0017_revoke_viewer_ai_use/migration.sql +32 -0
  210. package/migrations/0018_add_user_credentials/migration.sql +29 -0
  211. package/migrations/0019_add_device_session_credential_link/migration.sql +52 -0
  212. package/migrations/0020_add_worker_node_vitals/migration.sql +3 -0
  213. package/migrations/0021_add_job_trace_context/migration.sql +6 -0
  214. package/migrations/0022_add_retention_created_at_indexes/migration.sql +13 -0
  215. package/migrations/0023_add_organizations/migration.sql +142 -0
  216. package/migrations/0024_split_system_org_roles/migration.sql +131 -0
  217. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  218. package/migrations/0026_add_groups/migration.sql +165 -0
  219. package/migrations/0027_add_grants/migration.sql +117 -0
  220. package/migrations/0028_add_org_settings/migration.sql +49 -0
  221. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  222. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  223. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  224. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  225. package/migrations/0033_add_android_app/migration.sql +60 -0
  226. package/migrations/0034_open_job_reason/migration.sql +16 -0
  227. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  228. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  229. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  230. package/migrations/manifest.json +379 -0
  231. package/package.json +78 -4
  232. package/raw-sql-indexes.json +94 -0
  233. package/rls-policies.json +74 -0
  234. package/schema/ai.prisma +444 -0
  235. package/schema/android-app.prisma +47 -0
  236. package/schema/base.prisma +11 -0
  237. package/schema/credentials.prisma +170 -0
  238. package/schema/db-backup.prisma +376 -0
  239. package/schema/identity.prisma +439 -0
  240. package/schema/jobs.prisma +760 -0
  241. package/schema/notifications.prisma +649 -0
  242. package/schema/settings.prisma +60 -0
  243. package/schema/sharing.prisma +223 -0
  244. package/schema/storage.prisma +84 -0
@@ -0,0 +1,170 @@
1
+ // =============================================================================
2
+ // Encrypted Credential Store (issue #115, epic #108)
3
+ // =============================================================================
4
+ //
5
+ // Runtime-configured secrets (an SMTP password, an OAuth client secret, a
6
+ // second bucket's S3 key, ...) addressed by (purpose, name) rather than one
7
+ // column per consumer, so every future secret reuses this table instead of
8
+ // inventing its own column, its own encrypt call, and its own chance to leak.
9
+ //
10
+ // `secret` holds ONLY the opaque base64 ciphertext produced by
11
+ // `encryptSecret()` from `@marinoscar/platform-api/core`, encrypted under
12
+ // `purpose` as the sub-key derivation label — a ciphertext lifted from one
13
+ // row cannot be decrypted under a different purpose. This model stores
14
+ // ciphertext and non-secret metadata only; it never sees plaintext, and
15
+ // Prisma performs no encryption of its own.
16
+ //
17
+ // NEVER select `secret` into anything that reaches an API response or a log
18
+ // line. `CredentialsService` is the sole reader/writer and is what actually
19
+ // enforces that split (a plaintext-returning method for server-side
20
+ // consumers, a metadata-only method for presentation) — this comment is the
21
+ // signpost, not the guarantee.
22
+ // @extensible — back-relations only, added with "extend model Credential { ... }" in a
23
+ // fragment, so an app can hang its own NON-SECRET bookkeeping on a deployment credential
24
+ // (which feature uses it, when it was last rotated). The `secret` column is never the
25
+ // app's to read or relate to: an app reads plaintext only through `CredentialsService`,
26
+ // and no app table may copy ciphertext or plaintext of it.
27
+ model Credential {
28
+ id String @id @default(uuid()) @db.Uuid
29
+ purpose String
30
+ name String
31
+ // Opaque [iv][authTag][ciphertext] payload, base64-encoded by
32
+ // encryptSecret(). @db.Text (not the default `varchar`) because a base64
33
+ // AES-GCM payload has no meaningful bound: encrypted key material,
34
+ // passwords, or tokens of arbitrary length must never be truncated.
35
+ secret String @db.Text
36
+ // Non-secret display aid for the admin UI (e.g. last 4 chars, or a fixed
37
+ // mask like '••••'). Nullable: a credential can exist before anyone has
38
+ // decided how to hint it, and some secrets have no meaningful suffix to show.
39
+ hint String?
40
+ // Human-readable description for the admin UI. Nullable for the same reason.
41
+ label String?
42
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
43
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
44
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
45
+
46
+ // Relations
47
+ //
48
+ // onDelete: SetNull — deliberately NOT Cascade. A credential is
49
+ // infrastructure shared by whatever consumer looks it up by (purpose,
50
+ // name); the admin who last set it is provenance, not an owner the
51
+ // credential's lifetime should depend on. Offboarding the user who last
52
+ // typed in the SMTP password must not silently delete a working SMTP
53
+ // configuration — that failure mode (email breaks because someone left
54
+ // the company) is exactly what this FK behaviour avoids. The credential
55
+ // outliving its last editor is correct; losing it is not.
56
+ updatedByUser User? @relation("CredentialUpdatedBy", fields: [updatedByUserId], references: [id], onDelete: SetNull)
57
+
58
+ @@unique([purpose, name])
59
+ @@map("credentials")
60
+ }
61
+
62
+ // =============================================================================
63
+ // Per-User Encrypted Credentials (issue #387)
64
+ // =============================================================================
65
+ //
66
+ // The sibling of `Credential` above for secrets OWNED BY ONE USER — a user's
67
+ // own key for some external service (bring-your-own-key). Addressed by
68
+ // (userId, purpose, name); `credentials` is untouched and keeps its
69
+ // ownerless (purpose, name) address.
70
+ //
71
+ // `secret` is the same opaque base64 [iv][authTag][ciphertext] payload
72
+ // `encryptSecret()` produces, but encrypted under an OWNER-BOUND sub-key
73
+ // domain, `user:<userId>:<purpose>` (`userCredentialPurpose()` in
74
+ // `@marinoscar/platform-api/core`), not under `purpose` alone. A ciphertext
75
+ // copied from user A's row into user B's row therefore fails GCM
76
+ // authentication instead of handing B the use of A's key.
77
+ //
78
+ // All three unique columns are NOT NULL, so `@@unique` is a real Postgres
79
+ // constraint (NULLs are distinct in a unique index) and `findUnique`/`upsert`
80
+ // on `userId_purpose_name` work. Its leading column also serves every
81
+ // by-user lookup, so there is no separate `user_id` index.
82
+ //
83
+ // onDelete: Cascade — deliberately the OPPOSITE of `Credential.updatedByUser`
84
+ // (SetNull). There, the user is provenance for shared infrastructure; here,
85
+ // the user is the owner, and a secret nobody owns is a secret nobody can
86
+ // revoke. `UserCredentialsService` is the sole reader/writer; NEVER select
87
+ // `secret` into anything that reaches an API response or a log line.
88
+ model UserCredential {
89
+ id String @id @default(uuid()) @db.Uuid
90
+ userId String @map("user_id") @db.Uuid
91
+ purpose String
92
+ name String
93
+ // @db.Text for the same reason as `Credential.secret`: never truncate.
94
+ secret String @db.Text
95
+ // Non-secret display aid, derived from the plaintext on write.
96
+ hint String?
97
+ // Human-readable description. User-entered, non-secret.
98
+ label String?
99
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
100
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
101
+
102
+ user User @relation("UserCredentials", fields: [userId], references: [id], onDelete: Cascade)
103
+
104
+ @@unique([userId, purpose, name])
105
+ @@map("user_credentials")
106
+ }
107
+
108
+ extend model User {
109
+ credentialUpdates Credential[] @relation("CredentialUpdatedBy")
110
+ // Per-user encrypted credentials (issue #387). Cascade: a user-owned
111
+ // secret has no meaning once its owner is gone — see `UserCredential`.
112
+ userCredentials UserCredential[] @relation("UserCredentials")
113
+ }
114
+
115
+ // =============================================================================
116
+ // Organization-Owned Encrypted Credentials (issue #735, PP-8.8)
117
+ // =============================================================================
118
+ //
119
+ // The third tier: secrets OWNED BY ONE ORGANIZATION (an org's own AI provider
120
+ // key, an org's own storage or e-mail account), addressed by
121
+ // (orgId, purpose, name). It mirrors `UserCredential` exactly, with the owner
122
+ // an organization instead of a user.
123
+ //
124
+ // `secret` is the opaque [iv][authTag][ciphertext] payload `encryptSecret()`
125
+ // produces under the ORG-BOUND sub-key domain `org:<orgId>:<purpose>`
126
+ // (`orgCredentialPurpose()` in `@marinoscar/platform-api/core`): a ciphertext
127
+ // copied from one organization's row into another's fails GCM
128
+ // authentication.
129
+ //
130
+ // A plain composite unique suffices (no raw-SQL index): all three columns are
131
+ // NOT NULL. Its leading column serves every by-org lookup.
132
+ //
133
+ // TENANT DATA: `org_credentials` is an `org` table under FORCEd row-level
134
+ // security (`org_credentials_org_isolation`, as in 0025/0026), so every read
135
+ // and write runs in the owning organization's scope. Cascade with the
136
+ // organization; the last editor is provenance only (SetNull), as on
137
+ // `Credential`. `OrgCredentialsService` is the sole reader/writer; NEVER
138
+ // select `secret` into anything that reaches an API response or a log line.
139
+ // =============================================================================
140
+ model OrgCredential {
141
+ id String @id @default(uuid()) @db.Uuid
142
+ orgId String @map("org_id") @db.Uuid
143
+ purpose String
144
+ name String
145
+ // @db.Text for the same reason as `Credential.secret`: never truncate.
146
+ secret String @db.Text
147
+ // Non-secret display aid, derived from the plaintext on write.
148
+ hint String?
149
+ // Human-readable description. Admin-entered, non-secret.
150
+ label String?
151
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
152
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
153
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
154
+
155
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
156
+ updatedByUser User? @relation("OrgCredentialUpdatedBy", fields: [updatedByUserId], references: [id], onDelete: SetNull)
157
+
158
+ @@unique([orgId, purpose, name])
159
+ @@map("org_credentials")
160
+ }
161
+
162
+ extend model User {
163
+ // Provenance on an organization's credential (issue #735). SetNull: an
164
+ // org's key outlives the administrator who last typed it in.
165
+ orgCredentialUpdates OrgCredential[] @relation("OrgCredentialUpdatedBy")
166
+ }
167
+
168
+ extend model Organization {
169
+ orgCredentials OrgCredential[]
170
+ }
@@ -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
+ }