@crombolo/data 0.73.2 → 0.74.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/data",
3
- "version": "0.73.2",
3
+ "version": "0.74.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. SQLite and Postgres storage for crombolo: schema, migrations and repositories.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -29,7 +29,7 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@crombolo/core": "0.73.2",
32
+ "@crombolo/core": "0.74.1",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/index.ts CHANGED
@@ -20,6 +20,7 @@ export * from './relations.ts'
20
20
  export * from './repositories/approvals.ts'
21
21
  export * from './repositories/bundle-grants.ts'
22
22
  export * from './repositories/bundles.ts'
23
+ export * from './repositories/change-sources.ts'
23
24
  export * from './repositories/changes.ts'
24
25
  export * from './repositories/content-applied.ts'
25
26
  export * from './repositories/content-events.ts'
@@ -62,6 +63,7 @@ export * from './repositories/two-factor.ts'
62
63
  export * from './repositories/user-data.ts'
63
64
  export * from './repositories/users.ts'
64
65
  export * from './repositories/webhooks.ts'
66
+ export * from './repositories/workspace-events.ts'
65
67
  export * from './repositories/workspace-files.ts'
66
68
  export * from './repositories/workspace-links.ts'
67
69
  export * from './repositories/workspace-processes.ts'
@@ -83,6 +85,7 @@ export * from './schema/bundles-disabled.ts'
83
85
  export * from './schema/bundles-in-settings.ts'
84
86
  export * from './schema/bundles-rename.ts'
85
87
  export * from './schema/change-report.ts'
88
+ export * from './schema/change-sources.ts'
86
89
  export * from './schema/change-transfer.ts'
87
90
  export * from './schema/changes.ts'
88
91
  export * from './schema/cli-tokens.ts'
@@ -152,6 +155,7 @@ export * from './schema/user-start-nodes-dropped.ts'
152
155
  export * from './schema/users-localisation.ts'
153
156
  export * from './schema/values.ts'
154
157
  export * from './schema/webhooks.ts'
158
+ export * from './schema/workspace-conflicts.ts'
155
159
  export * from './schema/workspace-links.ts'
156
160
  export * from './schema/workspace-merge.ts'
157
161
  export * from './schema/workspace-privacy.ts'
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Where site bundles staged as changes come from (story 399). A source's base is the
3
+ * bundle's items as its last merged staging carried them; a workspace staged from a
4
+ * source holds what it staged until it merges, when that becomes the source's base, or
5
+ * is discarded, when the base stays as it was. docs/changes.md.
6
+ */
7
+ import type { Db } from '../database.ts'
8
+ import { DbDate } from '../dialect.ts'
9
+
10
+ export class ChangeSourceRepository {
11
+ #db: Db
12
+
13
+ constructor(db: Db) {
14
+ this.#db = db
15
+ }
16
+
17
+ /** The source's base, as text, when a staging from it has merged. */
18
+ async base(name: string): Promise<string | undefined> {
19
+ const row = await this.#db.q
20
+ .selectFrom('change_source')
21
+ .select('snapshot')
22
+ .where('name', '=', name)
23
+ .executeTakeFirst()
24
+ return row ? String(row.snapshot) : undefined
25
+ }
26
+
27
+ /** The open workspace staged from the source, when there is one. */
28
+ async stagedFrom(name: string): Promise<number | undefined> {
29
+ const row = await this.#db.q
30
+ .selectFrom('change_source_staged as s')
31
+ .innerJoin('workspace as w', 'w.id', 's.workspace_id')
32
+ .select('s.workspace_id')
33
+ .where('s.source', '=', name)
34
+ .where('w.state', '=', 'open')
35
+ .executeTakeFirst()
36
+ return row ? Number(row.workspace_id) : undefined
37
+ }
38
+
39
+ /** What a workspace holds, staged from the source: its base once the workspace merges. */
40
+ async staged(workspaceId: number, name: string, snapshot: string): Promise<void> {
41
+ await this.#db.q
42
+ .deleteFrom('change_source_staged')
43
+ .where('workspace_id', '=', workspaceId)
44
+ .execute()
45
+ await this.#db.q
46
+ .insertInto('change_source_staged')
47
+ .values({ workspace_id: workspaceId, source: name, snapshot })
48
+ .execute()
49
+ }
50
+
51
+ /** A workspace merged: what it staged from a source becomes that source's base. */
52
+ async merged(workspaceId: number): Promise<void> {
53
+ const row = await this.#db.q
54
+ .selectFrom('change_source_staged')
55
+ .select(['source', 'snapshot'])
56
+ .where('workspace_id', '=', workspaceId)
57
+ .executeTakeFirst()
58
+ if (!row) return
59
+ const name = String(row.source)
60
+ const now = DbDate.toDb(new Date())
61
+ await this.#db.q.deleteFrom('change_source').where('name', '=', name).execute()
62
+ await this.#db.q
63
+ .insertInto('change_source')
64
+ .values({ name, snapshot: String(row.snapshot), updated_at: now })
65
+ .execute()
66
+ await this.#db.q
67
+ .deleteFrom('change_source_staged')
68
+ .where('workspace_id', '=', workspaceId)
69
+ .execute()
70
+ }
71
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * A workspace's life as webhook events (story 400): opened, merged, discarded, and
3
+ * in conflict with Shared. Each is written to the outbox in the transaction that did
4
+ * it, carrying the workspace as it was then, so it goes out once that commits.
5
+ */
6
+ import { normaliseUuid } from '@crombolo/core'
7
+ import { currentAuditContext } from '../audit.ts'
8
+ import type { Db } from '../database.ts'
9
+ import { ContentEventRepository } from './content-events.ts'
10
+
11
+ export const WORKSPACE_OPENED = 'Crombolo.WorkspaceOpened'
12
+ export const WORKSPACE_MERGED = 'Crombolo.WorkspaceMerged'
13
+ export const WORKSPACE_DISCARDED = 'Crombolo.WorkspaceDiscarded'
14
+ export const WORKSPACE_CONFLICTED = 'Crombolo.WorkspaceConflicted'
15
+
16
+ export const WORKSPACE_EVENT_ALIASES = [
17
+ WORKSPACE_OPENED,
18
+ WORKSPACE_MERGED,
19
+ WORKSPACE_DISCARDED,
20
+ WORKSPACE_CONFLICTED,
21
+ ] as const
22
+
23
+ /** An item newly in conflict: a page, media or Library item by key, or a file by path. */
24
+ export interface ConflictedItem {
25
+ kind: string
26
+ key?: string
27
+ path?: string
28
+ name: string
29
+ }
30
+
31
+ /** The workspace as an event carries it. */
32
+ export interface WorkspaceFacts {
33
+ key: string
34
+ name: string
35
+ personal: boolean
36
+ owner: string
37
+ state: 'open' | 'merged'
38
+ }
39
+
40
+ const KINDS: Record<string, string> = {
41
+ [WORKSPACE_OPENED]: 'workspace-opened',
42
+ [WORKSPACE_MERGED]: 'workspace-merged',
43
+ [WORKSPACE_DISCARDED]: 'workspace-discarded',
44
+ [WORKSPACE_CONFLICTED]: 'workspace-conflicted',
45
+ }
46
+
47
+ /** A person, or a tool acting for one (a sign-in exchanged with an actor, story 364). */
48
+ function madeBy(): { by: 'person' | 'tool'; tool?: { id: string; name: string } } {
49
+ const actor = currentAuditContext()?.exchange?.actor
50
+ return actor
51
+ ? { by: 'tool', tool: { id: actor.id, name: actor.name ?? actor.id } }
52
+ : { by: 'person' }
53
+ }
54
+
55
+ /** Writes one workspace event to the outbox, on `db`: the transaction that did it. */
56
+ export async function recordWorkspaceEvent(
57
+ db: Db,
58
+ alias: (typeof WORKSPACE_EVENT_ALIASES)[number],
59
+ workspace: WorkspaceFacts,
60
+ more: {
61
+ by?: string | null
62
+ change?: { key: string; name: string | null }
63
+ items?: ConflictedItem[]
64
+ } = {},
65
+ ): Promise<void> {
66
+ const userKey = more.by ? normaliseUuid(more.by) : null
67
+ await new ContentEventRepository(db).record({
68
+ kind: KINDS[alias] as string,
69
+ entityType: 'Workspace',
70
+ entityKey: workspace.key,
71
+ facts: {
72
+ v: 1,
73
+ webhook: {
74
+ alias,
75
+ key: workspace.key,
76
+ workspace,
77
+ ...madeBy(),
78
+ ...(more.change ? { change: more.change } : {}),
79
+ ...(more.items ? { items: more.items } : {}),
80
+ },
81
+ },
82
+ actor: { kind: 'user', name: '', userKey },
83
+ })
84
+ }
@@ -7,7 +7,17 @@ import { normaliseUuid } from '@crombolo/core'
7
7
  import type { Db } from '../database.ts'
8
8
  import { DbDate, fromDbBool } from '../dialect.ts'
9
9
  import { Locks } from '../locks.ts'
10
+ import { ChangeSourceRepository } from './change-sources.ts'
10
11
  import { type ContentKind, deleteNodeRows } from './documents.ts'
12
+ import {
13
+ type ConflictedItem,
14
+ recordWorkspaceEvent,
15
+ WORKSPACE_CONFLICTED,
16
+ WORKSPACE_DISCARDED,
17
+ WORKSPACE_MERGED,
18
+ WORKSPACE_OPENED,
19
+ type WorkspaceFacts,
20
+ } from './workspace-events.ts'
11
21
  import { WorkspaceFileRepository } from './workspace-files.ts'
12
22
 
13
23
  /** A change staged in a workspace (story 383), with the schedules its merge sets (story 395). */
@@ -73,6 +83,19 @@ export interface WorkspaceChange {
73
83
  kind: 'changed' | 'made' | 'move' | 'sort' | 'trash' | 'delete' | 'orphaned' | 'gone'
74
84
  }
75
85
 
86
+ /** How an item in conflict is kept: a file by its path, anything else by its kind and key. */
87
+ const conflictId = (item: ConflictedItem) =>
88
+ (item.path ? `file:${item.path}` : `${item.kind}:${item.key}`).slice(0, 512)
89
+
90
+ /** A workspace as its events carry it (story 400). */
91
+ const factsOf = (workspace: Workspace): WorkspaceFacts => ({
92
+ key: workspace.key,
93
+ name: workspace.name,
94
+ personal: workspace.personal,
95
+ owner: workspace.ownerKey,
96
+ state: workspace.state,
97
+ })
98
+
76
99
  export class WorkspaceRepository {
77
100
  #db: Db
78
101
 
@@ -86,6 +109,8 @@ export class WorkspaceRepository {
86
109
  personal?: boolean
87
110
  visibility?: 'members' | 'editors'
88
111
  tellOthers?: boolean
112
+ /** Opened only to see what something would do, then discarded: raises nothing. */
113
+ quiet?: boolean
89
114
  }): Promise<Workspace> {
90
115
  const key = normaliseUuid(crypto.randomUUID())
91
116
  const now = DbDate.toDb(new Date())
@@ -102,7 +127,12 @@ export class WorkspaceRepository {
102
127
  updated_at: now,
103
128
  })
104
129
  .execute()
105
- return (await this.byKey(key)) as Workspace
130
+ const opened = (await this.byKey(key)) as Workspace
131
+ if (!input.quiet)
132
+ await recordWorkspaceEvent(this.#db, WORKSPACE_OPENED, factsOf(opened), {
133
+ by: input.ownerKey,
134
+ })
135
+ return opened
106
136
  }
107
137
 
108
138
  /** A person's own unnamed workspace, while it is open (story 380). */
@@ -117,6 +147,11 @@ export class WorkspaceRepository {
117
147
  return (await this.#withMembers(rows))[0]
118
148
  }
119
149
 
150
+ async byId(id: number): Promise<Workspace | undefined> {
151
+ const rows = await this.#db.q.selectFrom('workspace').selectAll().where('id', '=', id).execute()
152
+ return (await this.#withMembers(rows))[0]
153
+ }
154
+
120
155
  async byKey(key: string): Promise<Workspace | undefined> {
121
156
  const rows = await this.#db.q
122
157
  .selectFrom('workspace')
@@ -239,10 +274,13 @@ export class WorkspaceRepository {
239
274
  ]
240
275
  }
241
276
 
242
- /** Removes the workspace and everything carrying it; Shared is as it was. */
243
- async discard(id: number): Promise<void> {
277
+ /** Removes the workspace and everything carrying it; Shared is as it was. `by` discarded it. */
278
+ async discard(id: number, by?: string | null, options: { quiet?: boolean } = {}): Promise<void> {
244
279
  await this.#db.locks.withLock(Locks.ContentTree, () =>
245
280
  this.#db.transaction(async (tx) => {
281
+ const gone = await new WorkspaceRepository(tx).byId(id)
282
+ if (gone && !options.quiet)
283
+ await recordWorkspaceEvent(tx, WORKSPACE_DISCARDED, factsOf(gone), { by })
246
284
  const versions = () =>
247
285
  tx.q.selectFrom('content_version').select('id').where('workspace_id', '=', id)
248
286
  const made = (
@@ -262,6 +300,8 @@ export class WorkspaceRepository {
262
300
  'workspace_document',
263
301
  'workspace_member',
264
302
  'workspace_link',
303
+ 'workspace_conflict_raised',
304
+ 'change_source_staged',
265
305
  ] as const)
266
306
  await tx.q.deleteFrom(table).where('workspace_id', '=', id).execute()
267
307
  if (made.length > 0) await deleteNodeRows(tx, { ids: made })
@@ -438,9 +478,12 @@ export class WorkspaceRepository {
438
478
  'workspace_pending',
439
479
  'workspace_document_culture',
440
480
  'workspace_document',
481
+ 'workspace_conflict_raised',
441
482
  ] as const)
442
483
  await this.#db.q.deleteFrom(table).where('workspace_id', '=', id).execute()
443
484
  await dropWorkspaceSchema(this.#db, id)
485
+ // Story 399: what it staged from a source is now that source's base.
486
+ await new ChangeSourceRepository(this.#db).merged(id)
444
487
  const now = DbDate.toDb(new Date())
445
488
  await this.#db.q
446
489
  .updateTable('workspace')
@@ -449,6 +492,85 @@ export class WorkspaceRepository {
449
492
  .execute()
450
493
  }
451
494
 
495
+ /** Story 400: a merge closed it, making `change`: raises `WorkspaceMerged`, in the merge's transaction. */
496
+ async announceMerged(
497
+ id: number,
498
+ change: { key: string; name: string | null },
499
+ by: string | null,
500
+ ): Promise<void> {
501
+ const merged = await this.byId(id)
502
+ if (merged)
503
+ await recordWorkspaceEvent(this.#db, WORKSPACE_MERGED, factsOf(merged), { by, change })
504
+ }
505
+
506
+ /**
507
+ * Story 400: the items now in conflict with Shared. Those not raised before raise
508
+ * `WorkspaceConflicted` together, and are kept so they are raised once until settled.
509
+ */
510
+ async conflicted(id: number, items: readonly ConflictedItem[], by: string | null): Promise<void> {
511
+ if (items.length === 0) return
512
+ const raised = new Set(
513
+ (
514
+ await this.#db.q
515
+ .selectFrom('workspace_conflict_raised')
516
+ .select('item')
517
+ .where('workspace_id', '=', id)
518
+ .execute()
519
+ ).map((r) => String(r.item)),
520
+ )
521
+ const fresh = items.filter((i) => !raised.has(conflictId(i)))
522
+ if (fresh.length === 0) return
523
+ const now = DbDate.toDb(new Date())
524
+ for (const item of fresh)
525
+ await this.#db.q
526
+ .insertInto('workspace_conflict_raised')
527
+ .values({ workspace_id: id, item: conflictId(item), raised_at: now })
528
+ .execute()
529
+ const workspace = await this.byId(id)
530
+ if (workspace)
531
+ await recordWorkspaceEvent(this.#db, WORKSPACE_CONFLICTED, factsOf(workspace), {
532
+ by,
533
+ items: fresh,
534
+ })
535
+ }
536
+
537
+ /**
538
+ * Story 400: what a person settled in the workspace, a page by its key or a file by its
539
+ * path, so a conflict there later is raised again. `keepFiles` are files still in conflict.
540
+ */
541
+ async settled(id: number, settled: { key?: string; files?: { keep: readonly string[] } }) {
542
+ if (settled.key) {
543
+ const key = normaliseUuid(settled.key)
544
+ await this.#db.q
545
+ .deleteFrom('workspace_conflict_raised')
546
+ .where('workspace_id', '=', id)
547
+ .where(
548
+ 'item',
549
+ 'in',
550
+ ['document', 'media', 'element', 'blueprint'].map((kind) => `${kind}:${key}`),
551
+ )
552
+ .execute()
553
+ }
554
+ if (settled.files) {
555
+ let query = this.#db.q
556
+ .deleteFrom('workspace_conflict_raised')
557
+ .where('workspace_id', '=', id)
558
+ .where('item', 'like', 'file:%')
559
+ const keep = settled.files.keep.map((path) => `file:${path}`)
560
+ if (keep.length > 0) query = query.where('item', 'not in', keep)
561
+ await query.execute()
562
+ }
563
+ }
564
+
565
+ /** Story 400: an item no longer in conflict, so a conflict there later is raised again. */
566
+ async settle(id: number, item: ConflictedItem): Promise<void> {
567
+ await this.#db.q
568
+ .deleteFrom('workspace_conflict_raised')
569
+ .where('workspace_id', '=', id)
570
+ .where('item', '=', conflictId(item))
571
+ .execute()
572
+ }
573
+
452
574
  async #withMembers(
453
575
  rows: ReadonlyArray<{
454
576
  id: number
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Migration 094 — where a site bundle staged as a change came from (story 399): each
3
+ * source's base, the items as it last merged them, and what each workspace staged from
4
+ * one holds until it merges.
5
+ */
6
+ import type { Db } from '../database.ts'
7
+ import type { Migration } from '../migrations.ts'
8
+ import { sql } from '../query.ts'
9
+ import { STATE_WORKSPACE_CONFLICTS } from './workspace-conflicts.ts'
10
+
11
+ export const STATE_CHANGE_SOURCES = '{6d3b0f72-0094-4c8e-9f20-4b7e0d5c0094}'
12
+
13
+ export const changeSourcesMigration: Migration = {
14
+ from: STATE_WORKSPACE_CONFLICTS,
15
+ to: STATE_CHANGE_SOURCES,
16
+ name: 'AddChangeSources',
17
+ kind: 'expand',
18
+ release: '0.74.0',
19
+ async up(db: Db) {
20
+ const t = db.dialect.types
21
+ await db.q.schema
22
+ .createTable('change_source')
23
+ .addColumn('name', sql.raw(t.varchar(255)), (c) => c.primaryKey())
24
+ .addColumn('snapshot', sql.raw(t.text), (c) => c.notNull())
25
+ .addColumn('updated_at', sql.raw(t.timestamp), (c) => c.notNull())
26
+ .execute()
27
+ await db.q.schema
28
+ .createTable('change_source_staged')
29
+ .addColumn('workspace_id', sql.raw(t.integer), (c) => c.primaryKey())
30
+ .addColumn('source', sql.raw(t.varchar(255)), (c) => c.notNull())
31
+ .addColumn('snapshot', sql.raw(t.text), (c) => c.notNull())
32
+ .execute()
33
+ },
34
+ }
@@ -28,6 +28,7 @@ import { bundlesDisabledMigration } from './bundles-disabled.ts'
28
28
  import { bundlesInSettingsMigration } from './bundles-in-settings.ts'
29
29
  import { bundlesRenameMigration } from './bundles-rename.ts'
30
30
  import { changeReportMigration } from './change-report.ts'
31
+ import { changeSourcesMigration } from './change-sources.ts'
31
32
  import { changeTransferMigration } from './change-transfer.ts'
32
33
  import { changesMigration } from './changes.ts'
33
34
  import { cliTokensMigration } from './cli-tokens.ts'
@@ -99,6 +100,7 @@ import { userStartNodesDroppedMigration } from './user-start-nodes-dropped.ts'
99
100
  import { usersLocalisationMigration } from './users-localisation.ts'
100
101
  import { valuesMigration } from './values.ts'
101
102
  import { webhooksMigration } from './webhooks.ts'
103
+ import { workspaceConflictsMigration } from './workspace-conflicts.ts'
102
104
  import { workspaceLinksMigration } from './workspace-links.ts'
103
105
  import { workspaceMergeMigration } from './workspace-merge.ts'
104
106
  import { workspacePrivacyMigration } from './workspace-privacy.ts'
@@ -199,4 +201,6 @@ export const cromboloPlan = new MigrationPlan([
199
201
  workspacePrivacyMigration,
200
202
  servedChangesMigration,
201
203
  workspaceProcessesMigration,
204
+ workspaceConflictsMigration,
205
+ changeSourcesMigration,
202
206
  ])
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Migration 093 — the conflicts with Shared each workspace has been told of (story
3
+ * 400), so `Crombolo.WorkspaceConflicted` names an item once until it is settled.
4
+ */
5
+ import type { Db } from '../database.ts'
6
+ import type { Migration } from '../migrations.ts'
7
+ import { sql } from '../query.ts'
8
+ import { STATE_WORKSPACE_PROCESSES } from './workspace-processes.ts'
9
+
10
+ export const STATE_WORKSPACE_CONFLICTS = '{5c2a9e61-0093-4b7d-8e1f-3a6d9c4b0093}'
11
+
12
+ export const workspaceConflictsMigration: Migration = {
13
+ from: STATE_WORKSPACE_PROCESSES,
14
+ to: STATE_WORKSPACE_CONFLICTS,
15
+ name: 'AddWorkspaceConflictsRaised',
16
+ kind: 'expand',
17
+ release: '0.74.0',
18
+ async up(db: Db) {
19
+ const t = db.dialect.types
20
+ await db.q.schema
21
+ .createTable('workspace_conflict_raised')
22
+ .addColumn('workspace_id', sql.raw(t.integer), (c) => c.notNull())
23
+ .addColumn('item', sql.raw(t.varchar(512)), (c) => c.notNull())
24
+ .addColumn('raised_at', sql.raw(t.timestamp), (c) => c.notNull())
25
+ .addPrimaryKeyConstraint('pk_workspace_conflict_raised', ['workspace_id', 'item'])
26
+ .execute()
27
+ },
28
+ }
package/src/tables.gen.ts CHANGED
@@ -179,6 +179,16 @@ export interface CoreTables {
179
179
  subject_name: string | null
180
180
  subject_type: string
181
181
  }
182
+ change_source: {
183
+ name: string
184
+ snapshot: string
185
+ updated_at: Timestamp
186
+ }
187
+ change_source_staged: {
188
+ snapshot: string
189
+ source: string
190
+ workspace_id: Generated<number>
191
+ }
182
192
  cli_token: {
183
193
  created_at: Timestamp
184
194
  expires_at: Timestamp
@@ -1032,6 +1042,11 @@ export interface CoreTables {
1032
1042
  updated_at: Timestamp
1033
1043
  visibility: Generated<string>
1034
1044
  }
1045
+ workspace_conflict_raised: {
1046
+ item: string
1047
+ raised_at: Timestamp
1048
+ workspace_id: Generated<number>
1049
+ }
1035
1050
  workspace_document: {
1036
1051
  base_event_id: number | null
1037
1052
  base_published: Bool | null