@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.
- package/package.json +13 -13
- package/src/adapters/dictionary.ts +20 -7
- package/src/adapters/documents.ts +11 -0
- package/src/adapters/health.ts +96 -1
- package/src/adapters/media.ts +63 -23
- package/src/adapters/redirects.ts +17 -5
- package/src/approvals.ts +17 -3
- package/src/assistant.ts +7 -2
- package/src/bundle-install.ts +22 -5
- 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 +19 -4
- package/src/index.ts +1 -0
- package/src/jobs.ts +104 -75
- package/src/ports.ts +43 -10
- package/src/redirects.ts +10 -1
- package/src/schema.ts +66 -2
- package/src/server.ts +52 -8
- package/src/settings.ts +8 -0
- package/src/url-settings.ts +12 -1
- package/src/webhooks.ts +36 -42
package/src/jobs.ts
CHANGED
|
@@ -12,18 +12,20 @@ import { type DocumentOperations, systemActor } from '@crombolo/content'
|
|
|
12
12
|
import type { NodeSchemaState } from '@crombolo/data'
|
|
13
13
|
import {
|
|
14
14
|
AuditLog,
|
|
15
|
+
ContentEventRepository,
|
|
15
16
|
type Db,
|
|
16
17
|
DocumentRepository,
|
|
17
|
-
|
|
18
|
+
pruneCacheInstructions,
|
|
18
19
|
SearchIndex,
|
|
20
|
+
WebhookDeliveryRepository,
|
|
19
21
|
} from '@crombolo/data'
|
|
20
22
|
import type { PublishedCache } from '@crombolo/render'
|
|
21
|
-
import { auditRetainedSince
|
|
23
|
+
import { auditRetainedSince } from './adapters/audit.ts'
|
|
22
24
|
import type { Approvals } from './approvals.ts'
|
|
25
|
+
import type { ContentDispatcher } from './content-dispatch.ts'
|
|
23
26
|
import type {
|
|
24
27
|
ContentNotificationRunner,
|
|
25
28
|
ContentNotificationRunReport,
|
|
26
|
-
ContentNotifier,
|
|
27
29
|
} from './content-notifications.ts'
|
|
28
30
|
import type { WorkflowRunner, WorkflowRunReport } from './form-workflows.ts'
|
|
29
31
|
import { logger } from './logging.ts'
|
|
@@ -51,9 +53,14 @@ export interface JobsOptions {
|
|
|
51
53
|
*/
|
|
52
54
|
formWorkflows?: WorkflowRunner
|
|
53
55
|
formWorkflowsMs?: number
|
|
54
|
-
/**
|
|
55
|
-
webhooks?: Pick<WebhookService, '
|
|
56
|
+
/** Drains the delivery queue. */
|
|
57
|
+
webhooks?: Pick<WebhookService, 'runDue'>
|
|
56
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
|
|
57
64
|
/** How often the search indexer looks for queued items; a write here also starts it at once. */
|
|
58
65
|
searchIndexingMs?: number
|
|
59
66
|
/** Days the audit log keeps an entry; 0 or absent keeps them forever. */
|
|
@@ -61,17 +68,18 @@ export interface JobsOptions {
|
|
|
61
68
|
/** Content notifications (story 045): queued by changes, sent here. Absent without e-mail. */
|
|
62
69
|
contentNotifications?: ContentNotificationRunner
|
|
63
70
|
contentNotificationsMs?: number
|
|
64
|
-
/** Queues the notifications scheduled publishing makes, as an editor's publish does. */
|
|
65
|
-
notifier?: ContentNotifier
|
|
66
71
|
/** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
|
|
67
72
|
approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
|
|
68
73
|
/**
|
|
69
74
|
* Publishes what a schedule says, as the site (story 170): recorded, tracked and
|
|
70
|
-
* announced as an editor's publish is.
|
|
75
|
+
* announced as an editor's publish is.
|
|
71
76
|
*/
|
|
72
|
-
operations
|
|
77
|
+
operations: DocumentOperations
|
|
73
78
|
}
|
|
74
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
|
+
|
|
75
83
|
export interface ScheduledRun {
|
|
76
84
|
published: string[]
|
|
77
85
|
unpublished: string[]
|
|
@@ -84,6 +92,10 @@ export interface BackgroundJobs {
|
|
|
84
92
|
runFormWorkflows(now?: Date): Promise<WorkflowRunReport>
|
|
85
93
|
/** Delivers the webhook and bundle events that are due. */
|
|
86
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>
|
|
87
99
|
/** Sends the content notifications that are due (story 045). */
|
|
88
100
|
runContentNotifications(now?: Date): Promise<ContentNotificationRunReport>
|
|
89
101
|
/** Indexes every queued item, and returns how many. docs/search.md. */
|
|
@@ -106,7 +118,6 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
106
118
|
nodeId: options.nodeId,
|
|
107
119
|
})
|
|
108
120
|
const timers: Array<ReturnType<typeof setInterval>> = []
|
|
109
|
-
let running = false
|
|
110
121
|
const search = new SearchIndex(options.db)
|
|
111
122
|
let indexing: Promise<number> | undefined
|
|
112
123
|
let kicked: ReturnType<typeof setTimeout> | undefined
|
|
@@ -117,66 +128,61 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
117
128
|
if (!(await documents.claimSchedule(due.id))) continue
|
|
118
129
|
const cultures = due.culture ? [due.culture] : null
|
|
119
130
|
const release = due.action === 'Release'
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
result.ok ? { ok: true } : { ok: false, reason: result.reason },
|
|
134
|
-
)
|
|
135
|
-
continue
|
|
136
|
-
}
|
|
137
|
-
try {
|
|
138
|
-
const changed = release
|
|
139
|
-
? await documents.publish(due.key, cultures)
|
|
140
|
-
: await documents.unpublish(due.key, cultures)
|
|
141
|
-
;(release ? run.published : run.unpublished).push(due.key)
|
|
142
|
-
await recordAudit(options.db, {
|
|
143
|
-
category: 'content',
|
|
144
|
-
action: release ? 'Publish' : 'Unpublish',
|
|
145
|
-
source: 'job',
|
|
146
|
-
entityType: 'Document',
|
|
147
|
-
entityKey: due.key,
|
|
148
|
-
entityName: changed?.variants[0]?.name ?? null,
|
|
149
|
-
detail: `Scheduled${due.culture ? ` (${due.culture})` : ''}`,
|
|
150
|
-
})
|
|
151
|
-
options.onDocumentChanged?.(due.key)
|
|
152
|
-
await options.approvals?.scheduleFired(due.key, due.culture, due.action, { ok: true })
|
|
153
|
-
} catch (error) {
|
|
154
|
-
if (!(error instanceof PublishBlockedError)) throw error
|
|
155
|
-
run.failed.push({ key: due.key, reason: error.message })
|
|
156
|
-
await options.approvals?.scheduleFired(due.key, due.culture, due.action, {
|
|
157
|
-
ok: false,
|
|
158
|
-
reason: error.message,
|
|
159
|
-
})
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
await options.approvals?.sweepScheduled(now.getTime())
|
|
163
|
-
// The operations announced and refreshed what they did themselves.
|
|
164
|
-
if (options.operations) return run
|
|
165
|
-
if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
|
|
166
|
-
for (const key of run.published) {
|
|
167
|
-
await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
|
|
168
|
-
await options.notifier?.raise(
|
|
169
|
-
{ actions: ['Umb.Document.Publish'], key, keyKind: 'document' },
|
|
170
|
-
{ key: null, name: 'The schedule' },
|
|
171
|
-
'scheduled',
|
|
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 },
|
|
172
144
|
)
|
|
173
145
|
}
|
|
174
|
-
|
|
175
|
-
|
|
146
|
+
await options.approvals?.sweepScheduled(now.getTime())
|
|
147
|
+
// The operations recorded, announced and refreshed what they did themselves.
|
|
176
148
|
return run
|
|
177
149
|
}
|
|
178
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
|
+
|
|
179
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)
|
|
180
186
|
const runner = options.contentNotifications
|
|
181
187
|
return runner ? runner.runDue(now) : { claimed: 0, sent: 0, skipped: 0, retrying: 0, failed: 0 }
|
|
182
188
|
}
|
|
@@ -190,8 +196,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
190
196
|
return documents.cleanupVersions(now, options.versionCleanup)
|
|
191
197
|
}
|
|
192
198
|
|
|
193
|
-
|
|
194
|
-
|
|
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
|
+
)
|
|
195
213
|
}
|
|
196
214
|
|
|
197
215
|
async function runFormWorkflows(now = new Date()): Promise<WorkflowRunReport> {
|
|
@@ -219,15 +237,20 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
219
237
|
logger('jobs').error('Search indexing failed', { error })
|
|
220
238
|
})
|
|
221
239
|
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
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
|
+
}
|
|
231
254
|
}
|
|
232
255
|
}
|
|
233
256
|
|
|
@@ -243,6 +266,8 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
243
266
|
runAuditRetention,
|
|
244
267
|
runFormWorkflows,
|
|
245
268
|
runWebhooks,
|
|
269
|
+
runEvents,
|
|
270
|
+
runQueueUpkeep,
|
|
246
271
|
runContentNotifications,
|
|
247
272
|
runSearchIndexing,
|
|
248
273
|
kickSearchIndexing() {
|
|
@@ -264,6 +289,10 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
|
|
|
264
289
|
if (options.formWorkflows) every(options.formWorkflowsMs ?? 15_000, runFormWorkflows)
|
|
265
290
|
// As often, for the same reason: a receiver that is waiting notices a minute.
|
|
266
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)
|
|
267
296
|
// A digest waits a minute anyway; this is how soon after that it goes.
|
|
268
297
|
const notifications = options.contentNotifications
|
|
269
298
|
if (notifications) {
|
package/src/ports.ts
CHANGED
|
@@ -39,6 +39,8 @@ import {
|
|
|
39
39
|
permissionsForPath,
|
|
40
40
|
} from '@crombolo/core'
|
|
41
41
|
import {
|
|
42
|
+
appendCacheInstruction,
|
|
43
|
+
ContentEventRepository,
|
|
42
44
|
ContentTypeRepository,
|
|
43
45
|
type Db,
|
|
44
46
|
DynamicRootRepository,
|
|
@@ -398,6 +400,8 @@ export interface DepsOptions {
|
|
|
398
400
|
db?: Db
|
|
399
401
|
/** Where document operations announce what they did; nothing hears them when absent. */
|
|
400
402
|
contentEvents?: EventSink
|
|
403
|
+
/** Told when something was put in the event outbox, so it goes out now (story 171). */
|
|
404
|
+
nudgeEvents?: () => void
|
|
401
405
|
/** The site's webhooks, shared with the delivery job and the event source. */
|
|
402
406
|
webhooks?: WebhookService
|
|
403
407
|
/** Required alongside `db` to serve documents, which invalidate the cache. */
|
|
@@ -528,15 +532,30 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
528
532
|
endSessions: async (userId) => {
|
|
529
533
|
await store.endAllSessionsForUser(userId)
|
|
530
534
|
},
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
+
// Through the outbox, as a page's own changes are (story 171).
|
|
536
|
+
onPagePermissionsChanged: async (principal, nodeKeys) => {
|
|
537
|
+
const notifier = options.notifier
|
|
538
|
+
const db = options.db
|
|
539
|
+
if (!notifier || !db) return
|
|
540
|
+
await db.transaction(async (tx) => {
|
|
541
|
+
for (const key of nodeKeys) {
|
|
542
|
+
const notification = await notifier.factsFor(
|
|
543
|
+
tx,
|
|
535
544
|
{ actions: ['Umb.Document.Permissions'], key, keyKind: 'document' },
|
|
536
545
|
{ key: principal.id, name: principal.name },
|
|
537
|
-
)
|
|
538
|
-
|
|
539
|
-
|
|
546
|
+
)
|
|
547
|
+
if (notification)
|
|
548
|
+
await new ContentEventRepository(tx).record({
|
|
549
|
+
kind: 'permissionsChanged',
|
|
550
|
+
entityType: 'Document',
|
|
551
|
+
entityKey: key,
|
|
552
|
+
facts: { v: 1, notification },
|
|
553
|
+
actor: { kind: 'user', name: principal.name, userKey: principal.id },
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
})
|
|
557
|
+
options.nudgeEvents?.()
|
|
558
|
+
},
|
|
540
559
|
})
|
|
541
560
|
// Story 032: the authenticator provider, offered only where secrets can be sealed.
|
|
542
561
|
const twoFactor = new TwoFactorService(options.db, {
|
|
@@ -561,6 +580,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
561
580
|
nodeId: options.schema?.nodeId,
|
|
562
581
|
valueIntake,
|
|
563
582
|
onChange: () => options.cache?.invalidate(),
|
|
583
|
+
webhooks: options.webhooks,
|
|
584
|
+
nudge: options.nudgeEvents,
|
|
564
585
|
})
|
|
565
586
|
deps.blueprints = createBlueprintPort(options.db, {
|
|
566
587
|
nodeState: options.schema?.nodeState,
|
|
@@ -618,6 +639,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
618
639
|
deps.redirects = createRedirectPort(options.db, options.cache, {
|
|
619
640
|
isTracking: options.config.trackRedirects,
|
|
620
641
|
onChange: () => options.cache?.invalidate(),
|
|
642
|
+
nodeId: options.schema?.nodeId,
|
|
621
643
|
})
|
|
622
644
|
deps.packages = createPackagePort(options.db, {
|
|
623
645
|
siteName: options.config.siteName,
|
|
@@ -648,12 +670,20 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
648
670
|
}
|
|
649
671
|
deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
|
|
650
672
|
onChange: () => options.cache?.invalidate(),
|
|
673
|
+
nodeId: options.schema?.nodeId,
|
|
651
674
|
})
|
|
675
|
+
const db = options.db
|
|
652
676
|
const tracker = options.cache
|
|
653
677
|
? createRedirectTracker({
|
|
654
678
|
cache: options.cache,
|
|
655
|
-
redirects: new RedirectRepository(
|
|
679
|
+
redirects: new RedirectRepository(db),
|
|
656
680
|
enabled: options.config.trackRedirects,
|
|
681
|
+
instruct: () =>
|
|
682
|
+
appendCacheInstruction(db, {
|
|
683
|
+
kind: 'content',
|
|
684
|
+
payload: { redirects: true },
|
|
685
|
+
by: options.schema?.nodeId,
|
|
686
|
+
}),
|
|
657
687
|
})
|
|
658
688
|
: undefined
|
|
659
689
|
if (options.cache)
|
|
@@ -682,8 +712,11 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
682
712
|
backOfficeUrl: backOfficeUrl(options.config),
|
|
683
713
|
notifier: options.notifier,
|
|
684
714
|
publisher: {
|
|
685
|
-
publish: (key, cultures, actor) =>
|
|
686
|
-
(operations as DocumentOperations).publish(actor, key, {
|
|
715
|
+
publish: (key, cultures, actor, approvedHead) =>
|
|
716
|
+
(operations as DocumentOperations).publish(actor, key, {
|
|
717
|
+
cultures,
|
|
718
|
+
expectedHead: approvedHead,
|
|
719
|
+
}),
|
|
687
720
|
unpublish: (key, cultures, actor) =>
|
|
688
721
|
(operations as DocumentOperations).unpublish(actor, key, cultures),
|
|
689
722
|
},
|
package/src/redirects.ts
CHANGED
|
@@ -39,6 +39,12 @@ export function createRedirectTracker(options: {
|
|
|
39
39
|
cache: PublishedCache
|
|
40
40
|
redirects: RedirectRepository
|
|
41
41
|
enabled: boolean
|
|
42
|
+
/**
|
|
43
|
+
* Tells every node a redirect was written (story 174). The routes it compares
|
|
44
|
+
* are read from the published cache once the change has committed, so this
|
|
45
|
+
* moves the checkpoint just after the change rather than inside it.
|
|
46
|
+
*/
|
|
47
|
+
instruct?: () => Promise<unknown>
|
|
42
48
|
}): RedirectTracker {
|
|
43
49
|
if (!options.enabled) return NO_REDIRECT_TRACKING
|
|
44
50
|
const { cache, redirects } = options
|
|
@@ -99,7 +105,10 @@ export function createRedirectTracker(options: {
|
|
|
99
105
|
// The rules are part of the cache's snapshot, and reading the new routes
|
|
100
106
|
// above has just rebuilt it — so without this the redirect just written
|
|
101
107
|
// would not answer until something else dropped the cache.
|
|
102
|
-
if (wrote)
|
|
108
|
+
if (wrote) {
|
|
109
|
+
await options.instruct?.()
|
|
110
|
+
cache.invalidate()
|
|
111
|
+
}
|
|
103
112
|
},
|
|
104
113
|
}
|
|
105
114
|
}
|
package/src/schema.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
type Finding,
|
|
20
20
|
Locks,
|
|
21
21
|
latestCacheInstructionId,
|
|
22
|
+
latestCheckpoint,
|
|
22
23
|
latestLedgerId,
|
|
23
24
|
type NodeSchemaState,
|
|
24
25
|
readWritesPaused,
|
|
@@ -247,16 +248,36 @@ export interface CachePollerOptions {
|
|
|
247
248
|
role?: string
|
|
248
249
|
/** Called for instructions other nodes appended. */
|
|
249
250
|
onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
|
|
251
|
+
/**
|
|
252
|
+
* The published cache's freshness (story 174). With it, content and schema
|
|
253
|
+
* instructions only wake the poll: the node compares the latest committed
|
|
254
|
+
* checkpoint with the one it serves, and is told it is behind. Being ordered
|
|
255
|
+
* by commit, the checkpoint cannot skip a change that committed late.
|
|
256
|
+
*/
|
|
257
|
+
content?: {
|
|
258
|
+
served(): { checkpoint: number | undefined; builtAt: Date } | undefined
|
|
259
|
+
behind(latest: number): void
|
|
260
|
+
}
|
|
250
261
|
}
|
|
251
262
|
|
|
263
|
+
/** A rebuild asked for and not yet served is asked for again after this long. */
|
|
264
|
+
const REASK_AFTER_MS = 30_000
|
|
265
|
+
|
|
252
266
|
/**
|
|
253
267
|
* Polls `cache_instruction` from where this node came in; own instructions are
|
|
254
268
|
* skipped. Where the database can notify, a write wakes it at once and the
|
|
255
269
|
* timer is only the fallback.
|
|
256
270
|
*/
|
|
271
|
+
/** How far behind its cursor the poller looks for a views instruction that committed late. */
|
|
272
|
+
const CURSOR_WINDOW = 100
|
|
273
|
+
|
|
257
274
|
export class CacheInstructionPoller {
|
|
258
275
|
#options: CachePollerOptions
|
|
259
276
|
#cursor = 0
|
|
277
|
+
/** Where this node started: history before it was never this node's to apply. */
|
|
278
|
+
#origin = 0
|
|
279
|
+
/** Ids applied within the window behind the cursor. */
|
|
280
|
+
#seen = new Set<number>()
|
|
260
281
|
#timer: ReturnType<typeof setInterval> | undefined
|
|
261
282
|
#unlisten: (() => Promise<void>) | undefined
|
|
262
283
|
#running: Promise<number> | undefined
|
|
@@ -265,6 +286,14 @@ export class CacheInstructionPoller {
|
|
|
265
286
|
#bootLedgerId = 0
|
|
266
287
|
#readsUnsafe = false
|
|
267
288
|
#paused: WritesPaused | undefined
|
|
289
|
+
/** The checkpoint this node last asked its cache to catch up to, and when. */
|
|
290
|
+
#asked: { checkpoint: number; at: number } | undefined
|
|
291
|
+
#latest: number | undefined
|
|
292
|
+
|
|
293
|
+
/** The latest committed content checkpoint, as of the last poll. */
|
|
294
|
+
get latestCheckpoint(): number | undefined {
|
|
295
|
+
return this.#latest
|
|
296
|
+
}
|
|
268
297
|
|
|
269
298
|
/** True once an upgrade has moved the database past this node: reads only. */
|
|
270
299
|
get behind(): boolean {
|
|
@@ -294,6 +323,7 @@ export class CacheInstructionPoller {
|
|
|
294
323
|
this.#bootLedgerId = await latestLedgerId(this.#options.db)
|
|
295
324
|
this.#paused = await readWritesPaused(this.#options.db)
|
|
296
325
|
this.#cursor = await latestCacheInstructionId(this.#options.db)
|
|
326
|
+
this.#origin = this.#cursor
|
|
297
327
|
if (intervalMs > 0) {
|
|
298
328
|
this.#timer = setInterval(() => void this.poll().catch(() => {}), intervalMs)
|
|
299
329
|
this.#timer.unref()
|
|
@@ -331,19 +361,32 @@ export class CacheInstructionPoller {
|
|
|
331
361
|
|
|
332
362
|
async #pollOnce(): Promise<number> {
|
|
333
363
|
const { db, nodeId, nodeState, onInstruction } = this.#options
|
|
334
|
-
|
|
364
|
+
// A row can commit after one with a higher id (Postgres hands ids out
|
|
365
|
+
// before commit), so a short window behind the cursor is read again and
|
|
366
|
+
// the ids already seen are skipped.
|
|
367
|
+
const instructions = await cacheInstructionsAfter(db, Math.max(0, this.#cursor - CURSOR_WINDOW))
|
|
335
368
|
let applied = 0
|
|
336
369
|
for (const instruction of instructions) {
|
|
370
|
+
if (this.#seen.has(instruction.id) || instruction.id <= this.#origin) continue
|
|
371
|
+
this.#seen.add(instruction.id)
|
|
337
372
|
this.#cursor = Math.max(this.#cursor, instruction.id)
|
|
338
373
|
if (instruction.createdBy === nodeId) continue
|
|
339
|
-
onInstruction(instruction.kind, instruction.payload)
|
|
340
374
|
applied += 1
|
|
375
|
+
// The checkpoint below decides; an instruction about content only woke us.
|
|
376
|
+
if (this.#options.content && instruction.checkpoint !== null) continue
|
|
377
|
+
onInstruction(instruction.kind, instruction.payload)
|
|
341
378
|
}
|
|
379
|
+
for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
|
|
380
|
+
const served = await this.#catchUp()
|
|
342
381
|
await touchServer(db, {
|
|
343
382
|
nodeId,
|
|
344
383
|
...nodeState,
|
|
345
384
|
role: this.#options.role,
|
|
346
385
|
cromboloVersion: VERSION,
|
|
386
|
+
served:
|
|
387
|
+
served?.checkpoint === undefined
|
|
388
|
+
? undefined
|
|
389
|
+
: { checkpoint: served.checkpoint, at: served.builtAt },
|
|
347
390
|
})
|
|
348
391
|
const current = await currentSchemaState(db)
|
|
349
392
|
const behind = compareStates(nodeState, current) < 0
|
|
@@ -357,6 +400,27 @@ export class CacheInstructionPoller {
|
|
|
357
400
|
return applied
|
|
358
401
|
}
|
|
359
402
|
|
|
403
|
+
/**
|
|
404
|
+
* Tells the cache it is behind when the latest committed checkpoint is past
|
|
405
|
+
* the one it serves. A cache that has not been built yet is left to build on
|
|
406
|
+
* its first read. A request not served within a while is made again, so a
|
|
407
|
+
* failed rebuild is retried.
|
|
408
|
+
*/
|
|
409
|
+
async #catchUp() {
|
|
410
|
+
const content = this.#options.content
|
|
411
|
+
if (!content) return undefined
|
|
412
|
+
const latest = await latestCheckpoint(this.#options.db)
|
|
413
|
+
this.#latest = latest
|
|
414
|
+
const served = content.served()
|
|
415
|
+
if (served?.checkpoint === undefined || served.checkpoint >= latest) return served
|
|
416
|
+
const asked = this.#asked
|
|
417
|
+
if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
|
|
418
|
+
this.#asked = { checkpoint: latest, at: Date.now() }
|
|
419
|
+
content.behind(latest)
|
|
420
|
+
}
|
|
421
|
+
return served
|
|
422
|
+
}
|
|
423
|
+
|
|
360
424
|
stop(): void {
|
|
361
425
|
if (this.#timer) clearInterval(this.#timer)
|
|
362
426
|
this.#timer = undefined
|
package/src/server.ts
CHANGED
|
@@ -57,6 +57,7 @@ import {
|
|
|
57
57
|
resolveStaticFile,
|
|
58
58
|
serveStaticFile,
|
|
59
59
|
} from '@crombolo/backoffice-host'
|
|
60
|
+
import type { DocumentOperations } from '@crombolo/content'
|
|
60
61
|
import { servedContract } from '@crombolo/contracts'
|
|
61
62
|
import {
|
|
62
63
|
CHOICE_SOURCE_KINDS,
|
|
@@ -131,6 +132,7 @@ import {
|
|
|
131
132
|
type ServerRole,
|
|
132
133
|
VERSION,
|
|
133
134
|
} from './config.ts'
|
|
135
|
+
import { createContentDispatcher } from './content-dispatch.ts'
|
|
134
136
|
import { createContentEventSink } from './content-events.ts'
|
|
135
137
|
import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
|
|
136
138
|
import { attachDatabase, bootstrapDatabase } from './database.ts'
|
|
@@ -569,6 +571,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
569
571
|
cache,
|
|
570
572
|
redirects: new RedirectRepository(db),
|
|
571
573
|
enabled: config.trackRedirects,
|
|
574
|
+
instruct: () =>
|
|
575
|
+
appendCacheInstruction(db, {
|
|
576
|
+
kind: 'content',
|
|
577
|
+
payload: { redirects: true },
|
|
578
|
+
by: schema.nodeId,
|
|
579
|
+
}),
|
|
572
580
|
}),
|
|
573
581
|
}
|
|
574
582
|
const afterSync = async (report: SyncReport | undefined) => {
|
|
@@ -708,6 +716,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
708
716
|
// of the bytes this node reads, so a superseded one is harmless.
|
|
709
717
|
snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
|
|
710
718
|
},
|
|
719
|
+
// Behind the latest committed checkpoint: rebuilt now rather than on the next
|
|
720
|
+
// read, so an idle node catches up and says so (story 174).
|
|
721
|
+
content: {
|
|
722
|
+
served: () => cache.served(),
|
|
723
|
+
behind: () => {
|
|
724
|
+
cache.invalidate()
|
|
725
|
+
void cache
|
|
726
|
+
.snapshot()
|
|
727
|
+
.catch((error: unknown) =>
|
|
728
|
+
renderLog.error('Could not rebuild the published cache: {error}', { error }),
|
|
729
|
+
)
|
|
730
|
+
},
|
|
731
|
+
},
|
|
711
732
|
})
|
|
712
733
|
await poller.start(config.development ? 2_000 : 5_000)
|
|
713
734
|
const watcher =
|
|
@@ -945,8 +966,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
945
966
|
if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
|
|
946
967
|
previewHub.broadcast('refreshed', [event.key])
|
|
947
968
|
}
|
|
948
|
-
//
|
|
949
|
-
const
|
|
969
|
+
// Recorded content events become deliveries and notifications here (story 171).
|
|
970
|
+
const dispatcher = createContentDispatcher({ db, webhooks, notifier })
|
|
971
|
+
// Document writes record and announce themselves through this, from every entry point.
|
|
972
|
+
const contentEvents = createContentEventSink({
|
|
973
|
+
webhooks,
|
|
974
|
+
notifier,
|
|
975
|
+
live: announce,
|
|
976
|
+
nudge: () => dispatcher.nudge(),
|
|
977
|
+
})
|
|
950
978
|
|
|
951
979
|
const managementDeps = createDeps({
|
|
952
980
|
config,
|
|
@@ -955,6 +983,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
955
983
|
db,
|
|
956
984
|
webhooks,
|
|
957
985
|
contentEvents,
|
|
986
|
+
nudgeEvents: () => dispatcher.nudge(),
|
|
958
987
|
cache,
|
|
959
988
|
previewInApp: appPreview,
|
|
960
989
|
schema,
|
|
@@ -994,10 +1023,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
994
1023
|
onNotImplemented: config.development
|
|
995
1024
|
? (operation, request) => notImplemented.record(operation, request)
|
|
996
1025
|
: undefined,
|
|
997
|
-
// Queued after the response, so a slow receiver never holds an editor up.
|
|
998
|
-
onWebhookEvent: (event) => {
|
|
999
|
-
void webhooks.raise(event)
|
|
1000
|
-
},
|
|
1001
1026
|
// After the response too: the subscribers are worked out and queued, and sent a minute later.
|
|
1002
1027
|
onContentChange: (change, principal) => {
|
|
1003
1028
|
void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
|
|
@@ -1008,6 +1033,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1008
1033
|
// Fixed by the contract and the client's SDK, wherever the editor is mounted.
|
|
1009
1034
|
const apiPrefix = MANAGEMENT_API_PREFIX
|
|
1010
1035
|
|
|
1036
|
+
/**
|
|
1037
|
+
* Which committed changes this node's published cache holds (story 174):
|
|
1038
|
+
* numbers and times only. `latest` is as of the last poll; `behind` is null
|
|
1039
|
+
* until both are known.
|
|
1040
|
+
*/
|
|
1041
|
+
const contentFreshness = () => {
|
|
1042
|
+
const served = cache.served()
|
|
1043
|
+
const latest = poller.latestCheckpoint
|
|
1044
|
+
const checkpoint = served?.checkpoint
|
|
1045
|
+
return {
|
|
1046
|
+
checkpoint: checkpoint ?? null,
|
|
1047
|
+
latest: latest ?? null,
|
|
1048
|
+
behind: checkpoint === undefined || latest === undefined ? null : checkpoint < latest,
|
|
1049
|
+
builtAt: served?.builtAt.toISOString() ?? null,
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1011
1053
|
const health = () => {
|
|
1012
1054
|
const paused = poller.paused
|
|
1013
1055
|
const readOnly = schema.compatibilityMode || poller.behind || paused !== undefined
|
|
@@ -1031,6 +1073,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1031
1073
|
revision: schema.nodeState.revision,
|
|
1032
1074
|
nodeId: schema.nodeId,
|
|
1033
1075
|
role: config.role,
|
|
1076
|
+
content: contentFreshness(),
|
|
1034
1077
|
components: snapshots.status(),
|
|
1035
1078
|
}
|
|
1036
1079
|
}
|
|
@@ -1041,7 +1084,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1041
1084
|
db,
|
|
1042
1085
|
cache,
|
|
1043
1086
|
approvals: managementDeps.approvals as Approvals | undefined,
|
|
1044
|
-
operations: managementDeps.documentOperations,
|
|
1087
|
+
operations: managementDeps.documentOperations as DocumentOperations,
|
|
1088
|
+
dispatcher,
|
|
1089
|
+
eventRetentionDays: config.eventRetentionDays,
|
|
1045
1090
|
nodeState: schema.nodeState,
|
|
1046
1091
|
nodeId: schema.nodeId,
|
|
1047
1092
|
versionCleanup: config.versionCleanup,
|
|
@@ -1066,7 +1111,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
|
|
|
1066
1111
|
url: config.applicationUrl,
|
|
1067
1112
|
}),
|
|
1068
1113
|
}),
|
|
1069
|
-
notifier,
|
|
1070
1114
|
contentNotifications: email
|
|
1071
1115
|
? createContentNotificationRunner({
|
|
1072
1116
|
db,
|