@crombolo/server 0.23.0 → 0.25.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.
@@ -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
+ }
@@ -1,76 +1,89 @@
1
1
  /**
2
- * Where document operations announce what they did (story 170): the audit log,
3
- * webhooks, the people subscribed to a page, and — on a server — the live
4
- * backoffice. The command line wires the same sink without the live part, so a
5
- * change records and raises the same things wherever it was started.
2
+ * Where document operations record what they did (stories 170 and 171). Inside
3
+ * the change's own transaction: its audit entry, and — when anyone may hear of
4
+ * it — an outbox event holding the facts as they were. After the commit: the
5
+ * live backoffice, and a nudge so the dispatcher sends it now rather than at
6
+ * its next tick. The command line wires the same sink without the live part.
6
7
  */
7
8
  import {
9
+ type Actor,
8
10
  actorName,
9
11
  actorNote,
10
12
  actorUserKey,
11
13
  auditEntryFor,
14
+ type DocumentEvent,
12
15
  type EventSink,
13
16
  liveEventsFor,
14
17
  notificationFor,
15
18
  webhookFor,
16
19
  } from '@crombolo/content'
17
- import { AuditLog, type Db } from '@crombolo/data'
18
- import { recordAudit } from './adapters/audit.ts'
20
+ import { AuditLog, ContentEventRepository, type Db } from '@crombolo/data'
19
21
  import type { ContentNotifier } from './content-notifications.ts'
20
- import { logger } from './logging.ts'
21
22
  import type { WebhookService } from './webhooks.ts'
22
23
 
23
- const log = logger('Content')
24
-
25
24
  export interface ContentEventSinkOptions {
26
- db: Db
27
- webhooks?: Pick<WebhookService, 'raise'>
28
- notifier?: Pick<ContentNotifier, 'raise'>
25
+ webhooks?: Pick<WebhookService, 'factsFor'>
26
+ notifier?: Pick<ContentNotifier, 'factsFor'>
29
27
  /** Tells an open backoffice what changed: a server's event hub; absent on the command line. */
30
28
  live?(event: ReturnType<typeof liveEventsFor>[number]): void
29
+ /** Called after a commit that left work in the outbox. */
30
+ nudge?(): void
31
31
  }
32
32
 
33
+ /** The page an event is about, for the outbox row. */
34
+ const subjectOf = (event: DocumentEvent): string | null =>
35
+ 'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
36
+
37
+ /** Who made a change, as the outbox keeps it: enough to name them and leave them out. */
38
+ export const outboxActor = (actor: Actor) => ({
39
+ kind: actor.kind,
40
+ name: actorName(actor),
41
+ userKey: actorUserKey(actor),
42
+ })
43
+
33
44
  export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
34
- const audit = new AuditLog(options.db)
35
- const nameOf = async (entityType: string, key: string) => {
36
- try {
37
- return await audit.describe(entityType, key)
38
- } catch {
39
- return { entityType, entityKey: key, entityName: null }
40
- }
41
- }
42
45
  return {
43
- async emit(event, actor) {
46
+ async record(tx: Db, event, actor) {
44
47
  const entry = auditEntryFor(event, actor)
48
+ const audit = new AuditLog(tx)
45
49
  // A deleted page cannot be named after it went: the operation read its name first.
46
50
  const subject =
47
51
  event.type === 'deleted'
48
52
  ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
49
53
  : entry.entityKey
50
- ? await nameOf(entry.entityType, entry.entityKey)
54
+ ? await audit.describe(entry.entityType, entry.entityKey)
51
55
  : undefined
52
- await recordAudit(options.db, {
56
+ await audit.record({
53
57
  ...entry,
54
58
  entityType: subject?.entityType ?? entry.entityType,
55
59
  entityKey: subject?.entityKey ?? entry.entityKey,
56
60
  entityName: subject?.entityName ?? null,
57
61
  })
58
- // Queued and sent after: a slow receiver or an e-mail never holds the change up.
59
62
  const hook = webhookFor(event)
60
- if (hook)
61
- void options.webhooks
62
- ?.raise(hook)
63
- .catch((error: unknown) =>
64
- log.error('Could not queue the {alias} webhook: {error}', { alias: hook.alias, error }),
65
- )
66
63
  const change = notificationFor(event)
67
- if (change)
68
- void options.notifier
69
- ?.raise(change, { key: actorUserKey(actor), name: actorName(actor) }, actorNote(actor))
70
- .catch((error: unknown) =>
71
- log.error('Could not queue change notifications: {error}', { error }),
72
- )
64
+ const webhook =
65
+ hook && options.webhooks ? await options.webhooks.factsFor(tx, hook) : undefined
66
+ const notification =
67
+ change && options.notifier
68
+ ? await options.notifier.factsFor(
69
+ tx,
70
+ change,
71
+ { key: actorUserKey(actor), name: actorName(actor) },
72
+ actorNote(actor),
73
+ )
74
+ : undefined
75
+ if (!webhook && !notification) return
76
+ await new ContentEventRepository(tx).record({
77
+ kind: event.type,
78
+ entityType: 'Document',
79
+ entityKey: subjectOf(event),
80
+ facts: { v: 1, ...(webhook ? { webhook } : {}), ...(notification ? { notification } : {}) },
81
+ actor: outboxActor(actor),
82
+ })
83
+ },
84
+ afterCommit(event) {
73
85
  for (const live of liveEventsFor(event)) options.live?.(live)
86
+ if (webhookFor(event) || notificationFor(event)) options.nudge?.()
74
87
  },
75
88
  }
76
89
  }
@@ -44,7 +44,33 @@ export interface ContentNotifierOptions {
44
44
  delayMs?: number
45
45
  }
46
46
 
47
+ /**
48
+ * What a change's notifications need, read when it commits (story 171): the
49
+ * page as it was, where its subscribers are looked up, and who made the change.
50
+ */
51
+ export interface NotificationFacts {
52
+ actions: string[]
53
+ nodeKey: string
54
+ nodeName: string
55
+ /** Node ids, root first: where the page is, or where it was before the recycle bin. */
56
+ path: number[]
57
+ detail: string | null
58
+ actorUserKey: string | null
59
+ actorName: string | null
60
+ occurredAt: string
61
+ }
62
+
47
63
  export interface ContentNotifier {
64
+ /** The facts for a change, read on `db` — the change's transaction; undefined when it notifies no one. */
65
+ factsFor(
66
+ db: Db,
67
+ change: RaisedContentChange,
68
+ actor: Actor | null,
69
+ detail?: string,
70
+ ): Promise<NotificationFacts | undefined>
71
+ /** Queues one row per subscriber, once per event however often it is repeated. */
72
+ enqueueFor(db: Db, eventId: string | undefined, facts: NotificationFacts): Promise<void>
73
+ /** Facts and queue at once, outside any outbox: for a change with no event to record. */
48
74
  raise(change: RaisedContentChange, actor: Actor | null, detail?: string): Promise<void>
49
75
  }
50
76
 
@@ -56,71 +82,90 @@ const pathIds = (path: string): number[] =>
56
82
  .filter((id) => Number.isFinite(id) && id > 0)
57
83
 
58
84
  export function createContentNotifier(db: Db, options: ContentNotifierOptions): ContentNotifier {
59
- const nodes = new NodeRepository(db)
60
- const documents = new DocumentRepository(db)
61
- const subscriptions = new NotificationRepository(db)
62
- const outbox = new ContentNotificationRepository(db)
85
+ const factsFor: ContentNotifier['factsFor'] = async (on, change, actor, detail) => {
86
+ const nodes = new NodeRepository(on)
87
+ const documents = new DocumentRepository(on)
88
+ const node =
89
+ change.keyKind === 'version'
90
+ ? await documents
91
+ .atVersion(change.key)
92
+ .then((version) => (version ? nodes.byKey(version.document.key) : undefined))
93
+ : await nodes.byKey(change.key)
94
+ if (!node || node.objectType !== ObjectTypes.Document) return undefined
95
+ // A trashed page sits under the recycle bin now; its subscribers are
96
+ // the ones where it was.
97
+ let path = pathIds(node.path)
98
+ if (node.trashed) {
99
+ const parentKey = await documents.originalParent(node.key)
100
+ const parent = parentKey ? await nodes.byKey(parentKey) : undefined
101
+ path = [...(parent ? pathIds(parent.path) : []), node.id]
102
+ }
103
+ let summary = detail ?? null
104
+ if (change.withDescendants) {
105
+ const [row] = await on.query<{ n: number }>(
106
+ 'SELECT COUNT(*) AS n FROM node WHERE path LIKE ? AND node_object_type = ? AND trashed = ?',
107
+ [`${node.path},%`, ObjectTypes.Document, on.dialect.boolValue(false)],
108
+ )
109
+ const under = Number(row?.n ?? 0)
110
+ if (under > 0) summary = `and ${under} page${under === 1 ? '' : 's'} under it`
111
+ }
112
+ return {
113
+ actions: [...change.actions],
114
+ nodeKey: node.key,
115
+ nodeName: node.text ?? node.key,
116
+ path,
117
+ detail: summary,
118
+ actorUserKey: actor?.key ?? null,
119
+ actorName: actor?.name ?? null,
120
+ occurredAt: new Date().toISOString(),
121
+ }
122
+ }
63
123
 
64
- const resolve = async (change: RaisedContentChange) => {
65
- if (change.keyKind === 'version') {
66
- const version = await documents.atVersion(change.key)
67
- return version ? nodes.byKey(version.document.key) : undefined
124
+ const enqueueFor: ContentNotifier['enqueueFor'] = async (on, eventId, facts) => {
125
+ // A site that cannot send e-mail queues nothing, so nothing piles up.
126
+ if (!options.canSend) return
127
+ const subscriptions = new NotificationRepository(on)
128
+ const actorId = facts.actorUserKey
129
+ ? (await new UserRepository(on).byKey(facts.actorUserKey))?.id
130
+ : undefined
131
+ const occurredAt = new Date(facts.occurredAt)
132
+ const runAfter = new Date(Date.now() + (options.delayMs ?? DIGEST_DELAY_MS))
133
+ const rows = []
134
+ for (const actionId of facts.actions) {
135
+ const userIds = (await subscriptions.subscribersFor(actionId, facts.path)).filter(
136
+ (id) => id !== actorId,
137
+ )
138
+ if (userIds.length === 0) continue
139
+ const keys = await on.query<{ key: string }>(
140
+ `SELECT key FROM user_account WHERE id IN (${userIds.map(() => '?').join(', ')})`,
141
+ userIds,
142
+ )
143
+ for (const { key } of keys)
144
+ rows.push({
145
+ recipientUserKey: String(key),
146
+ actionId,
147
+ nodeKey: facts.nodeKey,
148
+ nodeName: facts.nodeName,
149
+ actorUserKey: facts.actorUserKey,
150
+ actorName: facts.actorName,
151
+ detail: facts.detail,
152
+ occurredAt,
153
+ runAfter,
154
+ eventId,
155
+ })
68
156
  }
69
- return nodes.byKey(change.key)
157
+ await new ContentNotificationRepository(on).enqueue(rows)
70
158
  }
71
159
 
72
160
  return {
161
+ factsFor,
162
+ enqueueFor,
73
163
  async raise(change, actor, detail) {
74
164
  if (!options.canSend) return
75
165
  try {
76
- const node = await resolve(change)
77
- if (!node || node.objectType !== ObjectTypes.Document) return
78
- // A trashed page sits under the recycle bin now; its subscribers are
79
- // the ones where it was.
80
- let path = pathIds(node.path)
81
- if (node.trashed) {
82
- const parentKey = await documents.originalParent(node.key)
83
- const parent = parentKey ? await nodes.byKey(parentKey) : undefined
84
- path = [...(parent ? pathIds(parent.path) : []), node.id]
85
- }
86
- let summary = detail ?? null
87
- if (change.withDescendants) {
88
- const [row] = await db.query<{ n: number }>(
89
- 'SELECT COUNT(*) AS n FROM node WHERE path LIKE ? AND node_object_type = ? AND trashed = ?',
90
- [`${node.path},%`, ObjectTypes.Document, db.dialect.boolValue(false)],
91
- )
92
- const under = Number(row?.n ?? 0)
93
- if (under > 0) summary = `and ${under} page${under === 1 ? '' : 's'} under it`
94
- }
95
- const actorId = actor?.key ? (await new UserRepository(db).byKey(actor.key))?.id : undefined
96
- const occurredAt = new Date()
97
- const runAfter = new Date(occurredAt.getTime() + (options.delayMs ?? DIGEST_DELAY_MS))
98
- const rows = []
99
- for (const actionId of change.actions) {
100
- const userIds = (await subscriptions.subscribersFor(actionId, path)).filter(
101
- (id) => id !== actorId,
102
- )
103
- if (userIds.length === 0) continue
104
- const keys = await db.query<{ key: string }>(
105
- `SELECT key FROM user_account WHERE id IN (${userIds.map(() => '?').join(', ')})`,
106
- userIds,
107
- )
108
- for (const { key } of keys)
109
- rows.push({
110
- recipientUserKey: String(key),
111
- actionId,
112
- nodeKey: node.key,
113
- nodeName: node.text ?? node.key,
114
- actorUserKey: actor?.key ?? null,
115
- actorName: actor?.name ?? null,
116
- detail: summary,
117
- occurredAt,
118
- runAfter,
119
- })
120
- }
121
- await outbox.enqueue(rows)
166
+ const facts = await factsFor(db, change, actor, detail)
167
+ if (facts) await enqueueFor(db, undefined, facts)
122
168
  } catch (error) {
123
- // Like the audit log: a notification that cannot be queued never costs the change.
124
169
  log.error('A content notification could not be queued: {error}', { error: String(error) })
125
170
  }
126
171
  },
@@ -11,7 +11,12 @@ import {
11
11
  type DocumentOperations,
12
12
  type EventSink,
13
13
  } from '@crombolo/content'
14
- import { currentSchemaState, type Db, RedirectRepository } from '@crombolo/data'
14
+ import {
15
+ appendCacheInstruction,
16
+ currentSchemaState,
17
+ type Db,
18
+ RedirectRepository,
19
+ } from '@crombolo/data'
15
20
  import { PublishedCache } from '@crombolo/render'
16
21
  import { createPublishedContentSource } from './adapters/documents.ts'
17
22
  import { createApprovals } from './approvals.ts'
@@ -46,7 +51,8 @@ export async function siteDocumentOperations(
46
51
  secretKey: config.secretKey,
47
52
  bundles: config.bundles,
48
53
  })
49
- const events = createContentEventSink({ db, webhooks, notifier })
54
+ // Recorded only: a running server's dispatcher sends what this records (story 171).
55
+ const events = createContentEventSink({ webhooks, notifier })
50
56
  const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
51
57
  let operations: DocumentOperations | undefined
52
58
  const approvals = createApprovals({
@@ -56,8 +62,11 @@ export async function siteDocumentOperations(
56
62
  backOfficeUrl: backOfficeUrl(config),
57
63
  notifier,
58
64
  publisher: {
59
- publish: (key, cultures, actor) =>
60
- (operations as DocumentOperations).publish(actor, key, { cultures }),
65
+ publish: (key, cultures, actor, approvedHead) =>
66
+ (operations as DocumentOperations).publish(actor, key, {
67
+ cultures,
68
+ expectedHead: approvedHead,
69
+ }),
61
70
  unpublish: (key, cultures, actor) =>
62
71
  (operations as DocumentOperations).unpublish(actor, key, cultures),
63
72
  },
@@ -71,6 +80,12 @@ export async function siteDocumentOperations(
71
80
  cache,
72
81
  redirects: new RedirectRepository(db),
73
82
  enabled: config.trackRedirects,
83
+ instruct: () =>
84
+ appendCacheInstruction(db, {
85
+ kind: 'content',
86
+ payload: { redirects: true },
87
+ by: `cli:${config.nodeId}`,
88
+ }),
74
89
  }),
75
90
  afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
76
91
  refusalReason: (error) =>
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export * from './bundles.ts'
25
25
  export * from './busy.ts'
26
26
  export * from './components.ts'
27
27
  export * from './config.ts'
28
+ export * from './content-dispatch.ts'
28
29
  export * from './content-events.ts'
29
30
  export * from './content-notifications.ts'
30
31
  export * from './content-operations.ts'