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

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 +74 -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,20 @@
1
+ -- CreateTable
2
+ CREATE TABLE "credentials" (
3
+ "id" UUID NOT NULL,
4
+ "purpose" TEXT NOT NULL,
5
+ "name" TEXT NOT NULL,
6
+ "secret" TEXT NOT NULL,
7
+ "hint" TEXT,
8
+ "label" TEXT,
9
+ "updated_by_user_id" UUID,
10
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
11
+ "updated_at" TIMESTAMPTZ NOT NULL,
12
+
13
+ CONSTRAINT "credentials_pkey" PRIMARY KEY ("id")
14
+ );
15
+
16
+ -- CreateIndex
17
+ CREATE UNIQUE INDEX "credentials_purpose_name_key" ON "credentials"("purpose", "name");
18
+
19
+ -- AddForeignKey
20
+ ALTER TABLE "credentials" ADD CONSTRAINT "credentials_updated_by_user_id_fkey" FOREIGN KEY ("updated_by_user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,27 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "NotificationDeliveryStatus" AS ENUM ('queued', 'sent', 'failed');
3
+
4
+ -- CreateTable
5
+ CREATE TABLE "notification_deliveries" (
6
+ "id" UUID NOT NULL,
7
+ "event_key" TEXT NOT NULL,
8
+ "user_id" UUID,
9
+ "recipient" TEXT NOT NULL,
10
+ "channel" TEXT NOT NULL,
11
+ "status" "NotificationDeliveryStatus" NOT NULL DEFAULT 'queued',
12
+ "provider_message_id" TEXT,
13
+ "error" TEXT,
14
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
15
+ "updated_at" TIMESTAMPTZ NOT NULL,
16
+
17
+ CONSTRAINT "notification_deliveries_pkey" PRIMARY KEY ("id")
18
+ );
19
+
20
+ -- CreateIndex
21
+ CREATE INDEX "notification_deliveries_user_id_event_key_idx" ON "notification_deliveries"("user_id", "event_key");
22
+
23
+ -- CreateIndex
24
+ CREATE INDEX "notification_deliveries_status_created_at_idx" ON "notification_deliveries"("status", "created_at");
25
+
26
+ -- AddForeignKey
27
+ ALTER TABLE "notification_deliveries" ADD CONSTRAINT "notification_deliveries_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,35 @@
1
+ -- AlterTable
2
+ ALTER TABLE "allowed_emails" ALTER COLUMN "id" DROP DEFAULT;
3
+
4
+ -- AlterTable
5
+ ALTER TABLE "audit_events" ALTER COLUMN "id" DROP DEFAULT;
6
+
7
+ -- AlterTable
8
+ ALTER TABLE "device_codes" ALTER COLUMN "id" DROP DEFAULT;
9
+
10
+ -- AlterTable
11
+ ALTER TABLE "permissions" ALTER COLUMN "id" DROP DEFAULT;
12
+
13
+ -- AlterTable
14
+ ALTER TABLE "refresh_tokens" ALTER COLUMN "id" DROP DEFAULT;
15
+
16
+ -- AlterTable
17
+ ALTER TABLE "roles" ALTER COLUMN "id" DROP DEFAULT;
18
+
19
+ -- AlterTable
20
+ ALTER TABLE "storage_object_chunks" ALTER COLUMN "id" DROP DEFAULT;
21
+
22
+ -- AlterTable
23
+ ALTER TABLE "storage_objects" ALTER COLUMN "id" DROP DEFAULT;
24
+
25
+ -- AlterTable
26
+ ALTER TABLE "system_settings" ALTER COLUMN "id" DROP DEFAULT;
27
+
28
+ -- AlterTable
29
+ ALTER TABLE "user_identities" ALTER COLUMN "id" DROP DEFAULT;
30
+
31
+ -- AlterTable
32
+ ALTER TABLE "user_settings" ALTER COLUMN "id" DROP DEFAULT;
33
+
34
+ -- AlterTable
35
+ ALTER TABLE "users" ALTER COLUMN "id" DROP DEFAULT;
@@ -0,0 +1,22 @@
1
+ -- CreateTable
2
+ CREATE TABLE "notifications" (
3
+ "id" UUID NOT NULL,
4
+ "user_id" UUID NOT NULL,
5
+ "event_key" TEXT NOT NULL,
6
+ "title" TEXT NOT NULL,
7
+ "body" TEXT NOT NULL,
8
+ "link" TEXT,
9
+ "read_at" TIMESTAMPTZ,
10
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
11
+
12
+ CONSTRAINT "notifications_pkey" PRIMARY KEY ("id")
13
+ );
14
+
15
+ -- CreateIndex
16
+ CREATE INDEX "notifications_user_id_read_at_idx" ON "notifications"("user_id", "read_at");
17
+
18
+ -- CreateIndex
19
+ CREATE INDEX "notifications_user_id_created_at_idx" ON "notifications"("user_id", "created_at" DESC);
20
+
21
+ -- AddForeignKey
22
+ ALTER TABLE "notifications" ADD CONSTRAINT "notifications_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,25 @@
1
+ -- CreateTable
2
+ CREATE TABLE "push_subscriptions" (
3
+ "id" UUID NOT NULL,
4
+ "user_id" UUID NOT NULL,
5
+ "endpoint" TEXT NOT NULL,
6
+ "p256dh" TEXT NOT NULL,
7
+ "auth" TEXT NOT NULL,
8
+ "expiration_time" TIMESTAMPTZ,
9
+ "user_agent" TEXT,
10
+ "failure_count" INTEGER NOT NULL DEFAULT 0,
11
+ "last_success_at" TIMESTAMPTZ,
12
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
13
+ "updated_at" TIMESTAMPTZ NOT NULL,
14
+
15
+ CONSTRAINT "push_subscriptions_pkey" PRIMARY KEY ("id")
16
+ );
17
+
18
+ -- CreateIndex
19
+ CREATE UNIQUE INDEX "push_subscriptions_endpoint_key" ON "push_subscriptions"("endpoint");
20
+
21
+ -- CreateIndex
22
+ CREATE INDEX "push_subscriptions_user_id_idx" ON "push_subscriptions"("user_id");
23
+
24
+ -- AddForeignKey
25
+ ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -0,0 +1,110 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "JobStatus" AS ENUM ('pending', 'running', 'succeeded', 'failed');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "JobReason" AS ENUM ('upload', 'rerun', 'backfill');
6
+
7
+ -- CreateTable
8
+ CREATE TABLE "jobs" (
9
+ "id" UUID NOT NULL,
10
+ "type" TEXT NOT NULL,
11
+ "subject_type" TEXT,
12
+ "subject_id" TEXT,
13
+ "dedup_key" TEXT,
14
+ "status" "JobStatus" NOT NULL DEFAULT 'pending',
15
+ "reason" "JobReason" NOT NULL,
16
+ "priority" INTEGER NOT NULL DEFAULT 0,
17
+ "provider_key" TEXT,
18
+ "model_version" TEXT,
19
+ "payload" JSONB,
20
+ "attempts" INTEGER NOT NULL DEFAULT 0,
21
+ "last_error" TEXT,
22
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
23
+ "started_at" TIMESTAMPTZ,
24
+ "finished_at" TIMESTAMPTZ,
25
+ "scheduled_for" TIMESTAMPTZ,
26
+ "rate_limited_at" TIMESTAMPTZ,
27
+ "rate_limit_hits" INTEGER NOT NULL DEFAULT 0,
28
+ "claimed_by_node_id" UUID,
29
+ "lease_expires_at" TIMESTAMPTZ,
30
+ "executor" TEXT,
31
+
32
+ CONSTRAINT "jobs_pkey" PRIMARY KEY ("id")
33
+ );
34
+
35
+ -- CreateTable
36
+ CREATE TABLE "job_stats_rollup" (
37
+ "type" TEXT NOT NULL,
38
+ "succeeded_count" INTEGER NOT NULL DEFAULT 0,
39
+ "failed_count" INTEGER NOT NULL DEFAULT 0,
40
+ "sum_duration_ms" DOUBLE PRECISION NOT NULL DEFAULT 0,
41
+ "duration_samples" INTEGER NOT NULL DEFAULT 0,
42
+ "updated_at" TIMESTAMPTZ NOT NULL,
43
+
44
+ CONSTRAINT "job_stats_rollup_pkey" PRIMARY KEY ("type")
45
+ );
46
+
47
+ -- CreateIndex
48
+ CREATE INDEX "jobs_status_priority_created_at_idx" ON "jobs"("status", "priority", "created_at");
49
+
50
+ -- CreateIndex
51
+ CREATE INDEX "jobs_status_scheduled_for_priority_created_at_idx" ON "jobs"("status", "scheduled_for", "priority", "created_at");
52
+
53
+ -- CreateIndex
54
+ CREATE INDEX "jobs_subject_type_subject_id_idx" ON "jobs"("subject_type", "subject_id");
55
+
56
+ -- CreateIndex
57
+ CREATE INDEX "jobs_type_status_idx" ON "jobs"("type", "status");
58
+
59
+ -- CreateIndex
60
+ CREATE INDEX "jobs_status_lease_expires_at_idx" ON "jobs"("status", "lease_expires_at");
61
+
62
+ -- CreateIndex
63
+ CREATE INDEX "jobs_claimed_by_node_id_idx" ON "jobs"("claimed_by_node_id");
64
+
65
+ -- CreateIndex
66
+ CREATE INDEX "jobs_created_at_idx" ON "jobs"("created_at" DESC);
67
+
68
+ -- CreateIndex
69
+ -- Covering index for the two unconditional admin groupBy({ by: ['status'] })-
70
+ -- shaped counts: status, type and id are the only columns those queries read,
71
+ -- so Postgres can answer them as an index-only scan without visiting the heap.
72
+ CREATE INDEX "jobs_status_type_id_idx" ON "jobs"("status", "type", "id");
73
+
74
+ -- =============================================================================
75
+ -- HAND-WRITTEN INDEXES — INTENTIONAL SCHEMA DRIFT (issue #255, epic #254)
76
+ -- =============================================================================
77
+ -- The three indexes below are NOT emitted by `prisma migrate dev`/`diff` and
78
+ -- never will be: each needs a partial-index `WHERE` clause, which the Prisma
79
+ -- schema language has no syntax for. They are written here by hand, and the
80
+ -- block comment above the `Job` model in prisma/schema.prisma records the
81
+ -- same fact for anyone reading the schema without this file open. Do not
82
+ -- "reconcile" this migration by dropping them, and do not expect `prisma
83
+ -- migrate diff` against the live database to come back clean — this drift is
84
+ -- deliberate and permanent for as long as Prisma's DSL lacks partial indexes.
85
+ -- =============================================================================
86
+
87
+ -- Enforces the active-dedup constraint described at length above the `Job`
88
+ -- model in prisma/schema.prisma ("dedupKey / the active-dedup unique index").
89
+ -- The key format itself is defined once in buildDedupKey()
90
+ -- (apps/api/src/jobs/job-keys.ts) — this index does not care how the string
91
+ -- was built, only that it is unique among jobs that are still active.
92
+ -- `dedup_key IS NOT NULL` lets jobs that opt out of dedup (a NULL key) insert
93
+ -- freely; the status filter is what makes a key reusable once its job
94
+ -- finishes (succeeded or failed jobs drop out of this index's predicate).
95
+ CREATE UNIQUE INDEX "jobs_active_dedup_uniq_idx"
96
+ ON "jobs"("dedup_key") WHERE "status" IN ('pending','running') AND "dedup_key" IS NOT NULL;
97
+
98
+ -- "Show me flaky jobs" without indexing the (large) majority that succeeded
99
+ -- on their first attempt. See "attempts vs rateLimitedAt/rateLimitHits" above
100
+ -- the `Job` model for why `attempts` and rate-limit deferrals are counted
101
+ -- separately in the first place.
102
+ CREATE INDEX "jobs_attempts_gt1_idx" ON "jobs"("attempts") WHERE "attempts" > 1;
103
+
104
+ -- Feeds the per-type duration stats that `JobStatsRollup` accumulates:
105
+ -- only jobs that actually reached `succeeded` with both timestamps recorded
106
+ -- have a meaningful duration, so the index is scoped to exactly those rows
107
+ -- rather than the full table.
108
+ CREATE INDEX "jobs_succeeded_duration_idx"
109
+ ON "jobs"("finished_at","started_at","type")
110
+ WHERE "status"='succeeded' AND "started_at" IS NOT NULL AND "finished_at" IS NOT NULL;
@@ -0,0 +1,90 @@
1
+ -- =============================================================================
2
+ -- Worker Nodes (issue #267, epic #254)
3
+ -- =============================================================================
4
+ -- Adds `worker_nodes` and `node_credentials`, and wires the FK on
5
+ -- `jobs.claimed_by_node_id` that was deliberately left unconstrained by
6
+ -- 20260906120000_add_jobs (see that migration's own header comment, and the
7
+ -- block comment above the `Job` model and the `WorkerNode` model in
8
+ -- prisma/schema.prisma for the full reasoning behind every choice below —
9
+ -- this file intentionally does not restate it at length).
10
+ -- =============================================================================
11
+
12
+ -- CreateEnum
13
+ CREATE TYPE "NodeStatus" AS ENUM ('online', 'draining', 'offline', 'disabled');
14
+
15
+ -- CreateTable
16
+ CREATE TABLE "worker_nodes" (
17
+ "id" UUID NOT NULL,
18
+ "name" TEXT NOT NULL,
19
+ "hostname" TEXT NOT NULL,
20
+ "platform" TEXT NOT NULL,
21
+ "cli_version" TEXT NOT NULL,
22
+ "eligible_types" TEXT[],
23
+ "concurrency" INTEGER NOT NULL,
24
+ "status" "NodeStatus" NOT NULL DEFAULT 'offline',
25
+ "capabilities" JSONB,
26
+ "registered_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
27
+ "last_heartbeat_at" TIMESTAMPTZ,
28
+ "created_by_id" UUID NOT NULL,
29
+
30
+ CONSTRAINT "worker_nodes_pkey" PRIMARY KEY ("id")
31
+ );
32
+
33
+ -- CreateTable
34
+ CREATE TABLE "node_credentials" (
35
+ "id" UUID NOT NULL,
36
+ "user_id" UUID NOT NULL,
37
+ "name" TEXT NOT NULL,
38
+ "token_hash" TEXT NOT NULL,
39
+ "token_prefix" TEXT NOT NULL,
40
+ "expires_at" TIMESTAMPTZ,
41
+ "last_used_at" TIMESTAMPTZ,
42
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
43
+ "revoked_at" TIMESTAMPTZ,
44
+
45
+ CONSTRAINT "node_credentials_pkey" PRIMARY KEY ("id")
46
+ );
47
+
48
+ -- CreateIndex
49
+ -- The register-or-reattach anchor (#268's own words: "existing exactly this
50
+ -- way") — see the block comment above the `WorkerNode` model.
51
+ CREATE UNIQUE INDEX "worker_nodes_created_by_id_name_key" ON "worker_nodes"("created_by_id", "name");
52
+
53
+ -- CreateIndex
54
+ -- "Every online/draining/offline/disabled node" — the fleet page's primary
55
+ -- filter, and what #270's lifecycle cron scans.
56
+ CREATE INDEX "worker_nodes_status_idx" ON "worker_nodes"("status");
57
+
58
+ -- CreateIndex
59
+ -- "This user's own nodes" — backs `GET /nodes` and `assertOwnership` (#268).
60
+ CREATE INDEX "worker_nodes_created_by_id_idx" ON "worker_nodes"("created_by_id");
61
+
62
+ -- CreateIndex
63
+ CREATE UNIQUE INDEX "node_credentials_token_hash_key" ON "node_credentials"("token_hash");
64
+
65
+ -- CreateIndex
66
+ -- "This user's own credentials" — backs `GET /api/node-credentials`, the
67
+ -- same query shape as `personal_access_tokens_user_id_idx`.
68
+ CREATE INDEX "node_credentials_user_id_idx" ON "node_credentials"("user_id");
69
+
70
+ -- AddForeignKey
71
+ -- onDelete: Cascade — a WorkerNode is a live registration with no standalone
72
+ -- value once its owner is gone (its NodeCredential rows are already gone via
73
+ -- their own Cascade below, so an orphaned node could never authenticate
74
+ -- again). See the block comment above `WorkerNode.createdBy` in
75
+ -- prisma/schema.prisma for the full reasoning, including why this is NOT the
76
+ -- SetNull audit-trail pattern used elsewhere in this schema (AuditEvent,
77
+ -- Credential, NotificationDelivery).
78
+ ALTER TABLE "worker_nodes" ADD CONSTRAINT "worker_nodes_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
79
+
80
+ -- AddForeignKey
81
+ -- onDelete: Cascade — mirrors `personal_access_tokens_user_id_fkey` exactly
82
+ -- (per issue #267): a node credential is a live authentication artifact with
83
+ -- no standalone value once its owning account is deleted.
84
+ ALTER TABLE "node_credentials" ADD CONSTRAINT "node_credentials_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
85
+
86
+ -- AddForeignKey
87
+ -- The FK deferred by 20260906120000_add_jobs. onDelete: SetNull — deleting a
88
+ -- WorkerNode must release the jobs it was holding, never delete job history.
89
+ -- See the "claimedByNodeId" block comment above the `Job` model.
90
+ ALTER TABLE "jobs" ADD CONSTRAINT "jobs_claimed_by_node_id_fkey" FOREIGN KEY ("claimed_by_node_id") REFERENCES "worker_nodes"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,104 @@
1
+ -- CreateEnum
2
+ CREATE TYPE "DatabaseBackupStatus" AS ENUM ('pending', 'running', 'completed', 'failed', 'stale');
3
+
4
+ -- CreateEnum
5
+ CREATE TYPE "DatabaseBackupTrigger" AS ENUM ('manual', 'scheduled', 'pre_restore');
6
+
7
+ -- CreateTable
8
+ CREATE TABLE "database_backup_runs" (
9
+ "id" UUID NOT NULL,
10
+ "status" "DatabaseBackupStatus" NOT NULL DEFAULT 'pending',
11
+ "trigger" "DatabaseBackupTrigger" NOT NULL,
12
+ "started_at" TIMESTAMPTZ,
13
+ "finished_at" TIMESTAMPTZ,
14
+ "last_heartbeat_at" TIMESTAMPTZ,
15
+ "bytes_written" BIGINT NOT NULL DEFAULT 0,
16
+ "size_bytes" BIGINT NOT NULL DEFAULT 0,
17
+ "storage_provider" TEXT NOT NULL,
18
+ "storage_key" TEXT NOT NULL,
19
+ "bucket" TEXT NOT NULL,
20
+ "format" TEXT NOT NULL,
21
+ "checksum_sha256" TEXT,
22
+ "db_version" TEXT,
23
+ "app_version" TEXT,
24
+ "migration_name" TEXT,
25
+ "verified_at" TIMESTAMPTZ,
26
+ "last_error" TEXT,
27
+ "created_by_id" UUID,
28
+ "restore_status" TEXT,
29
+ "restore_error" TEXT,
30
+ "restored_at" TIMESTAMPTZ,
31
+ "restored_by_id" UUID,
32
+ "restore_scratch_db" TEXT,
33
+ "restore_old_db" TEXT,
34
+ "swapped_at" TIMESTAMPTZ,
35
+ "pre_restore_backup_id" UUID,
36
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
37
+ "updated_at" TIMESTAMPTZ NOT NULL,
38
+
39
+ CONSTRAINT "database_backup_runs_pkey" PRIMARY KEY ("id")
40
+ );
41
+
42
+ -- CreateIndex
43
+ CREATE INDEX "database_backup_runs_created_at_idx" ON "database_backup_runs"("created_at" DESC);
44
+
45
+ -- CreateIndex
46
+ CREATE INDEX "database_backup_runs_started_at_idx" ON "database_backup_runs"("started_at" DESC);
47
+
48
+ -- CreateIndex
49
+ CREATE INDEX "database_backup_runs_status_idx" ON "database_backup_runs"("status");
50
+
51
+ -- CreateIndex
52
+ CREATE INDEX "database_backup_runs_status_created_at_idx" ON "database_backup_runs"("status", "created_at" DESC);
53
+
54
+ -- AddForeignKey
55
+ ALTER TABLE "database_backup_runs" ADD CONSTRAINT "database_backup_runs_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
56
+
57
+ -- AddForeignKey
58
+ ALTER TABLE "database_backup_runs" ADD CONSTRAINT "database_backup_runs_restored_by_id_fkey" FOREIGN KEY ("restored_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
59
+
60
+ -- AddForeignKey
61
+ ALTER TABLE "database_backup_runs" ADD CONSTRAINT "database_backup_runs_pre_restore_backup_id_fkey" FOREIGN KEY ("pre_restore_backup_id") REFERENCES "database_backup_runs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
62
+
63
+ -- =============================================================================
64
+ -- HAND-WRITTEN INDEX — INTENTIONAL SCHEMA DRIFT (issue #281, epic #254)
65
+ -- =============================================================================
66
+ -- The index below is NOT emitted by `prisma migrate dev`/`diff` and never will
67
+ -- be: it needs a partial-index `WHERE` clause, which the Prisma schema language
68
+ -- has no syntax for. It is written here by hand, and the block comment above
69
+ -- the `DatabaseBackupRun` model in prisma/schema.prisma records the same fact
70
+ -- for anyone reading the schema without this file open.
71
+ --
72
+ -- ⚠ `prisma migrate dev` WILL WANT TO DROP IT on the next diff, exactly as it
73
+ -- would for the three partial indexes in 20260906120000_add_jobs. Do not
74
+ -- "reconcile" this migration by accepting that drop, and do not expect
75
+ -- `prisma migrate diff` against a live database to come back clean. This drift
76
+ -- is deliberate and permanent for as long as Prisma's DSL lacks partial
77
+ -- indexes. If a future `migrate dev` run emits a `DROP INDEX
78
+ -- "database_backup_runs_active_uniq_idx"`, delete that line from the generated
79
+ -- migration before committing it.
80
+ -- =============================================================================
81
+
82
+ -- THE single-active-run guard. It is what makes "at most one backup at a time"
83
+ -- true ACROSS REPLICAS, rather than true only within one process: a scheduled
84
+ -- tick on one container and an administrator's click on another cannot both
85
+ -- insert, so two `pg_dump` processes can never stream into the derived storage
86
+ -- key at once. `DatabaseBackupRunnerService.startBackup` inserts optimistically
87
+ -- and turns the loser's P2002 into a typed
88
+ -- `DatabaseBackupAlreadyRunningError` carrying the winner's id; there is
89
+ -- deliberately no `findFirst` pre-check anywhere in that path, because
90
+ -- check-then-act is racy exactly when this constraint matters.
91
+ --
92
+ -- No cast is needed on the literals: Postgres coerces an unadorned string
93
+ -- literal to the column's enum type in an `IN` list, the same way
94
+ -- "jobs_active_dedup_uniq_idx" does for "JobStatus".
95
+ --
96
+ -- ⚠ WHAT THIS ADMITS, PRECISELY: a UNIQUE index on ("status") filtered to two
97
+ -- values permits at most one 'pending' row AND at most one 'running' row. The
98
+ -- runner only ever inserts 'running', so today the ceiling is exactly one
99
+ -- active run; 'pending' is covered so that a future path which does insert one
100
+ -- is still arbitrated here rather than in application code. A future design
101
+ -- that genuinely needs both states populated at once must TIGHTEN this index
102
+ -- (to a constant expression) — never relax the guard into a service.
103
+ CREATE UNIQUE INDEX "database_backup_runs_active_uniq_idx"
104
+ ON "database_backup_runs" ("status") WHERE "status" IN ('pending','running');
@@ -0,0 +1,57 @@
1
+ -- =============================================================================
2
+ -- Notification Broadcasts (issue #320, epic #319)
3
+ -- =============================================================================
4
+ -- Adds `notification_broadcasts`. See the block comment above the
5
+ -- `NotificationBroadcast` model in prisma/schema.prisma for the full
6
+ -- reasoning behind every choice below (why a table at all rather than
7
+ -- `Job.payload`, why `channels` is a plain string array, why `status` carries
8
+ -- a currently-unreachable `draft` member, why `cursor_user_id` pairs with
9
+ -- `audience_cutoff` to freeze and replay the fan-out's audience, why
10
+ -- `created_by_id` is SetNull, and the rejected per-recipient join table) —
11
+ -- this file intentionally does not restate it at length.
12
+ -- =============================================================================
13
+
14
+ -- CreateEnum
15
+ CREATE TYPE "NotificationBroadcastStatus" AS ENUM ('draft', 'scheduled', 'sending', 'sent', 'canceled', 'failed');
16
+
17
+ -- CreateTable
18
+ CREATE TABLE "notification_broadcasts" (
19
+ "id" UUID NOT NULL,
20
+ "title" TEXT NOT NULL,
21
+ "body" TEXT NOT NULL,
22
+ "link" TEXT,
23
+ "cta_label" TEXT,
24
+ "event_key" TEXT NOT NULL,
25
+ "channels" TEXT[],
26
+ "status" "NotificationBroadcastStatus" NOT NULL DEFAULT 'scheduled',
27
+ "scheduled_for" TIMESTAMPTZ,
28
+ "started_at" TIMESTAMPTZ,
29
+ "finished_at" TIMESTAMPTZ,
30
+ "canceled_at" TIMESTAMPTZ,
31
+ "audience_cutoff" TIMESTAMPTZ,
32
+ "cursor_user_id" UUID,
33
+ "recipients_targeted" INTEGER,
34
+ "recipients_dispatched" INTEGER NOT NULL DEFAULT 0,
35
+ "last_error" TEXT,
36
+ "created_by_id" UUID,
37
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
38
+ "updated_at" TIMESTAMPTZ NOT NULL,
39
+
40
+ CONSTRAINT "notification_broadcasts_pkey" PRIMARY KEY ("id")
41
+ );
42
+
43
+ -- CreateIndex
44
+ -- "What is pending" — the scheduler's own query.
45
+ CREATE INDEX "notification_broadcasts_status_scheduled_for_idx" ON "notification_broadcasts"("status", "scheduled_for");
46
+
47
+ -- CreateIndex
48
+ -- The admin list page's default order, "most recently composed first".
49
+ CREATE INDEX "notification_broadcasts_created_at_idx" ON "notification_broadcasts"("created_at" DESC);
50
+
51
+ -- AddForeignKey
52
+ -- onDelete: SetNull — same audit-trail reasoning as
53
+ -- `audit_events_actor_user_id_fkey`: deleting the admin who composed a
54
+ -- broadcast must not delete the record of what they announced. Takes a
55
+ -- brief lock on `users` while the constraint is validated, as any new FK to
56
+ -- that table does.
57
+ ALTER TABLE "notification_broadcasts" ADD CONSTRAINT "notification_broadcasts_created_by_id_fkey" FOREIGN KEY ("created_by_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
@@ -0,0 +1,87 @@
1
+ -- =============================================================================
2
+ -- Backup Run <-> Job link, and tightening the single-active-run guard
3
+ -- (issue #351, epic #345)
4
+ -- =============================================================================
5
+ -- Two independent changes land together because the second is only safe once
6
+ -- the first is possible to reason about (see the second block below for why
7
+ -- they must not be split across two migrations).
8
+ --
9
+ -- 1. `database_backup_runs.job_id`: the FK from a backup run back to the
10
+ -- queue job that drove it, once the dump becomes a job (`db.backup.run`).
11
+ -- Nullable, no default, no backfill — see the block comment above
12
+ -- `DatabaseBackupRun` in prisma/schema.prisma ("jobId") for the full
13
+ -- reasoning behind `@unique` / nullable / `SetNull`, which this migration
14
+ -- intentionally does not restate.
15
+ --
16
+ -- 2. Tightening `database_backup_runs_active_uniq_idx` from a UNIQUE index on
17
+ -- the `status` COLUMN to a UNIQUE index on the CONSTANT EXPRESSION `(true)`
18
+ -- — both filtered to `status IN ('pending','running')`. See the block
19
+ -- comment above `DatabaseBackupRun` in prisma/schema.prisma
20
+ -- ("THE SINGLE-ACTIVE-RUN GUARD...") for the full story; the short version:
21
+ -- the old, column-keyed index admits one `pending` row AND one `running`
22
+ -- row AT THE SAME TIME (two active runs), which was harmless only because
23
+ -- nothing ever wrote `pending`. #351's service half makes
24
+ -- `POST /api/admin/db-backup/runs` enqueue the job and insert the run row
25
+ -- as `pending` before any worker claims it, so `pending` rows become real.
26
+ -- Keying on `(true)` instead makes every active row — whichever status it
27
+ -- holds — collide on the same key, so at most one can exist across both
28
+ -- statuses combined.
29
+ -- =============================================================================
30
+
31
+ -- AlterTable
32
+ ALTER TABLE "database_backup_runs" ADD COLUMN "job_id" UUID;
33
+
34
+ -- CreateIndex
35
+ CREATE UNIQUE INDEX "database_backup_runs_job_id_key" ON "database_backup_runs"("job_id");
36
+
37
+ -- AddForeignKey
38
+ -- onDelete: SetNull, NOT Cascade — `job.history.purge` deletes `jobs` rows on
39
+ -- a retention schedule independent of the archive's own retention. Cascade
40
+ -- would let a routine job-history purge delete the record of a still-restorable
41
+ -- backup. See the block comment above `DatabaseBackupRun.jobId` in
42
+ -- prisma/schema.prisma.
43
+ ALTER TABLE "database_backup_runs" ADD CONSTRAINT "database_backup_runs_job_id_fkey" FOREIGN KEY ("job_id") REFERENCES "jobs"("id") ON DELETE SET NULL ON UPDATE CASCADE;
44
+
45
+ -- =============================================================================
46
+ -- HAND-WRITTEN INDEX CHANGE — INTENTIONAL SCHEMA DRIFT (issue #351, epic #345)
47
+ -- =============================================================================
48
+ -- `database_backup_runs_active_uniq_idx` is NOT emitted by `prisma migrate
49
+ -- dev`/`diff` and never will be: Prisma's schema language has no syntax for a
50
+ -- partial index OR an expression index, so both the original (partial, on
51
+ -- `status`) and this tightened form (partial, on the expression `(true)`) are
52
+ -- written here by hand — exactly the drift `20260907120000_add_database_backup
53
+ -- _runs/migration.sql` already carries, now one step further. The block
54
+ -- comment above the `DatabaseBackupRun` model in prisma/schema.prisma records
55
+ -- the same fact for anyone reading the schema without this file open.
56
+ --
57
+ -- ⚠ `prisma migrate dev` WILL WANT TO DROP THIS INDEX on the next diff, the
58
+ -- same as its predecessor. Do not "reconcile" this migration by accepting
59
+ -- that drop, and do not expect `prisma migrate diff` against a live database
60
+ -- to come back clean. This drift is deliberate and permanent for as long as
61
+ -- Prisma's DSL lacks expression indexes.
62
+ -- =============================================================================
63
+
64
+ -- The ORIGINAL guard admitted at most one 'pending' row AND at most one
65
+ -- 'running' row AT THE SAME TIME — two active runs, not one — because the
66
+ -- index was keyed on the `status` column itself: a 'pending' row and a
67
+ -- 'running' row have different key values, so both could satisfy the same
68
+ -- unique index simultaneously. That was harmless only because nothing ever
69
+ -- wrote 'pending'. #351 makes the dump a queue job, and the run row is now
70
+ -- created 'pending' before any worker has claimed it, so 'pending' rows are
71
+ -- no longer hypothetical.
72
+ DROP INDEX "database_backup_runs_active_uniq_idx";
73
+
74
+ -- THE tightened single-active-run guard. Keying on the constant expression
75
+ -- `(true)` — rather than on `status` — makes every row matching the WHERE
76
+ -- predicate (any 'pending' or 'running' row) index to the exact same key, so
77
+ -- Postgres now enforces "at most one active row, full stop" across BOTH
78
+ -- statuses combined, not "at most one of each". A 'completed', 'failed' or
79
+ -- 'stale' row does not match the predicate at all and is never constrained by
80
+ -- this index, so any number of them may coexist.
81
+ --
82
+ -- `DatabaseBackupRunnerService.startBackup` still inserts optimistically and
83
+ -- turns the loser's P2002 into a typed `DatabaseBackupAlreadyRunningError`
84
+ -- carrying the winner's id; there is deliberately no `findFirst` pre-check,
85
+ -- because check-then-act is racy exactly when this constraint matters.
86
+ CREATE UNIQUE INDEX "database_backup_runs_active_uniq_idx"
87
+ ON "database_backup_runs" ((true)) WHERE "status" IN ('pending','running');
@@ -0,0 +1,61 @@
1
+ -- =============================================================================
2
+ -- Per-job secret broker: the handle ledger (issue #349, epic #345)
3
+ -- =============================================================================
4
+ -- One table, and the interesting thing about it is a column that is NOT here.
5
+ --
6
+ -- A worker node holds no credentials by design (docs/specs/worker-nodes.md §8).
7
+ -- Epic #345 needs it to run work that genuinely requires one, so the server
8
+ -- mints a credential per job, hands it over exactly once, and destroys it when
9
+ -- the job settles. `job_node_secrets` records THAT A GRANT EXISTED — which node,
10
+ -- of what kind, from when until when, revoked or not — so "did a node ever hold
11
+ -- a credential to this database, and when" is answerable.
12
+ --
13
+ -- ⚠ THERE IS NO COLUMN CAPABLE OF HOLDING SECRET MATERIAL, AND ADDING ONE IS
14
+ -- THE ONE CHANGE THIS TABLE MUST NEVER RECEIVE. Not `password`, not
15
+ -- `encrypted_material`, not "just a base64 blob for debugging". `handle` is an
16
+ -- identifier for the grant (a role name) and is what `JobSecretBroker.revoke`
17
+ -- takes; the material is serialised into one HTTP response and dropped.
18
+ -- Reusing SECRETS_ENCRYPTION_KEY here was considered and rejected: a credential
19
+ -- that can be re-read is a credential that can be stolen twice, and nothing
20
+ -- needs to re-read this one. Storing it — even encrypted — would put a live
21
+ -- database password into this table, into every pg_dump of it, and into every
22
+ -- copy of that dump. See the block comment above `JobNodeSecret` in
23
+ -- prisma/schema.prisma for the full argument.
24
+ --
25
+ -- NO FOREIGN KEYS, deliberately. `job_id` and `node_id` are plain UUIDs. A
26
+ -- `jobs` row is deleted on a retention schedule (`job.history.purge`) that has
27
+ -- nothing to do with a grant's lifetime, and a cascade from that purge would
28
+ -- erase the audit record this table exists to keep; a grant must also stay
29
+ -- revocable after its job row is gone, which is why the sweeper resolves a
30
+ -- broker by `kind` rather than by the job's `type`.
31
+ -- =============================================================================
32
+
33
+ -- CreateTable
34
+ CREATE TABLE "job_node_secrets" (
35
+ "id" UUID NOT NULL,
36
+ "job_id" UUID NOT NULL,
37
+ "node_id" UUID NOT NULL,
38
+ "kind" TEXT NOT NULL,
39
+ -- The grant's identifier. NEVER the password — see the header.
40
+ "handle" TEXT NOT NULL,
41
+ "issued_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
42
+ "expires_at" TIMESTAMPTZ NOT NULL,
43
+ "revoked_at" TIMESTAMPTZ,
44
+
45
+ CONSTRAINT "job_node_secrets_pkey" PRIMARY KEY ("id")
46
+ );
47
+
48
+ -- CreateIndex
49
+ -- ONE CREDENTIAL PER JOB, EVER. A node asks for its secret more than once as a
50
+ -- matter of course (a restarted process still holding the lease, a lost
51
+ -- response, a retry), and every one of those calls must extend the SAME grant.
52
+ -- The revocation paths know exactly one handle per (job, kind); a sibling grant
53
+ -- would be one nothing ever destroys. This index makes the second row
54
+ -- unrepresentable rather than leaving it to the service to remember.
55
+ CREATE UNIQUE INDEX "job_node_secrets_job_id_kind_key" ON "job_node_secrets"("job_id", "kind");
56
+
57
+ -- CreateIndex
58
+ -- The sweeper's scan: unrevoked grants whose own clock has lapsed. See
59
+ -- `NodeSecretBrokerService.sweep` for why the sweeper is not redundant with the
60
+ -- settle-event revoker — three real cases emit no event at all.
61
+ CREATE INDEX "job_node_secrets_expires_at_idx" ON "job_node_secrets"("expires_at");