@crombolo/server 0.23.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 +13 -13
- package/src/adapters/health.ts +54 -0
- package/src/adapters/media.ts +63 -23
- package/src/approvals.ts +17 -3
- package/src/assistant.ts +7 -2
- package/src/config.ts +11 -1
- package/src/content-dispatch.ts +87 -0
- package/src/content-events.ts +49 -36
- package/src/content-notifications.ts +101 -56
- package/src/content-operations.ts +7 -3
- package/src/index.ts +1 -0
- package/src/jobs.ts +104 -75
- package/src/ports.ts +32 -9
- package/src/schema.ts +15 -1
- package/src/server.ts +15 -8
- package/src/settings.ts +8 -0
- package/src/webhooks.ts +36 -42
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crombolo/server",
|
|
3
|
-
"version": "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,18 +30,18 @@
|
|
|
30
30
|
"access": "public"
|
|
31
31
|
},
|
|
32
32
|
"dependencies": {
|
|
33
|
-
"@crombolo/api-delivery": "0.
|
|
34
|
-
"@crombolo/api-management": "0.
|
|
35
|
-
"@crombolo/assistant": "0.
|
|
36
|
-
"@crombolo/auth": "0.
|
|
37
|
-
"@crombolo/backoffice-host": "0.
|
|
38
|
-
"@crombolo/content": "0.
|
|
39
|
-
"@crombolo/contracts": "0.
|
|
40
|
-
"@crombolo/core": "0.
|
|
41
|
-
"@crombolo/data": "0.
|
|
42
|
-
"@crombolo/render": "0.
|
|
43
|
-
"@crombolo/schema": "0.
|
|
44
|
-
"@crombolo/transfer": "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",
|
|
45
45
|
"@logtape/logtape": "^2.3.8"
|
|
46
46
|
}
|
|
47
47
|
}
|
package/src/adapters/health.ts
CHANGED
|
@@ -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 {
|
package/src/adapters/media.ts
CHANGED
|
@@ -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
|
|
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
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
|
149
|
-
|
|
150
|
-
componentKey: null,
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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
|
|
164
|
-
|
|
165
|
-
key,
|
|
166
|
-
|
|
167
|
-
|
|
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
|
@@ -51,7 +51,9 @@ export interface ApprovalPublisher {
|
|
|
51
51
|
key: string,
|
|
52
52
|
cultures: string[] | null,
|
|
53
53
|
actor: Actor,
|
|
54
|
-
|
|
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 }>
|
|
55
57
|
unpublish(
|
|
56
58
|
key: string,
|
|
57
59
|
cultures: string[] | null,
|
|
@@ -594,9 +596,21 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
|
|
|
594
596
|
})
|
|
595
597
|
const result =
|
|
596
598
|
request.action === 'publish'
|
|
597
|
-
? await options.publisher.publish(
|
|
599
|
+
? await options.publisher.publish(
|
|
600
|
+
request.nodeKey,
|
|
601
|
+
cultures,
|
|
602
|
+
actor,
|
|
603
|
+
request.eventId ?? undefined,
|
|
604
|
+
)
|
|
598
605
|
: await options.publisher.unpublish(request.nodeKey, cultures, actor)
|
|
599
|
-
if (!result.ok)
|
|
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
|
+
)
|
|
600
614
|
await repo.record(request.id, {
|
|
601
615
|
kind: request.action === 'publish' ? 'published' : 'unpublished',
|
|
602
616
|
userKey: principal?.id ?? null,
|
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 {
|
|
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.
|
|
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
|
+
}
|
package/src/content-events.ts
CHANGED
|
@@ -1,76 +1,89 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Where document operations
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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
|
-
|
|
27
|
-
|
|
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
|
|
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
|
|
54
|
+
? await audit.describe(entry.entityType, entry.entityKey)
|
|
51
55
|
: undefined
|
|
52
|
-
await
|
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
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
|
}
|