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