@crombolo/server 0.37.0 → 0.38.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.
Files changed (79) hide show
  1. package/package.json +15 -14
  2. package/src/access.ts +29 -27
  3. package/src/adapters/audit.ts +1 -1
  4. package/src/adapters/blueprints.ts +22 -13
  5. package/src/adapters/content.ts +1 -1
  6. package/src/adapters/dictionary.ts +1 -1
  7. package/src/adapters/documents.ts +17 -10
  8. package/src/adapters/elements.ts +47 -37
  9. package/src/adapters/file-system.ts +1 -1
  10. package/src/adapters/health.ts +10 -5
  11. package/src/adapters/media.ts +12 -8
  12. package/src/adapters/member-groups.ts +8 -6
  13. package/src/adapters/members.ts +6 -4
  14. package/src/adapters/public-access.ts +7 -5
  15. package/src/adapters/redirects.ts +1 -1
  16. package/src/adapters/references.ts +1 -1
  17. package/src/adapters/relations.ts +1 -1
  18. package/src/adapters/schema-files.ts +33 -1
  19. package/src/adapters/search-index.ts +1 -1
  20. package/src/adapters/template-query.ts +1 -1
  21. package/src/adapters/users.ts +13 -13
  22. package/src/adapters/webhooks.ts +1 -1
  23. package/src/anonymise-rules.ts +83 -0
  24. package/src/approvals-api.ts +1 -1
  25. package/src/approvals.ts +75 -38
  26. package/src/back-office-url.ts +20 -0
  27. package/src/backup.ts +26 -2
  28. package/src/bundle-code.ts +1 -1
  29. package/src/bundle-grants.ts +265 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +126 -43
  33. package/src/component-snippets.ts +1 -1
  34. package/src/components.ts +6 -1
  35. package/src/config.ts +61 -3
  36. package/src/content-notifications.ts +13 -9
  37. package/src/content-operations.ts +23 -65
  38. package/src/content-query.ts +1 -1
  39. package/src/core.ts +663 -0
  40. package/src/cron.ts +139 -0
  41. package/src/custom-tables.ts +274 -0
  42. package/src/database.ts +22 -14
  43. package/src/dictionary-transfer.ts +1 -1
  44. package/src/git-routes.ts +1 -1
  45. package/src/identity-provider-overrides.ts +18 -16
  46. package/src/imaging.ts +65 -15
  47. package/src/index.ts +10 -1
  48. package/src/job-wake.ts +23 -0
  49. package/src/live-reload.ts +195 -0
  50. package/src/log-viewer.ts +6 -1
  51. package/src/marketplace.ts +82 -10
  52. package/src/media-access.ts +12 -9
  53. package/src/member-auth.ts +6 -4
  54. package/src/models-builder.ts +1 -1
  55. package/src/node-operations.ts +122 -0
  56. package/src/owner-jobs.ts +428 -0
  57. package/src/ports.ts +36 -154
  58. package/src/preview-tokens.ts +6 -12
  59. package/src/remote.ts +3 -1
  60. package/src/schema.ts +8 -3
  61. package/src/seed/compile.ts +7 -5
  62. package/src/seed/export.ts +6 -4
  63. package/src/seo.ts +2 -2
  64. package/src/server.ts +333 -452
  65. package/src/settings.ts +18 -2
  66. package/src/site-data.ts +195 -0
  67. package/src/site-file.ts +30 -4
  68. package/src/site-queries.ts +140 -0
  69. package/src/site-replace.ts +25 -19
  70. package/src/site-sections.ts +1 -1
  71. package/src/site-services.ts +23 -6
  72. package/src/status-pages.ts +19 -5
  73. package/src/status.ts +11 -9
  74. package/src/url-settings.ts +1 -2
  75. package/src/webhook-files.ts +1 -1
  76. package/src/webhooks.ts +31 -23
  77. package/src/worker-watch.ts +73 -0
  78. package/src/worker.ts +138 -0
  79. package/src/bundle-tables.ts +0 -161
@@ -4,7 +4,7 @@
4
4
  * some group could withhold it, and a property the user cannot read may not be
5
5
  * filtered or sorted on.
6
6
  */
7
- import type { Principal } from '@crombolo/api-management'
7
+ import type { Principal } from '@crombolo/api-management/domain'
8
8
  import {
9
9
  DocumentPermissions,
10
10
  type GroupGrant,
package/src/core.ts ADDED
@@ -0,0 +1,663 @@
1
+ /**
2
+ * What every node is built on (story 223), whatever it serves: the database and
3
+ * schema, the site's code and bundles, the published cache, the views for
4
+ * e-mail, the document operations, the outbox and the jobs. docs/operations.md,
5
+ * "Running a cluster".
6
+ */
7
+ import type { ServerEvent } from '@crombolo/api-management/domain'
8
+ import { createBackOfficePaths, createExtensionRegistry } from '@crombolo/backoffice-host/registry'
9
+ import { ObjectTypes } from '@crombolo/core'
10
+ import {
11
+ appendCacheInstruction,
12
+ type JobWake,
13
+ notifyJobs,
14
+ RedirectRepository,
15
+ SITE_OWNER,
16
+ UserGroupRepository,
17
+ } from '@crombolo/data'
18
+ import {
19
+ DEFAULT_MEDIA_CACHE_MEGABYTES,
20
+ DEVELOPMENT_LIMITS,
21
+ enableComponentStack,
22
+ ISLANDS_PATH,
23
+ islandTransform,
24
+ MEMBER_EXTERNAL_SIGN_IN_PATH,
25
+ MediaCache,
26
+ PublishedCache,
27
+ Renderer,
28
+ setFormFieldTypes,
29
+ setFormTokenSigner,
30
+ ViewSnapshots,
31
+ } from '@crombolo/render'
32
+ import type { SyncReport } from '@crombolo/schema'
33
+ import { createMediaSource, createPublishedContentSource } from './adapters/documents.ts'
34
+ import { backOfficeUrl, documentEditUrl } from './back-office-url.ts'
35
+ import { BACKOFFICE_EXTERNAL_PATH } from './backoffice-external.ts'
36
+ import { createBundleGrants } from './bundle-grants.ts'
37
+ import {
38
+ type BundleMediaFactory,
39
+ createBundleMedia,
40
+ type ResolvedMediaFolder,
41
+ resolveBundleMediaFolders,
42
+ } from './bundle-media.ts'
43
+ import { createBundleRedirects, createServerBundles, validateServerBundles } from './bundles.ts'
44
+ import { type CromboloConfig, VERSION } from './config.ts'
45
+ import { createContentDispatcher } from './content-dispatch.ts'
46
+ import { createContentEventSink } from './content-events.ts'
47
+ import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
48
+ import { databaseFor, openTables, siteTablesProblems, tablesChains } from './custom-tables.ts'
49
+ import { attachDatabase, bootstrapDatabase } from './database.ts'
50
+ import { createDiagnostics } from './diagnostics.ts'
51
+ import { resolveEmailPort } from './email.ts'
52
+ import { createFormRegistry, formSigningSecret, signFormToken } from './form-submit.ts'
53
+ import { formTypesOf } from './form-types.ts'
54
+ import { createWorkflowRunner } from './form-workflows.ts'
55
+ import {
56
+ createBundleIdentityProviders,
57
+ IdentityProviderOverrides,
58
+ } from './identity-provider-overrides.ts'
59
+ import { buildIslands } from './islands.ts'
60
+ import { listenForJobs, runsJobs } from './job-wake.ts'
61
+ import { createBackgroundJobs } from './jobs.ts'
62
+ import { logger } from './logging.ts'
63
+ import { MediaFileStore } from './media-files.ts'
64
+ import { mediaStoreFromEnvironment } from './media-store.ts'
65
+ import { createNodeOperations } from './node-operations.ts'
66
+ import {
67
+ createJobRunner,
68
+ type JobHandler,
69
+ type JobOwner,
70
+ siteJobHandlers,
71
+ siteJobProblems,
72
+ } from './owner-jobs.ts'
73
+ import { createRedirectTracker } from './redirects.ts'
74
+ import { withRemoteMedia } from './remote-media.ts'
75
+ import { bootSchema, CacheInstructionPoller } from './schema.ts'
76
+ import { publishSchema, type SchemaStore, useSchemaStore } from './schema-store.ts'
77
+ import { createSiteQueries, queryProblems } from './site-queries.ts'
78
+ import { createSiteServices } from './site-services.ts'
79
+ import { redirectAfterUrlChange, type UrlChangeContext } from './url-settings.ts'
80
+ import { assertViewRuntime } from './view-runtime.ts'
81
+ import { bundleEventProblems, createWebhookService } from './webhooks.ts'
82
+ import { createWorkerWatch } from './worker-watch.ts'
83
+
84
+ /** What only the serving half of a node supplies; a worker leaves each out. */
85
+ export interface CoreHooks {
86
+ /** The published cache was dropped: a server drops its drafts and reloads open pages. */
87
+ onCacheInvalidate?: () => void
88
+ /** A newer views generation replaced the one in use. */
89
+ onViewsSwap?: () => void
90
+ /** Whether a views generation builds its islands' browser code; e-mails need none. */
91
+ buildIslands: boolean
92
+ /** What an open back office hears of a change. */
93
+ announce?: (event: ServerEvent) => void
94
+ /** Told about each document a job changed, for the server event hub. */
95
+ onDocumentChanged?: (key: string) => void
96
+ /** A protected media file, for a bundle uploading as a member (story 198). */
97
+ streamMemberFile?: (src: string, search: URLSearchParams) => Promise<Response>
98
+ /** The site's name as its settings give it, for the e-mails a form sends. */
99
+ siteName?: () => Promise<string>
100
+ }
101
+
102
+ /**
103
+ * What every node is built on (story 223): the database and the schema, the
104
+ * site's code and its bundles, the published cache, the views for e-mail, the
105
+ * document operations, the outbox and the jobs. `createServer` adds the back
106
+ * office, the APIs and the site; `createWorker` adds `/health`.
107
+ */
108
+ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
109
+ const log = logger('server')
110
+ const schemaLog = logger('schema')
111
+ const renderLog = logger('render')
112
+ const bundleLog = (id: string) => {
113
+ const named = logger('bundle', id)
114
+ return {
115
+ info: (message: string, properties?: Record<string, unknown>) =>
116
+ named.info(message, properties),
117
+ warn: (message: string, properties?: Record<string, unknown>) =>
118
+ named.warn(message, properties),
119
+ error: (message: string, properties?: Record<string, unknown>) =>
120
+ named.error(message, properties),
121
+ }
122
+ }
123
+ const diagnostics = createDiagnostics(config.diagnostics)
124
+ // Extensions are the site's own npm dependencies (`docs/bundles.md`).
125
+ // Uncached in development so an author editing one sees a reload pick it up.
126
+ const extensions = createExtensionRegistry(config.siteDir, { cache: !config.development })
127
+ const paths = createBackOfficePaths({ backOfficePath: config.backOfficePath })
128
+ // Two questions, not one: what this process answers, and what it is
129
+ // responsible for converging at boot. `all` and `api` are both owners; a
130
+ // `worker` runs jobs but, like `web`, converges and migrates nothing.
131
+ const owns = config.role === 'all' || config.role === 'api'
132
+ // Bundles are checked before the database is touched, because a bundle that
133
+ // owns tables is migrated at boot, and a bad declaration must not get that far.
134
+ // On every role: a bundle's form types are needed wherever forms render and
135
+ // submit, and its member and public routes wherever the site is served. Its
136
+ // tables are migrated only by the nodes that own the database.
137
+ const bundlePackages = extensions.bundles().bundles
138
+ const formTypes = formTypesOf(config)
139
+ {
140
+ const problems = [
141
+ ...validateServerBundles(config.bundles, bundlePackages, VERSION),
142
+ ...formTypes.problems,
143
+ ...bundleEventProblems(config.bundles),
144
+ ]
145
+ if (problems.length > 0)
146
+ throw new Error(`The configured bundles cannot be mounted:\n- ${problems.join('\n- ')}`)
147
+ const site = [
148
+ ...siteTablesProblems(config),
149
+ ...queryProblems(config),
150
+ ...siteJobProblems(config),
151
+ ]
152
+ if (site.length > 0)
153
+ throw new Error(`The site's own tables cannot be used:\n- ${site.join('\n- ')}`)
154
+ }
155
+ setFormFieldTypes(formTypes.types, formTypes.renderers)
156
+ const chains = tablesChains(config, config.bundles, bundlePackages)
157
+ // A `web` node reads the site's tables for its named queries, and nothing of a
158
+ // bundle's; a worker runs bundles' jobs, so it opens every owner's.
159
+ const siteChains = chains.filter((chain) => chain.id === SITE_OWNER)
160
+ const opened = config.role === 'web' ? siteChains : chains
161
+ const { db, seededAdminPassword } = owns
162
+ ? await bootstrapDatabase(config, chains)
163
+ : await attachDatabase(config, opened)
164
+ await openTables(db, config, opened, { provision: owns })
165
+ // Story 222: a bundle runs only while an administrator's grant covers what it declares.
166
+ const bundleGrants = createBundleGrants({
167
+ db,
168
+ packages: () => new Map(extensions.bundles().bundles.map((pkg) => [pkg.id, pkg])),
169
+ })
170
+ await bundleGrants.refresh()
171
+ // Story 187: the site's and its bundles' background jobs, on one queue. The
172
+ // owners are read when the runner asks, once everything below is built.
173
+ const jobRunner = createJobRunner({
174
+ db,
175
+ nodeId: config.nodeId,
176
+ owners: () => jobOwners(),
177
+ // Queued where jobs do not run: the worker hears of it now.
178
+ onEnqueued: () => {
179
+ if (!runsJobs(config)) wake('jobs')
180
+ },
181
+ })
182
+ for (const bundle of config.bundles) {
183
+ const pkg = bundlePackages.find((candidate) => candidate.id === bundle.id)
184
+ if (pkg && !bundleGrants.isOn(bundle.id))
185
+ log.warning(
186
+ 'The bundle {bundle} is off until an administrator approves what it may do: {permissions}. Grant it in Packages → Installed, or run `crombolo bundle grant {bundle}`.',
187
+ { bundle: bundle.id, permissions: bundleGrants.state(pkg).missing.join(', ') },
188
+ )
189
+ }
190
+ // A configured schema store is copied down before anything reads `schema/`, and
191
+ // becomes the schema directory for this boot. Everything after here — loading,
192
+ // validation, hashing, sync, the writer — works on files exactly as it always has.
193
+ const copied = await useSchemaStore(config)
194
+ if (config.schemaStore)
195
+ schemaLog.info('Schema read from {store}: {count} files in {dir}', {
196
+ store: config.schemaStore.description,
197
+ count: copied,
198
+ dir: config.schemaCacheDir,
199
+ })
200
+ // A node that does not own the schema still loads it — the renderer needs the
201
+ // property definitions — but writes none of it.
202
+ const schema = await bootSchema(db, owns ? config : { ...config, syncSchemaAtBoot: false })
203
+
204
+ // Form definitions are files, so they are re-read rather than cached with the
205
+ // content: nothing about a publish tells this node that a form changed.
206
+ const forms = createFormRegistry(config.schemaDir, { formTypes: formTypes.types })
207
+ // Every form this node renders carries a token signed with the site's key, so
208
+ // the timing guard cannot be bypassed by posting a made-up render time.
209
+ const formSecret = await formSigningSecret(db)
210
+ setFormTokenSigner((formKey, renderedAt) => signFormToken(formSecret, formKey, renderedAt))
211
+ const publishedSource = createPublishedContentSource(db, {
212
+ nodeState: schema.nodeState,
213
+ nodeId: schema.nodeId,
214
+ })
215
+ // Media is cached apart from the pages (story 197), item by item within a
216
+ // budget, and shared by the published and draft caches: media has no drafts.
217
+ const mediaCache = new MediaCache(
218
+ createMediaSource(db, { nodeState: schema.nodeState, nodeId: schema.nodeId }),
219
+ { budgetBytes: (config.mediaCacheMegabytes ?? DEFAULT_MEDIA_CACHE_MEGABYTES) * 1024 * 1024 },
220
+ )
221
+ const cacheOptions = { form: (key: string) => forms.byKey(key), media: mediaCache }
222
+ if (config.errors.showDetails) enableComponentStack()
223
+ const cache = new PublishedCache(publishedSource, {
224
+ ...cacheOptions,
225
+ onInvalidate: () => hooks.onCacheInvalidate?.(),
226
+ })
227
+ // A sync or a Settings change that alters how URLs are built moves every URL:
228
+ // the old ones redirect, as a rename's do.
229
+ const urlChange: UrlChangeContext = {
230
+ db,
231
+ config,
232
+ source: publishedSource,
233
+ cacheOptions,
234
+ cache,
235
+ tracker: createRedirectTracker({
236
+ cache,
237
+ redirects: new RedirectRepository(db),
238
+ enabled: config.trackRedirects,
239
+ instruct: () =>
240
+ appendCacheInstruction(db, {
241
+ kind: 'content',
242
+ payload: { redirects: true },
243
+ by: schema.nodeId,
244
+ }),
245
+ }),
246
+ }
247
+ const afterSync = async (report: SyncReport | undefined) => {
248
+ if (!report?.urls) return
249
+ await redirectAfterUrlChange(urlChange, report.urls.before)
250
+ log.info('Page addresses now {mode} the top-level page; old addresses redirect', {
251
+ mode: report.urls.after.hideTopLevel ? 'leave out' : 'include',
252
+ })
253
+ }
254
+ await afterSync(schema.report)
255
+ // A snapshot of the views, so a template edited anywhere — the backoffice, a
256
+ // deploy, a bucket synced underneath — is picked up without restarting this
257
+ // node. `assertViewRuntime` first, because a cache directory the JSX runtime
258
+ // cannot be resolved from fails every render rather than the boot.
259
+ assertViewRuntime(config.componentsCacheDir)
260
+ const snapshots = new ViewSnapshots({
261
+ sourceDir: config.componentsDir,
262
+ cacheDir: config.componentsCacheDir,
263
+ limits: { ...(config.development ? DEVELOPMENT_LIMITS : {}), ...config.componentsSnapshot },
264
+ onProblem: (message) => renderLog.error('{message}', { message }),
265
+ // Only a change: every boot takes a generation, and saying so each time is
266
+ // noise. The start banner names the one a node came up on.
267
+ onSwap: (hash, previous) => {
268
+ if (!previous) return
269
+ renderLog.info('Views changed: generation {previous} to {hash}', {
270
+ previous: previous.slice(0, 8),
271
+ hash: hash.slice(0, 8),
272
+ })
273
+ hooks.onViewsSwap?.()
274
+ },
275
+ // Story 209: a `'use client'` view is a stub on the server, and its browser
276
+ // code is built with the generation, unless a site's Vite build supplies it.
277
+ transform: islandTransform,
278
+ beforeSwap: async (generation) => {
279
+ if (!hooks.buildIslands) return
280
+ if (config.islands?.manifest || (config.development && config.islands?.devServer)) return
281
+ try {
282
+ await buildIslands({ ...generation, development: config.development })
283
+ } catch (error) {
284
+ renderLog.error(
285
+ "The views' islands did not build; their pages show each island's fallback: {problems}",
286
+ {
287
+ problems: error instanceof Error ? error.message : String(error),
288
+ },
289
+ )
290
+ }
291
+ },
292
+ })
293
+ await snapshots.prepare()
294
+ // Before the poller, which tells it to look again on a `views` instruction
295
+ // from another node: a closure over a `const` declared later would be a
296
+ // temporal dead zone waiting for the first instruction to land.
297
+ const renderer = new Renderer({
298
+ cache,
299
+ componentsDir: config.componentsDir,
300
+ snapshots,
301
+ renderTimeoutMs: config.renderTimeoutMs,
302
+ islandsManifest: (generation) =>
303
+ config.development && config.islands?.devServer
304
+ ? `${ISLANDS_PATH}/dev/manifest.json`
305
+ : config.islands?.manifest
306
+ ? `${ISLANDS_PATH}/vite/manifest.json`
307
+ : generation && `${ISLANDS_PATH}/${generation}/manifest.json`,
308
+ })
309
+
310
+ // The site's config may name a store; without one the environment decides,
311
+ // and that falls back to the media directory on this disk.
312
+ // A site pulled with `--lazy-media` reads files through from its remote (story 108).
313
+ const mediaStore = withRemoteMedia(
314
+ config.mediaStore ?? (await mediaStoreFromEnvironment(config.mediaDir)),
315
+ config.siteDir,
316
+ )
317
+ // Resolved once: constructing it twice would warn twice about a provider that
318
+ // is half-configured, and the adapters are cheap but not free of side effects.
319
+ const email = resolveEmailPort(config)
320
+ // Story 045: a change queues the e-mails its subscribers asked for. Nothing is
321
+ // queued on a site that cannot send; development sends to the console.
322
+ const notifier = createContentNotifier(db, { canSend: Boolean(email) })
323
+ const mediaFiles = new MediaFileStore(mediaStore)
324
+ const webhooks = createWebhookService({
325
+ db,
326
+ schemaDir: config.schemaDir,
327
+ filesWritable: config.schemaWritable,
328
+ secretKey: config.secretKey,
329
+ bundles: config.bundles,
330
+ isBundleOn: (bundleId) => bundleGrants.isOn(bundleId),
331
+ onFilesChanged: config.schemaStore
332
+ ? async () => {
333
+ await publishSchema(config.schemaStore as SchemaStore, config.schemaDir)
334
+ }
335
+ : undefined,
336
+ })
337
+ // Recorded content events become deliveries and notifications here (story 171).
338
+ const dispatcher = createContentDispatcher({ db, webhooks, notifier })
339
+ /**
340
+ * Work a write left for the jobs: run now where the jobs run, or announced
341
+ * to the worker that runs them when they do not run here (story 223).
342
+ */
343
+ const wake = (work: JobWake) => {
344
+ if (runsJobs(config)) {
345
+ if (work === 'events') dispatcher.nudge()
346
+ else if (work === 'search') jobs.kickSearchIndexing()
347
+ else jobRunner.wake()
348
+ return
349
+ }
350
+ void notifyJobs(db, work).catch((error: unknown) =>
351
+ log.error('Could not wake the worker: {error}', { error: String(error) }),
352
+ )
353
+ }
354
+ // Document writes record and announce themselves through this, from every entry point.
355
+ const contentEvents = createContentEventSink({
356
+ webhooks,
357
+ notifier,
358
+ live: (event) => {
359
+ hooks.announce?.(event)
360
+ wake('search')
361
+ },
362
+ nudge: () => wake('events'),
363
+ })
364
+ const operations = createNodeOperations({
365
+ db,
366
+ config,
367
+ cache,
368
+ nodeState: schema.nodeState,
369
+ nodeId: schema.nodeId,
370
+ mediaFiles,
371
+ email,
372
+ notifier,
373
+ contentEvents,
374
+ webhooks,
375
+ nudgeEvents: () => wake('events'),
376
+ backOfficeUrl: backOfficeUrl(config),
377
+ })
378
+
379
+ /**
380
+ * The server halves of the site's bundles. Back-office routes answer only
381
+ * where the backoffice is; site routes (story 211) wherever the site is
382
+ * served, through the site's route table.
383
+ *
384
+ * Capabilities are built here, from what this node already holds, so a bundle
385
+ * is handed a narrow interface rather than the database. A bad bundle fails the
386
+ * boot — see `createServerBundles`.
387
+ */
388
+ // Story 198: media as the member, built at the first request.
389
+ let bundleMedia: BundleMediaFactory | undefined
390
+ let bundleMediaFolders = new Map<string, ResolvedMediaFolder[]>()
391
+ const bundles =
392
+ config.bundles.length > 0
393
+ ? createServerBundles({
394
+ bundles: config.bundles,
395
+ packages: bundlePackages,
396
+ coreVersion: VERSION,
397
+ database: (bundle) => {
398
+ const chain = chains.find((candidate) => candidate.id === bundle.id)
399
+ return chain ? databaseFor(chain) : undefined
400
+ },
401
+ isOn: (bundleId) => bundleGrants.isOn(bundleId),
402
+ jobs: (bundleId, queuedBy) => jobRunner.jobsFor(bundleId, queuedBy),
403
+ pluginApiPath: `${paths.pluginPath}/api`,
404
+ host: {
405
+ redirects: createBundleRedirects({ db, cache }),
406
+ documents: {
407
+ url: async (key, culture) => {
408
+ const content = await cache.byKey(key, culture ?? null)
409
+ return content && content.url !== '#' ? content.url : undefined
410
+ },
411
+ },
412
+ log: bundleLog('bundle'),
413
+ identityProviders: createBundleIdentityProviders({
414
+ overrides: new IdentityProviderOverrides(db, config.secretKey),
415
+ members: config.memberIdentityProviders,
416
+ backoffice: config.backofficeIdentityProviders,
417
+ memberCallbackPath: MEMBER_EXTERNAL_SIGN_IN_PATH,
418
+ backofficeCallbackPath: BACKOFFICE_EXTERNAL_PATH,
419
+ groups: async (audience) =>
420
+ audience === 'user'
421
+ ? (await new UserGroupRepository(db).all()).map((g) => ({
422
+ value: g.alias,
423
+ name: g.name,
424
+ }))
425
+ : (
426
+ await db.q
427
+ .selectFrom('node')
428
+ .select('text')
429
+ .where('node_object_type', '=', ObjectTypes.MemberGroup)
430
+ .orderBy('text')
431
+ .execute()
432
+ ).map((g) => ({ value: String(g.text), name: String(g.text) })),
433
+ }),
434
+ },
435
+ log: (id) => bundleLog(id),
436
+ callerHost: {
437
+ media: (caller, bundle) => {
438
+ bundleMedia ??= createBundleMedia({
439
+ db,
440
+ operations: operations.media,
441
+ files: mediaFiles,
442
+ cache: mediaCache,
443
+ folders: (id) => bundleMediaFolders.get(id) ?? [],
444
+ bundleName: (id) => bundles?.mounted.find((b) => b.id === id)?.name ?? id,
445
+ stream: (src, search) =>
446
+ hooks.streamMemberFile?.(src, search) ??
447
+ Promise.resolve(new Response(null, { status: 404 })),
448
+ })
449
+ return bundleMedia(caller, bundle)
450
+ },
451
+ },
452
+ })
453
+ : undefined
454
+ if (bundles) {
455
+ // A declared folder that is not there would fail on the first upload; the
456
+ // boot says so instead, naming the bundle and the path.
457
+ const names = new Map(bundles.mounted.map((bundle) => [bundle.id, bundle.name]))
458
+ const resolved = await resolveBundleMediaFolders(
459
+ db,
460
+ config.bundles,
461
+ (id) => names.get(id) ?? id,
462
+ )
463
+ if (resolved.problems.length > 0)
464
+ throw new Error(
465
+ `The configured bundles cannot be mounted:\n- ${resolved.problems.join('\n- ')}`,
466
+ )
467
+ bundleMediaFolders = resolved.folders
468
+ }
469
+
470
+ const poller = new CacheInstructionPoller({
471
+ db,
472
+ nodeId: schema.nodeId,
473
+ nodeState: schema.nodeState,
474
+ role: config.role,
475
+ // `schema` and `content` change what renders: schema alters property
476
+ // definitions. `views` changes the code that renders it, which is a new
477
+ // snapshot rather than anything in the published cache.
478
+ onInstruction: (kind, payload) => {
479
+ if (kind !== 'components') return cache.invalidate()
480
+ // The hash only says when to stop looking eagerly; the snapshot is always
481
+ // of the bytes this node reads, so a superseded one is harmless.
482
+ snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
483
+ },
484
+ // Behind the latest committed checkpoint: rebuilt now rather than on the next
485
+ // read, so an idle node catches up and says so (story 174). A worker builds
486
+ // the cache only when a job asks, so it only drops it.
487
+ content: {
488
+ served: () => cache.served(),
489
+ covered: (checkpoint) => cache.covered(checkpoint),
490
+ behind: () => {
491
+ // Already dropped by a change made here: the next reader rebuilds it and
492
+ // waits, so a read after this node's own write is never answered stale.
493
+ const dropped = cache.stale
494
+ cache.invalidate()
495
+ if (config.role === 'worker' || dropped) return
496
+ return cache
497
+ .fresh()
498
+ .then(() => {})
499
+ .catch((error: unknown) =>
500
+ renderLog.error('Could not rebuild the published cache: {error}', { error }),
501
+ )
502
+ },
503
+ },
504
+ media: {
505
+ apply: (change) => mediaCache.apply(change),
506
+ clear: () => mediaCache.clear(),
507
+ },
508
+ })
509
+ await poller.start(config.development ? 2_000 : 5_000)
510
+
511
+ const siteServicesFor = createSiteServices({
512
+ db,
513
+ cache,
514
+ queries: createSiteQueries({ queries: config.queries, chain: siteChains[0] }),
515
+ jobs: (queuedBy) => ({
516
+ enqueue: async (name, payload) =>
517
+ jobRunner.jobsFor(SITE_OWNER, await queuedBy()).enqueue(name, payload),
518
+ status: (id) => jobRunner.jobsFor(SITE_OWNER, null).status(id),
519
+ }),
520
+ })
521
+ const siteJobs = siteJobHandlers(config.jobs)
522
+ /** Every owner with jobs: the site's given its tables and `site()` as a visitor; a bundle's, its capabilities for no caller. */
523
+ const jobOwners = (): JobOwner[] => [
524
+ ...(siteJobs.size > 0
525
+ ? [
526
+ {
527
+ id: SITE_OWNER,
528
+ handlers: siteJobs,
529
+ schedules: config.schedules ?? [],
530
+ context: () => ({
531
+ ...(siteChains[0] ? { db: databaseFor(siteChains[0]) } : {}),
532
+ site: siteServicesFor(undefined)(),
533
+ }),
534
+ on: () => true,
535
+ },
536
+ ]
537
+ : []),
538
+ ...config.bundles
539
+ .filter((bundle) => bundle.jobs && Object.keys(bundle.jobs).length > 0)
540
+ .map((bundle) => ({
541
+ id: bundle.id,
542
+ handlers: new Map(Object.entries(bundle.jobs ?? {})) as Map<string, JobHandler>,
543
+ schedules: bundle.schedules ?? [],
544
+ context: () => ({ bundle: bundles?.jobContext(bundle.id) }),
545
+ on: () => bundleGrants.isOn(bundle.id),
546
+ })),
547
+ ]
548
+
549
+ const jobs = createBackgroundJobs({
550
+ db,
551
+ cache,
552
+ approvals: operations.approvals,
553
+ operations: operations.documents,
554
+ dispatcher,
555
+ eventRetentionDays: config.eventRetentionDays,
556
+ nodeState: schema.nodeState,
557
+ nodeId: schema.nodeId,
558
+ versionCleanup: config.versionCleanup,
559
+ auditRetentionDays: config.auditRetentionDays,
560
+ mediaFiles,
561
+ // The workflow queue drains here rather than in the request: a submission is
562
+ // stored first, and an e-mail that cannot be sent yet must not cost it.
563
+ webhooks,
564
+ formWorkflows: createWorkflowRunner({
565
+ db,
566
+ forms,
567
+ email,
568
+ mediaFiles,
569
+ nodeState: schema.nodeState,
570
+ nodeId: schema.nodeId,
571
+ onContentChanged: () => cache.invalidate(),
572
+ operations: operations.documents,
573
+ bundleWorkflows: formTypes.workflows,
574
+ renderEmail: (alias, props) => renderer.renderEmail(alias, props),
575
+ site: async () => ({
576
+ name: (await hooks.siteName?.()) || config.siteName,
577
+ url: config.applicationUrl,
578
+ }),
579
+ }),
580
+ contentNotifications: email
581
+ ? createContentNotificationRunner({
582
+ db,
583
+ email,
584
+ siteName: config.siteName,
585
+ editUrl: (key) => documentEditUrl(config, key),
586
+ })
587
+ : undefined,
588
+ onDocumentChanged: (key) => hooks.onDocumentChanged?.(key),
589
+ })
590
+
591
+ let listening: (() => Promise<void>) | undefined
592
+ // Where jobs are left to a worker: whether one is running them (decision 4).
593
+ const workerWatch = createWorkerWatch({ db, config })
594
+ return {
595
+ diagnostics,
596
+ extensions,
597
+ paths,
598
+ owns,
599
+ bundlePackages,
600
+ formTypes,
601
+ chains,
602
+ siteChains,
603
+ db,
604
+ seededAdminPassword,
605
+ bundleGrants,
606
+ jobRunner,
607
+ schema,
608
+ forms,
609
+ formSecret,
610
+ publishedSource,
611
+ mediaCache,
612
+ cacheOptions,
613
+ cache,
614
+ afterSync,
615
+ urlChange,
616
+ snapshots,
617
+ renderer,
618
+ mediaStore,
619
+ email,
620
+ notifier,
621
+ mediaFiles,
622
+ webhooks,
623
+ dispatcher,
624
+ contentEvents,
625
+ operations,
626
+ bundles,
627
+ /** Each bundle's declared media folders, as resolved at boot (story 198). */
628
+ bundleMediaFolders: () => bundleMediaFolders,
629
+ poller,
630
+ siteServicesFor,
631
+ jobs,
632
+ wake,
633
+ workerWatch,
634
+ /** Whether this node runs the jobs: an owner unless told not to, and a worker always. */
635
+ runsJobs: runsJobs(config),
636
+ /**
637
+ * Starts the jobs where this node runs them. A worker also listens for the
638
+ * writes that leave it work, so it runs them at once rather than at its next
639
+ * poll; Postgres only, as a worker is.
640
+ */
641
+ async startJobs(): Promise<void> {
642
+ if (!runsJobs(config)) return workerWatch.start()
643
+ jobs.start()
644
+ jobRunner.start()
645
+ if (config.role === 'worker')
646
+ listening = await listenForJobs(db, (work) => {
647
+ if (work === 'events') void jobs.runEvents().catch(() => {})
648
+ else if (work === 'search') jobs.kickSearchIndexing()
649
+ else jobRunner.wake()
650
+ })
651
+ },
652
+ /** Stops listening, the jobs and the runner, letting what is running finish or go back. */
653
+ async stopJobs(): Promise<void> {
654
+ workerWatch.stop()
655
+ await listening?.()
656
+ listening = undefined
657
+ await jobRunner.stop()
658
+ await jobs.stop()
659
+ },
660
+ }
661
+ }
662
+
663
+ export type Core = Awaited<ReturnType<typeof createCore>>