@crombolo/data 0.75.0 → 0.77.0

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.75.0",
3
+ "version": "0.77.0",
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.75.0",
32
+ "@crombolo/core": "0.77.0",
33
33
  "kysely": "0.29.6"
34
34
  }
35
35
  }
package/src/index.ts CHANGED
@@ -63,6 +63,7 @@ export * from './repositories/two-factor.ts'
63
63
  export * from './repositories/user-data.ts'
64
64
  export * from './repositories/users.ts'
65
65
  export * from './repositories/webhooks.ts'
66
+ export * from './repositories/workspace-errors.ts'
66
67
  export * from './repositories/workspace-events.ts'
67
68
  export * from './repositories/workspace-files.ts'
68
69
  export * from './repositories/workspace-links.ts'
@@ -157,10 +158,12 @@ export * from './schema/users-localisation.ts'
157
158
  export * from './schema/values.ts'
158
159
  export * from './schema/webhooks.ts'
159
160
  export * from './schema/workspace-conflicts.ts'
161
+ export * from './schema/workspace-errors.ts'
160
162
  export * from './schema/workspace-links.ts'
161
163
  export * from './schema/workspace-merge.ts'
162
164
  export * from './schema/workspace-privacy.ts'
163
165
  export * from './schema/workspace-processes.ts'
166
+ export * from './schema/workspace-schedules.ts'
164
167
  export * from './schema/workspace-schema.ts'
165
168
  export * from './schema/workspaces.ts'
166
169
  export * from './schema-ops.ts'
@@ -2,6 +2,8 @@
2
2
  * A cluster-wide pause on editing, held in `key_value` so every node sees it on
3
3
  * its next write rather than its next poll. Readers are never affected; the
4
4
  * write gate (`assertNodeMayWrite`) refuses editor writes while it is set.
5
+ * Story 409: a pause may carry when it ends; past that, by the reading node's own
6
+ * clock, it is no pause, so nothing has to run for it to end.
5
7
  */
6
8
  import type { Db } from './database.ts'
7
9
  import { readKeyValue, writeKeyValue } from './migrations.ts'
@@ -12,34 +14,59 @@ export interface WritesPaused {
12
14
  reason: string
13
15
  by: string | null
14
16
  at: string
17
+ /** When it ends, as an ISO time; null for a pause that lasts until resumed. */
18
+ until: string | null
15
19
  }
16
20
 
17
- export function parseWritesPaused(value: string | null | undefined): WritesPaused | undefined {
21
+ /** Whether a pause read back is over by now: it had an end, and that has passed. Pure. */
22
+ export const pauseEnded = (paused: { until: string | null }, now = new Date()): boolean =>
23
+ paused.until !== null && Date.parse(paused.until) <= now.getTime()
24
+
25
+ /** The pause a stored value holds, or undefined for none, or one whose time has passed. */
26
+ export function parseWritesPaused(
27
+ value: string | null | undefined,
28
+ now = new Date(),
29
+ ): WritesPaused | undefined {
18
30
  if (!value) return undefined
31
+ let paused: WritesPaused
19
32
  try {
20
33
  const parsed = JSON.parse(value) as Partial<WritesPaused>
21
- return {
34
+ paused = {
22
35
  reason: String(parsed.reason ?? ''),
23
36
  by: parsed.by ?? null,
24
37
  at: String(parsed.at ?? ''),
38
+ // A pause stored before story 409 has no end: it lasts until resumed.
39
+ until: typeof parsed.until === 'string' && parsed.until ? parsed.until : null,
25
40
  }
26
41
  } catch {
27
- return { reason: '', by: null, at: '' }
42
+ return { reason: '', by: null, at: '', until: null }
28
43
  }
44
+ return pauseEnded(paused, now) ? undefined : paused
29
45
  }
30
46
 
31
- export async function readWritesPaused(db: Db): Promise<WritesPaused | undefined> {
32
- return parseWritesPaused(await readKeyValue(db, WRITES_PAUSED_KEY))
47
+ export async function readWritesPaused(
48
+ db: Db,
49
+ now = new Date(),
50
+ ): Promise<WritesPaused | undefined> {
51
+ return parseWritesPaused(await readKeyValue(db, WRITES_PAUSED_KEY), now)
33
52
  }
34
53
 
54
+ /**
55
+ * Pauses editing, until `until` or until resumed. Pausing again for the same reason keeps
56
+ * who paused and when, and moves the end; another reason replaces the pause.
57
+ */
35
58
  export async function pauseWrites(
36
59
  db: Db,
37
- options: { reason: string; by?: string },
60
+ options: { reason: string; by?: string | null; until?: Date | null },
61
+ now = new Date(),
38
62
  ): Promise<WritesPaused> {
63
+ const before = await readWritesPaused(db, now)
64
+ const same = before !== undefined && before.reason === options.reason
39
65
  const paused: WritesPaused = {
40
66
  reason: options.reason,
41
- by: options.by ?? null,
42
- at: new Date().toISOString(),
67
+ by: same ? before.by : (options.by ?? null),
68
+ at: same ? before.at : now.toISOString(),
69
+ until: options.until ? options.until.toISOString() : null,
43
70
  }
44
71
  await writeKeyValue(db, WRITES_PAUSED_KEY, JSON.stringify(paused))
45
72
  return paused
@@ -21,6 +21,24 @@ export const EDIT_WINDOW_MS = 10 * 60 * 1000
21
21
  /** Where a change keeps a page's schedule among its items (story 395): `schedules/<page key>`. */
22
22
  export const SCHEDULE_PREFIX = 'schedules/'
23
23
 
24
+ /** Story 411: where a change keeps a page's place and whether it was published: `places/<key>`. */
25
+ export const PLACE_PREFIX = 'places/'
26
+
27
+ /** Story 411: where a change keeps the order of a parent's children: `orders/<key>` or `orders/root`. */
28
+ export const ORDER_PREFIX = 'orders/'
29
+
30
+ /** Where a page stood, beside its content, as a change carries it (story 411). */
31
+ export interface PagePlace {
32
+ parentKey: string | null
33
+ published: boolean
34
+ /** In the recycle bin. */
35
+ trashed?: boolean
36
+ }
37
+
38
+ /** The item path for a parent's children's order. */
39
+ export const orderPath = (parentKey: string | null) =>
40
+ `${ORDER_PREFIX}${parentKey ? normaliseUuid(parentKey) : 'root'}`
41
+
24
42
  export interface Change {
25
43
  id: string
26
44
  kind: ChangeSource
@@ -252,6 +270,133 @@ export class ChangeRepository {
252
270
  await this.#touch(id, now)
253
271
  }
254
272
 
273
+ /**
274
+ * A page a person moved, restored or unpublished straight in Shared (story 411): in
275
+ * their open change, with where it stood before their first such change and now.
276
+ */
277
+ async placed(
278
+ madeBy: string,
279
+ page: { key: string; kind: string },
280
+ before: PagePlace,
281
+ after: PagePlace,
282
+ now = new Date(),
283
+ ): Promise<boolean> {
284
+ const id = await this.#openEdit(madeBy, now)
285
+ if (!(await this.#recordPage(id, page))) return false
286
+ await this.#keepItem(id, `${PLACE_PREFIX}${normaliseUuid(page.key)}`, before, after)
287
+ await this.#touch(id, now)
288
+ return true
289
+ }
290
+
291
+ /** A parent's children a person reordered straight in Shared (story 411), before and now. */
292
+ async ordered(
293
+ madeBy: string,
294
+ parentKey: string | null,
295
+ before: readonly string[],
296
+ after: readonly string[],
297
+ now = new Date(),
298
+ ): Promise<void> {
299
+ const id = await this.#openEdit(madeBy, now)
300
+ await this.#keepItem(id, orderPath(parentKey), before, after)
301
+ await this.#touch(id, now)
302
+ }
303
+
304
+ /**
305
+ * A page a person deleted straight in Shared, to the recycle bin or for good (story
306
+ * 411): in their open change as a removal, keeping the page as it stood.
307
+ */
308
+ async removedBy(
309
+ madeBy: string,
310
+ page: { key: string; kind: string },
311
+ was: object,
312
+ now = new Date(),
313
+ ): Promise<void> {
314
+ const id = await this.#openEdit(madeBy, now)
315
+ const nodeKey = normaliseUuid(page.key)
316
+ const recorded = await this.#db.q
317
+ .selectFrom('content_transfer_change')
318
+ .select('id')
319
+ .where('run_id', '=', id)
320
+ .where('node_key', '=', nodeKey)
321
+ .execute()
322
+ // Gone for good, it cannot be read back: one the change already holds keeps its row.
323
+ if (recorded.length === 0 && !(await this.#recordPage(id, page)))
324
+ await this.#db.q
325
+ .insertInto('content_transfer_change')
326
+ .values({
327
+ run_id: id,
328
+ node_key: nodeKey,
329
+ kind: page.kind,
330
+ action: 'recycle',
331
+ before_event_id: null,
332
+ before_published_event_id: null,
333
+ event_id: null,
334
+ })
335
+ .execute()
336
+ await this.#db.q
337
+ .updateTable('content_transfer_change')
338
+ .set({ action: 'recycle', event_id: null })
339
+ .where('run_id', '=', id)
340
+ .where('node_key', '=', nodeKey)
341
+ .execute()
342
+ const path = `pages/${nodeKey}`
343
+ const found = await this.#db.q
344
+ .selectFrom('change_item')
345
+ .select('id')
346
+ .where('run_id', '=', id)
347
+ .where('path', '=', path)
348
+ .execute()
349
+ if (!found[0])
350
+ await this.item(id, {
351
+ path,
352
+ kind: 'page',
353
+ class: 'none',
354
+ before: JSON.stringify(was),
355
+ after: null,
356
+ })
357
+ await this.#touch(id, now)
358
+ }
359
+
360
+ /** Closes a person's open change (story 411): finished, to be passed on. */
361
+ async closeOpen(
362
+ madeBy: string,
363
+ now = new Date(),
364
+ ): Promise<{ key: string; name: string | null } | undefined> {
365
+ const open = await this.#db.q
366
+ .selectFrom('content_transfer_run')
367
+ .select('id')
368
+ .where('change_kind', '=', 'edit')
369
+ .where('made_by', '=', madeBy)
370
+ .where('closed_at', 'is', null)
371
+ .orderBy('started_at', 'desc')
372
+ .executeTakeFirst()
373
+ return open ? this.#close(String(open.id), now) : undefined
374
+ }
375
+
376
+ /** An item that keeps its first "before" and takes the latest "after". */
377
+ async #keepItem(id: string, path: string, before: unknown, after: unknown) {
378
+ const found = await this.#db.q
379
+ .selectFrom('change_item')
380
+ .select('id')
381
+ .where('run_id', '=', id)
382
+ .where('path', '=', path)
383
+ .execute()
384
+ if (found[0])
385
+ await this.#db.q
386
+ .updateTable('change_item')
387
+ .set({ after_hash: await this.#put(JSON.stringify(after)) })
388
+ .where('id', '=', Number(found[0].id))
389
+ .execute()
390
+ else
391
+ await this.item(id, {
392
+ path,
393
+ kind: 'page',
394
+ class: 'none',
395
+ before: JSON.stringify(before),
396
+ after: JSON.stringify(after),
397
+ })
398
+ }
399
+
255
400
  /**
256
401
  * A page a person published straight in Shared (story 388): in their open change as
257
402
  * it is now, and the change closed, so it is finished and can be passed on. Their
@@ -264,6 +409,10 @@ export class ChangeRepository {
264
409
  ): Promise<{ key: string; name: string | null } | undefined> {
265
410
  const id = await this.#openEdit(madeBy, now)
266
411
  if (!(await this.#recordPage(id, page))) return undefined
412
+ return this.#close(id, now)
413
+ }
414
+
415
+ async #close(id: string, now: Date): Promise<{ key: string; name: string | null }> {
267
416
  await this.#touch(id, now)
268
417
  await this.#db.q
269
418
  .updateTable('content_transfer_run')
@@ -453,6 +602,44 @@ export class ChangeRepository {
453
602
  return this.#view(rows[0], counts.items.get(id) ?? 0, counts.pages.get(id) ?? 0)
454
603
  }
455
604
 
605
+ /**
606
+ * The changes added to since this one was last added to, oldest first (story 406);
607
+ * undefined where the site holds no such change. One applied from another site is
608
+ * known by the key it travelled with too.
609
+ */
610
+ async addedToSince(id: string): Promise<Change[] | undefined> {
611
+ const wanted = normaliseUuid(id)
612
+ const applied = await this.#db.q
613
+ .selectFrom('applied_change')
614
+ .select('run_id')
615
+ .where('change_key', '=', wanted)
616
+ .execute()
617
+ const base = (
618
+ await this.#db.q
619
+ .selectFrom('content_transfer_run')
620
+ .select(['id', 'started_at', 'finished_at'])
621
+ .where('id', 'in', [wanted, ...applied.map((a) => String(a.run_id))])
622
+ .execute()
623
+ )[0]
624
+ if (!base) return undefined
625
+ const rows = await this.#db.q
626
+ .selectFrom('content_transfer_run')
627
+ .selectAll()
628
+ .where('id', '<>', String(base.id))
629
+ .where(
630
+ (eb) => eb.fn.coalesce('finished_at', 'started_at'),
631
+ '>=',
632
+ base.finished_at ?? base.started_at,
633
+ )
634
+ .orderBy((eb) => eb.fn.coalesce('finished_at', 'started_at'))
635
+ .orderBy('id')
636
+ .execute()
637
+ const counts = await this.#counts(rows.map((r) => String(r.id)))
638
+ return rows.map((r) =>
639
+ this.#view(r, counts.items.get(String(r.id)) ?? 0, counts.pages.get(String(r.id)) ?? 0),
640
+ )
641
+ }
642
+
456
643
  async #texts(hashes: readonly (string | null)[]): Promise<Map<string, string>> {
457
644
  const wanted = [...new Set(hashes.filter((h): h is string => Boolean(h)))]
458
645
  if (wanted.length === 0) return new Map()
@@ -694,6 +694,25 @@ export class DocumentRepository {
694
694
  }
695
695
 
696
696
  /** The workspace's latest event for a page, with its name, template and date. */
697
+ /** A version as a page's head reads it (story 411): for a workspace page with none of its own. */
698
+ async #versionHead(versionId: number | null) {
699
+ if (versionId === null) return undefined
700
+ const rows = await this.#db.q
701
+ .selectFrom('content_version as cv')
702
+ .innerJoin('document_version as dv', 'dv.id', 'cv.id')
703
+ .leftJoin('node as tn', 'tn.id', 'dv.template_id')
704
+ .select([
705
+ 'cv.id',
706
+ 'cv.text',
707
+ 'cv.version_date',
708
+ 'dv.template_id',
709
+ 'tn.unique_id as template_key',
710
+ ])
711
+ .where('cv.id', '=', versionId)
712
+ .execute()
713
+ return rows[0]
714
+ }
715
+
697
716
  async #workspaceHead(nodeId: number) {
698
717
  const rows = await this.#db.q
699
718
  .selectFrom('content_version as cv')
@@ -786,7 +805,9 @@ export class DocumentRepository {
786
805
  .where('c.node_id', '=', node.id)
787
806
  .execute()
788
807
  const row = rows[0]
789
- const head = await this.#workspaceHead(node.id)
808
+ // Unpublished there and not saved there, it has no version of its own: Shared's it began from.
809
+ const head =
810
+ (await this.#workspaceHead(node.id)) ?? (await this.#versionHead(wd.baseEventId ?? null))
790
811
  if (!row || !head) return undefined
791
812
  const propertyTypes = await this.#propertyTypes(Number(row.content_type_id))
792
813
  const languages = await this.#languages()
@@ -3108,6 +3129,24 @@ export class DocumentRepository {
3108
3129
  const languages = await this.#languages()
3109
3130
  const workspace = this.#workspace ?? null
3110
3131
  await this.#db.transaction(async (tx) => {
3132
+ // Story 414: the first time a workspace sets one, Shared's as it was then.
3133
+ if (workspace !== null) {
3134
+ const held = await tx.q
3135
+ .selectFrom('workspace_schedule')
3136
+ .select('node_id')
3137
+ .where('workspace_id', '=', workspace)
3138
+ .where('node_id', '=', node.id)
3139
+ .execute()
3140
+ if (held.length === 0)
3141
+ await tx.q
3142
+ .insertInto('workspace_schedule')
3143
+ .values({
3144
+ workspace_id: workspace,
3145
+ node_id: node.id,
3146
+ base: JSON.stringify(await scheduleEntriesOf(tx, node.id, null)),
3147
+ })
3148
+ .execute()
3149
+ }
3111
3150
  for (const entry of entries) {
3112
3151
  const languageId = entry.culture
3113
3152
  ? (languages.find((l) => l.isoCode.toLowerCase() === entry.culture?.toLowerCase())?.id ??
@@ -3165,17 +3204,44 @@ export class DocumentRepository {
3165
3204
  }))
3166
3205
  }
3167
3206
 
3207
+ /**
3208
+ * A page's schedule as a change carries it (story 414): per language, when it goes live
3209
+ * and comes down, in this repository's view, Shared's or the workspace's.
3210
+ */
3211
+ async scheduleEntries(key: string): Promise<ScheduleEntryAt[]> {
3212
+ const node = await this.#nodes.byKey(key)
3213
+ if (!node) return []
3214
+ return scheduleEntriesOf(this.#db, node.id, this.#workspace ?? null)
3215
+ }
3216
+
3217
+ /** Story 414: the change that set the page's schedule in Shared, named when it fires. */
3218
+ async scheduleSetBy(key: string, changeKey: string): Promise<void> {
3219
+ const node = await this.#nodes.byKey(key)
3220
+ if (!node) return
3221
+ await this.#db.q
3222
+ .updateTable('content_schedule')
3223
+ .set({ change_key: changeKey })
3224
+ .where('node_id', '=', node.id)
3225
+ .where('workspace_id', 'is', null)
3226
+ .execute()
3227
+ }
3228
+
3168
3229
  /** Schedules whose time has come, oldest first. */
3169
- async dueSchedules(
3170
- now: Date,
3171
- ): Promise<
3172
- Array<{ id: number; key: string; culture: string | null; action: 'Release' | 'Expire' }>
3230
+ async dueSchedules(now: Date): Promise<
3231
+ Array<{
3232
+ id: number
3233
+ key: string
3234
+ culture: string | null
3235
+ action: 'Release' | 'Expire'
3236
+ /** Story 414: the change that set it, when one did. */
3237
+ changeKey: string | null
3238
+ }>
3173
3239
  > {
3174
3240
  const rows = await this.#db.q
3175
3241
  .selectFrom('content_schedule as s')
3176
3242
  .innerJoin('node as n', 'n.id', 's.node_id')
3177
3243
  .leftJoin('language as l', 'l.id', 's.language_id')
3178
- .select(['s.id', 's.action', 'n.unique_id', 'l.iso_code'])
3244
+ .select(['s.id', 's.action', 'n.unique_id', 'l.iso_code', 's.change_key'])
3179
3245
  .where('s.date', '<=', DbDate.toDb(now))
3180
3246
  .where('n.node_object_type', '=', this.objectType)
3181
3247
  // A workspace's schedules wait for it to be served (story 379).
@@ -3188,6 +3254,7 @@ export class DocumentRepository {
3188
3254
  key: normaliseUuid(String(row.unique_id)),
3189
3255
  culture: (row.iso_code as string | null) ?? null,
3190
3256
  action: String(row.action) as 'Release' | 'Expire',
3257
+ changeKey: (row.change_key as string | null) ?? null,
3191
3258
  }))
3192
3259
  }
3193
3260
 
@@ -5029,6 +5096,7 @@ export async function deleteNodeRows(
5029
5096
  )
5030
5097
  await tx.q.deleteFrom('property_value').where('node_id', 'in', nodes()).execute()
5031
5098
  await tx.q.deleteFrom('content_schedule').where('node_id', 'in', nodes()).execute()
5099
+ await tx.q.deleteFrom('workspace_schedule').where('node_id', 'in', nodes()).execute()
5032
5100
  await tx.q.deleteFrom('user_notification').where('node_id', 'in', nodes()).execute()
5033
5101
  await tx.q.deleteFrom('domain').where('node_id', 'in', nodes()).execute()
5034
5102
  await tx.q
@@ -5069,3 +5137,35 @@ export async function deleteNodeRows(
5069
5137
  )
5070
5138
  .execute()
5071
5139
  }
5140
+
5141
+ /** A page's schedule per language, as a change carries it (story 414). */
5142
+ export interface ScheduleEntryAt {
5143
+ culture: string | null
5144
+ publishTime: string | null
5145
+ unpublishTime: string | null
5146
+ }
5147
+
5148
+ /** A page's schedule rows as entries, in Shared (`workspace` null) or a workspace, by language. */
5149
+ async function scheduleEntriesOf(
5150
+ db: Db,
5151
+ nodeId: number,
5152
+ workspace: number | null,
5153
+ ): Promise<ScheduleEntryAt[]> {
5154
+ const rows = await db.q
5155
+ .selectFrom('content_schedule as s')
5156
+ .leftJoin('language as l', 'l.id', 's.language_id')
5157
+ .select(['s.action', 's.date', 'l.iso_code'])
5158
+ .where('s.node_id', '=', nodeId)
5159
+ .where('s.workspace_id', workspace === null ? 'is' : '=', workspace)
5160
+ .execute()
5161
+ const byCulture = new Map<string | null, ScheduleEntryAt>()
5162
+ for (const row of rows) {
5163
+ const culture = (row.iso_code as string | null) ?? null
5164
+ const entry = byCulture.get(culture) ?? { culture, publishTime: null, unpublishTime: null }
5165
+ const at = (DbDate.fromDb(row.date) ?? new Date(0)).toISOString()
5166
+ if (row.action === 'Release') entry.publishTime = at
5167
+ else entry.unpublishTime = at
5168
+ byCulture.set(culture, entry)
5169
+ }
5170
+ return [...byCulture.values()].sort((a, b) => (a.culture ?? '').localeCompare(b.culture ?? ''))
5171
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * What went wrong rendering a workspace's pages, as each node notes it (story 408):
3
+ * the newest kept per workspace, so any node answers for the whole site.
4
+ */
5
+ import { normaliseUuid } from '@crombolo/core'
6
+ import type { Db } from '../database.ts'
7
+ import { DbDate } from '../dialect.ts'
8
+
9
+ /** How many of a workspace's errors are kept, the newest. */
10
+ export const WORKSPACE_ERRORS_KEPT = 200
11
+
12
+ export interface WorkspaceError {
13
+ at: Date
14
+ node: string
15
+ page: string
16
+ says: string
17
+ }
18
+
19
+ export class WorkspaceErrorRepository {
20
+ #db: Db
21
+
22
+ constructor(db: Db) {
23
+ this.#db = db
24
+ }
25
+
26
+ /** Notes one, and drops what is past the newest kept. */
27
+ async note(
28
+ workspaceKey: string,
29
+ error: { node: string; page: string; says: string },
30
+ now = new Date(),
31
+ kept = WORKSPACE_ERRORS_KEPT,
32
+ ): Promise<void> {
33
+ const key = normaliseUuid(workspaceKey)
34
+ await this.#db.q
35
+ .insertInto('workspace_error')
36
+ .values({
37
+ workspace_key: key,
38
+ node_id: error.node.slice(0, 64),
39
+ page: error.page.slice(0, 1000),
40
+ says: error.says.slice(0, 4000),
41
+ noted_at: DbDate.toDb(now),
42
+ })
43
+ .execute()
44
+ const oldestKept = (
45
+ await this.#db.q
46
+ .selectFrom('workspace_error')
47
+ .select('id')
48
+ .where('workspace_key', '=', key)
49
+ .orderBy('id', 'desc')
50
+ .limit(1)
51
+ .offset(kept - 1)
52
+ .execute()
53
+ )[0]
54
+ if (oldestKept)
55
+ await this.#db.q
56
+ .deleteFrom('workspace_error')
57
+ .where('workspace_key', '=', key)
58
+ .where('id', '<', oldestKept.id)
59
+ .execute()
60
+ }
61
+
62
+ /** A workspace's errors from every node, oldest first, from `since` on. */
63
+ async of(workspaceKey: string, since?: Date): Promise<WorkspaceError[]> {
64
+ const rows = await this.#db.q
65
+ .selectFrom('workspace_error')
66
+ .select(['node_id', 'page', 'says', 'noted_at'])
67
+ .where('workspace_key', '=', normaliseUuid(workspaceKey))
68
+ .orderBy('id')
69
+ .execute()
70
+ return rows
71
+ .map((r) => ({
72
+ at: DbDate.fromDb(r.noted_at) ?? new Date(0),
73
+ node: String(r.node_id),
74
+ page: String(r.page),
75
+ says: String(r.says),
76
+ }))
77
+ .filter((e) => !since || e.at >= since)
78
+ }
79
+
80
+ /** A merged or discarded workspace keeps none. */
81
+ async clear(workspaceKey: string): Promise<void> {
82
+ await this.#db.q
83
+ .deleteFrom('workspace_error')
84
+ .where('workspace_key', '=', normaliseUuid(workspaceKey))
85
+ .execute()
86
+ }
87
+ }
@@ -294,6 +294,8 @@ export class WorkspaceRepository {
294
294
  await tx.q.deleteFrom('document_version').where('id', 'in', versions()).execute()
295
295
  await tx.q.deleteFrom('content_version').where('workspace_id', '=', id).execute()
296
296
  await tx.q.deleteFrom('content_schedule').where('workspace_id', '=', id).execute()
297
+ await tx.q.deleteFrom('workspace_schedule').where('workspace_id', '=', id).execute()
298
+ await tx.q.deleteFrom('workspace_schedule').where('workspace_id', '=', id).execute()
297
299
  for (const table of [
298
300
  'workspace_pending',
299
301
  'workspace_document_culture',
@@ -419,6 +421,41 @@ export class WorkspaceRepository {
419
421
  }
420
422
 
421
423
  /** Drops what waits for the merge for one page, or one marker: the change is not to go. */
424
+ /**
425
+ * The pages a workspace set a schedule for (story 414), each with Shared's schedule as
426
+ * it was when it first did.
427
+ */
428
+ async scheduled(
429
+ id: number,
430
+ ): Promise<Array<{ nodeId: number; key: string; name: string; base: unknown[] }>> {
431
+ const rows = await this.#db.q
432
+ .selectFrom('workspace_schedule as w')
433
+ .innerJoin('node as n', 'n.id', 'w.node_id')
434
+ .select(['w.node_id', 'n.unique_id', 'n.text', 'w.base'])
435
+ .where('w.workspace_id', '=', id)
436
+ .execute()
437
+ return rows.map((r) => ({
438
+ nodeId: Number(r.node_id),
439
+ key: normaliseUuid(String(r.unique_id)),
440
+ name: String(r.text ?? ''),
441
+ base: JSON.parse(String(r.base)) as unknown[],
442
+ }))
443
+ }
444
+
445
+ /** Story 414: a page's schedule gone into Shared with a merge of it alone. */
446
+ async dropSchedule(id: number, nodeId: number): Promise<void> {
447
+ await this.#db.q
448
+ .deleteFrom('content_schedule')
449
+ .where('workspace_id', '=', id)
450
+ .where('node_id', '=', nodeId)
451
+ .execute()
452
+ await this.#db.q
453
+ .deleteFrom('workspace_schedule')
454
+ .where('workspace_id', '=', id)
455
+ .where('node_id', '=', nodeId)
456
+ .execute()
457
+ }
458
+
422
459
  async dropPending(id: number, nodeId: number): Promise<void> {
423
460
  await this.#db.q
424
461
  .deleteFrom('workspace_pending')
@@ -474,6 +511,7 @@ export class WorkspaceRepository {
474
511
  await this.#db.q.deleteFrom('document_version').where('id', 'in', versions()).execute()
475
512
  await this.#db.q.deleteFrom('content_version').where('workspace_id', '=', id).execute()
476
513
  await this.#db.q.deleteFrom('content_schedule').where('workspace_id', '=', id).execute()
514
+ await this.#db.q.deleteFrom('workspace_schedule').where('workspace_id', '=', id).execute()
477
515
  for (const table of [
478
516
  'workspace_pending',
479
517
  'workspace_document_culture',
@@ -534,6 +572,20 @@ export class WorkspaceRepository {
534
572
  })
535
573
  }
536
574
 
575
+ /** Story 407: how many items each workspace has in conflict, as last found; none where it has none. */
576
+ async conflictCounts(ids: readonly number[]): Promise<Map<number, number>> {
577
+ const out = new Map<number, number>()
578
+ if (ids.length === 0) return out
579
+ for (const row of await this.#db.q
580
+ .selectFrom('workspace_conflict_raised')
581
+ .select(['workspace_id', (eb) => eb.fn.countAll<number>().as('n')])
582
+ .where('workspace_id', 'in', [...ids])
583
+ .groupBy('workspace_id')
584
+ .execute())
585
+ out.set(Number(row.workspace_id), Number(row.n))
586
+ return out
587
+ }
588
+
537
589
  /**
538
590
  * Story 400: what a person settled in the workspace, a page by its key or a file by its
539
591
  * path, so a conflict there later is raised again. `keepFiles` are files still in conflict.
@@ -102,10 +102,12 @@ import { usersLocalisationMigration } from './users-localisation.ts'
102
102
  import { valuesMigration } from './values.ts'
103
103
  import { webhooksMigration } from './webhooks.ts'
104
104
  import { workspaceConflictsMigration } from './workspace-conflicts.ts'
105
+ import { workspaceErrorsMigration } from './workspace-errors.ts'
105
106
  import { workspaceLinksMigration } from './workspace-links.ts'
106
107
  import { workspaceMergeMigration } from './workspace-merge.ts'
107
108
  import { workspacePrivacyMigration } from './workspace-privacy.ts'
108
109
  import { workspaceProcessesMigration } from './workspace-processes.ts'
110
+ import { workspaceSchedulesMigration } from './workspace-schedules.ts'
109
111
  import { workspaceSchemaMigration } from './workspace-schema.ts'
110
112
  import { workspacesMigration } from './workspaces.ts'
111
113
 
@@ -205,4 +207,6 @@ export const cromboloPlan = new MigrationPlan([
205
207
  workspaceConflictsMigration,
206
208
  changeSourcesMigration,
207
209
  groupStartKeysMigration,
210
+ workspaceErrorsMigration,
211
+ workspaceSchedulesMigration,
208
212
  ])
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Migration 096 — what went wrong rendering a workspace's pages, as each node notes it
3
+ * (story 408), so any node answers a workspace's errors for the whole site.
4
+ */
5
+ import type { Db } from '../database.ts'
6
+ import type { Migration } from '../migrations.ts'
7
+ import { sql } from '../query.ts'
8
+ import { STATE_GROUP_START_KEYS } from './group-start-keys.ts'
9
+
10
+ export const STATE_WORKSPACE_ERRORS = '{3b9f6d52-0096-4e1a-b7c4-2a8d5f1e0096}'
11
+
12
+ export const workspaceErrorsMigration: Migration = {
13
+ from: STATE_GROUP_START_KEYS,
14
+ to: STATE_WORKSPACE_ERRORS,
15
+ name: 'AddWorkspaceErrors',
16
+ kind: 'expand',
17
+ release: '0.76.0',
18
+ async up(db: Db) {
19
+ const t = db.dialect.types
20
+ await db.q.schema
21
+ .createTable('workspace_error')
22
+ .addColumn('id', sql.raw(t.identity))
23
+ .addColumn('workspace_key', sql.raw(t.varchar(64)), (c) => c.notNull())
24
+ .addColumn('node_id', sql.raw(t.varchar(64)), (c) => c.notNull())
25
+ .addColumn('page', sql.raw(t.varchar(1000)), (c) => c.notNull())
26
+ .addColumn('says', sql.raw(t.varchar(4000)), (c) => c.notNull())
27
+ .addColumn('noted_at', sql.raw(t.timestamp), (c) => c.notNull())
28
+ .execute()
29
+ await db.q.schema
30
+ .createIndex('ix_workspace_error_workspace')
31
+ .on('workspace_error')
32
+ .columns(['workspace_key', 'id'])
33
+ .execute()
34
+ },
35
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Migration 097 — a schedule set in a workspace goes with its change (story 414): which
3
+ * pages a workspace set a schedule for, with Shared's as it was then, so its merge knows
4
+ * a clear from no change and a schedule changed in Shared since; and which change set
5
+ * each schedule Shared holds, named when it fires.
6
+ */
7
+ import type { Db } from '../database.ts'
8
+ import type { Migration } from '../migrations.ts'
9
+ import { sql } from '../query.ts'
10
+ import { STATE_WORKSPACE_ERRORS } from './workspace-errors.ts'
11
+
12
+ export const STATE_WORKSPACE_SCHEDULES = '{3b9f6d52-0097-4e1a-b7c4-2a8d5f1e0097}'
13
+
14
+ export const workspaceSchedulesMigration: Migration = {
15
+ from: STATE_WORKSPACE_ERRORS,
16
+ to: STATE_WORKSPACE_SCHEDULES,
17
+ name: 'AddWorkspaceSchedules',
18
+ kind: 'expand',
19
+ release: '0.77.0',
20
+ async up(db: Db) {
21
+ const t = db.dialect.types
22
+ await db.q.schema
23
+ .createTable('workspace_schedule')
24
+ .addColumn('workspace_id', sql.raw(t.integer), (c) => c.notNull())
25
+ .addColumn('node_id', sql.raw(t.integer), (c) => c.notNull())
26
+ .addColumn('base', sql.raw(t.text), (c) => c.notNull())
27
+ .addPrimaryKeyConstraint('pk_workspace_schedule', ['workspace_id', 'node_id'])
28
+ .execute()
29
+ await db.q.schema
30
+ .alterTable('content_schedule')
31
+ .addColumn('change_key', sql.raw(t.varchar(64)))
32
+ .execute()
33
+ },
34
+ }
package/src/tables.gen.ts CHANGED
@@ -256,6 +256,7 @@ export interface CoreTables {
256
256
  }
257
257
  content_schedule: {
258
258
  action: string
259
+ change_key: string | null
259
260
  date: Timestamp
260
261
  id: Generated<number>
261
262
  language_id: number | null
@@ -1073,6 +1074,14 @@ export interface CoreTables {
1073
1074
  published_name: string | null
1074
1075
  workspace_id: Generated<number>
1075
1076
  }
1077
+ workspace_error: {
1078
+ id: Generated<number>
1079
+ node_id: string
1080
+ noted_at: Timestamp
1081
+ page: string
1082
+ says: string
1083
+ workspace_key: string
1084
+ }
1076
1085
  workspace_file: {
1077
1086
  base_hash: string | null
1078
1087
  class: string | null
@@ -1120,4 +1129,9 @@ export interface CoreTables {
1120
1129
  reason: string
1121
1130
  workspace_key: string
1122
1131
  }
1132
+ workspace_schedule: {
1133
+ base: string
1134
+ node_id: number
1135
+ workspace_id: Generated<number>
1136
+ }
1123
1137
  }