@crombolo/content 0.45.0 → 0.46.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/content",
3
- "version": "0.45.0",
3
+ "version": "0.46.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The rules every page and media write follows, whoever starts it: who may, where it may go, approvals, and what it announces. No transport.",
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.45.0",
33
- "@crombolo/data": "0.45.0"
32
+ "@crombolo/core": "0.46.1",
33
+ "@crombolo/data": "0.46.1"
34
34
  }
35
35
  }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Block aliases (story 253): a block may be given a name on its page, kept on
3
+ * its layout entry, that views and the `content block` commands pick it out
4
+ * by. Two blocks in one list may not share one.
5
+ */
6
+ import type { DocumentValue } from '@crombolo/core'
7
+
8
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
9
+ typeof value === 'object' && value !== null && !Array.isArray(value)
10
+
11
+ /** The layout entries of a block value, its areas' included, or none when it is not one. */
12
+ function layoutLists(value: unknown): unknown[][] {
13
+ if (!isRecord(value) || !isRecord(value.layout)) return []
14
+ const lists: unknown[][] = []
15
+ const walk = (items: unknown) => {
16
+ if (!Array.isArray(items)) return
17
+ lists.push(items)
18
+ for (const item of items)
19
+ if (isRecord(item) && Array.isArray(item.areas))
20
+ for (const area of item.areas) if (isRecord(area)) walk(area.items)
21
+ }
22
+ for (const items of Object.values(value.layout)) walk(items)
23
+ return lists
24
+ }
25
+
26
+ /** The block values inside a block value's own elements, for a list within a block. */
27
+ function nested(value: unknown): unknown[] {
28
+ if (!isRecord(value)) return []
29
+ return ['contentData', 'settingsData'].flatMap((name) =>
30
+ Array.isArray(value[name])
31
+ ? (value[name] as unknown[]).flatMap((data) =>
32
+ isRecord(data) && Array.isArray(data.values)
33
+ ? data.values.flatMap((v) => (isRecord(v) ? [v.value] : []))
34
+ : [],
35
+ )
36
+ : [],
37
+ )
38
+ }
39
+
40
+ /** The first alias two blocks of one list share, with the property it is in. */
41
+ export function duplicateBlockAlias(
42
+ values: readonly DocumentValue[],
43
+ ): { property: string; alias: string } | undefined {
44
+ const inValue = (value: unknown): string | undefined => {
45
+ for (const list of layoutLists(value)) {
46
+ const seen = new Set<string>()
47
+ for (const item of list) {
48
+ if (!isRecord(item) || typeof item.alias !== 'string' || !item.alias) continue
49
+ const alias = item.alias.toLowerCase()
50
+ if (seen.has(alias)) return item.alias
51
+ seen.add(alias)
52
+ }
53
+ }
54
+ for (const inner of nested(value)) {
55
+ const found = inValue(inner)
56
+ if (found) return found
57
+ }
58
+ return undefined
59
+ }
60
+ for (const v of values) {
61
+ const alias = inValue(v.value)
62
+ if (alias) return { property: v.alias, alias }
63
+ }
64
+ return undefined
65
+ }
@@ -147,6 +147,88 @@ export interface MediaOperationsOptions {
147
147
  onChange?(change: MediaChange): void | Promise<void>
148
148
  /** Errors a value's intake throws that are the sender's to fix, as the reason to give. */
149
149
  refusalReason?(error: unknown): string | undefined
150
+ /**
151
+ * Where a branch of more than `largeBranch` items is handed, so the request
152
+ * answers at once (story 246): the core job queue, recording who asked.
153
+ */
154
+ background?: (queuedBy: string) => { enqueue(name: string, payload: unknown): Promise<string> }
155
+ /** How many items a branch holds before its trash, restore, move, delete or emptying is queued. */
156
+ largeBranch?: number
157
+ }
158
+
159
+ /** The background jobs that write a large branch (story 246), run by `mediaJobHandlers`. */
160
+ export const MEDIA_JOBS = {
161
+ trash: 'media.trash',
162
+ restore: 'media.restore',
163
+ move: 'media.move',
164
+ delete: 'media.delete',
165
+ emptyBin: 'media.emptyBin',
166
+ } as const
167
+
168
+ /** A branch past this many items is written by a background job, not the request. */
169
+ export const DEFAULT_LARGE_BRANCH = 5_000
170
+
171
+ /** How many items emptying the bin deletes in one transaction. */
172
+ export const EMPTY_BIN_CHUNK = 5_000
173
+
174
+ /** Who queued a job, as the job's actor names them in the audit. */
175
+ interface QueuedBy {
176
+ name: string
177
+ userKey: string | null
178
+ }
179
+
180
+ /** The actor a queued job writes as: the site, for the person whose request was checked. */
181
+ const jobActor = (by: QueuedBy): MediaActor => ({
182
+ kind: 'system',
183
+ name: by.name,
184
+ origin: { source: 'job' },
185
+ ...(by.userKey ? { user: { id: by.userKey, name: by.name } } : {}),
186
+ })
187
+
188
+ /** The handlers for `MEDIA_JOBS`, for the core job owner; each runs the write itself. */
189
+ export function mediaJobHandlers(
190
+ media: MediaOperations,
191
+ ): Map<string, (payload: never, context: { job: JobProgressReporter }) => Promise<void>> {
192
+ const settled = (result: { ok: boolean; reason?: string }) => {
193
+ if (!result.ok) throw new Error(result.reason ?? 'The media change could not be made.')
194
+ }
195
+ return new Map<string, (payload: never, context: { job: JobProgressReporter }) => Promise<void>>([
196
+ [
197
+ MEDIA_JOBS.trash,
198
+ async (p: { keys: string[]; by: QueuedBy }) =>
199
+ settled(await media.trashMany(jobActor(p.by), p.keys, { inline: true })),
200
+ ],
201
+ [
202
+ MEDIA_JOBS.restore,
203
+ async (p: { key: string; targetKey: string | null | undefined; by: QueuedBy }) =>
204
+ settled(await media.restore(jobActor(p.by), p.key, p.targetKey, { inline: true })),
205
+ ],
206
+ [
207
+ MEDIA_JOBS.move,
208
+ async (p: { keys: string[]; targetKey: string | null; by: QueuedBy }) =>
209
+ settled(await media.moveMany(jobActor(p.by), p.keys, p.targetKey, { inline: true })),
210
+ ],
211
+ [
212
+ MEDIA_JOBS.delete,
213
+ async (p: { key: string; fromBin: boolean; by: QueuedBy }) =>
214
+ settled(await media.delete(jobActor(p.by), p.key, { fromBin: p.fromBin, inline: true })),
215
+ ],
216
+ [
217
+ MEDIA_JOBS.emptyBin,
218
+ async (p: { by: QueuedBy }, { job }) =>
219
+ settled(
220
+ await media.emptyBin(jobActor(p.by), {
221
+ inline: true,
222
+ progress: (done, total) => job.progress(done, total),
223
+ }),
224
+ ),
225
+ ],
226
+ ])
227
+ }
228
+
229
+ /** What a job reports while it runs. */
230
+ export interface JobProgressReporter {
231
+ progress(done: number, total?: number, note?: string): Promise<void>
150
232
  }
151
233
 
152
234
  /** What a media change touched: the items, and the old paths of any whose branch moved with them. */
@@ -219,6 +301,36 @@ export function createMediaOperations(options: MediaOperationsOptions) {
219
301
  return result
220
302
  }
221
303
  /** The keys, and the old paths of branches that moved: what a move, trash or delete touched. */
304
+ const largeBranch = options.largeBranch ?? DEFAULT_LARGE_BRANCH
305
+
306
+ /** How many items these branches hold, roots included. */
307
+ const branchSize = async (rows: readonly NodeRow[]): Promise<number> => {
308
+ let total = 0
309
+ for (const row of rows) {
310
+ const counted = await db.q
311
+ .selectFrom('node')
312
+ .select((eb) => eb.fn.countAll().as('n'))
313
+ .where((eb) => eb.or([eb('id', '=', row.id), eb('path', 'like', `${row.path},%`)]))
314
+ .execute()
315
+ total += Number(counted[0]?.n ?? 0)
316
+ }
317
+ return total
318
+ }
319
+
320
+ /** Queues a large branch's write, or undefined when it is small enough to make now. */
321
+ const queueWhenLarge = async (
322
+ actor: MediaActor,
323
+ rows: readonly NodeRow[],
324
+ inline: boolean | undefined,
325
+ job: string,
326
+ payload: Record<string, unknown>,
327
+ ): Promise<string | undefined> => {
328
+ if (inline || !options.background || rows.length === 0) return undefined
329
+ if ((await branchSize(rows)) <= largeBranch) return undefined
330
+ const by: QueuedBy = { name: actorName(actor), userKey: actorUserKey(actor) }
331
+ return options.background(by.name).enqueue(job, { ...payload, by })
332
+ }
333
+
222
334
  const branches = (rows: readonly NodeRow[]): MediaChange => ({
223
335
  keys: rows.map((row) => row.key),
224
336
  moved: rows.map((row) => row.path),
@@ -323,25 +435,76 @@ export function createMediaOperations(options: MediaOperationsOptions) {
323
435
  }
324
436
 
325
437
  /** The files a branch holds, read before its rows go. */
438
+ /** The files a branch's items are served from, read from `file_url` in one query (story 246). */
326
439
  const filesIn = async (root: NodeRow): Promise<string[]> => {
327
440
  const rows = await db.q
328
- .selectFrom('node')
329
- .select('unique_id')
330
- .where((eb) => eb.or([eb('id', '=', root.id), eb('path', 'like', `${root.path},%`)]))
331
- .where('node_object_type', '=', ObjectTypes.Media)
441
+ .selectFrom('node as n')
442
+ .innerJoin('content as c', 'c.node_id', 'n.id')
443
+ .select('c.file_url')
444
+ .where((eb) => eb.or([eb('n.id', '=', root.id), eb('n.path', 'like', `${root.path},%`)]))
445
+ .where('n.node_object_type', '=', ObjectTypes.Media)
446
+ .where('c.file_url', 'is not', null)
332
447
  .execute()
333
- const found: string[] = []
334
- for (const row of rows) {
335
- const media = await repo.byKey(normaliseUuid(String(row.unique_id)))
336
- const file = media ? mediaFileOf(media) : null
337
- if (file) found.push(file)
338
- }
339
- return found
448
+ return rows.map((row) => String(row.file_url)).filter(Boolean)
340
449
  }
341
450
  const removeFiles = async (paths: readonly string[]) => {
342
451
  for (const path of paths) await options.files?.remove(path)
343
452
  }
344
453
 
454
+ /**
455
+ * Empties the bin a chunk at a time, deepest first, each chunk a transaction of
456
+ * its own and its files removed once it has committed: a background job's way,
457
+ * so no transaction holds a hundred thousand rows (story 246).
458
+ */
459
+ const emptyInChunks = async (
460
+ actor: MediaActor,
461
+ roots: readonly NodeRow[],
462
+ progress: (done: number, total: number) => Promise<void>,
463
+ ): Promise<number> => {
464
+ const total = await branchSize(roots)
465
+ let done = 0
466
+ let deleted = 0
467
+ for (const root of roots) {
468
+ for (;;) {
469
+ const chunk = await db.q
470
+ .selectFrom('node as n')
471
+ .leftJoin('content as c', 'c.node_id', 'n.id')
472
+ .select(['n.id', 'c.file_url'])
473
+ .where((eb) => eb.or([eb('n.id', '=', root.id), eb('n.path', 'like', `${root.path},%`)]))
474
+ .orderBy('n.level', 'desc')
475
+ .orderBy('n.id')
476
+ .limit(EMPTY_BIN_CHUNK)
477
+ .execute()
478
+ if (chunk.length === 0) break
479
+ const ids = chunk.map((row) => Number(row.id))
480
+ const last = ids.includes(root.id)
481
+ await commit(
482
+ actor,
483
+ async (tx) => {
484
+ await tx.deleteNodes(ids)
485
+ return last
486
+ },
487
+ (finished): MediaEvent[] =>
488
+ finished ? [{ type: 'deleted', key: root.key, name: root.text ?? null }] : [],
489
+ () => branches([root]),
490
+ )
491
+ await removeFiles(chunk.flatMap((row) => (row.file_url ? [String(row.file_url)] : [])))
492
+ done += ids.length
493
+ await progress(done, total)
494
+ if (last) {
495
+ deleted += 1
496
+ break
497
+ }
498
+ }
499
+ }
500
+ await commit(
501
+ actor,
502
+ async () => true,
503
+ (): MediaEvent[] => [{ type: 'binEmptied' }],
504
+ )
505
+ return deleted
506
+ }
507
+
345
508
  /** Every item checked before any is written: the reasons each one cannot be moved there. */
346
509
  const moveBlockers = async (
347
510
  actor: MediaActor,
@@ -453,9 +616,10 @@ export function createMediaOperations(options: MediaOperationsOptions) {
453
616
  }
454
617
  },
455
618
 
456
- async trash(actor: MediaActor, key: string): Promise<Result> {
619
+ async trash(actor: MediaActor, key: string): Promise<Result<{ queued?: string }>> {
457
620
  const result = await operations.trashMany(actor, [key])
458
- return result.ok ? { ok: true } : result
621
+ if (!result.ok) return result
622
+ return result.queued ? { ok: true, queued: result.queued } : { ok: true }
459
623
  },
460
624
 
461
625
  /**
@@ -466,7 +630,7 @@ export function createMediaOperations(options: MediaOperationsOptions) {
466
630
  async trashMany(
467
631
  actor: MediaActor,
468
632
  keys: readonly string[],
469
- many: { dryRun?: boolean } = {},
633
+ many: { dryRun?: boolean; inline?: boolean } = {},
470
634
  ): Promise<SelectionResult> {
471
635
  const found = await nodesFor(keys)
472
636
  if (!Array.isArray(found)) return found
@@ -478,6 +642,10 @@ export function createMediaOperations(options: MediaOperationsOptions) {
478
642
  const unchanged = found.filter((node) => node.trashed).map((node) => node.key)
479
643
  const changedKeys = found.filter((node) => !node.trashed).map((node) => node.key)
480
644
  if (many.dryRun || writes.length === 0) return { ok: true, changed: changedKeys, unchanged }
645
+ const queued = await queueWhenLarge(actor, writes, many.inline, MEDIA_JOBS.trash, {
646
+ keys: writes.map((node) => node.key),
647
+ })
648
+ if (queued) return { ok: true, changed: changedKeys, unchanged, queued }
481
649
  await commit(
482
650
  actor,
483
651
  async (tx) => {
@@ -495,14 +663,19 @@ export function createMediaOperations(options: MediaOperationsOptions) {
495
663
  async delete(
496
664
  actor: MediaActor,
497
665
  key: string,
498
- deleting: { fromBin?: boolean } = {},
499
- ): Promise<Result> {
666
+ deleting: { fromBin?: boolean; inline?: boolean } = {},
667
+ ): Promise<Result<{ queued?: string }>> {
500
668
  const node = await nodes.byKey(key)
501
669
  if (!node || node.objectType !== ObjectTypes.Media) return refuse('notFound', 404, NOT_FOUND)
502
670
  if (deleting.fromBin && !node.trashed)
503
671
  return refuse('invalid', 400, 'The media item is not in the recycle bin')
504
672
  if (!(await permits(actor, deleting.fromBin ? 'bin' : key, { branch: true })))
505
673
  return forbidden()
674
+ const queued = await queueWhenLarge(actor, [node], deleting.inline, MEDIA_JOBS.delete, {
675
+ key,
676
+ fromBin: deleting.fromBin === true,
677
+ })
678
+ if (queued) return { ok: true, queued }
506
679
  const paths = await filesIn(node)
507
680
  const removed = await commit(
508
681
  actor,
@@ -515,9 +688,20 @@ export function createMediaOperations(options: MediaOperationsOptions) {
515
688
  return { ok: true }
516
689
  },
517
690
 
518
- async emptyBin(actor: MediaActor): Promise<Result<{ deleted: number }>> {
691
+ async emptyBin(
692
+ actor: MediaActor,
693
+ run: {
694
+ inline?: boolean
695
+ /** A background job's: deleted a chunk at a time, saying how far it has got. */
696
+ progress?: (done: number, total: number) => Promise<void>
697
+ } = {},
698
+ ): Promise<Result<{ deleted: number; queued?: string }>> {
519
699
  if (!(await permits(actor, 'bin'))) return forbidden()
520
700
  const roots = await repo.trashedRoots()
701
+ const queued = await queueWhenLarge(actor, roots, run.inline, MEDIA_JOBS.emptyBin, {})
702
+ if (queued) return { ok: true, deleted: 0, queued }
703
+ if (run.progress)
704
+ return { ok: true, deleted: await emptyInChunks(actor, roots, run.progress) }
521
705
  const paths: string[] = []
522
706
  for (const node of roots) paths.push(...(await filesIn(node)))
523
707
  const gone = await commit(
@@ -542,7 +726,8 @@ export function createMediaOperations(options: MediaOperationsOptions) {
542
726
  actor: MediaActor,
543
727
  key: string,
544
728
  targetKey: string | null | undefined,
545
- ): Promise<Result> {
729
+ run: { inline?: boolean } = {},
730
+ ): Promise<Result<{ queued?: string }>> {
546
731
  if (!(await permits(actor, 'bin'))) return forbidden()
547
732
  if (targetKey !== undefined) {
548
733
  const type = await typeOf(key)
@@ -550,6 +735,10 @@ export function createMediaOperations(options: MediaOperationsOptions) {
550
735
  if (misplaced) return refuse('invalid', 400, misplaced)
551
736
  }
552
737
  const before = await nodes.byKey(key)
738
+ const queued = before
739
+ ? await queueWhenLarge(actor, [before], run.inline, MEDIA_JOBS.restore, { key, targetKey })
740
+ : undefined
741
+ if (queued) return { ok: true, queued }
553
742
  const result = await commit(
554
743
  actor,
555
744
  (tx) => tx.restore(key, targetKey),
@@ -563,9 +752,13 @@ export function createMediaOperations(options: MediaOperationsOptions) {
563
752
  return { ok: true }
564
753
  },
565
754
 
566
- async move(actor: MediaActor, key: string, targetKey: string | null): Promise<Result> {
755
+ async move(
756
+ actor: MediaActor,
757
+ key: string,
758
+ targetKey: string | null,
759
+ ): Promise<Result<{ queued?: string }>> {
567
760
  const result = await operations.moveMany(actor, [key], targetKey)
568
- if (result.ok) return { ok: true }
761
+ if (result.ok) return result.queued ? { ok: true, queued: result.queued } : { ok: true }
569
762
  const first = 'blocked' in result ? result.blocked?.[0]?.reasons[0] : undefined
570
763
  return first ? { ...result, reason: first } : result
571
764
  },
@@ -578,7 +771,7 @@ export function createMediaOperations(options: MediaOperationsOptions) {
578
771
  actor: MediaActor,
579
772
  keys: readonly string[],
580
773
  targetKey: string | null,
581
- many: { dryRun?: boolean } = {},
774
+ many: { dryRun?: boolean; inline?: boolean } = {},
582
775
  ): Promise<SelectionResult> {
583
776
  const found = await nodesFor(keys)
584
777
  if (!Array.isArray(found)) return found
@@ -605,6 +798,11 @@ export function createMediaOperations(options: MediaOperationsOptions) {
605
798
  const unchanged = found.filter(stays).map((node) => node.key)
606
799
  if (many.dryRun || writes.length === 0)
607
800
  return { ok: true, changed: writes.map((node) => node.key), unchanged }
801
+ const queued = await queueWhenLarge(actor, writes, many.inline, MEDIA_JOBS.move, {
802
+ keys: writes.map((node) => node.key),
803
+ targetKey,
804
+ })
805
+ if (queued) return { ok: true, changed: writes.map((node) => node.key), unchanged, queued }
608
806
  try {
609
807
  const done = await commit(
610
808
  actor,
package/src/operations.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  WriteRejectedError,
30
30
  } from '@crombolo/data'
31
31
  import type { Actor, ContentPrincipal } from './actor.ts'
32
+ import { duplicateBlockAlias } from './block-aliases.ts'
32
33
  import type { DocumentEvent, EventSink } from './events.ts'
33
34
  import {
34
35
  deniedPropertyWrite,
@@ -40,6 +41,9 @@ import {
40
41
  } from './policy.ts'
41
42
 
42
43
  /** A page as a save sends it. */
44
+ const sharedAlias = (twice: { property: string; alias: string }) =>
45
+ `Two blocks in "${twice.property}" are called "${twice.alias}": give one another name.`
46
+
43
47
  export interface DocumentInput {
44
48
  key: string
45
49
  contentTypeKey: string
@@ -86,7 +90,8 @@ export type Blocked = Array<{ key: string; reasons: string[] }>
86
90
  * would change) and those already as asked; or, refused, each item's reasons.
87
91
  */
88
92
  export type SelectionResult =
89
- | Done<{ changed: string[]; unchanged: string[] }>
93
+ /** `queued`: a large branch handed to a background job, which writes it (story 246). */
94
+ | Done<{ changed: string[]; unchanged: string[]; queued?: string }>
90
95
  | (Refusal & { blocked?: Blocked })
91
96
 
92
97
  /**
@@ -510,6 +515,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
510
515
  input.values,
511
516
  )
512
517
  if (denied) return denied
518
+ const twice = duplicateBlockAlias(input.values)
519
+ if (twice) return refuse('invalid', 400, sharedAlias(twice))
513
520
  const misplaced = await placement(actor, input.contentTypeKey, input.parentKey)
514
521
  if (misplaced) return refuse('invalid', 400, misplaced)
515
522
  try {
@@ -543,6 +550,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
543
550
  input.values,
544
551
  )
545
552
  if (denied) return denied
553
+ const twice = duplicateBlockAlias(input.values)
554
+ if (twice) return refuse('invalid', 400, sharedAlias(twice))
546
555
  const unbased = revisionRefusal(actor, precondition)
547
556
  if (unbased) return unbased
548
557
  const gate = gateFor(actor)
@@ -589,6 +598,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
589
598
  input.values,
590
599
  )
591
600
  if (denied) return denied
601
+ const twice = duplicateBlockAlias(input.values)
602
+ if (twice) return refuse('invalid', 400, sharedAlias(twice))
592
603
  const misplaced = await placement(actor, input.contentTypeKey, input.parentKey)
593
604
  if (misplaced) return refuse('invalid', 400, misplaced)
594
605
  const gate = gateFor(actor)
@@ -638,6 +649,8 @@ export function createDocumentOperations(options: DocumentOperationsOptions) {
638
649
  input.values,
639
650
  )
640
651
  if (denied) return denied
652
+ const twice = duplicateBlockAlias(input.values)
653
+ if (twice) return refuse('invalid', 400, sharedAlias(twice))
641
654
  const unbased = revisionRefusal(actor, precondition)
642
655
  if (unbased) return unbased
643
656
  const gate = gateFor(actor)
package/src/rules.ts CHANGED
@@ -4,5 +4,6 @@
4
4
  * imports nothing that reaches the database.
5
5
  */
6
6
  export * from './actor.ts'
7
+ export * from './block-aliases.ts'
7
8
  export * from './events.ts'
8
9
  export * from './policy.ts'