@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.22.0",
3
+ "version": "0.24.1",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.22.0",
34
- "@crombolo/api-management": "0.22.0",
35
- "@crombolo/assistant": "0.22.0",
36
- "@crombolo/auth": "0.22.0",
37
- "@crombolo/backoffice-host": "0.22.0",
38
- "@crombolo/contracts": "0.22.0",
39
- "@crombolo/core": "0.22.0",
40
- "@crombolo/data": "0.22.0",
41
- "@crombolo/render": "0.22.0",
42
- "@crombolo/schema": "0.22.0",
43
- "@crombolo/transfer": "0.22.0",
33
+ "@crombolo/api-delivery": "0.24.1",
34
+ "@crombolo/api-management": "0.24.1",
35
+ "@crombolo/assistant": "0.24.1",
36
+ "@crombolo/auth": "0.24.1",
37
+ "@crombolo/backoffice-host": "0.24.1",
38
+ "@crombolo/content": "0.24.1",
39
+ "@crombolo/contracts": "0.24.1",
40
+ "@crombolo/core": "0.24.1",
41
+ "@crombolo/data": "0.24.1",
42
+ "@crombolo/render": "0.24.1",
43
+ "@crombolo/schema": "0.24.1",
44
+ "@crombolo/transfer": "0.24.1",
44
45
  "@logtape/logtape": "^2.3.8"
45
46
  }
46
47
  }
@@ -11,6 +11,8 @@ import {
11
11
  liveNodes,
12
12
  type NodeSchemaState,
13
13
  pendingMigrations,
14
+ type QueueCounts,
15
+ queueCounts,
14
16
  } from '@crombolo/data'
15
17
  import { BundleConfigurationError, bundleChainsFor, pendingBundleSteps } from '../bundle-tables.ts'
16
18
  import { type CromboloConfig, describeDatabase, VERSION } from '../config.ts'
@@ -29,8 +31,12 @@ const CHECKS = {
29
31
  media: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000003', name: 'Media storage' },
30
32
  email: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000004', name: 'E-mail delivery' },
31
33
  nodes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000005', name: 'Servers' },
34
+ outgoing: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000006', name: 'Outgoing changes' },
32
35
  } as const
33
36
 
37
+ /** Waiting longer than this means nothing is sending: no server is running its jobs, or one is stuck. */
38
+ export const BACKLOG_AFTER_MS = 10 * 60_000
39
+
34
40
  const GROUPS: HealthCheckGroup[] = [
35
41
  {
36
42
  name: 'Database',
@@ -57,10 +63,49 @@ const GROUPS: HealthCheckGroup[] = [
57
63
  ...CHECKS.nodes,
58
64
  description: 'The servers running this site, and whether they run the same release.',
59
65
  },
66
+ {
67
+ ...CHECKS.outgoing,
68
+ description:
69
+ 'Whether changes are reaching webhooks and the people who asked to hear of them.',
70
+ },
60
71
  ],
61
72
  },
62
73
  ]
63
74
 
75
+ const QUEUE_LABELS = {
76
+ changes: 'change(s) waiting to be passed on',
77
+ webhooks: 'webhook delivery(ies)',
78
+ notifications: 'change e-mail(s)',
79
+ } as const
80
+
81
+ /** What the outgoing queues say about delivery, worst first (story 171). Pure. */
82
+ export function outgoingResults(
83
+ queues: Record<keyof typeof QUEUE_LABELS, QueueCounts>,
84
+ at: Date,
85
+ ): HealthCheckResult[] {
86
+ const results: HealthCheckResult[] = []
87
+ for (const [name, counts] of Object.entries(queues) as Array<
88
+ [keyof typeof QUEUE_LABELS, QueueCounts]
89
+ >) {
90
+ if (counts.failed > 0)
91
+ results.push(
92
+ result(
93
+ 'Warning',
94
+ `${counts.failed} ${QUEUE_LABELS[name]} failed. \`crombolo events failed\` says why; \`crombolo events retry --all\` sends them again.`,
95
+ ),
96
+ )
97
+ if (counts.oldestPending && at.getTime() - counts.oldestPending.getTime() > BACKLOG_AFTER_MS)
98
+ results.push(
99
+ result(
100
+ 'Warning',
101
+ `${counts.pending} ${QUEUE_LABELS[name]} waiting, the oldest since ${counts.oldestPending.toISOString()}. Check a server is running background jobs.`,
102
+ ),
103
+ )
104
+ }
105
+ if (results.length === 0) results.push(result('Success', 'Changes are going out as they happen.'))
106
+ return results
107
+ }
108
+
64
109
  export interface HealthCheckOptions {
65
110
  config: CromboloConfig
66
111
  db: Db
@@ -237,6 +282,15 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
237
282
  [CHECKS.media.id]: mediaStorage,
238
283
  [CHECKS.email.id]: email,
239
284
  [CHECKS.nodes.id]: nodes,
285
+ [CHECKS.outgoing.id]: async () =>
286
+ outgoingResults(
287
+ {
288
+ changes: await queueCounts(db, 'content_event'),
289
+ webhooks: await queueCounts(db, 'webhook_delivery'),
290
+ notifications: await queueCounts(db, 'content_notification'),
291
+ },
292
+ now(),
293
+ ),
240
294
  }
241
295
 
242
296
  return {
@@ -15,6 +15,7 @@ import {
15
15
  } from '@crombolo/core'
16
16
  import {
17
17
  appendCacheInstruction,
18
+ ContentEventRepository,
18
19
  ContentTypeRepository,
19
20
  DataTypeRepository,
20
21
  type Db,
@@ -27,6 +28,7 @@ import {
27
28
  } from '@crombolo/data'
28
29
  import { TemporaryFileMissingError } from '../file-intake.ts'
29
30
  import type { MediaFileStore } from '../media-files.ts'
31
+ import type { WebhookService } from '../webhooks.ts'
30
32
 
31
33
  /** The file path an item's `umbracoFile` holds, whether an upload or a cropper value. */
32
34
  export function mediaFileOf(media: DocumentAggregate): string | null {
@@ -45,18 +47,56 @@ export function createMediaPort(
45
47
  valueIntake?: ValueIntake
46
48
  /** Told after every change, so pages that show media refresh. */
47
49
  onChange?: () => void | Promise<void>
50
+ /** Reads what a `MediaSave` or `MediaDelete` delivery needs, inside the change. */
51
+ webhooks?: Pick<WebhookService, 'factsFor'>
52
+ /** Told after a commit that left an event in the outbox (story 171). */
53
+ nudge?: () => void
48
54
  } = {},
49
55
  ): MediaPort {
56
+ /** Every node is told inside the change's transaction; this node's pages refresh after. */
57
+ const instruct = (on: Db) =>
58
+ appendCacheInstruction(on, { kind: 'content', payload: { media: true }, by: options.nodeId })
50
59
  const changed = async () => {
51
- await appendCacheInstruction(db, {
52
- kind: 'content',
53
- payload: { media: true },
54
- by: options.nodeId,
55
- })
60
+ await instruct(db)
56
61
  await options.onChange?.()
57
62
  }
58
63
  const repo = new DocumentRepository(db, { ...options, kind: 'media' })
59
64
 
65
+ /**
66
+ * Writes a media change, its cache instruction and its webhook event in one
67
+ * transaction (story 171), so the event commits with the change or not at all.
68
+ */
69
+ const commit = async <T>(
70
+ write: (tx: DocumentRepository) => Promise<T>,
71
+ announce: (result: T) => { alias: string; key: string } | undefined,
72
+ principal?: Principal,
73
+ ): Promise<T> => {
74
+ let recorded = false
75
+ const result = await repo.atomically(async (tx, txDb) => {
76
+ const written = await write(tx)
77
+ const event = announce(written)
78
+ if (!event) return written
79
+ await instruct(txDb)
80
+ const webhook = await options.webhooks?.factsFor(txDb, event)
81
+ if (webhook) {
82
+ await new ContentEventRepository(txDb).record({
83
+ kind: event.alias === 'Umbraco.MediaDelete' ? 'mediaDeleted' : 'mediaSaved',
84
+ entityType: 'Media',
85
+ entityKey: event.key,
86
+ facts: { v: 1, webhook },
87
+ actor: principal
88
+ ? { kind: 'user', name: principal.name, userKey: principal.id }
89
+ : { kind: 'system', name: 'The site', userKey: null },
90
+ })
91
+ recorded = true
92
+ }
93
+ return written
94
+ })
95
+ if (announce(result)) await options.onChange?.()
96
+ if (recorded) options.nudge?.()
97
+ return result
98
+ }
99
+
60
100
  const userIdOf = async (principal: Principal): Promise<number | undefined> => {
61
101
  const rows = await db.query<{ id: number }>('SELECT id FROM user_account WHERE key = ?', [
62
102
  principal.id,
@@ -131,11 +171,12 @@ export function createMediaPort(
131
171
  }
132
172
  const removeBranch = async (key: string) => {
133
173
  const paths = await filesIn(key)
134
- const removed = await repo.delete(key)
135
- if (removed) {
136
- for (const path of paths) await files.remove(path)
137
- await changed()
138
- }
174
+ const removed = await commit(
175
+ (tx) => tx.delete(key),
176
+ (done) => (done ? { alias: 'Umbraco.MediaDelete', key } : undefined),
177
+ )
178
+ // The files go once the rows have: a failed delete leaves both.
179
+ if (removed) for (const path of paths) await files.remove(path)
139
180
  return removed
140
181
  }
141
182
 
@@ -145,12 +186,12 @@ export function createMediaPort(
145
186
 
146
187
  async create(input, principal) {
147
188
  try {
148
- const created = await repo.create({
149
- ...input,
150
- componentKey: null,
151
- userId: await userIdOf(principal),
152
- })
153
- await changed()
189
+ const userId = await userIdOf(principal)
190
+ const created = await commit(
191
+ (tx) => tx.create({ ...input, componentKey: null, userId }),
192
+ (doc) => ({ alias: 'Umbraco.MediaSave', key: doc.key }),
193
+ principal,
194
+ )
154
195
  return { ok: true as const, key: created.key }
155
196
  } catch (error) {
156
197
  return failure(error)
@@ -160,17 +201,16 @@ export function createMediaPort(
160
201
  async update(key, input, principal) {
161
202
  try {
162
203
  const before = await repo.byKey(key)
163
- const updated = await repo.update({
164
- ...input,
165
- key,
166
- componentKey: null,
167
- userId: await userIdOf(principal),
168
- })
204
+ const userId = await userIdOf(principal)
205
+ const updated = await commit(
206
+ (tx) => tx.update({ ...input, key, componentKey: null, userId }),
207
+ (doc) => (doc ? { alias: 'Umbraco.MediaSave', key } : undefined),
208
+ principal,
209
+ )
169
210
  if (!updated) return notFound()
170
211
  // A replaced file is no longer anyone's: Umbraco deletes it too.
171
212
  const was = before ? mediaFileOf(before) : null
172
213
  if (was && was !== mediaFileOf(updated)) await files.remove(was)
173
- await changed()
174
214
  return { ok: true as const }
175
215
  } catch (error) {
176
216
  return failure(error)
package/src/approvals.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import type { Principal } from '@crombolo/api-management'
13
+ import { type Actor, systemActor } from '@crombolo/content'
13
14
  import {
14
15
  approvalsNeeded,
15
16
  DocumentPermissions,
@@ -45,13 +46,18 @@ import type { EmailPort } from './email.ts'
45
46
 
46
47
  /** What publishing and unpublishing go through when approval says yes. */
47
48
  export interface ApprovalPublisher {
49
+ /** As the site, on the approver's behalf: the gate has been passed by approving. */
48
50
  publish(
49
51
  key: string,
50
52
  cultures: string[] | null,
51
- ): Promise<{ ok: true } | { ok: false; reason: string }>
53
+ actor: Actor,
54
+ /** The event the request was approved on; anything later is not published (story 172). */
55
+ approvedHead?: number,
56
+ ): Promise<{ ok: true } | { ok: false; reason: string; kind?: string }>
52
57
  unpublish(
53
58
  key: string,
54
59
  cultures: string[] | null,
60
+ actor: Actor,
55
61
  ): Promise<{ ok: true } | { ok: false; reason: string }>
56
62
  }
57
63
 
@@ -135,24 +141,24 @@ export interface Approvals {
135
141
  workflows(): Promise<StoredWorkflow[]>
136
142
  /** Undefined when the caller may go ahead; otherwise why not. */
137
143
  publishRefusal(
138
- principal: Principal,
144
+ principal: Principal | undefined,
139
145
  key: string,
140
146
  action: ApprovalAction,
141
147
  ): Promise<string | undefined>
142
148
  /** A branch publish: the root and every page below it. */
143
- branchRefusal(principal: Principal, key: string): Promise<string | undefined>
149
+ branchRefusal(principal: Principal | undefined, key: string): Promise<string | undefined>
144
150
  /** For a page being created and published at once: by its parent and type. */
145
151
  newPageRefusal(
146
- principal: Principal,
152
+ principal: Principal | undefined,
147
153
  parentKey: string | null,
148
154
  contentTypeKey: string,
149
155
  ): Promise<string | undefined>
150
156
  /** Undefined when the save may go ahead; otherwise why not. */
151
- beforeSave(principal: Principal, key: string): Promise<string | undefined>
157
+ beforeSave(principal: Principal | undefined, key: string): Promise<string | undefined>
152
158
  /** What the save does to a waiting request, once it has gone through. */
153
- afterSave(principal: Principal, key: string): Promise<void>
159
+ afterSave(principal: Principal | undefined, key: string): Promise<void>
154
160
  /** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
155
- afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
161
+ afterDirectPublish(principal: Principal | undefined, key: string, what: string): Promise<void>
156
162
  /** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
157
163
  scheduleFired(
158
164
  key: string,
@@ -292,11 +298,17 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
292
298
  const groupAliases = async (principal: Principal): Promise<Set<string>> =>
293
299
  new Set((await groups.byKeys(principal.groupKeys)).map((g) => g.alias))
294
300
 
295
- const mayPublish = (principal: Principal, facts: PageFacts, action: ApprovalAction): boolean =>
296
- principal.isAdmin ||
297
- permissionsForPath(principal.groups, facts.chain).has(
298
- action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
299
- )
301
+ /** A local operator (no principal) holds no publishing rights of their own. */
302
+ const mayPublish = (
303
+ principal: Principal | undefined,
304
+ facts: PageFacts,
305
+ action: ApprovalAction,
306
+ ): boolean =>
307
+ principal !== undefined &&
308
+ (principal.isAdmin ||
309
+ permissionsForPath(principal.groups, facts.chain).has(
310
+ action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
311
+ ))
300
312
 
301
313
  /**
302
314
  * Refuses, with a 403, a caller who cannot reach the page through their start
@@ -315,7 +327,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
315
327
  workflow !== undefined && (action === 'publish' || workflow.unpublish)
316
328
 
317
329
  const refusalFor = (
318
- principal: Principal,
330
+ principal: Principal | undefined,
319
331
  facts: PageFacts,
320
332
  workflow: SchemaWorkflow | undefined,
321
333
  action: ApprovalAction,
@@ -576,22 +588,34 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
576
588
  : undefined
577
589
  }
578
590
  if (cultures !== undefined) {
591
+ // As the site, on the approver's behalf; the publish raises the notification, with this note.
592
+ const actor = systemActor('Approval', {
593
+ source: principal ? 'request' : 'job',
594
+ user: principal ? { id: principal.id, name: principal.name } : undefined,
595
+ note: `approved through "${request.workflow.name}"`,
596
+ })
579
597
  const result =
580
598
  request.action === 'publish'
581
- ? await options.publisher.publish(request.nodeKey, cultures)
582
- : await options.publisher.unpublish(request.nodeKey, cultures)
583
- if (!result.ok) return unpublishable(request, facts, result.reason)
599
+ ? await options.publisher.publish(
600
+ request.nodeKey,
601
+ cultures,
602
+ actor,
603
+ request.eventId ?? undefined,
604
+ )
605
+ : await options.publisher.unpublish(request.nodeKey, cultures, actor)
606
+ if (!result.ok)
607
+ return unpublishable(
608
+ request,
609
+ facts,
610
+ 'kind' in result && result.kind === 'stale'
611
+ ? 'it was changed after it was approved, so it needs approving again'
612
+ : result.reason,
613
+ )
584
614
  await repo.record(request.id, {
585
615
  kind: request.action === 'publish' ? 'published' : 'unpublished',
586
616
  userKey: principal?.id ?? null,
587
617
  comment: passed ? 'the requested time had passed when it was approved' : null,
588
618
  })
589
- if (request.action === 'publish')
590
- await options.notifier?.raise(
591
- { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
592
- principal ? { key: principal.id, name: principal.name } : null,
593
- `approved through "${request.workflow.name}"`,
594
- )
595
619
  }
596
620
  if (later.length + expires.length > 0)
597
621
  await documents().setSchedule(request.nodeKey, [...later, ...expires])
@@ -774,7 +798,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
774
798
 
775
799
  async beforeSave(principal, key) {
776
800
  const request = await requests().openFor(key)
777
- if (!request || principal.isAdmin) return undefined
801
+ if (!request || principal?.isAdmin) return undefined
778
802
  const edit = request.workflow.onEdit
779
803
  if (request.state === 'scheduled') {
780
804
  if (edit === 'lock' || edit === 'lock-after-first-approval')
@@ -800,18 +824,18 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
800
824
  ?.head ?? null
801
825
  if (head === request.eventId) return
802
826
  // Administrators may always edit; the request goes on, on what they saved.
803
- if (!principal.isAdmin && request.workflow.onEdit === 'withdraw') {
827
+ if (!principal?.isAdmin && request.workflow.onEdit === 'withdraw') {
804
828
  await repo.setState(request.id, 'withdrawn')
805
829
  await repo.record(request.id, {
806
830
  kind: 'withdrawn',
807
- userKey: principal.id,
831
+ userKey: principal?.id ?? null,
808
832
  comment: 'the page was changed after it was sent',
809
833
  })
810
834
  if (request.state === 'scheduled') await clearSchedule(request)
811
835
  return
812
836
  }
813
837
  await repo.setEvent(request.id, head)
814
- await repo.record(request.id, { kind: 'edited', userKey: principal.id })
838
+ await repo.record(request.id, { kind: 'edited', userKey: principal?.id ?? null })
815
839
  },
816
840
 
817
841
  async send(principal, key, action, cultures, comment, schedule) {
@@ -1010,8 +1034,8 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1010
1034
  await repo.setState(request.id, 'superseded')
1011
1035
  await repo.record(request.id, {
1012
1036
  kind: 'superseded',
1013
- userKey: principal.id,
1014
- comment: `${principal.name} ${what} directly`,
1037
+ userKey: principal?.id ?? null,
1038
+ comment: `${principal?.name ?? 'Someone at the command line'} ${what} directly`,
1015
1039
  })
1016
1040
  await auditStep(
1017
1041
  principal,
package/src/assistant.ts CHANGED
@@ -161,13 +161,14 @@ export function createAssistantHost(options: AssistantHostOptions): AssistantHos
161
161
  const origin = new URL(source.url).origin
162
162
  const cookie = source.headers.get('cookie')
163
163
  const authorization = source.headers.get('authorization')
164
- return async ({ method, path, query, body }) => {
164
+ return async ({ method, path, query, body, headers: extra }) => {
165
165
  const url = new URL(path, origin)
166
166
  for (const [name, value] of Object.entries(query ?? {})) url.searchParams.set(name, value)
167
167
  const headers = new Headers({ accept: 'application/json' })
168
168
  if (cookie) headers.set('cookie', cookie)
169
169
  if (authorization) headers.set('authorization', authorization)
170
170
  if (body !== undefined) headers.set('content-type', 'application/json')
171
+ for (const [name, value] of Object.entries(extra ?? {})) headers.set(name, value)
171
172
  const response = await options.dispatch(
172
173
  new Request(url, {
173
174
  method: method.toUpperCase(),
@@ -184,7 +185,11 @@ export function createAssistantHost(options: AssistantHostOptions): AssistantHos
184
185
  // A non-JSON body is passed through as text; the tools report it as-is.
185
186
  }
186
187
  }
187
- return { status: response.status, body: parsed }
188
+ return {
189
+ status: response.status,
190
+ body: parsed,
191
+ etag: response.headers.get('etag') ?? undefined,
192
+ }
188
193
  }
189
194
  }
190
195
 
package/src/config.ts CHANGED
@@ -255,6 +255,11 @@ export interface CromboloConfig {
255
255
  }
256
256
  /** How many days the audit log keeps an entry; 0 keeps them forever. docs/audit-log.md. */
257
257
  auditRetentionDays: number
258
+ /**
259
+ * How many days delivered webhooks, their log and dispatched content events
260
+ * are kept; 0 keeps them forever. Failed work stays until retried. docs/webhooks.md.
261
+ */
262
+ eventRetentionDays: number
258
263
  /** Where uploaded media files live; served at `/media/`. */
259
264
  mediaDir: string
260
265
  /**
@@ -455,6 +460,7 @@ export const DEFAULTS = {
455
460
  keepAllVersionsNewerThanDays: 7,
456
461
  keepLatestVersionPerDayForDays: 90,
457
462
  auditRetentionDays: 365,
463
+ eventRetentionDays: 30,
458
464
  memberRegistrationType: 'Member',
459
465
  memberSessionMinutes: 60 * 24 * 14,
460
466
  maxFailedPasswordAttempts: 5,
@@ -598,6 +604,10 @@ export function loadConfig(
598
604
  setting('CROMBOLO_AUDIT_RETENTION_DAYS'),
599
605
  DEFAULTS.auditRetentionDays,
600
606
  ),
607
+ eventRetentionDays: nonNegative(
608
+ setting('CROMBOLO_EVENT_RETENTION_DAYS'),
609
+ DEFAULTS.eventRetentionDays,
610
+ ),
601
611
  mediaDir: setting('CROMBOLO_MEDIA_DIR') ?? DEFAULTS.mediaDir,
602
612
  mediaStore: undefined,
603
613
  logsDir: setting('CROMBOLO_LOGS_DIR') ?? DEFAULTS.logsDir,
@@ -788,7 +798,7 @@ export function describeDatabase(
788
798
  }
789
799
  }
790
800
 
791
- export const VERSION = '0.22.0'
801
+ export const VERSION = '0.24.1'
792
802
 
793
803
  /** A whole number of seconds from the environment; undefined when unset or not one. */
794
804
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -0,0 +1,87 @@
1
+ /**
2
+ * The outbox dispatcher (story 171): turns each recorded content event into
3
+ * webhook deliveries and content notifications, and marks it dispatched in the
4
+ * same transaction. A crash anywhere repeats the step; the queues' unique keys
5
+ * absorb the repeat. An event that keeps failing is kept as failed, for
6
+ * `crombolo events retry`.
7
+ */
8
+ import { ContentEventRepository, type Db } from '@crombolo/data'
9
+ import type { ContentNotifier, NotificationFacts } from './content-notifications.ts'
10
+ import { retryAfter, type WorkflowRunReport } from './form-workflows.ts'
11
+ import { logger } from './logging.ts'
12
+ import type { WebhookFacts, WebhookService } from './webhooks.ts'
13
+
14
+ const log = logger('Events')
15
+
16
+ /** An event a node took and never finished is retried after this long: that node died. */
17
+ export const EVENT_STALE_AFTER_MS = 15 * 60_000
18
+
19
+ export interface ContentDispatcherOptions {
20
+ db: Db
21
+ webhooks?: Pick<WebhookService, 'enqueueFor'>
22
+ notifier?: Pick<ContentNotifier, 'enqueueFor'>
23
+ }
24
+
25
+ export interface ContentDispatcher {
26
+ runDue(now?: Date, limit?: number): Promise<WorkflowRunReport>
27
+ /** Dispatches soon, once, however many changes ask: a commit just left work. */
28
+ nudge(): void
29
+ /** Resolves when a nudged run has finished: for tests and an orderly shutdown. */
30
+ settled(): Promise<void>
31
+ }
32
+
33
+ export function createContentDispatcher(options: ContentDispatcherOptions): ContentDispatcher {
34
+ const events = new ContentEventRepository(options.db)
35
+ let running: Promise<unknown> | undefined
36
+ let again = false
37
+
38
+ const runDue = async (at = new Date(), limit = 50): Promise<WorkflowRunReport> => {
39
+ const report: WorkflowRunReport = { claimed: 0, done: 0, retrying: 0, failed: 0 }
40
+ await events.releaseStale(new Date(at.getTime() - EVENT_STALE_AFTER_MS))
41
+ for (const id of await events.due(at, limit)) {
42
+ const event = await events.claim(id)
43
+ if (!event) continue
44
+ report.claimed++
45
+ try {
46
+ await options.db.transaction(async (tx) => {
47
+ const webhook = event.facts.webhook as WebhookFacts | undefined
48
+ const notification = event.facts.notification as NotificationFacts | undefined
49
+ if (webhook) await options.webhooks?.enqueueFor(tx, event.id, webhook)
50
+ if (notification) await options.notifier?.enqueueFor(tx, event.id, notification)
51
+ await new ContentEventRepository(tx).dispatched(event.id)
52
+ })
53
+ report.done++
54
+ } catch (error) {
55
+ const again = retryAfter(event.attempts, at)
56
+ await events.fail(event.id, error instanceof Error ? error.message : String(error), again)
57
+ if (again) report.retrying++
58
+ else report.failed++
59
+ log.warning('Could not dispatch the {kind} event {id}: {error}', {
60
+ kind: event.kind,
61
+ id: event.id,
62
+ error,
63
+ })
64
+ }
65
+ }
66
+ return report
67
+ }
68
+
69
+ const nudge = () => {
70
+ if (running) {
71
+ again = true
72
+ return
73
+ }
74
+ running = (async () => {
75
+ do {
76
+ again = false
77
+ await runDue().catch((error: unknown) =>
78
+ log.error('The event dispatcher stopped: {error}', { error }),
79
+ )
80
+ } while (again)
81
+ })().finally(() => {
82
+ running = undefined
83
+ })
84
+ }
85
+
86
+ return { runDue, nudge, settled: async () => void (await running) }
87
+ }