@marinoscar/platform-db 0.1.0-next.3 → 0.1.0-next.30

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 (132) hide show
  1. package/CHANGELOG.md +107 -0
  2. package/README.md +158 -13
  3. package/dist/baseline/deps.d.ts.map +1 -1
  4. package/dist/baseline/deps.js +2 -0
  5. package/dist/baseline/deps.js.map +1 -1
  6. package/dist/baseline/errors.d.ts +3 -1
  7. package/dist/baseline/errors.d.ts.map +1 -1
  8. package/dist/baseline/errors.js.map +1 -1
  9. package/dist/baseline/report.d.ts +3 -1
  10. package/dist/baseline/report.d.ts.map +1 -1
  11. package/dist/baseline/report.js +4 -0
  12. package/dist/baseline/report.js.map +1 -1
  13. package/dist/baseline/run.d.ts +12 -1
  14. package/dist/baseline/run.d.ts.map +1 -1
  15. package/dist/baseline/run.js +19 -0
  16. package/dist/baseline/run.js.map +1 -1
  17. package/dist/bin/db-commands.d.ts +1 -1
  18. package/dist/bin/db-commands.d.ts.map +1 -1
  19. package/dist/bin/db-commands.js +40 -5
  20. package/dist/bin/db-commands.js.map +1 -1
  21. package/dist/drift/app-objects.d.ts +107 -0
  22. package/dist/drift/app-objects.d.ts.map +1 -0
  23. package/dist/drift/app-objects.js +193 -0
  24. package/dist/drift/app-objects.js.map +1 -0
  25. package/dist/drift/db-conformance.d.ts +3 -0
  26. package/dist/drift/db-conformance.d.ts.map +1 -1
  27. package/dist/drift/db-conformance.js +24 -0
  28. package/dist/drift/db-conformance.js.map +1 -1
  29. package/dist/drift/index.d.ts +5 -2
  30. package/dist/drift/index.d.ts.map +1 -1
  31. package/dist/drift/index.js +18 -1
  32. package/dist/drift/index.js.map +1 -1
  33. package/dist/drift/raw-sql-tripwire.d.ts +44 -3
  34. package/dist/drift/raw-sql-tripwire.d.ts.map +1 -1
  35. package/dist/drift/raw-sql-tripwire.js +39 -11
  36. package/dist/drift/raw-sql-tripwire.js.map +1 -1
  37. package/dist/drift/rls-policies.d.ts +226 -0
  38. package/dist/drift/rls-policies.d.ts.map +1 -0
  39. package/dist/drift/rls-policies.js +317 -0
  40. package/dist/drift/rls-policies.js.map +1 -0
  41. package/dist/drift/run.d.ts +24 -0
  42. package/dist/drift/run.d.ts.map +1 -1
  43. package/dist/drift/run.js +52 -1
  44. package/dist/drift/run.js.map +1 -1
  45. package/dist/drift/sql-expression.d.ts +27 -0
  46. package/dist/drift/sql-expression.d.ts.map +1 -0
  47. package/dist/drift/sql-expression.js +64 -0
  48. package/dist/drift/sql-expression.js.map +1 -0
  49. package/dist/lock/index.d.ts +1 -1
  50. package/dist/lock/index.d.ts.map +1 -1
  51. package/dist/lock/index.js.map +1 -1
  52. package/dist/lock/lock.d.ts +37 -0
  53. package/dist/lock/lock.d.ts.map +1 -1
  54. package/dist/lock/lock.js +11 -0
  55. package/dist/lock/lock.js.map +1 -1
  56. package/dist/lock/manifest.d.ts +8 -0
  57. package/dist/lock/manifest.d.ts.map +1 -1
  58. package/dist/lock/manifest.js +1 -0
  59. package/dist/lock/manifest.js.map +1 -1
  60. package/dist/seed/index.d.ts +1 -0
  61. package/dist/seed/index.d.ts.map +1 -1
  62. package/dist/seed/index.js +7 -1
  63. package/dist/seed/index.js.map +1 -1
  64. package/dist/seed/seed-platform.d.ts +16 -3
  65. package/dist/seed/seed-platform.d.ts.map +1 -1
  66. package/dist/seed/seed-platform.js +37 -5
  67. package/dist/seed/seed-platform.js.map +1 -1
  68. package/dist/seed/steps.d.ts +172 -0
  69. package/dist/seed/steps.d.ts.map +1 -0
  70. package/dist/seed/steps.js +136 -0
  71. package/dist/seed/steps.js.map +1 -0
  72. package/dist/seed/types.d.ts +12 -2
  73. package/dist/seed/types.d.ts.map +1 -1
  74. package/dist/sync/app-migrations.d.ts +52 -0
  75. package/dist/sync/app-migrations.d.ts.map +1 -0
  76. package/dist/sync/app-migrations.js +62 -0
  77. package/dist/sync/app-migrations.js.map +1 -0
  78. package/dist/sync/apply.d.ts.map +1 -1
  79. package/dist/sync/apply.js +1 -0
  80. package/dist/sync/apply.js.map +1 -1
  81. package/dist/sync/check.d.ts +5 -2
  82. package/dist/sync/check.d.ts.map +1 -1
  83. package/dist/sync/check.js +8 -1
  84. package/dist/sync/check.js.map +1 -1
  85. package/dist/sync/errors.d.ts +2 -1
  86. package/dist/sync/errors.d.ts.map +1 -1
  87. package/dist/sync/errors.js.map +1 -1
  88. package/dist/sync/index.d.ts +1 -0
  89. package/dist/sync/index.d.ts.map +1 -1
  90. package/dist/sync/index.js +3 -1
  91. package/dist/sync/index.js.map +1 -1
  92. package/dist/sync/plan.d.ts +3 -1
  93. package/dist/sync/plan.d.ts.map +1 -1
  94. package/dist/sync/plan.js +9 -2
  95. package/dist/sync/plan.js.map +1 -1
  96. package/dist/sync/promote.d.ts +4 -0
  97. package/dist/sync/promote.d.ts.map +1 -1
  98. package/dist/sync/promote.js +2 -0
  99. package/dist/sync/promote.js.map +1 -1
  100. package/migrations/0025_org_scoped_rls/migration.sql +215 -0
  101. package/migrations/0026_add_groups/migration.sql +165 -0
  102. package/migrations/0027_add_grants/migration.sql +117 -0
  103. package/migrations/0028_add_org_settings/migration.sql +49 -0
  104. package/migrations/0029_add_org_credentials/migration.sql +54 -0
  105. package/migrations/0030_add_jobs_org_id/migration.sql +18 -0
  106. package/migrations/0031_add_jobs_org_id_status_index/migration.sql +6 -0
  107. package/migrations/0032_add_broadcast_target_org/migration.sql +21 -0
  108. package/migrations/0033_add_android_app/migration.sql +60 -0
  109. package/migrations/0034_open_job_reason/migration.sql +16 -0
  110. package/migrations/0035_ai_usage_feature/migration.sql +37 -0
  111. package/migrations/0036_add_app_metadata/migration.sql +49 -0
  112. package/migrations/0037_open_sharing_vocabularies/migration.sql +97 -0
  113. package/migrations/0038_add_worker_node_events/migration.sql +21 -0
  114. package/migrations/0039_add_webhooks/migration.sql +125 -0
  115. package/migrations/0040_add_alerts/migration.sql +66 -0
  116. package/migrations/0041_notifications_state_counted/migration.sql +19 -0
  117. package/migrations/0042_add_storage_migrations/migration.sql +130 -0
  118. package/migrations/manifest.json +185 -0
  119. package/package.json +5 -2
  120. package/raw-sql-indexes.json +72 -0
  121. package/rls-policies.json +102 -0
  122. package/schema/ai.prisma +59 -2
  123. package/schema/alerts.prisma +75 -0
  124. package/schema/android-app.prisma +47 -0
  125. package/schema/credentials.prisma +62 -0
  126. package/schema/identity.prisma +34 -1
  127. package/schema/jobs.prisma +69 -7
  128. package/schema/notifications.prisma +84 -5
  129. package/schema/settings.prisma +25 -0
  130. package/schema/sharing.prisma +223 -0
  131. package/schema/storage.prisma +143 -4
  132. package/schema/webhooks.prisma +108 -0
@@ -79,6 +79,9 @@
79
79
  // filter on both columns, from an account's delivery history view.
80
80
  // - [status, createdAt]: "what failed recently?" — status = 'failed'
81
81
  // filtered and ordered by recency, for on-call triage.
82
+ // @extensible — back-relations only, added with "extend model NotificationDelivery { ... }" in a
83
+ // fragment (an app's own delivery annotations, for example a provider-specific receipt).
84
+ // The delivery ledger itself (status, error, provider id) stays the platform's.
82
85
  model NotificationDelivery {
83
86
  id String @id @default(uuid()) @db.Uuid
84
87
  eventKey String @map("event_key")
@@ -153,6 +156,11 @@ enum NotificationDeliveryStatus {
153
156
  // different questions for different audiences and are kept apart.
154
157
  // =============================================================================
155
158
 
159
+ // @extensible — back-relations only, added with "extend model Notification { ... }" in a
160
+ // fragment (an app's own side table keyed by a notification, for example a per-notification
161
+ // follow-up). A user-owned row: the table has no organization column, so a plain foreign
162
+ // key on `id` is the right shape. `onDelete: Cascade` on the app side keeps the retention
163
+ // sweep (`notifications.inbox.purge`) working.
156
164
  model Notification {
157
165
  id String @id @default(uuid()) @db.Uuid
158
166
  // NOT NULL, unlike NotificationDelivery.userId. An inbox belongs to an
@@ -202,10 +210,48 @@ model Notification {
202
210
 
203
211
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
204
212
 
205
- // NO `updatedAt`. The only mutation this row ever undergoes is being marked
206
- // read, and `readAt` already timestamps that with more precision than an
207
- // `updatedAt` would carry. A second, redundant answer to "when did this
208
- // change?" is a second thing to keep consistent for no reader.
213
+ // ---------------------------------------------------------------------------
214
+ // STATE and COUNTED rows (issue #1077) — all additive and nullable/defaulted,
215
+ // so every existing row and the plain `notify()` insert are unchanged.
216
+ // ---------------------------------------------------------------------------
217
+ //
218
+ // `notify()` appends one row per call. Two producers cannot live with that:
219
+ // a STATE notification ("N items await review") is ONE live row per
220
+ // (user, scope, event) refreshed in place, and a COUNTED event ("N uploads
221
+ // finished") folds repeated occurrences into ONE row whose `data.count`
222
+ // grows. These columns carry them:
223
+ //
224
+ // data the producer's payload; STATE and COUNTED rows always write
225
+ // it (`count`, and `countAtRead` once read). NULL for a plain
226
+ // `notify()` row.
227
+ // scopeId an optional scope the row belongs to (a group, an
228
+ // organization, a workspace), so one user can hold one live
229
+ // STATE row per scope. NOT authorization: the producer decides
230
+ // the recipients.
231
+ // dismissedAt "stop showing me this", distinct from `readAt` ("I saw it").
232
+ // A dismissed row leaves the list and the unread count; the
233
+ // retention sweep removes it by age.
234
+ // updatedAt the rolling-window anchor of a COUNTED row and the refresh
235
+ // time of a STATE row. Raw SQL does not run Prisma's
236
+ // `@updatedAt`, so every raw UPDATE sets it explicitly.
237
+ // dedupKey the fold key of a STATE or COUNTED row (NULL for a plain
238
+ // `notify()` row, which is how the retention sweep tells them
239
+ // apart); see the raw-SQL partial unique index below.
240
+ data Json?
241
+ scopeId String? @map("scope_id") @db.Uuid
242
+ dismissedAt DateTime? @map("dismissed_at") @db.Timestamptz
243
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at") @db.Timestamptz
244
+ dedupKey String? @map("dedup_key")
245
+
246
+ // RAW-SQL INDEX, intentional schema drift (packages/platform-db/raw-sql-indexes.json):
247
+ // notifications_live_dedup_uniq_idx
248
+ // UNIQUE (user_id, dedup_key) WHERE dismissed_at IS NULL AND dedup_key IS NOT NULL
249
+ // At most one LIVE foldable row per (user, dedup key). The DATABASE decides a
250
+ // race, not a find-then-insert. A COUNTED row whose window closed is retired
251
+ // by rewriting its `dedup_key` to `retired:<id>` (it stays in the inbox, and
252
+ // still reads as a folded row to the retention sweep), which frees the key
253
+ // for the next row. Prisma cannot express a partial unique index: never
254
+ // replace it with `@@unique` or a `findFirst` pre-check.
209
255
 
210
256
  // Relations
211
257
  //
@@ -233,6 +279,8 @@ model Notification {
233
279
  // The retention sweep (`notifications.inbox.purge`, #681): "oldest first,
234
280
  // older than the cutoff" across every user, which neither index above serves.
235
281
  @@index([createdAt])
282
+ // The retention sweep's dismissed pass (issue #1077): "dismissed longer ago than the cutoff".
283
+ @@index([dismissedAt])
236
284
  @@map("notifications")
237
285
  }
238
286
 
@@ -334,6 +382,18 @@ model PushSubscription {
334
382
  // subscription has never had one.
335
383
  lastSuccessAt DateTime? @map("last_success_at") @db.Timestamptz
336
384
 
385
+ // Which surface registered this subscription (#746, PP-9.4; harvested from
386
+ // EvoPath #312): `browser` (a browser tab or installed PWA) or `android_app`
387
+ // (the Android companion's Trusted Web Activity). The `android_app`
388
+ // notification channel pushes to these rows alone; `push` keeps meaning
389
+ // every subscription. A re-post of the same endpoint as `android_app`
390
+ // re-tags a `browser` row, a `browser` re-post never downgrades an
391
+ // `android_app` row (push-subscription.service.ts). The CHECK constraint
392
+ // `push_subscriptions_platform_check` lives in the migration SQL only
393
+ // (Prisma cannot express one; see PUSH_SUBSCRIPTION_PLATFORMS in the
394
+ // notifications contract).
395
+ platform String @default("browser")
396
+
337
397
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
338
398
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
339
399
 
@@ -583,11 +643,26 @@ model NotificationBroadcast {
583
643
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
584
644
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
585
645
 
646
+ // The audience's organization (#738, PP-8.5). NULL = every active user of
647
+ // the deployment (a system broadcast, as before #738); set = the ACTIVE
648
+ // members of that organization only. Read by the start and chunk handlers
649
+ // from the row (the job payloads carry only the broadcast id, unchanged), so
650
+ // `audienceWhere(cutoff, targetOrgId)` and the keyset cursor stay one query.
651
+ // No row-level security on this table: a system broadcast belongs to no
652
+ // organization, and RLS would hide it from the job that delivers it; the
653
+ // API authorizes `targetOrgId` instead (`broadcasts:*` may name any org,
654
+ // `org_broadcasts:*` only the caller's active org). CASCADE: an
655
+ // organization's broadcasts have no audience once it is deleted.
656
+ targetOrgId String? @map("target_org_id") @db.Uuid
657
+
586
658
  // Relations
587
- createdBy User? @relation("BroadcastAuthor", fields: [createdById], references: [id], onDelete: SetNull)
659
+ createdBy User? @relation("BroadcastAuthor", fields: [createdById], references: [id], onDelete: SetNull)
660
+ targetOrg Organization? @relation("BroadcastTargetOrg", fields: [targetOrgId], references: [id], onDelete: Cascade)
588
661
 
589
662
  @@index([status, scheduledFor])
590
663
  @@index([createdAt(sort: Desc)])
664
+ // A holder of only `org_broadcasts:read` lists its organization's broadcasts.
665
+ @@index([targetOrgId])
591
666
  @@map("notification_broadcasts")
592
667
  }
593
668
 
@@ -608,3 +683,7 @@ extend model User {
608
683
  pushSubscriptions PushSubscription[] @relation("UserPushSubscriptions")
609
684
  broadcastsCreated NotificationBroadcast[] @relation("BroadcastAuthor")
610
685
  }
686
+
687
+ extend model Organization {
688
+ notificationBroadcasts NotificationBroadcast[] @relation("BroadcastTargetOrg")
689
+ }
@@ -29,7 +29,32 @@ model UserSettings {
29
29
  @@map("user_settings")
30
30
  }
31
31
 
32
+ // One organization's overrides of the org-overridable system settings
33
+ // namespaces (#733): `{ "<namespace>": { "<field>": value } }`, only the fields
34
+ // each namespace's `org.schema` allows. An org table: FORCEd row-level security
35
+ // on org_id (`org_settings_org_isolation`, migration 0028_add_org_settings),
36
+ // reached only through `runInOrg`. Its own `version` for If-Match.
37
+ model OrgSettings {
38
+ id String @id @default(uuid()) @db.Uuid
39
+ orgId String @unique @map("org_id") @db.Uuid
40
+ value Json @db.JsonB
41
+ version Int @default(1)
42
+ updatedByUserId String? @map("updated_by_user_id") @db.Uuid
43
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
44
+
45
+ // Relations
46
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
47
+ updatedByUser User? @relation("OrgSettingsUpdater", fields: [updatedByUserId], references: [id], onDelete: SetNull)
48
+
49
+ @@map("org_settings")
50
+ }
51
+
32
52
  extend model User {
33
53
  userSettings UserSettings?
34
54
  settingsUpdates SystemSettings[] @relation("SettingsUpdater")
55
+ orgSettingsUpdates OrgSettings[] @relation("OrgSettingsUpdater")
56
+ }
57
+
58
+ extend model Organization {
59
+ settings OrgSettings?
35
60
  }
@@ -0,0 +1,223 @@
1
+ // =============================================================================
2
+ // Sharing: groups (PP-7.1, issue #728) and grants (PP-7.2, issue #729)
3
+ // =============================================================================
4
+ //
5
+ // A GROUP is a set of users INSIDE ONE ORGANIZATION that can own and share
6
+ // content (spec decision D6: groups are sharing groups, never tenants). Every
7
+ // row carries `org_id` and falls under the organization row-level-security
8
+ // model of `0025_org_scoped_rls`: the three tables `ENABLE` and `FORCE ROW
9
+ // LEVEL SECURITY` with one `<table>_org_isolation` policy each (migration
10
+ // `0026_add_groups`, listed in `rls-policies.json`).
11
+ //
12
+ // A member row and an invite row reach their group through the COMPOSITE key
13
+ // `(group_id, org_id)` -> `groups (id, org_id)`: a foreign-key check bypasses
14
+ // row-level security, so a plain key would let one organization store a
15
+ // reference to another organization's group, and the composite key also
16
+ // guarantees `group_members.org_id = groups.org_id`.
17
+ //
18
+ // `group_invites_pending_uniq_idx` (one PENDING invite per group and address)
19
+ // exists only in migration SQL: it is a partial unique index, which Prisma
20
+ // cannot express. Never "fix" the drift with `@@unique([groupId, email])`: a
21
+ // declined or revoked address must be invitable again.
22
+ //
23
+ // The names below are part of the public contract once released.
24
+ // =============================================================================
25
+
26
+ // The member and invite `role` columns are plain text (migration
27
+ // `0037_open_sharing_vocabularies`): the vocabulary is the API's group-role
28
+ // registry (`registerGroupRole`), which ships `admin` (manage the group, its
29
+ // members and invites; full rights on group-owned resources), `editor` (write
30
+ // on group-owned resources, MemoriaHub "collaborator") and `viewer` (read).
31
+ // A row must outlive the registry that produced it, so there is no CHECK.
32
+
33
+ // @extensible — back-relations only, added with "extend model Group { ... }" in a fragment
34
+ model Group {
35
+ id String @id @default(uuid()) @db.Uuid
36
+ orgId String @map("org_id") @db.Uuid
37
+ name String
38
+ description String?
39
+ /// Apps keep extra fields here (spec: never add columns to package-owned tables).
40
+ metadata Json? @db.JsonB
41
+ createdById String? @map("created_by_id") @db.Uuid
42
+ // Optimistic concurrency for PATCH (If-Match), per docs/API.md.
43
+ version Int @default(1)
44
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
45
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
46
+
47
+ // Relations
48
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
49
+ createdBy User? @relation("GroupCreatedBy", fields: [createdById], references: [id], onDelete: SetNull)
50
+ members GroupMember[]
51
+ invites GroupInvite[]
52
+ grants Grant[]
53
+
54
+ // The target of the members' and invites' composite foreign keys.
55
+ @@unique([id, orgId])
56
+ @@index([orgId])
57
+ @@map("groups")
58
+ }
59
+
60
+ model GroupMember {
61
+ id String @id @default(uuid()) @db.Uuid
62
+ groupId String @map("group_id") @db.Uuid
63
+ userId String @map("user_id") @db.Uuid
64
+ // Denormalised for row-level security; equal to groups.org_id by the
65
+ // composite foreign key below.
66
+ orgId String @map("org_id") @db.Uuid
67
+ /// A registered group role id (`registerGroupRole`). A plain string: a row must outlive the registry that produced it.
68
+ role String @default("viewer")
69
+ addedById String? @map("added_by_id") @db.Uuid
70
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
71
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
72
+
73
+ // Relations
74
+ //
75
+ // Composite: (group_id, org_id) -> groups (id, org_id).
76
+ group Group @relation(fields: [groupId, orgId], references: [id, orgId], onDelete: Cascade)
77
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
78
+ user User @relation("GroupMemberUser", fields: [userId], references: [id], onDelete: Cascade)
79
+ addedBy User? @relation("GroupMemberAddedBy", fields: [addedById], references: [id], onDelete: SetNull)
80
+
81
+ @@unique([groupId, userId])
82
+ @@index([userId])
83
+ @@index([orgId])
84
+ @@map("group_members")
85
+ }
86
+
87
+ model GroupInvite {
88
+ id String @id @default(uuid()) @db.Uuid
89
+ groupId String @map("group_id") @db.Uuid
90
+ orgId String @map("org_id") @db.Uuid
91
+ // Stored lower-cased. At most one PENDING invite per (group, email):
92
+ // group_invites_pending_uniq_idx, raw SQL only.
93
+ email String
94
+ /// The role the invitee gets on acceptance: a registered group role id. A plain string.
95
+ role String @default("viewer")
96
+ invitedById String? @map("invited_by_id") @db.Uuid
97
+ // NULL: no expiry. Expiry is evaluated when the invite is read; no sweep.
98
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
99
+ acceptedAt DateTime? @map("accepted_at") @db.Timestamptz
100
+ acceptedById String? @map("accepted_by_id") @db.Uuid
101
+ declinedAt DateTime? @map("declined_at") @db.Timestamptz
102
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
103
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
104
+
105
+ // Relations
106
+ //
107
+ // Composite: (group_id, org_id) -> groups (id, org_id).
108
+ group Group @relation(fields: [groupId, orgId], references: [id, orgId], onDelete: Cascade)
109
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
110
+ invitedBy User? @relation("GroupInviteInvitedBy", fields: [invitedById], references: [id], onDelete: SetNull)
111
+ acceptedBy User? @relation("GroupInviteAcceptedBy", fields: [acceptedById], references: [id], onDelete: SetNull)
112
+
113
+ @@index([email])
114
+ @@index([groupId])
115
+ @@index([orgId])
116
+ @@map("group_invites")
117
+ }
118
+
119
+ // =============================================================================
120
+ // Sharing: grants (PP-7.2, issue #729)
121
+ // =============================================================================
122
+ //
123
+ // A GRANT shares ONE record of a registered resource type with a user, a
124
+ // group of the same organization or (#730) a link, with a role and an
125
+ // optional expiry. The resource is POLYMORPHIC, `(resource_type,
126
+ // resource_id)`, with no foreign key: the platform cannot know app tables.
127
+ // Integrity comes from `GrantsService.deleteForResources()` (called inside the
128
+ // app's delete transaction) and the `sharing.grants.prune` job.
129
+ //
130
+ // Revocation is SOFT (`revoked_at`, `revoked_by_id`) so the audit trail
131
+ // survives; the prune job deletes revoked and expired rows after the
132
+ // retention period.
133
+ //
134
+ // Raw SQL only (migration `0027_add_grants`, intentional schema drift):
135
+ // grants_active_user_uniq_idx one ACTIVE grant per (resource, user)
136
+ // grants_active_group_uniq_idx one ACTIVE grant per (resource, group)
137
+ // grants_grantee_consistency_check the grantee columns match grantee_kind
138
+ // grants_active_ref_uniq_idx one ACTIVE grant per (resource, app kind, reference) (0037)
139
+ // Never "fix" the drift with `@@unique`, and never replace the indexes with a
140
+ // `findFirst` pre-check: the service upserts on them.
141
+ //
142
+ // The group grantee reaches its group through the COMPOSITE key
143
+ // `(grantee_group_id, org_id)` -> `groups (id, org_id)`, so a grant can never
144
+ // point at another organization's group (a foreign-key check bypasses
145
+ // row-level security).
146
+ // =============================================================================
147
+
148
+ // `grants.grantee_kind` is plain text (migration `0037_open_sharing_vocabularies`):
149
+ // the platform ships `user` (one user of the resource's organization), `group`
150
+ // (one group of the organization) and `link` (anyone holding the link token,
151
+ // #730), and an app registers more with `registerGranteeKind`. A grant of an
152
+ // app kind stores its reference in `grantee_ref` and leaves the three
153
+ // built-in grantee columns NULL; `grants_grantee_consistency_check` allows
154
+ // exactly those four shapes and `grants_active_ref_uniq_idx` keeps one ACTIVE
155
+ // grant per (resource, kind, reference).
156
+
157
+ // @extensible — back-relations only, added with "extend model Grant { ... }" in a fragment
158
+ // (an app's own annotation of a grant, for example an approval record). The table is
159
+ // org-owned with row-level security forced, so a table of the app's that holds `org_id`
160
+ // links with a composite foreign key `(grant_id, org_id)` -> `grants (id, org_id)`; the
161
+ // `@@unique([id, orgId])` below exists for it. The two partial unique indexes of the
162
+ // table stay raw SQL (never an `@@unique` on their columns).
163
+ model Grant {
164
+ id String @id @default(uuid()) @db.Uuid
165
+ orgId String @map("org_id") @db.Uuid
166
+ /// Registered resource type id. Permanent once rows exist, like a job type string.
167
+ resourceType String @map("resource_type")
168
+ resourceId String @map("resource_id") @db.Uuid
169
+ /// `user`, `group`, `link` or a registered app kind. A plain string: a row must outlive the registry that produced it.
170
+ granteeKind String @map("grantee_kind")
171
+ granteeUserId String? @map("grantee_user_id") @db.Uuid
172
+ granteeGroupId String? @map("grantee_group_id") @db.Uuid
173
+ /// The reference of an app-registered grantee kind (a domain, a team id), as its `validateGrantee` normalised it. NULL for the built-in kinds.
174
+ granteeRef String? @map("grantee_ref")
175
+ /// One of the resource type's registered roles. A plain string: a row must outlive the registry that produced it.
176
+ role String
177
+ /// Link grants only (#730): SHA-256 of the token, and the token encrypted with the platform secret cipher.
178
+ linkTokenHash String? @unique @map("link_token_hash")
179
+ linkTokenCiphertext String? @map("link_token_ciphertext") @db.Text
180
+ linkLabel String? @map("link_label")
181
+ expiresAt DateTime? @map("expires_at") @db.Timestamptz
182
+ revokedAt DateTime? @map("revoked_at") @db.Timestamptz
183
+ revokedById String? @map("revoked_by_id") @db.Uuid
184
+ grantedById String? @map("granted_by_id") @db.Uuid
185
+ /// Apps keep extra fields here (spec: never add columns to package-owned tables).
186
+ metadata Json? @db.JsonB
187
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
188
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
189
+
190
+ // Relations
191
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Cascade)
192
+ granteeUser User? @relation("GrantGranteeUser", fields: [granteeUserId], references: [id], onDelete: Cascade)
193
+ // Composite: (grantee_group_id, org_id) -> groups (id, org_id).
194
+ granteeGroup Group? @relation(fields: [granteeGroupId, orgId], references: [id, orgId], onDelete: Cascade)
195
+ revokedBy User? @relation("GrantRevokedBy", fields: [revokedById], references: [id], onDelete: SetNull)
196
+ grantedBy User? @relation("GrantGrantedBy", fields: [grantedById], references: [id], onDelete: SetNull)
197
+
198
+ @@index([resourceType, resourceId])
199
+ @@index([granteeUserId])
200
+ @@index([granteeGroupId])
201
+ @@index([orgId])
202
+ // The target of an app table's composite foreign key (id, org_id); see the note above the model.
203
+ @@unique([id, orgId])
204
+ @@map("grants")
205
+ }
206
+
207
+ extend model User {
208
+ groupsCreated Group[] @relation("GroupCreatedBy")
209
+ groupMemberships GroupMember[] @relation("GroupMemberUser")
210
+ groupMembersAdded GroupMember[] @relation("GroupMemberAddedBy")
211
+ groupInvitesSent GroupInvite[] @relation("GroupInviteInvitedBy")
212
+ groupInvitesClaimed GroupInvite[] @relation("GroupInviteAcceptedBy")
213
+ grantsReceived Grant[] @relation("GrantGranteeUser")
214
+ grantsRevoked Grant[] @relation("GrantRevokedBy")
215
+ grantsGiven Grant[] @relation("GrantGrantedBy")
216
+ }
217
+
218
+ extend model Organization {
219
+ groups Group[]
220
+ groupMembers GroupMember[]
221
+ groupInvites GroupInvite[]
222
+ grants Grant[]
223
+ }
@@ -23,16 +23,31 @@ model StorageObject {
23
23
  s3UploadId String? @map("s3_upload_id") // S3 multipart upload ID
24
24
  metadata Json? // JSONB for flexible metadata
25
25
  uploadedById String? @map("uploaded_by_id") @db.Uuid
26
+ // The organization the object belongs to (#725). NOT NULL, row-level
27
+ // security forced (policy `storage_objects_org_isolation`, see
28
+ // `0025_org_scoped_rls`). `Restrict`: an organization with objects cannot be
29
+ // deleted until they are purged deliberately.
30
+ orgId String @map("org_id") @db.Uuid
26
31
  createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
27
32
  updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
28
33
 
29
34
  // Relations
30
- uploadedBy User? @relation("UserStorageObjects", fields: [uploadedById], references: [id], onDelete: SetNull)
31
- chunks StorageObjectChunk[]
35
+ uploadedBy User? @relation("UserStorageObjects", fields: [uploadedById], references: [id], onDelete: SetNull)
36
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
37
+ chunks StorageObjectChunk[]
38
+ migrationItems StorageMigrationItem[]
32
39
 
40
+ // The target of the chunks' composite foreign key (object_id, org_id): a
41
+ // reference between two org-owned tables is composite, because a foreign-key
42
+ // check bypasses row-level security (ADR 0002 D5).
43
+ @@unique([id, orgId])
33
44
  @@index([uploadedById])
34
45
  @@index([status])
35
46
  @@index([createdAt])
47
+ // The policy filter `org_id = X` leads every query; these serve the hot paths
48
+ // behind it (a user's list, newest first; the cleanup sweep by status).
49
+ @@index([orgId, uploadedById, createdAt])
50
+ @@index([orgId, status])
36
51
  @@map("storage_objects")
37
52
  }
38
53
 
@@ -42,16 +57,140 @@ model StorageObjectChunk {
42
57
  partNumber Int @map("part_number") // S3 part number (1-10000)
43
58
  eTag String @map("e_tag") // S3 ETag for verification
44
59
  size BigInt // Chunk size in bytes
60
+ // The organization of the parent object (#725), carried here because a policy
61
+ // cannot join through the parent. NOT NULL, row-level security forced.
62
+ orgId String @map("org_id") @db.Uuid
45
63
  uploadedAt DateTime @default(now()) @map("uploaded_at") @db.Timestamptz
46
64
 
47
65
  // Relations
48
- object StorageObject @relation(fields: [objectId], references: [id], onDelete: Cascade)
66
+ //
67
+ // Composite: (object_id, org_id) -> storage_objects (id, org_id), so a chunk
68
+ // can never name another organization's object. Cascade, as before.
69
+ object StorageObject @relation(fields: [objectId, orgId], references: [id, orgId], onDelete: Cascade)
70
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
49
71
 
50
72
  @@unique([objectId, partNumber])
51
73
  @@index([objectId])
74
+ @@index([orgId, objectId])
52
75
  @@map("storage_object_chunks")
53
76
  }
54
77
 
78
+ // =============================================================================
79
+ // Copy-only provider migration (issue #1093)
80
+ // =============================================================================
81
+ //
82
+ // An administrator copies every `ready` object recorded on one storage driver
83
+ // to another: copy (streamed), verify (size and sha256 of the bytes read back
84
+ // from the target), repoint the `storage_objects` row, and leave the source
85
+ // object in place as a fallback. One job (`storage.migrate_object`) per item.
86
+ //
87
+ // A RUN is deployment-wide (storage configuration is system scope), so its
88
+ // `org_id` is NULL today: visible to the bypass (system) client only, like a
89
+ // system-scope `webhook_endpoints` row. The column exists so a future
90
+ // organization-owned run needs no migration. An ITEM carries its object's
91
+ // organization (NOT NULL), and its link to the object is the composite
92
+ // (object_id, org_id) foreign key, so an item can never name another
93
+ // organization's object (ADR 0002 D5).
94
+ //
95
+ // At most ONE run is pending or running: the raw-SQL partial unique index
96
+ // `storage_migration_runs_active_uniq_idx` (raw-sql-indexes.json), never a
97
+ // findFirst pre-check.
98
+ // =============================================================================
99
+
100
+ enum StorageMigrationRunStatus {
101
+ pending // Created; the planner job has not started yet
102
+ running // Planning or copying
103
+ completed // Every item migrated or skipped
104
+ failed // Finished with at least one failed item, or the planner gave up
105
+ cancelled // Stopped by an administrator
106
+ }
107
+
108
+ enum StorageMigrationItemStatus {
109
+ pending // Queued, not claimed
110
+ copying // A job is copying it now
111
+ migrated // Copied, verified and repointed
112
+ failed // Gave up (attempt budget spent, or verification failed every time)
113
+ skipped // Nothing to do: deleted, moved, already on the target, or run cancelled
114
+ }
115
+
116
+ model StorageMigrationRun {
117
+ id String @id @default(uuid()) @db.Uuid
118
+ // NULL: a deployment-wide run (today, every run). Row-level security forced
119
+ // (policy `storage_migration_runs_org_isolation`).
120
+ orgId String? @map("org_id") @db.Uuid
121
+ sourceProvider String @map("source_provider") @db.VarChar(48)
122
+ targetProvider String @map("target_provider") @db.VarChar(48)
123
+ status StorageMigrationRunStatus @default(pending)
124
+ // Snapshots written by the planner and the per-item jobs; GET recomputes
125
+ // them from the items, so a crash between an item write and a counter write
126
+ // never shows a wrong figure.
127
+ totalCount Int @default(0) @map("total_count")
128
+ migratedCount Int @default(0) @map("migrated_count")
129
+ failedCount Int @default(0) @map("failed_count")
130
+ skippedCount Int @default(0) @map("skipped_count")
131
+ // Set when the planner has created every item and enqueued every job; the
132
+ // run cannot finalize before.
133
+ plannedAt DateTime? @map("planned_at") @db.Timestamptz
134
+ startedById String? @map("started_by_id") @db.Uuid
135
+ cancelledById String? @map("cancelled_by_id") @db.Uuid
136
+ startedAt DateTime? @map("started_at") @db.Timestamptz
137
+ finishedAt DateTime? @map("finished_at") @db.Timestamptz
138
+ cancelledAt DateTime? @map("cancelled_at") @db.Timestamptz
139
+ lastError String? @map("last_error") @db.VarChar(1000)
140
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
141
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
142
+
143
+ org Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)
144
+ startedBy User? @relation("StorageMigrationRunsStarted", fields: [startedById], references: [id], onDelete: SetNull)
145
+ cancelledBy User? @relation("StorageMigrationRunsCancelled", fields: [cancelledById], references: [id], onDelete: SetNull)
146
+ items StorageMigrationItem[]
147
+
148
+ @@index([createdAt(sort: Desc)])
149
+ @@index([status])
150
+ @@index([orgId])
151
+ @@map("storage_migration_runs")
152
+ }
153
+
154
+ model StorageMigrationItem {
155
+ id String @id @default(uuid()) @db.Uuid
156
+ runId String @map("run_id") @db.Uuid
157
+ objectId String @map("object_id") @db.Uuid
158
+ // The object's organization, carried here because a policy cannot join
159
+ // through the parent. NOT NULL, row-level security forced.
160
+ orgId String @map("org_id") @db.Uuid
161
+ status StorageMigrationItemStatus @default(pending)
162
+ // The job that copies it, once the planner enqueued one (a retried planner
163
+ // enqueues only the items that have none).
164
+ jobId String? @map("job_id") @db.Uuid
165
+ // The object's byte count and the sha256 the copy was verified against.
166
+ sizeBytes BigInt? @map("size_bytes")
167
+ checksumSha256 String? @map("checksum_sha256") @db.Char(64)
168
+ lastError String? @map("last_error") @db.VarChar(1000)
169
+ createdAt DateTime @default(now()) @map("created_at") @db.Timestamptz
170
+ updatedAt DateTime @updatedAt @map("updated_at") @db.Timestamptz
171
+
172
+ run StorageMigrationRun @relation(fields: [runId], references: [id], onDelete: Cascade)
173
+ // Composite: (object_id, org_id) -> storage_objects (id, org_id). Cascade: an
174
+ // object deleted mid-run takes its item with it.
175
+ object StorageObject @relation(fields: [objectId, orgId], references: [id, orgId], onDelete: Cascade)
176
+ org Organization @relation(fields: [orgId], references: [id], onDelete: Restrict)
177
+
178
+ // The idempotency anchor: one item per object per run.
179
+ @@unique([runId, objectId])
180
+ @@index([runId, status])
181
+ @@index([orgId, objectId])
182
+ @@map("storage_migration_items")
183
+ }
184
+
55
185
  extend model User {
56
- storageObjects StorageObject[] @relation("UserStorageObjects")
186
+ storageObjects StorageObject[] @relation("UserStorageObjects")
187
+ storageMigrationRunsStarted StorageMigrationRun[] @relation("StorageMigrationRunsStarted")
188
+ storageMigrationRunsCancelled StorageMigrationRun[] @relation("StorageMigrationRunsCancelled")
189
+ }
190
+
191
+ extend model Organization {
192
+ storageObjects StorageObject[]
193
+ storageObjectChunks StorageObjectChunk[]
194
+ storageMigrationRuns StorageMigrationRun[]
195
+ storageMigrationItems StorageMigrationItem[]
57
196
  }