@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
|
@@ -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
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
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
|
|
77
|
-
if (
|
|
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
|
},
|
|
@@ -46,7 +46,8 @@ export async function siteDocumentOperations(
|
|
|
46
46
|
secretKey: config.secretKey,
|
|
47
47
|
bundles: config.bundles,
|
|
48
48
|
})
|
|
49
|
-
|
|
49
|
+
// Recorded only: a running server's dispatcher sends what this records (story 171).
|
|
50
|
+
const events = createContentEventSink({ webhooks, notifier })
|
|
50
51
|
const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
|
|
51
52
|
let operations: DocumentOperations | undefined
|
|
52
53
|
const approvals = createApprovals({
|
|
@@ -56,8 +57,11 @@ export async function siteDocumentOperations(
|
|
|
56
57
|
backOfficeUrl: backOfficeUrl(config),
|
|
57
58
|
notifier,
|
|
58
59
|
publisher: {
|
|
59
|
-
publish: (key, cultures, actor) =>
|
|
60
|
-
(operations as DocumentOperations).publish(actor, key, {
|
|
60
|
+
publish: (key, cultures, actor, approvedHead) =>
|
|
61
|
+
(operations as DocumentOperations).publish(actor, key, {
|
|
62
|
+
cultures,
|
|
63
|
+
expectedHead: approvedHead,
|
|
64
|
+
}),
|
|
61
65
|
unpublish: (key, cultures, actor) =>
|
|
62
66
|
(operations as DocumentOperations).unpublish(actor, key, cultures),
|
|
63
67
|
},
|
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'
|
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,7 @@ import {
|
|
|
39
39
|
permissionsForPath,
|
|
40
40
|
} from '@crombolo/core'
|
|
41
41
|
import {
|
|
42
|
+
ContentEventRepository,
|
|
42
43
|
ContentTypeRepository,
|
|
43
44
|
type Db,
|
|
44
45
|
DynamicRootRepository,
|
|
@@ -398,6 +399,8 @@ export interface DepsOptions {
|
|
|
398
399
|
db?: Db
|
|
399
400
|
/** Where document operations announce what they did; nothing hears them when absent. */
|
|
400
401
|
contentEvents?: EventSink
|
|
402
|
+
/** Told when something was put in the event outbox, so it goes out now (story 171). */
|
|
403
|
+
nudgeEvents?: () => void
|
|
401
404
|
/** The site's webhooks, shared with the delivery job and the event source. */
|
|
402
405
|
webhooks?: WebhookService
|
|
403
406
|
/** Required alongside `db` to serve documents, which invalidate the cache. */
|
|
@@ -528,15 +531,30 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
528
531
|
endSessions: async (userId) => {
|
|
529
532
|
await store.endAllSessionsForUser(userId)
|
|
530
533
|
},
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
534
|
+
// Through the outbox, as a page's own changes are (story 171).
|
|
535
|
+
onPagePermissionsChanged: async (principal, nodeKeys) => {
|
|
536
|
+
const notifier = options.notifier
|
|
537
|
+
const db = options.db
|
|
538
|
+
if (!notifier || !db) return
|
|
539
|
+
await db.transaction(async (tx) => {
|
|
540
|
+
for (const key of nodeKeys) {
|
|
541
|
+
const notification = await notifier.factsFor(
|
|
542
|
+
tx,
|
|
535
543
|
{ actions: ['Umb.Document.Permissions'], key, keyKind: 'document' },
|
|
536
544
|
{ key: principal.id, name: principal.name },
|
|
537
|
-
)
|
|
538
|
-
|
|
539
|
-
|
|
545
|
+
)
|
|
546
|
+
if (notification)
|
|
547
|
+
await new ContentEventRepository(tx).record({
|
|
548
|
+
kind: 'permissionsChanged',
|
|
549
|
+
entityType: 'Document',
|
|
550
|
+
entityKey: key,
|
|
551
|
+
facts: { v: 1, notification },
|
|
552
|
+
actor: { kind: 'user', name: principal.name, userKey: principal.id },
|
|
553
|
+
})
|
|
554
|
+
}
|
|
555
|
+
})
|
|
556
|
+
options.nudgeEvents?.()
|
|
557
|
+
},
|
|
540
558
|
})
|
|
541
559
|
// Story 032: the authenticator provider, offered only where secrets can be sealed.
|
|
542
560
|
const twoFactor = new TwoFactorService(options.db, {
|
|
@@ -561,6 +579,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
561
579
|
nodeId: options.schema?.nodeId,
|
|
562
580
|
valueIntake,
|
|
563
581
|
onChange: () => options.cache?.invalidate(),
|
|
582
|
+
webhooks: options.webhooks,
|
|
583
|
+
nudge: options.nudgeEvents,
|
|
564
584
|
})
|
|
565
585
|
deps.blueprints = createBlueprintPort(options.db, {
|
|
566
586
|
nodeState: options.schema?.nodeState,
|
|
@@ -682,8 +702,11 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
|
|
|
682
702
|
backOfficeUrl: backOfficeUrl(options.config),
|
|
683
703
|
notifier: options.notifier,
|
|
684
704
|
publisher: {
|
|
685
|
-
publish: (key, cultures, actor) =>
|
|
686
|
-
(operations as DocumentOperations).publish(actor, key, {
|
|
705
|
+
publish: (key, cultures, actor, approvedHead) =>
|
|
706
|
+
(operations as DocumentOperations).publish(actor, key, {
|
|
707
|
+
cultures,
|
|
708
|
+
expectedHead: approvedHead,
|
|
709
|
+
}),
|
|
687
710
|
unpublish: (key, cultures, actor) =>
|
|
688
711
|
(operations as DocumentOperations).unpublish(actor, key, cultures),
|
|
689
712
|
},
|
package/src/schema.ts
CHANGED
|
@@ -254,9 +254,16 @@ export interface CachePollerOptions {
|
|
|
254
254
|
* skipped. Where the database can notify, a write wakes it at once and the
|
|
255
255
|
* timer is only the fallback.
|
|
256
256
|
*/
|
|
257
|
+
/** How far behind its cursor the poller looks for a row that committed late. */
|
|
258
|
+
const CURSOR_WINDOW = 100
|
|
259
|
+
|
|
257
260
|
export class CacheInstructionPoller {
|
|
258
261
|
#options: CachePollerOptions
|
|
259
262
|
#cursor = 0
|
|
263
|
+
/** Where this node started: history before it was never this node's to apply. */
|
|
264
|
+
#origin = 0
|
|
265
|
+
/** Ids applied within the window behind the cursor. */
|
|
266
|
+
#seen = new Set<number>()
|
|
260
267
|
#timer: ReturnType<typeof setInterval> | undefined
|
|
261
268
|
#unlisten: (() => Promise<void>) | undefined
|
|
262
269
|
#running: Promise<number> | undefined
|
|
@@ -294,6 +301,7 @@ export class CacheInstructionPoller {
|
|
|
294
301
|
this.#bootLedgerId = await latestLedgerId(this.#options.db)
|
|
295
302
|
this.#paused = await readWritesPaused(this.#options.db)
|
|
296
303
|
this.#cursor = await latestCacheInstructionId(this.#options.db)
|
|
304
|
+
this.#origin = this.#cursor
|
|
297
305
|
if (intervalMs > 0) {
|
|
298
306
|
this.#timer = setInterval(() => void this.poll().catch(() => {}), intervalMs)
|
|
299
307
|
this.#timer.unref()
|
|
@@ -331,14 +339,20 @@ export class CacheInstructionPoller {
|
|
|
331
339
|
|
|
332
340
|
async #pollOnce(): Promise<number> {
|
|
333
341
|
const { db, nodeId, nodeState, onInstruction } = this.#options
|
|
334
|
-
|
|
342
|
+
// A row can commit after one with a higher id (Postgres hands ids out
|
|
343
|
+
// before commit), so a short window behind the cursor is read again and
|
|
344
|
+
// the ids already seen are skipped.
|
|
345
|
+
const instructions = await cacheInstructionsAfter(db, Math.max(0, this.#cursor - CURSOR_WINDOW))
|
|
335
346
|
let applied = 0
|
|
336
347
|
for (const instruction of instructions) {
|
|
348
|
+
if (this.#seen.has(instruction.id) || instruction.id <= this.#origin) continue
|
|
349
|
+
this.#seen.add(instruction.id)
|
|
337
350
|
this.#cursor = Math.max(this.#cursor, instruction.id)
|
|
338
351
|
if (instruction.createdBy === nodeId) continue
|
|
339
352
|
onInstruction(instruction.kind, instruction.payload)
|
|
340
353
|
applied += 1
|
|
341
354
|
}
|
|
355
|
+
for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
|
|
342
356
|
await touchServer(db, {
|
|
343
357
|
nodeId,
|
|
344
358
|
...nodeState,
|