@crombolo/server 0.37.0 → 0.39.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 +15 -14
- package/src/access.ts +29 -27
- package/src/adapters/audit.ts +1 -1
- package/src/adapters/blueprints.ts +22 -13
- package/src/adapters/content.ts +1 -1
- package/src/adapters/dictionary.ts +1 -1
- package/src/adapters/documents.ts +17 -10
- package/src/adapters/elements.ts +47 -37
- package/src/adapters/file-system.ts +1 -1
- package/src/adapters/health.ts +10 -5
- package/src/adapters/media.ts +12 -8
- package/src/adapters/member-groups.ts +8 -6
- package/src/adapters/members.ts +6 -4
- package/src/adapters/public-access.ts +7 -5
- package/src/adapters/redirects.ts +1 -1
- package/src/adapters/references.ts +1 -1
- package/src/adapters/relations.ts +1 -1
- package/src/adapters/schema-files.ts +33 -1
- package/src/adapters/search-index.ts +1 -1
- package/src/adapters/template-query.ts +1 -1
- package/src/adapters/users.ts +13 -13
- package/src/adapters/webhooks.ts +1 -1
- package/src/anonymise-rules.ts +83 -0
- package/src/approvals-api.ts +1 -1
- package/src/approvals.ts +75 -38
- package/src/back-office-url.ts +20 -0
- package/src/backup.ts +26 -2
- package/src/bundle-code.ts +1 -1
- package/src/bundle-grants.ts +250 -0
- package/src/bundle-install.ts +13 -2
- package/src/bundle-media.ts +12 -11
- package/src/bundles.ts +131 -43
- package/src/component-snippets.ts +1 -1
- package/src/components.ts +6 -1
- package/src/config.ts +61 -3
- package/src/content-notifications.ts +13 -9
- package/src/content-operations.ts +23 -65
- package/src/content-query.ts +1 -1
- package/src/core.ts +675 -0
- package/src/cron.ts +139 -0
- package/src/custom-tables.ts +274 -0
- package/src/database.ts +22 -14
- package/src/dictionary-transfer.ts +1 -1
- package/src/git-routes.ts +1 -1
- package/src/identity-provider-overrides.ts +18 -16
- package/src/imaging.ts +65 -15
- package/src/index.ts +10 -1
- package/src/job-wake.ts +23 -0
- package/src/live-reload.ts +195 -0
- package/src/log-viewer.ts +6 -1
- package/src/marketplace.ts +82 -10
- package/src/media-access.ts +12 -9
- package/src/member-auth.ts +6 -4
- package/src/models-builder.ts +1 -1
- package/src/node-operations.ts +122 -0
- package/src/owner-jobs.ts +428 -0
- package/src/ports.ts +36 -154
- package/src/preview-tokens.ts +6 -12
- package/src/remote.ts +3 -1
- package/src/routes.ts +18 -1
- package/src/schema.ts +8 -3
- package/src/seed/compile.ts +7 -5
- package/src/seed/export.ts +6 -4
- package/src/seo.ts +2 -2
- package/src/server.ts +328 -452
- package/src/settings.ts +18 -2
- package/src/site-data.ts +195 -0
- package/src/site-file.ts +30 -4
- package/src/site-queries.ts +140 -0
- package/src/site-replace.ts +25 -19
- package/src/site-sections.ts +1 -1
- package/src/site-services.ts +23 -6
- package/src/status-pages.ts +19 -5
- package/src/status.ts +11 -9
- package/src/url-settings.ts +1 -2
- package/src/webhook-files.ts +1 -1
- package/src/webhooks.ts +31 -23
- package/src/worker-watch.ts +73 -0
- package/src/worker.ts +138 -0
- package/src/bundle-tables.ts +0 -161
package/src/member-auth.ts
CHANGED
|
@@ -199,10 +199,12 @@ export function createMemberAuth(
|
|
|
199
199
|
const groupKeysFor = async (names: readonly string[]): Promise<string[]> => {
|
|
200
200
|
const keys: string[] = []
|
|
201
201
|
for (const groupName of names) {
|
|
202
|
-
const rows = await db.
|
|
203
|
-
'
|
|
204
|
-
|
|
205
|
-
|
|
202
|
+
const rows = await db.q
|
|
203
|
+
.selectFrom('node')
|
|
204
|
+
.select('unique_id')
|
|
205
|
+
.where('text', '=', groupName)
|
|
206
|
+
.where('node_object_type', '=', ObjectTypes.MemberGroup)
|
|
207
|
+
.execute()
|
|
206
208
|
if (rows[0]) keys.push(String(rows[0].unique_id))
|
|
207
209
|
}
|
|
208
210
|
return keys
|
package/src/models-builder.ts
CHANGED
|
@@ -15,7 +15,7 @@ import type {
|
|
|
15
15
|
ModelsBuilderInfo,
|
|
16
16
|
ModelsBuilderPort,
|
|
17
17
|
OutOfDateStatus,
|
|
18
|
-
} from '@crombolo/api-management'
|
|
18
|
+
} from '@crombolo/api-management/domain'
|
|
19
19
|
import type { FormTypes } from '@crombolo/core'
|
|
20
20
|
import { generateTypes, loadSchemaDirectory, validateSchemaSet } from '@crombolo/schema'
|
|
21
21
|
import type { CromboloConfig } from './config.ts'
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every document and media write, whoever starts it (stories 165 and 170): the
|
|
3
|
+
* operations with their approvals and redirect tracking. Built once per node
|
|
4
|
+
* and shared by the Management API, the jobs and the command line, so a worker
|
|
5
|
+
* (story 223) publishes a schedule exactly as an editor's node does.
|
|
6
|
+
*/
|
|
7
|
+
import {
|
|
8
|
+
createDocumentOperations,
|
|
9
|
+
createMediaOperations,
|
|
10
|
+
type DocumentOperations,
|
|
11
|
+
type EventSink,
|
|
12
|
+
type MediaOperations,
|
|
13
|
+
SILENT,
|
|
14
|
+
} from '@crombolo/content'
|
|
15
|
+
import {
|
|
16
|
+
appendCacheInstruction,
|
|
17
|
+
type Db,
|
|
18
|
+
type NodeSchemaState,
|
|
19
|
+
RedirectRepository,
|
|
20
|
+
} from '@crombolo/data'
|
|
21
|
+
import type { PublishedCache } from '@crombolo/render'
|
|
22
|
+
import { type Approvals, approvalsGate, createApprovals } from './approvals.ts'
|
|
23
|
+
import type { CromboloConfig } from './config.ts'
|
|
24
|
+
import { createMediaEventSink } from './content-events.ts'
|
|
25
|
+
import type { ContentNotifier } from './content-notifications.ts'
|
|
26
|
+
import { writeDomainsFor } from './domains.ts'
|
|
27
|
+
import type { EmailPort } from './email.ts'
|
|
28
|
+
import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
|
|
29
|
+
import type { MediaFileStore } from './media-files.ts'
|
|
30
|
+
import { createRedirectTracker, NO_REDIRECT_TRACKING, type RedirectTracker } from './redirects.ts'
|
|
31
|
+
import type { WebhookService } from './webhooks.ts'
|
|
32
|
+
|
|
33
|
+
export interface NodeOperations {
|
|
34
|
+
valueIntake: ReturnType<typeof createFileIntake>
|
|
35
|
+
tracker: RedirectTracker
|
|
36
|
+
approvals: Approvals
|
|
37
|
+
documents: DocumentOperations
|
|
38
|
+
media: MediaOperations
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface NodeOperationsOptions {
|
|
42
|
+
db: Db
|
|
43
|
+
config: CromboloConfig
|
|
44
|
+
/** Absent only in tests of the API's contract: nothing is cached, so nothing is tracked. */
|
|
45
|
+
cache?: PublishedCache
|
|
46
|
+
nodeState?: NodeSchemaState
|
|
47
|
+
nodeId?: string
|
|
48
|
+
/** Who a redirect's cache instruction says it is from; the node, unless said otherwise. */
|
|
49
|
+
instructedBy?: string
|
|
50
|
+
mediaFiles: MediaFileStore
|
|
51
|
+
email?: EmailPort
|
|
52
|
+
notifier?: ContentNotifier
|
|
53
|
+
/** Where document operations announce what they did; nothing hears them when absent. */
|
|
54
|
+
contentEvents?: EventSink
|
|
55
|
+
webhooks?: WebhookService
|
|
56
|
+
nudgeEvents?: () => void
|
|
57
|
+
backOfficeUrl?: string
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function createNodeOperations(options: NodeOperationsOptions): NodeOperations {
|
|
61
|
+
const { db, cache } = options
|
|
62
|
+
const repository = {
|
|
63
|
+
nodeState: options.nodeState,
|
|
64
|
+
nodeId: options.nodeId,
|
|
65
|
+
valueIntake: createFileIntake(options.mediaFiles),
|
|
66
|
+
}
|
|
67
|
+
const refusalReason = (error: unknown) =>
|
|
68
|
+
error instanceof TemporaryFileMissingError ? error.message : undefined
|
|
69
|
+
const tracker = cache
|
|
70
|
+
? createRedirectTracker({
|
|
71
|
+
cache,
|
|
72
|
+
redirects: new RedirectRepository(db),
|
|
73
|
+
enabled: options.config.trackRedirects,
|
|
74
|
+
instruct: () =>
|
|
75
|
+
appendCacheInstruction(db, {
|
|
76
|
+
kind: 'content',
|
|
77
|
+
payload: { redirects: true },
|
|
78
|
+
by: options.instructedBy ?? options.nodeId,
|
|
79
|
+
}),
|
|
80
|
+
})
|
|
81
|
+
: NO_REDIRECT_TRACKING
|
|
82
|
+
// Approvals publish through the operations too, so what an approval publishes
|
|
83
|
+
// is cached, tracked and announced as any publish is.
|
|
84
|
+
let documents: DocumentOperations | undefined
|
|
85
|
+
const approvals = createApprovals({
|
|
86
|
+
db,
|
|
87
|
+
nodeState: options.nodeState,
|
|
88
|
+
email: options.email,
|
|
89
|
+
backOfficeUrl: options.backOfficeUrl,
|
|
90
|
+
notifier: options.notifier,
|
|
91
|
+
publisher: {
|
|
92
|
+
publish: (key, cultures, actor, approvedHead) =>
|
|
93
|
+
(documents as DocumentOperations).publish(actor, key, {
|
|
94
|
+
cultures,
|
|
95
|
+
expectedHead: approvedHead,
|
|
96
|
+
}),
|
|
97
|
+
unpublish: (key, cultures, actor) =>
|
|
98
|
+
(documents as DocumentOperations).unpublish(actor, key, cultures),
|
|
99
|
+
},
|
|
100
|
+
})
|
|
101
|
+
documents = createDocumentOperations({
|
|
102
|
+
db,
|
|
103
|
+
repository,
|
|
104
|
+
events: options.contentEvents ?? SILENT,
|
|
105
|
+
approvals: approvalsGate(approvals),
|
|
106
|
+
redirects: tracker,
|
|
107
|
+
onChange: () => cache?.invalidate(),
|
|
108
|
+
afterDomains: (node, assignment) =>
|
|
109
|
+
writeDomainsFor(db, options.config.siteDir, node, assignment),
|
|
110
|
+
refusalReason,
|
|
111
|
+
})
|
|
112
|
+
const media = createMediaOperations({
|
|
113
|
+
db,
|
|
114
|
+
repository,
|
|
115
|
+
events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
|
|
116
|
+
files: options.mediaFiles,
|
|
117
|
+
// Only the items it touched: a media change leaves the pages alone (story 197).
|
|
118
|
+
onChange: (change) => cache?.media?.apply(change),
|
|
119
|
+
refusalReason,
|
|
120
|
+
})
|
|
121
|
+
return { valueIntake: repository.valueIntake, tracker, approvals, documents, media }
|
|
122
|
+
}
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Background and scheduled work for the site and its bundles (story 187): one
|
|
3
|
+
* queue in crombolo's own tables, one runner on every node that owns writes,
|
|
4
|
+
* and schedules each occurrence of which exactly one node runs. A job sees what
|
|
5
|
+
* its owner's public route sees, and nothing acts as the site.
|
|
6
|
+
* docs/rendering.md, "Background jobs"; docs/bundles.md, "Jobs".
|
|
7
|
+
*/
|
|
8
|
+
import {
|
|
9
|
+
type Db,
|
|
10
|
+
type JobProgress,
|
|
11
|
+
JobRepository,
|
|
12
|
+
type JobRow,
|
|
13
|
+
type JobState,
|
|
14
|
+
} from '@crombolo/data'
|
|
15
|
+
import { type Cron, isTimezone, nextOccurrence, parseCron } from './cron.ts'
|
|
16
|
+
import { logger } from './logging.ts'
|
|
17
|
+
|
|
18
|
+
/** The largest payload a job may carry, as JSON. */
|
|
19
|
+
export const MAX_PAYLOAD_BYTES = 64 * 1024
|
|
20
|
+
/** How many times a job runs before it is failed for good, unless it says otherwise. */
|
|
21
|
+
export const DEFAULT_ATTEMPTS = 5
|
|
22
|
+
const MAX_NOTE = 1024
|
|
23
|
+
const MAX_ERROR = 4096
|
|
24
|
+
|
|
25
|
+
/** What a schedule says: run this job on this timetable. */
|
|
26
|
+
export interface JobSchedule {
|
|
27
|
+
/** The job: `module.export` for the site, the job's name for a bundle. */
|
|
28
|
+
job: string
|
|
29
|
+
/** Five fields: minute, hour, day, month, weekday. */
|
|
30
|
+
cron: string
|
|
31
|
+
/** An IANA zone, such as `Europe/London`; UTC when not given. */
|
|
32
|
+
timezone?: string
|
|
33
|
+
/** After downtime, `run` (the default) runs a missed occurrence once; `skip` drops it. */
|
|
34
|
+
missed?: 'run' | 'skip'
|
|
35
|
+
/** The payload each occurrence carries. */
|
|
36
|
+
payload?: unknown
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** What every job is given, whoever owns it. */
|
|
40
|
+
export interface JobInfo {
|
|
41
|
+
readonly id: string
|
|
42
|
+
/** From 1. */
|
|
43
|
+
readonly attempt: number
|
|
44
|
+
/** Who queued it, shown to administrators; it grants nothing. */
|
|
45
|
+
readonly queuedBy: string | null
|
|
46
|
+
/** Aborts when the node is stopping: finish soon, or throw and be run again. */
|
|
47
|
+
readonly signal: AbortSignal
|
|
48
|
+
/** Saves how far it has got, for its owner's routes to show. */
|
|
49
|
+
progress(done: number, total?: number, note?: string): Promise<void>
|
|
50
|
+
/** Queues another of its owner's jobs. */
|
|
51
|
+
enqueue(name: string, payload?: unknown): Promise<string>
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A job as its owner's routes read it. */
|
|
55
|
+
export interface JobStatus {
|
|
56
|
+
id: string
|
|
57
|
+
name: string
|
|
58
|
+
state: JobState
|
|
59
|
+
attempts: number
|
|
60
|
+
progress: JobProgress | null
|
|
61
|
+
error: string | null
|
|
62
|
+
queuedBy: string | null
|
|
63
|
+
createdAt: string
|
|
64
|
+
finishedAt: string | null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** An owner's jobs: queue one, and read how one is going. */
|
|
68
|
+
export interface OwnerJobs {
|
|
69
|
+
enqueue(name: string, payload?: unknown): Promise<string>
|
|
70
|
+
/** One of this owner's jobs; another owner's is not found. */
|
|
71
|
+
status(id: string): Promise<JobStatus | undefined>
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A payload too big to queue: nothing was queued. */
|
|
75
|
+
export class JobPayloadTooLargeError extends Error {
|
|
76
|
+
constructor(
|
|
77
|
+
readonly job: string,
|
|
78
|
+
readonly bytes: number,
|
|
79
|
+
) {
|
|
80
|
+
super(
|
|
81
|
+
`The job ${job}'s payload is ${bytes} bytes of JSON, past the ${MAX_PAYLOAD_BYTES} a job may carry: keep the data in your own tables and pass its key.`,
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class UnknownJobError extends Error {
|
|
87
|
+
constructor(owner: string, name: string) {
|
|
88
|
+
super(
|
|
89
|
+
`${owner === 'site' ? 'The site' : `The bundle "${owner}"`} has no job "${name}" to queue.`,
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// biome-ignore lint/suspicious/noExplicitAny: a job's payload and context are its owner's to type
|
|
95
|
+
export type JobHandler = (payload: any, context: any) => unknown
|
|
96
|
+
|
|
97
|
+
/** One owner's jobs as the runner holds them. */
|
|
98
|
+
export interface JobOwner {
|
|
99
|
+
/** `site`, or the bundle's id. */
|
|
100
|
+
id: string
|
|
101
|
+
handlers: ReadonlyMap<string, JobHandler>
|
|
102
|
+
schedules: readonly JobSchedule[]
|
|
103
|
+
/** What a handler is given besides `job`: the owner's handles, with no caller. */
|
|
104
|
+
context(): Record<string, unknown>
|
|
105
|
+
/** Whether it may run now: a bundle that is off waits (story 222). */
|
|
106
|
+
on(): boolean
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Every reason a set of handlers and schedules cannot be used. */
|
|
110
|
+
export function jobProblems(
|
|
111
|
+
label: string,
|
|
112
|
+
handlers: Record<string, unknown> | undefined,
|
|
113
|
+
schedules: readonly JobSchedule[] | undefined,
|
|
114
|
+
): string[] {
|
|
115
|
+
const problems: string[] = []
|
|
116
|
+
const names = new Set<string>()
|
|
117
|
+
const seen = new Map<unknown, string>()
|
|
118
|
+
for (const [name, handler] of Object.entries(handlers ?? {})) {
|
|
119
|
+
if (typeof handler !== 'function')
|
|
120
|
+
problems.push(`${label}: the job "${name}" is not a function`)
|
|
121
|
+
else if (seen.has(handler))
|
|
122
|
+
problems.push(`${label}: the job "${name}" is the same function as "${seen.get(handler)}"`)
|
|
123
|
+
else seen.set(handler, name)
|
|
124
|
+
names.add(name)
|
|
125
|
+
}
|
|
126
|
+
for (const [index, schedule] of (schedules ?? []).entries()) {
|
|
127
|
+
const which = `${label}: schedule ${index + 1} (${schedule?.job ?? 'no job'})`
|
|
128
|
+
if (!schedule || typeof schedule.job !== 'string' || !names.has(schedule.job)) {
|
|
129
|
+
problems.push(`${which} names no job of its own`)
|
|
130
|
+
continue
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const cron = parseCron(String(schedule.cron))
|
|
134
|
+
const zone = schedule.timezone ?? 'UTC'
|
|
135
|
+
if (!isTimezone(zone)) problems.push(`${which}: "${zone}" is not a timezone`)
|
|
136
|
+
else nextOccurrence(cron, zone, new Date())
|
|
137
|
+
} catch (error) {
|
|
138
|
+
problems.push(`${which}: ${error instanceof Error ? error.message : String(error)}`)
|
|
139
|
+
}
|
|
140
|
+
if (schedule.missed !== undefined && schedule.missed !== 'run' && schedule.missed !== 'skip')
|
|
141
|
+
problems.push(`${which}: "missed" is "run" or "skip"`)
|
|
142
|
+
if (schedule.payload !== undefined) {
|
|
143
|
+
const size = payloadSize(schedule.payload)
|
|
144
|
+
if (size > MAX_PAYLOAD_BYTES)
|
|
145
|
+
problems.push(`${which}: its payload is ${size} bytes, past ${MAX_PAYLOAD_BYTES}`)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return problems.map((problem) => `${problem}.`)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const payloadSize = (payload: unknown): number =>
|
|
152
|
+
Buffer.byteLength(JSON.stringify(payload ?? null) ?? 'null')
|
|
153
|
+
|
|
154
|
+
/** When to try again after this many attempts: 30 s, doubling, at most an hour. */
|
|
155
|
+
export function retryDelayMs(attempts: number): number {
|
|
156
|
+
return Math.min(30_000 * 2 ** Math.max(0, attempts - 1), 60 * 60_000)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const statusOf = (job: JobRow): JobStatus => ({
|
|
160
|
+
id: job.id,
|
|
161
|
+
name: job.name,
|
|
162
|
+
state: job.state,
|
|
163
|
+
attempts: job.attempts,
|
|
164
|
+
progress: job.progress,
|
|
165
|
+
error: job.lastError,
|
|
166
|
+
queuedBy: job.queuedBy,
|
|
167
|
+
createdAt: job.createdAt.toISOString(),
|
|
168
|
+
finishedAt: job.finishedAt?.toISOString() ?? null,
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
/** A schedule's key in `job_schedule`: its owner, its job and its timetable. */
|
|
172
|
+
const scheduleKey = (owner: string, schedule: JobSchedule) =>
|
|
173
|
+
`${owner}:${schedule.job}:${schedule.cron}:${schedule.timezone ?? 'UTC'}`.slice(0, 200)
|
|
174
|
+
|
|
175
|
+
export interface JobRunner {
|
|
176
|
+
/** An owner's queue, recording `queuedBy` on what it queues. */
|
|
177
|
+
jobsFor(owner: string, queuedBy: string | null): OwnerJobs
|
|
178
|
+
/** Queues each occurrence that has fallen due, on this node only if it wins the claim. */
|
|
179
|
+
runSchedules(now?: Date): Promise<number>
|
|
180
|
+
/** Claims and runs due jobs until none is left or `limit` have run; what tests drive. */
|
|
181
|
+
runDue(limit?: number): Promise<number>
|
|
182
|
+
/** Starts the timer: schedules, then due jobs, every `intervalMs`. */
|
|
183
|
+
start(): void
|
|
184
|
+
/** Runs a tick now rather than at the next, on a started runner: something was queued. */
|
|
185
|
+
wake(): void
|
|
186
|
+
/** The job this node is running, and when it last claimed one; what a worker's `/health` says. */
|
|
187
|
+
state(): { running: string | null; lastClaimAt: string | null }
|
|
188
|
+
/** Aborts the running job's signal, waits for it a while, and releases it if it has not finished. */
|
|
189
|
+
stop(): Promise<void>
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function createJobRunner(options: {
|
|
193
|
+
db: Db
|
|
194
|
+
nodeId: string
|
|
195
|
+
owners: () => readonly JobOwner[]
|
|
196
|
+
intervalMs?: number
|
|
197
|
+
/** How long a stopping node waits for its running job before releasing it. */
|
|
198
|
+
graceMs?: number
|
|
199
|
+
now?: () => Date
|
|
200
|
+
/** Told after each job is queued, so whoever runs them can start on it. */
|
|
201
|
+
onEnqueued?: () => void
|
|
202
|
+
}): JobRunner {
|
|
203
|
+
const jobs = new JobRepository(options.db)
|
|
204
|
+
const log = logger('jobs')
|
|
205
|
+
const now = options.now ?? (() => new Date())
|
|
206
|
+
const crons = new Map<string, Cron>()
|
|
207
|
+
let timer: ReturnType<typeof setInterval> | undefined
|
|
208
|
+
let stopping = new AbortController()
|
|
209
|
+
let running: { id: string; done: Promise<void> } | undefined
|
|
210
|
+
let staleAt = 0
|
|
211
|
+
let lastClaimAt: Date | null = null
|
|
212
|
+
|
|
213
|
+
const ownerOf = (id: string) => options.owners().find((owner) => owner.id === id)
|
|
214
|
+
|
|
215
|
+
const enqueue = async (
|
|
216
|
+
owner: string,
|
|
217
|
+
name: string,
|
|
218
|
+
payload: unknown,
|
|
219
|
+
queuedBy: string | null,
|
|
220
|
+
) => {
|
|
221
|
+
if (!ownerOf(owner)?.handlers.has(name)) throw new UnknownJobError(owner, name)
|
|
222
|
+
const json = JSON.stringify(payload ?? null) ?? 'null'
|
|
223
|
+
const bytes = Buffer.byteLength(json)
|
|
224
|
+
if (bytes > MAX_PAYLOAD_BYTES)
|
|
225
|
+
throw new JobPayloadTooLargeError(owner === 'site' ? name : `${owner}/${name}`, bytes)
|
|
226
|
+
const id = await jobs.enqueue({
|
|
227
|
+
owner,
|
|
228
|
+
name,
|
|
229
|
+
payload: json,
|
|
230
|
+
maxAttempts: DEFAULT_ATTEMPTS,
|
|
231
|
+
queuedBy,
|
|
232
|
+
})
|
|
233
|
+
options.onEnqueued?.()
|
|
234
|
+
return id
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const jobsFor = (owner: string, queuedBy: string | null): OwnerJobs =>
|
|
238
|
+
Object.freeze({
|
|
239
|
+
enqueue: (name: string, payload?: unknown) => enqueue(owner, name, payload, queuedBy),
|
|
240
|
+
async status(id: string) {
|
|
241
|
+
const job = await jobs.get(id).catch(() => undefined)
|
|
242
|
+
return job && job.owner === owner ? statusOf(job) : undefined
|
|
243
|
+
},
|
|
244
|
+
})
|
|
245
|
+
|
|
246
|
+
const run = async (job: JobRow): Promise<void> => {
|
|
247
|
+
const owner = ownerOf(job.owner)
|
|
248
|
+
const handler = owner?.handlers.get(job.name)
|
|
249
|
+
if (!owner || !handler) {
|
|
250
|
+
// Its owner is no longer wired, or no longer has the job: it waits, and says why.
|
|
251
|
+
await jobs.fail(job.id, `Nothing here runs ${job.owner}'s job "${job.name}".`, undefined)
|
|
252
|
+
return
|
|
253
|
+
}
|
|
254
|
+
const signal = stopping.signal
|
|
255
|
+
const heartbeat = setInterval(() => void jobs.heartbeat(job.id).catch(() => {}), 30_000)
|
|
256
|
+
const info: JobInfo = Object.freeze({
|
|
257
|
+
id: job.id,
|
|
258
|
+
attempt: job.attempts,
|
|
259
|
+
queuedBy: job.queuedBy,
|
|
260
|
+
signal,
|
|
261
|
+
progress: (done: number, total?: number, note?: string) =>
|
|
262
|
+
jobs.heartbeat(job.id, {
|
|
263
|
+
done,
|
|
264
|
+
...(total !== undefined ? { total } : {}),
|
|
265
|
+
...(note ? { note: String(note).slice(0, MAX_NOTE) } : {}),
|
|
266
|
+
}),
|
|
267
|
+
enqueue: (name: string, payload?: unknown) =>
|
|
268
|
+
enqueue(owner.id, name, payload, `job ${job.id}`),
|
|
269
|
+
})
|
|
270
|
+
try {
|
|
271
|
+
await handler(job.payload, { ...owner.context(), job: info })
|
|
272
|
+
await jobs.succeed(job.id)
|
|
273
|
+
} catch (error) {
|
|
274
|
+
if (signal.aborted) {
|
|
275
|
+
await jobs.release(job.id)
|
|
276
|
+
return
|
|
277
|
+
}
|
|
278
|
+
const message = (error instanceof Error ? error.message : String(error)).slice(0, MAX_ERROR)
|
|
279
|
+
const retryAt =
|
|
280
|
+
job.attempts < job.maxAttempts
|
|
281
|
+
? new Date(now().getTime() + retryDelayMs(job.attempts))
|
|
282
|
+
: undefined
|
|
283
|
+
await jobs.fail(job.id, message, retryAt)
|
|
284
|
+
log.warning('The job {job} failed on attempt {attempt}{retry}: {error}', {
|
|
285
|
+
job: `${job.owner}/${job.name}`,
|
|
286
|
+
attempt: job.attempts,
|
|
287
|
+
retry: retryAt ? '' : ', for the last time',
|
|
288
|
+
error: message,
|
|
289
|
+
})
|
|
290
|
+
} finally {
|
|
291
|
+
clearInterval(heartbeat)
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
let busy = false
|
|
296
|
+
/** Schedules, then due jobs; a tick while one runs is dropped, as the next catches up. */
|
|
297
|
+
const tick = async () => {
|
|
298
|
+
if (busy) return
|
|
299
|
+
busy = true
|
|
300
|
+
try {
|
|
301
|
+
await runner.runSchedules()
|
|
302
|
+
await runner.runDue()
|
|
303
|
+
} catch (error) {
|
|
304
|
+
log.error('Background jobs could not run: {error}', {
|
|
305
|
+
error: error instanceof Error ? error.message : String(error),
|
|
306
|
+
})
|
|
307
|
+
} finally {
|
|
308
|
+
busy = false
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const runner: JobRunner = {
|
|
313
|
+
jobsFor,
|
|
314
|
+
|
|
315
|
+
async runSchedules(at = now()) {
|
|
316
|
+
let queued = 0
|
|
317
|
+
for (const owner of options.owners()) {
|
|
318
|
+
if (!owner.on()) continue
|
|
319
|
+
for (const schedule of owner.schedules) {
|
|
320
|
+
const key = scheduleKey(owner.id, schedule)
|
|
321
|
+
let cron = crons.get(key)
|
|
322
|
+
if (!cron) {
|
|
323
|
+
cron = parseCron(schedule.cron)
|
|
324
|
+
crons.set(key, cron)
|
|
325
|
+
}
|
|
326
|
+
const since = await jobs.scheduleSince(key, at)
|
|
327
|
+
const due = nextOccurrence(cron, schedule.timezone ?? 'UTC', since)
|
|
328
|
+
if (due > at) continue
|
|
329
|
+
// Of the nodes that saw it due, the one whose claim lands queues it.
|
|
330
|
+
if (!(await jobs.advanceSchedule(key, since, at))) continue
|
|
331
|
+
const late = at.getTime() - due.getTime() > 90_000
|
|
332
|
+
if (late && schedule.missed === 'skip') continue
|
|
333
|
+
await enqueue(owner.id, schedule.job, schedule.payload, `schedule ${schedule.cron}`)
|
|
334
|
+
queued++
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return queued
|
|
338
|
+
},
|
|
339
|
+
|
|
340
|
+
async runDue(limit = 25) {
|
|
341
|
+
if (Date.now() - staleAt > 60_000) {
|
|
342
|
+
staleAt = Date.now()
|
|
343
|
+
// A running job beats every 30 s; two minutes of silence is a node that died.
|
|
344
|
+
const released = await jobs.releaseStale(new Date(now().getTime() - 120_000))
|
|
345
|
+
if (released > 0)
|
|
346
|
+
log.info('{count} job(s) whose node stopped were queued again', { count: released })
|
|
347
|
+
await jobs.pruneSucceeded(new Date(now().getTime() - 7 * 24 * 60 * 60_000))
|
|
348
|
+
}
|
|
349
|
+
let ran = 0
|
|
350
|
+
while (ran < limit && !stopping.signal.aborted) {
|
|
351
|
+
const owners = options
|
|
352
|
+
.owners()
|
|
353
|
+
.filter((owner) => owner.on())
|
|
354
|
+
.map((owner) => owner.id)
|
|
355
|
+
if (owners.length === 0) break
|
|
356
|
+
const job = await jobs.claimNext(options.nodeId, now(), owners)
|
|
357
|
+
if (!job) break
|
|
358
|
+
const done = run(job)
|
|
359
|
+
lastClaimAt = now()
|
|
360
|
+
running = { id: job.id, done }
|
|
361
|
+
await done
|
|
362
|
+
running = undefined
|
|
363
|
+
ran++
|
|
364
|
+
}
|
|
365
|
+
return ran
|
|
366
|
+
},
|
|
367
|
+
|
|
368
|
+
start() {
|
|
369
|
+
if (timer) return
|
|
370
|
+
stopping = new AbortController()
|
|
371
|
+
timer = setInterval(tick, options.intervalMs ?? 5_000)
|
|
372
|
+
},
|
|
373
|
+
|
|
374
|
+
wake() {
|
|
375
|
+
if (timer) void tick()
|
|
376
|
+
},
|
|
377
|
+
|
|
378
|
+
state() {
|
|
379
|
+
return { running: running?.id ?? null, lastClaimAt: lastClaimAt?.toISOString() ?? null }
|
|
380
|
+
},
|
|
381
|
+
|
|
382
|
+
async stop() {
|
|
383
|
+
if (timer) clearInterval(timer)
|
|
384
|
+
timer = undefined
|
|
385
|
+
stopping.abort()
|
|
386
|
+
const current = running
|
|
387
|
+
if (!current) return
|
|
388
|
+
const grace = new Promise<'late'>((resolve) =>
|
|
389
|
+
setTimeout(() => resolve('late'), options.graceMs ?? 10_000),
|
|
390
|
+
)
|
|
391
|
+
if ((await Promise.race([current.done.then(() => 'done' as const), grace])) === 'late')
|
|
392
|
+
await jobs.release(current.id)
|
|
393
|
+
},
|
|
394
|
+
}
|
|
395
|
+
return runner
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** The site's jobs by `module.export`, from the modules its config lists. */
|
|
399
|
+
export function siteJobHandlers(
|
|
400
|
+
modules: Readonly<Record<string, Readonly<Record<string, unknown>>>> | undefined,
|
|
401
|
+
): Map<string, JobHandler> {
|
|
402
|
+
const out = new Map<string, JobHandler>()
|
|
403
|
+
for (const [module, exports] of Object.entries(modules ?? {}))
|
|
404
|
+
for (const [name, handler] of Object.entries(exports ?? {}))
|
|
405
|
+
if (typeof handler === 'function') out.set(`${module}.${name}`, handler as JobHandler)
|
|
406
|
+
return out
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Every reason the site's jobs and schedules cannot be used. */
|
|
410
|
+
export function siteJobProblems(config: {
|
|
411
|
+
jobs?: Readonly<Record<string, Readonly<Record<string, unknown>>>>
|
|
412
|
+
schedules?: readonly JobSchedule[]
|
|
413
|
+
}): string[] {
|
|
414
|
+
const problems: string[] = []
|
|
415
|
+
const handlers: Record<string, unknown> = {}
|
|
416
|
+
for (const [module, exports] of Object.entries(config.jobs ?? {})) {
|
|
417
|
+
if (!/^[A-Za-z_$][\w$]*$/.test(module))
|
|
418
|
+
problems.push(`The site: the job module "${module}" is not a name: letters, digits, _ and $.`)
|
|
419
|
+
if (!exports || typeof exports !== 'object') {
|
|
420
|
+
problems.push(
|
|
421
|
+
`The site: jobs.${module} is not a module: list it as \`import * as ${module} from …\`.`,
|
|
422
|
+
)
|
|
423
|
+
continue
|
|
424
|
+
}
|
|
425
|
+
for (const [name, handler] of Object.entries(exports)) handlers[`${module}.${name}`] = handler
|
|
426
|
+
}
|
|
427
|
+
return [...problems, ...jobProblems('The site', handlers, config.schedules)]
|
|
428
|
+
}
|