@crombolo/server 0.22.0 → 0.24.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/src/jobs.ts CHANGED
@@ -8,21 +8,24 @@
8
8
  * it runs once.
9
9
  */
10
10
 
11
+ import { type DocumentOperations, systemActor } from '@crombolo/content'
11
12
  import type { NodeSchemaState } from '@crombolo/data'
12
13
  import {
13
14
  AuditLog,
15
+ ContentEventRepository,
14
16
  type Db,
15
17
  DocumentRepository,
16
- PublishBlockedError,
18
+ pruneCacheInstructions,
17
19
  SearchIndex,
20
+ WebhookDeliveryRepository,
18
21
  } from '@crombolo/data'
19
22
  import type { PublishedCache } from '@crombolo/render'
20
- import { auditRetainedSince, recordAudit } from './adapters/audit.ts'
23
+ import { auditRetainedSince } from './adapters/audit.ts'
21
24
  import type { Approvals } from './approvals.ts'
25
+ import type { ContentDispatcher } from './content-dispatch.ts'
22
26
  import type {
23
27
  ContentNotificationRunner,
24
28
  ContentNotificationRunReport,
25
- ContentNotifier,
26
29
  } from './content-notifications.ts'
27
30
  import type { WorkflowRunner, WorkflowRunReport } from './form-workflows.ts'
28
31
  import { logger } from './logging.ts'
@@ -50,9 +53,14 @@ export interface JobsOptions {
50
53
  */
51
54
  formWorkflows?: WorkflowRunner
52
55
  formWorkflowsMs?: number
53
- /** Raises the publishes scheduled publishing makes, and drains the delivery queue. */
54
- webhooks?: Pick<WebhookService, 'raise' | 'runDue'>
56
+ /** Drains the delivery queue. */
57
+ webhooks?: Pick<WebhookService, 'runDue'>
55
58
  webhooksMs?: number
59
+ /** Turns recorded content events into deliveries and notifications (story 171). */
60
+ dispatcher?: ContentDispatcher
61
+ dispatcherMs?: number
62
+ /** Days delivered webhooks, their log and dispatched events are kept; failed work stays. */
63
+ eventRetentionDays?: number
56
64
  /** How often the search indexer looks for queued items; a write here also starts it at once. */
57
65
  searchIndexingMs?: number
58
66
  /** Days the audit log keeps an entry; 0 or absent keeps them forever. */
@@ -60,12 +68,18 @@ export interface JobsOptions {
60
68
  /** Content notifications (story 045): queued by changes, sent here. Absent without e-mail. */
61
69
  contentNotifications?: ContentNotificationRunner
62
70
  contentNotificationsMs?: number
63
- /** Queues the notifications scheduled publishing makes, as an editor's publish does. */
64
- notifier?: ContentNotifier
65
71
  /** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
66
72
  approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
73
+ /**
74
+ * Publishes what a schedule says, as the site (story 170): recorded, tracked and
75
+ * announced as an editor's publish is.
76
+ */
77
+ operations: DocumentOperations
67
78
  }
68
79
 
80
+ /** A delivery a node took and never finished is retried after this long: that node died. */
81
+ export const WEBHOOK_STALE_AFTER_MS = 15 * 60_000
82
+
69
83
  export interface ScheduledRun {
70
84
  published: string[]
71
85
  unpublished: string[]
@@ -78,6 +92,10 @@ export interface BackgroundJobs {
78
92
  runFormWorkflows(now?: Date): Promise<WorkflowRunReport>
79
93
  /** Delivers the webhook and bundle events that are due. */
80
94
  runWebhooks(now?: Date): Promise<WorkflowRunReport>
95
+ /** Dispatches the content events waiting in the outbox (story 171). */
96
+ runEvents(now?: Date): Promise<WorkflowRunReport>
97
+ /** Releases claims left by a node that died, and prunes delivered work. */
98
+ runQueueUpkeep(now?: Date): Promise<void>
81
99
  /** Sends the content notifications that are due (story 045). */
82
100
  runContentNotifications(now?: Date): Promise<ContentNotificationRunReport>
83
101
  /** Indexes every queued item, and returns how many. docs/search.md. */
@@ -100,7 +118,6 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
100
118
  nodeId: options.nodeId,
101
119
  })
102
120
  const timers: Array<ReturnType<typeof setInterval>> = []
103
- let running = false
104
121
  const search = new SearchIndex(options.db)
105
122
  let indexing: Promise<number> | undefined
106
123
  let kicked: ReturnType<typeof setTimeout> | undefined
@@ -110,48 +127,62 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
110
127
  for (const due of await documents.dueSchedules(now)) {
111
128
  if (!(await documents.claimSchedule(due.id))) continue
112
129
  const cultures = due.culture ? [due.culture] : null
113
- try {
114
- const release = due.action === 'Release'
115
- const changed = release
116
- ? await documents.publish(due.key, cultures)
117
- : await documents.unpublish(due.key, cultures)
118
- ;(release ? run.published : run.unpublished).push(due.key)
119
- await recordAudit(options.db, {
120
- category: 'content',
121
- action: release ? 'Publish' : 'Unpublish',
122
- source: 'job',
123
- entityType: 'Document',
124
- entityKey: due.key,
125
- entityName: changed?.variants[0]?.name ?? null,
126
- detail: `Scheduled${due.culture ? ` (${due.culture})` : ''}`,
127
- })
128
- options.onDocumentChanged?.(due.key)
129
- await options.approvals?.scheduleFired(due.key, due.culture, due.action, { ok: true })
130
- } catch (error) {
131
- if (!(error instanceof PublishBlockedError)) throw error
132
- run.failed.push({ key: due.key, reason: error.message })
133
- await options.approvals?.scheduleFired(due.key, due.culture, due.action, {
134
- ok: false,
135
- reason: error.message,
136
- })
137
- }
138
- }
139
- await options.approvals?.sweepScheduled(now.getTime())
140
- if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
141
- for (const key of run.published) {
142
- await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
143
- await options.notifier?.raise(
144
- { actions: ['Umb.Document.Publish'], key, keyKind: 'document' },
145
- { key: null, name: 'The schedule' },
146
- 'scheduled',
130
+ const release = due.action === 'Release'
131
+ const actor = systemActor('The schedule', {
132
+ note: `scheduled${due.culture ? ` (${due.culture})` : ''}`,
133
+ })
134
+ const result = release
135
+ ? await options.operations.publish(actor, due.key, { cultures })
136
+ : await options.operations.unpublish(actor, due.key, cultures)
137
+ if (result.ok) (release ? run.published : run.unpublished).push(due.key)
138
+ else run.failed.push({ key: due.key, reason: result.reason })
139
+ await options.approvals?.scheduleFired(
140
+ due.key,
141
+ due.culture,
142
+ due.action,
143
+ result.ok ? { ok: true } : { ok: false, reason: result.reason },
147
144
  )
148
145
  }
149
- for (const key of run.unpublished)
150
- await options.webhooks?.raise({ alias: 'Umbraco.ContentUnpublish', key })
146
+ await options.approvals?.sweepScheduled(now.getTime())
147
+ // The operations recorded, announced and refreshed what they did themselves.
151
148
  return run
152
149
  }
153
150
 
151
+ async function runEvents(now?: Date): Promise<WorkflowRunReport> {
152
+ // A run a commit already started finishes first, so this sees what it left.
153
+ await options.dispatcher?.settled()
154
+ return (
155
+ (await options.dispatcher?.runDue(notBefore(now))) ?? {
156
+ claimed: 0,
157
+ done: 0,
158
+ retrying: 0,
159
+ failed: 0,
160
+ }
161
+ )
162
+ }
163
+
164
+ /**
165
+ * Hourly: claims left by a node that died go back in their queues, and what
166
+ * was delivered long enough ago goes (story 171). Failed work stays until
167
+ * someone retries it.
168
+ */
169
+ async function runQueueUpkeep(now = new Date()): Promise<void> {
170
+ const staleBefore = new Date(now.getTime() - WEBHOOK_STALE_AFTER_MS)
171
+ const deliveries = new WebhookDeliveryRepository(options.db)
172
+ await deliveries.releaseStale(staleBefore)
173
+ const days = options.eventRetentionDays ?? 30
174
+ if (days > 0) {
175
+ const before = new Date(now.getTime() - days * 86_400_000)
176
+ await deliveries.prune(before)
177
+ await new ContentEventRepository(options.db).prune(before)
178
+ }
179
+ // Every node starts from the newest instruction at boot, so a day's history is plenty.
180
+ await pruneCacheInstructions(options.db, new Date(now.getTime() - 86_400_000))
181
+ }
182
+
154
183
  async function runContentNotifications(now = new Date()): Promise<ContentNotificationRunReport> {
184
+ // What is waiting in the outbox is queued first, so it goes in this run.
185
+ await runEvents(now)
155
186
  const runner = options.contentNotifications
156
187
  return runner ? runner.runDue(now) : { claimed: 0, sent: 0, skipped: 0, retrying: 0, failed: 0 }
157
188
  }
@@ -165,8 +196,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
165
196
  return documents.cleanupVersions(now, options.versionCleanup)
166
197
  }
167
198
 
168
- async function runWebhooks(now = new Date()): Promise<WorkflowRunReport> {
169
- return (await options.webhooks?.runDue(now)) ?? { claimed: 0, done: 0, retrying: 0, failed: 0 }
199
+ /** The later of the time asked for and now: what was queued a moment ago is due too. */
200
+ const notBefore = (asked: Date | undefined) =>
201
+ new Date(Math.max(asked?.getTime() ?? 0, Date.now()))
202
+
203
+ async function runWebhooks(now?: Date): Promise<WorkflowRunReport> {
204
+ await runEvents(now)
205
+ return (
206
+ (await options.webhooks?.runDue(notBefore(now))) ?? {
207
+ claimed: 0,
208
+ done: 0,
209
+ retrying: 0,
210
+ failed: 0,
211
+ }
212
+ )
170
213
  }
171
214
 
172
215
  async function runFormWorkflows(now = new Date()): Promise<WorkflowRunReport> {
@@ -194,15 +237,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
194
237
  logger('jobs').error('Search indexing failed', { error })
195
238
  })
196
239
 
197
- const guarded = (job: () => Promise<unknown>) => async () => {
198
- if (running) return
199
- running = true
200
- try {
201
- await job()
202
- } catch (error) {
203
- logger('jobs').error('A background job failed', { error })
204
- } finally {
205
- running = false
240
+ // One guard per job: a slow webhook run skips its own next tick, never a
241
+ // scheduled publish's.
242
+ const guarded = (job: () => Promise<unknown>) => {
243
+ let running = false
244
+ return async () => {
245
+ if (running) return
246
+ running = true
247
+ try {
248
+ await job()
249
+ } catch (error) {
250
+ logger('jobs').error('A background job failed', { error })
251
+ } finally {
252
+ running = false
253
+ }
206
254
  }
207
255
  }
208
256
 
@@ -218,6 +266,8 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
218
266
  runAuditRetention,
219
267
  runFormWorkflows,
220
268
  runWebhooks,
269
+ runEvents,
270
+ runQueueUpkeep,
221
271
  runContentNotifications,
222
272
  runSearchIndexing,
223
273
  kickSearchIndexing() {
@@ -239,6 +289,10 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
239
289
  if (options.formWorkflows) every(options.formWorkflowsMs ?? 15_000, runFormWorkflows)
240
290
  // As often, for the same reason: a receiver that is waiting notices a minute.
241
291
  if (options.webhooks) every(options.webhooksMs ?? 15_000, runWebhooks)
292
+ // A commit nudges the dispatcher at once; this picks up what another node,
293
+ // the command line or a crash left behind.
294
+ if (options.dispatcher) every(options.dispatcherMs ?? 15_000, runEvents)
295
+ every(60 * 60_000, runQueueUpkeep)
242
296
  // A digest waits a minute anyway; this is how soon after that it goes.
243
297
  const notifications = options.contentNotifications
244
298
  if (notifications) {
package/src/ports.ts CHANGED
@@ -23,6 +23,14 @@ import {
23
23
  type ExtensionRegistry,
24
24
  toResponseModels,
25
25
  } from '@crombolo/backoffice-host'
26
+ import {
27
+ type ApprovalsGate,
28
+ type ContentPrincipal,
29
+ createDocumentOperations,
30
+ type DocumentOperations,
31
+ type EventSink,
32
+ SILENT,
33
+ } from '@crombolo/content'
26
34
  import {
27
35
  CORE_SECTION_ALIASES,
28
36
  DEFAULT_UPLOAD_SETTINGS,
@@ -31,6 +39,7 @@ import {
31
39
  permissionsForPath,
32
40
  } from '@crombolo/core'
33
41
  import {
42
+ ContentEventRepository,
34
43
  ContentTypeRepository,
35
44
  type Db,
36
45
  DynamicRootRepository,
@@ -72,12 +81,13 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
72
81
  import { createTemplateQueryPort } from './adapters/template-query.ts'
73
82
  import { avatarUrls, createUserPorts } from './adapters/users.ts'
74
83
  import { createWebhookPort } from './adapters/webhooks.ts'
75
- import { createApprovals } from './approvals.ts'
84
+ import { type Approvals, createApprovals } from './approvals.ts'
76
85
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
77
86
  import { type CromboloConfig, type UserLinkSender, VERSION } from './config.ts'
78
87
  import type { ContentNotifier } from './content-notifications.ts'
88
+ import { writeDomainsFor } from './domains.ts'
79
89
  import { type EmailPort, resolveEmailPort } from './email.ts'
80
- import { createFileIntake } from './file-intake.ts'
90
+ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
81
91
  import { formTypesFor } from './form-types.ts'
82
92
  import { createLogViewerPort } from './log-viewer.ts'
83
93
  import { logger } from './logging.ts'
@@ -387,6 +397,10 @@ export interface DepsOptions {
387
397
  extensions: ExtensionRegistry
388
398
  /** Omitted only by tests that exercise the contract without a database. */
389
399
  db?: Db
400
+ /** Where document operations announce what they did; nothing hears them when absent. */
401
+ contentEvents?: EventSink
402
+ /** Told when something was put in the event outbox, so it goes out now (story 171). */
403
+ nudgeEvents?: () => void
390
404
  /** The site's webhooks, shared with the delivery job and the event source. */
391
405
  webhooks?: WebhookService
392
406
  /** Required alongside `db` to serve documents, which invalidate the cache. */
@@ -517,15 +531,30 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
517
531
  endSessions: async (userId) => {
518
532
  await store.endAllSessionsForUser(userId)
519
533
  },
520
- onPagePermissionsChanged: (principal, nodeKeys) =>
521
- Promise.all(
522
- nodeKeys.map((key) =>
523
- options.notifier?.raise(
534
+ // Through the outbox, as a page's own changes are (story 171).
535
+ onPagePermissionsChanged: async (principal, nodeKeys) => {
536
+ const notifier = options.notifier
537
+ const db = options.db
538
+ if (!notifier || !db) return
539
+ await db.transaction(async (tx) => {
540
+ for (const key of nodeKeys) {
541
+ const notification = await notifier.factsFor(
542
+ tx,
524
543
  { actions: ['Umb.Document.Permissions'], key, keyKind: 'document' },
525
544
  { key: principal.id, name: principal.name },
526
- ),
527
- ),
528
- ).then(() => undefined),
545
+ )
546
+ if (notification)
547
+ await new ContentEventRepository(tx).record({
548
+ kind: 'permissionsChanged',
549
+ entityType: 'Document',
550
+ entityKey: key,
551
+ facts: { v: 1, notification },
552
+ actor: { kind: 'user', name: principal.name, userKey: principal.id },
553
+ })
554
+ }
555
+ })
556
+ options.nudgeEvents?.()
557
+ },
529
558
  })
530
559
  // Story 032: the authenticator provider, offered only where secrets can be sealed.
531
560
  const twoFactor = new TwoFactorService(options.db, {
@@ -550,6 +579,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
550
579
  nodeId: options.schema?.nodeId,
551
580
  valueIntake,
552
581
  onChange: () => options.cache?.invalidate(),
582
+ webhooks: options.webhooks,
583
+ nudge: options.nudgeEvents,
553
584
  })
554
585
  deps.blueprints = createBlueprintPort(options.db, {
555
586
  nodeState: options.schema?.nodeState,
@@ -638,6 +669,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
638
669
  deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
639
670
  onChange: () => options.cache?.invalidate(),
640
671
  })
672
+ const tracker = options.cache
673
+ ? createRedirectTracker({
674
+ cache: options.cache,
675
+ redirects: new RedirectRepository(options.db),
676
+ enabled: options.config.trackRedirects,
677
+ })
678
+ : undefined
641
679
  if (options.cache)
642
680
  deps.documents = createDocumentPort(
643
681
  options.db,
@@ -647,29 +685,50 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
647
685
  nodeId: options.schema?.nodeId,
648
686
  valueIntake,
649
687
  },
650
- createRedirectTracker({
651
- cache: options.cache,
652
- redirects: new RedirectRepository(options.db),
653
- enabled: options.config.trackRedirects,
654
- }),
688
+ tracker,
655
689
  options.config.siteDir,
656
690
  Boolean(email),
657
691
  )
658
692
  if (deps.documents) {
659
- const documents = deps.documents
660
- deps.approvals = createApprovals({
661
- db: options.db,
693
+ const db = options.db
694
+ // Every document write, whoever starts it (story 170). Approvals publish
695
+ // through it too, so what an approval publishes is cached, tracked and
696
+ // announced as any publish is.
697
+ let operations: DocumentOperations | undefined
698
+ const approvals = createApprovals({
699
+ db,
662
700
  nodeState: options.schema?.nodeState,
663
701
  email,
664
702
  backOfficeUrl: backOfficeUrl(options.config),
665
703
  notifier: options.notifier,
666
- // Through the same port an editor's publish takes, so what approval
667
- // publishes is cached, tracked and announced as any publish is.
668
704
  publisher: {
669
- publish: (key, cultures) => documents.publish(key, cultures),
670
- unpublish: (key, cultures) => documents.unpublish(key, cultures),
705
+ publish: (key, cultures, actor, approvedHead) =>
706
+ (operations as DocumentOperations).publish(actor, key, {
707
+ cultures,
708
+ expectedHead: approvedHead,
709
+ }),
710
+ unpublish: (key, cultures, actor) =>
711
+ (operations as DocumentOperations).unpublish(actor, key, cultures),
671
712
  },
672
713
  })
714
+ deps.approvals = approvals
715
+ operations = createDocumentOperations({
716
+ db,
717
+ repository: {
718
+ nodeState: options.schema?.nodeState,
719
+ nodeId: options.schema?.nodeId,
720
+ valueIntake,
721
+ },
722
+ events: options.contentEvents ?? SILENT,
723
+ approvals: approvalsGate(approvals),
724
+ redirects: tracker,
725
+ onChange: () => options.cache?.invalidate(),
726
+ afterDomains: (node, assignment) =>
727
+ writeDomainsFor(db, options.config.siteDir, node, assignment),
728
+ refusalReason: (error) =>
729
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
730
+ })
731
+ deps.documentOperations = operations
673
732
  }
674
733
  }
675
734
  return deps
@@ -715,3 +774,20 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
715
774
  reset: (userKey) => service.reset(userKey, provider),
716
775
  }
717
776
  }
777
+
778
+ /**
779
+ * The approval workflows as the document operations meet them. A user's principal
780
+ * is the backoffice's own, passed straight through; a local operator has none.
781
+ */
782
+ export function approvalsGate(approvals: Approvals): ApprovalsGate {
783
+ const as = (who: ContentPrincipal | undefined) => who as Principal | undefined
784
+ return {
785
+ publishRefusal: (who, key, action) => approvals.publishRefusal(as(who), key, action),
786
+ branchRefusal: (who, key) => approvals.branchRefusal(as(who), key),
787
+ newPageRefusal: (who, parentKey, typeKey) =>
788
+ approvals.newPageRefusal(as(who), parentKey, typeKey),
789
+ beforeSave: (who, key) => approvals.beforeSave(as(who), key),
790
+ afterSave: (who, key) => approvals.afterSave(as(who), key),
791
+ afterDirectPublish: (who, key, what) => approvals.afterDirectPublish(as(who), key, what),
792
+ }
793
+ }
package/src/remote.ts CHANGED
@@ -48,6 +48,11 @@ export interface RemoteOptions {
48
48
  db: Db
49
49
  config: CromboloConfig
50
50
  authenticate(request: Request): Promise<Principal | undefined>
51
+ /**
52
+ * Told once a push has landed, so this node's published cache is rebuilt: the
53
+ * import's cache instruction carries this node's id, and a node skips its own.
54
+ */
55
+ onApplied?(): void
51
56
  }
52
57
 
53
58
  export interface Remote {
@@ -307,6 +312,7 @@ export function createRemote(options: RemoteOptions): Remote {
307
312
  })
308
313
  return
309
314
  }
315
+ options.onApplied?.()
310
316
  await jobs.update(job.id, {
311
317
  state: 'done',
312
318
  stage:
package/src/schema.ts CHANGED
@@ -254,9 +254,16 @@ export interface CachePollerOptions {
254
254
  * skipped. Where the database can notify, a write wakes it at once and the
255
255
  * timer is only the fallback.
256
256
  */
257
+ /** How far behind its cursor the poller looks for a row that committed late. */
258
+ const CURSOR_WINDOW = 100
259
+
257
260
  export class CacheInstructionPoller {
258
261
  #options: CachePollerOptions
259
262
  #cursor = 0
263
+ /** Where this node started: history before it was never this node's to apply. */
264
+ #origin = 0
265
+ /** Ids applied within the window behind the cursor. */
266
+ #seen = new Set<number>()
260
267
  #timer: ReturnType<typeof setInterval> | undefined
261
268
  #unlisten: (() => Promise<void>) | undefined
262
269
  #running: Promise<number> | undefined
@@ -294,6 +301,7 @@ export class CacheInstructionPoller {
294
301
  this.#bootLedgerId = await latestLedgerId(this.#options.db)
295
302
  this.#paused = await readWritesPaused(this.#options.db)
296
303
  this.#cursor = await latestCacheInstructionId(this.#options.db)
304
+ this.#origin = this.#cursor
297
305
  if (intervalMs > 0) {
298
306
  this.#timer = setInterval(() => void this.poll().catch(() => {}), intervalMs)
299
307
  this.#timer.unref()
@@ -331,14 +339,20 @@ export class CacheInstructionPoller {
331
339
 
332
340
  async #pollOnce(): Promise<number> {
333
341
  const { db, nodeId, nodeState, onInstruction } = this.#options
334
- const instructions = await cacheInstructionsAfter(db, this.#cursor)
342
+ // A row can commit after one with a higher id (Postgres hands ids out
343
+ // before commit), so a short window behind the cursor is read again and
344
+ // the ids already seen are skipped.
345
+ const instructions = await cacheInstructionsAfter(db, Math.max(0, this.#cursor - CURSOR_WINDOW))
335
346
  let applied = 0
336
347
  for (const instruction of instructions) {
348
+ if (this.#seen.has(instruction.id) || instruction.id <= this.#origin) continue
349
+ this.#seen.add(instruction.id)
337
350
  this.#cursor = Math.max(this.#cursor, instruction.id)
338
351
  if (instruction.createdBy === nodeId) continue
339
352
  onInstruction(instruction.kind, instruction.payload)
340
353
  applied += 1
341
354
  }
355
+ for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
342
356
  await touchServer(db, {
343
357
  nodeId,
344
358
  ...nodeState,
package/src/server.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  createManagementApiRouter,
30
30
  hasSection,
31
31
  type Principal,
32
+ type ServerEvent,
32
33
  } from '@crombolo/api-management'
33
34
  import {
34
35
  AuthService,
@@ -56,6 +57,7 @@ import {
56
57
  resolveStaticFile,
57
58
  serveStaticFile,
58
59
  } from '@crombolo/backoffice-host'
60
+ import type { DocumentOperations } from '@crombolo/content'
59
61
  import { servedContract } from '@crombolo/contracts'
60
62
  import {
61
63
  CHOICE_SOURCE_KINDS,
@@ -130,6 +132,8 @@ import {
130
132
  type ServerRole,
131
133
  VERSION,
132
134
  } from './config.ts'
135
+ import { createContentDispatcher } from './content-dispatch.ts'
136
+ import { createContentEventSink } from './content-events.ts'
133
137
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
134
138
  import { attachDatabase, bootstrapDatabase } from './database.ts'
135
139
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
@@ -741,7 +745,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
741
745
  },
742
746
  )
743
747
  : undefined
744
- const remote = createRemote({ db, config, authenticate })
748
+ const remote = createRemote({ db, config, authenticate, onApplied: () => cache.invalidate() })
745
749
  const members = createMemberAuth(db, config, {
746
750
  nodeState: schema.nodeState,
747
751
  nodeId: schema.nodeId,
@@ -932,12 +936,35 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
932
936
  }
933
937
  : undefined,
934
938
  })
939
+ /**
940
+ * What an open backoffice hears of a change: the event hub drops its cached
941
+ * copy, whatever was queued gets indexed now, and an open preview reloads.
942
+ * Called only once requests are served, by which time the hubs below exist.
943
+ */
944
+ function announce(event: ServerEvent): void {
945
+ events.broadcast('notify', [event])
946
+ jobs.kickSearchIndexing()
947
+ if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
948
+ previewHub.broadcast('refreshed', [event.key])
949
+ }
950
+ // Recorded content events become deliveries and notifications here (story 171).
951
+ const dispatcher = createContentDispatcher({ db, webhooks, notifier })
952
+ // Document writes record and announce themselves through this, from every entry point.
953
+ const contentEvents = createContentEventSink({
954
+ webhooks,
955
+ notifier,
956
+ live: announce,
957
+ nudge: () => dispatcher.nudge(),
958
+ })
959
+
935
960
  const managementDeps = createDeps({
936
961
  config,
937
962
  paths,
938
963
  extensions,
939
964
  db,
940
965
  webhooks,
966
+ contentEvents,
967
+ nudgeEvents: () => dispatcher.nudge(),
941
968
  cache,
942
969
  previewInApp: appPreview,
943
970
  schema,
@@ -977,22 +1004,11 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
977
1004
  onNotImplemented: config.development
978
1005
  ? (operation, request) => notImplemented.record(operation, request)
979
1006
  : undefined,
980
- // Queued after the response, so a slow receiver never holds an editor up.
981
- onWebhookEvent: (event) => {
982
- void webhooks.raise(event)
983
- },
984
1007
  // After the response too: the subscribers are worked out and queued, and sent a minute later.
985
1008
  onContentChange: (change, principal) => {
986
1009
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
987
1010
  },
988
- onServerEvent: (event) => {
989
- events.broadcast('notify', [event])
990
- // Saves, deletes and moves all announce themselves; whatever they queued gets indexed now.
991
- jobs.kickSearchIndexing()
992
- // An open preview of the document reloads when it changes.
993
- if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
994
- previewHub.broadcast('refreshed', [event.key])
995
- },
1011
+ onServerEvent: announce,
996
1012
  })
997
1013
 
998
1014
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
@@ -1031,6 +1047,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1031
1047
  db,
1032
1048
  cache,
1033
1049
  approvals: managementDeps.approvals as Approvals | undefined,
1050
+ operations: managementDeps.documentOperations as DocumentOperations,
1051
+ dispatcher,
1052
+ eventRetentionDays: config.eventRetentionDays,
1034
1053
  nodeState: schema.nodeState,
1035
1054
  nodeId: schema.nodeId,
1036
1055
  versionCleanup: config.versionCleanup,
@@ -1047,6 +1066,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1047
1066
  nodeState: schema.nodeState,
1048
1067
  nodeId: schema.nodeId,
1049
1068
  onContentChanged: () => cache.invalidate(),
1069
+ operations: managementDeps.documentOperations,
1050
1070
  bundleWorkflows: formTypes.workflows,
1051
1071
  renderEmail: (alias, props) => renderer.renderEmail(alias, props),
1052
1072
  site: async () => ({
@@ -1054,7 +1074,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1054
1074
  url: config.applicationUrl,
1055
1075
  }),
1056
1076
  }),
1057
- notifier,
1058
1077
  contentNotifications: email
1059
1078
  ? createContentNotificationRunner({
1060
1079
  db,
package/src/settings.ts CHANGED
@@ -194,6 +194,14 @@ const DECLARED = [
194
194
  section: 'Database',
195
195
  description: 'How many days the audit log keeps an entry. `0` keeps them all.',
196
196
  },
197
+ {
198
+ env: 'CROMBOLO_EVENT_RETENTION_DAYS',
199
+ kind: 'number',
200
+ default: '30',
201
+ section: 'Database',
202
+ description:
203
+ 'How many days delivered webhooks, their log, and sent change events are kept. Failed ones stay until retried. `0` keeps them all.',
204
+ },
197
205
 
198
206
  // Sign-in and secrets
199
207
  {