@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
package/src/bundles.ts CHANGED
@@ -38,20 +38,22 @@
38
38
  * release refuses the boot.
39
39
  *
40
40
  * - A bundle that declares `tables` owns them: its own ledgered chain, written
41
- * with the declarative builder in `@crombolo/data`, and a `tables`
42
- * capability confined to them (`docs/bundles.md`, Part 4).
41
+ * with the declarative builder in `@crombolo/data`, in a schema or file of
42
+ * its own, and `context.bundle.database`, a Kysely handle on the connection
43
+ * that reaches only them (`docs/bundles.md`, Part 4; story 189).
43
44
  *
44
- * Deliberately not offered: raw SQL, a `Db`, and anything that writes the
45
+ * Deliberately not offered: crombolo's own `Db`, and anything that writes the
45
46
  * site's files.
46
47
  */
47
48
 
48
- import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management'
49
+ import { hasCultureAccess, hasSection, type Principal } from '@crombolo/api-management/domain'
49
50
  import {
50
51
  BUNDLE_ID,
51
52
  BUNDLE_SCHEMA_VERSION,
52
53
  type BundlePackage,
53
54
  peerRangeProblem,
54
- } from '@crombolo/backoffice-host'
55
+ schemaProblem,
56
+ } from '@crombolo/backoffice-host/registry'
55
57
  import type { Middleware, RouteMethod, SiteRoute } from '@crombolo/common'
56
58
  import {
57
59
  type AppAlias,
@@ -62,14 +64,15 @@ import {
62
64
  } from '@crombolo/core'
63
65
  import {
64
66
  type BundleTables,
65
- type BundleTablesCapability,
66
67
  bundleTablesCompatibility,
67
- compileBundleTables,
68
+ compileTables,
68
69
  type Db,
69
70
  type RedirectMatchKind,
70
71
  RedirectRepository,
71
72
  type RedirectRow,
72
73
  type RedirectTargetKind,
74
+ SITE_OWNER,
75
+ type TablesDatabase,
73
76
  } from '@crombolo/data'
74
77
  import {
75
78
  normaliseRedirectPath,
@@ -78,9 +81,12 @@ import {
78
81
  type RequestMember,
79
82
  type SiteServices,
80
83
  } from '@crombolo/render'
84
+ import { anonymiseProblems } from './anonymise-rules.ts'
85
+ import { declaredPermissions, gated, permissionProblems, waitingResponse } from './bundle-grants.ts'
81
86
  import type { BundleMedia, BundleMediaDeclaration } from './bundle-media.ts'
82
87
  import type { BundleForms } from './form-types.ts'
83
88
  import type { BundleIdentityProviders } from './identity-provider-overrides.ts'
89
+ import { type JobInfo, type JobSchedule, jobProblems, type OwnerJobs } from './owner-jobs.ts'
84
90
  import type { DeclaredRoute } from './routes.ts'
85
91
  import type { BundleEvents } from './webhooks.ts'
86
92
 
@@ -164,8 +170,6 @@ export interface BundleHost {
164
170
  log: BundleLog
165
171
  /** The identity providers the config declares, and an administrator's overrides of their settings (story 033). */
166
172
  identityProviders: BundleIdentityProviders
167
- /** The bundle's own tables, and only for a bundle that declares some. */
168
- tables: BundleTablesCapability
169
173
  /**
170
174
  * Media items in the folders the bundle declares, as the member a route was
171
175
  * given or the back-office user; refused on a public route (story 198).
@@ -208,19 +212,20 @@ export const BUNDLE_CAPABILITIES: readonly BundleCapability[] = [
208
212
  'redirects',
209
213
  'documents',
210
214
  'log',
211
- 'tables',
212
215
  'identityProviders',
213
216
  'media',
214
217
  ]
215
218
 
216
- /** What a handler is handed: the declared capabilities, with `tables` typed from the declaration. */
217
- export type HostFor<C extends BundleCapability, T extends BundleTables> = Pick<
218
- BundleHost,
219
- Exclude<C, 'tables'>
220
- > &
221
- ('tables' extends C
222
- ? { tables: T extends BundleTables<infer S> ? BundleTablesCapability<S> : never }
223
- : unknown)
219
+ /**
220
+ * What a handler is handed: the declared capabilities, and for a bundle that
221
+ * declares tables, `database`, typed from the declaration (story 189).
222
+ */
223
+ export type HostFor<C extends BundleCapability, T extends BundleTables> = Pick<BundleHost, C> & {
224
+ /** Only for a bundle that declares tables: a Kysely handle on them and nothing else. */
225
+ readonly database: TablesDatabase<T>
226
+ /** Only for a bundle that declares jobs: queue one, or read how one is going (story 187). */
227
+ readonly jobs: OwnerJobs
228
+ }
224
229
 
225
230
  /** A signed-in member as a member route is given them: nothing of the back office. */
226
231
  export interface BundleMember {
@@ -240,6 +245,8 @@ export type BundleCaller =
240
245
  | { readonly kind: 'backoffice'; readonly principal: Principal }
241
246
  | { readonly kind: 'member'; readonly member: BundleMember; readonly via: 'cookie' | 'token' }
242
247
  | { readonly kind: 'public' }
248
+ /** A background job (story 187): nobody, treated as the public. */
249
+ | { readonly kind: 'job' }
243
250
 
244
251
  /**
245
252
  * What a bundle's route handler is given besides 211's context: its declared
@@ -306,8 +313,24 @@ export interface ServerBundle<
306
313
  * to the chain by itself.
307
314
  */
308
315
  middleware?: Middleware<SiteServices, PublishedContent, RequestMember>
316
+ /**
317
+ * Its background jobs, by name (story 187): each `(payload, context)`, given
318
+ * its capabilities for no caller and its own `database`, as a public route
319
+ * would be, with `context.job` for its progress and its signal.
320
+ */
321
+ jobs?: Record<string, BundleJob<C, T>>
322
+ /** When its jobs run by themselves: cron expressions in a timezone. */
323
+ schedules?: readonly JobSchedule[]
309
324
  }
310
325
 
326
+ /** A bundle's background job (story 187). */
327
+ export type BundleJob<
328
+ C extends BundleCapability = BundleCapability,
329
+ T extends BundleTables = BundleTables,
330
+ // biome-ignore lint/suspicious/noExplicitAny: a payload is the bundle's to type
331
+ P = any,
332
+ > = (payload: P, context: { bundle: HostFor<C, T>; job: JobInfo }) => unknown
333
+
311
334
  /** A bundle as mounted, with the prefix its routes answer below. */
312
335
  export interface MountedBundle {
313
336
  id: string
@@ -369,9 +392,13 @@ export function validateServerBundles(
369
392
  problems.push(
370
393
  `Bundle "${label}" asked for the capability "${capability}", which no host offers.`,
371
394
  )
372
- if (bundle.capabilities.includes('tables') && !bundle.tables)
395
+ if ((bundle.capabilities as readonly string[]).includes('tables'))
396
+ problems.push(
397
+ `Bundle "${label}" asks for "tables", which is gone: declaring tables gives its handlers context.bundle.database (docs/bundles.md, Part 4).`,
398
+ )
399
+ if (bundle.tables && bundle.id === SITE_OWNER)
373
400
  problems.push(
374
- `Bundle "${label}" asked for the capability "tables", but declares no tables of its own.`,
401
+ `Bundle "${label}" declares tables under the id "${SITE_OWNER}", which names the site's own tables.`,
375
402
  )
376
403
  if (bundle.tables) {
377
404
  if (bundle.tables.id !== bundle.id)
@@ -379,8 +406,12 @@ export function validateServerBundles(
379
406
  `Bundle "${label}" declares its tables under the id "${bundle.tables.id}"; a bundle's tables are under its own id.`,
380
407
  )
381
408
  const owner = packages.find((pkg) => pkg.id === bundle.id)
382
- for (const problem of compileBundleTables(bundle.tables, owner?.version).problems)
409
+ const compiled = compileTables(bundle.tables, owner?.version)
410
+ for (const problem of compiled.problems)
383
411
  problems.push(`Bundle "${label}" tables: ${problem}.`)
412
+ if (owner?.field.anonymise !== undefined && compiled.problems.length === 0)
413
+ for (const problem of anonymiseProblems(owner.field.anonymise, compiled.schema))
414
+ problems.push(`Bundle "${label}"'s package.json: crombolo.${problem}.`)
384
415
  // Read by an operator's tooling before anything is installed, so it must
385
416
  // say what the plan does — derived, not asserted, as core's is.
386
417
  if (owner) {
@@ -391,13 +422,21 @@ export function validateServerBundles(
391
422
  )
392
423
  }
393
424
  }
425
+ if (!bundle.tables && packages.find((pkg) => pkg.id === bundle.id)?.field.anonymise)
426
+ problems.push(
427
+ `Bundle "${label}"'s package.json declares "crombolo.anonymise", and the bundle declares no tables for it to describe.`,
428
+ )
394
429
  for (const problem of mediaProblems(bundle))
395
430
  problems.push(`Bundle "${label}" media: ${problem}.`)
431
+ problems.push(...jobProblems(`Bundle "${label}"`, bundle.jobs, bundle.schedules))
432
+ {
433
+ const pkg = packages.find((candidate) => candidate.id === bundle.id)
434
+ if (pkg?.carries.server && Array.isArray(pkg.field.permissions))
435
+ problems.push(...permissionProblems(label, bundle.capabilities, declaredPermissions(pkg)))
436
+ }
396
437
  const owner = packages.find((pkg) => pkg.id === bundle.id)
397
438
  if (owner?.carries.server && (owner.field.schemaVersion ?? 1) < BUNDLE_SCHEMA_VERSION)
398
- problems.push(
399
- `Bundle "${label}" is written for bundle schema ${owner.field.schemaVersion ?? 1}; this release reads ${BUNDLE_SCHEMA_VERSION}. Its routes are route handlers since 0.37: see "Routes" in docs/bundles.md, then set "crombolo.schemaVersion": ${BUNDLE_SCHEMA_VERSION}.`,
400
- )
439
+ problems.push(`Bundle "${label}": ${schemaProblem(owner.field.schemaVersion ?? 1)}.`)
401
440
  const routes = new Set<string>()
402
441
  for (const route of bundle.routes ?? []) {
403
442
  if (!route || typeof route !== 'object' || !route.handlers || !route.options) {
@@ -634,10 +673,7 @@ export function createBundleRedirects(options: {
634
673
  * refuses a public caller. It is told the bundle too, for what it declared.
635
674
  */
636
675
  export type CallerCapabilities = {
637
- [K in Exclude<BundleCapability, 'tables'>]?: (
638
- caller: BundleCaller,
639
- bundle: ServerBundle,
640
- ) => BundleHost[K]
676
+ [K in BundleCapability]?: (caller: BundleCaller, bundle: ServerBundle) => BundleHost[K]
641
677
  }
642
678
 
643
679
  export interface ServerBundlesOptions {
@@ -648,13 +684,20 @@ export interface ServerBundlesOptions {
648
684
  coreVersion: string
649
685
  /** `<backoffice>/crombolo/api`, from `createBackOfficePaths`. */
650
686
  pluginApiPath: string
651
- host: Omit<BundleHost, 'tables' | 'media'> & { media?: BundleMedia }
687
+ host: Omit<BundleHost, 'media'> & { media?: BundleMedia }
652
688
  /** Capabilities built per request from the caller, in place of the ones in `host`. */
653
689
  callerHost?: CallerCapabilities
654
690
  /** Named per bundle, so a log line says which one wrote it. */
655
691
  log(bundleId: string): BundleLog
656
- /** A bundle's own tables, resolved against its schema alone; absent where none are offered. */
657
- tables?(bundle: ServerBundle): BundleTablesCapability | undefined
692
+ /** A bundle's own tables, on the connection that reaches only them; absent where none are. */
693
+ database?(bundle: ServerBundle): TablesDatabase | undefined
694
+ /**
695
+ * Whether a bundle is turned on: its grant covers what it declares (story
696
+ * 222). A bundle that is off answers every route as waiting. Absent, all are on.
697
+ */
698
+ isOn?(bundleId: string): boolean
699
+ /** A bundle's queue, recording who queued from the caller (story 187). */
700
+ jobs?(bundleId: string, queuedBy: string | null): OwnerJobs
658
701
  }
659
702
 
660
703
  /** Runs a route through 211's pipeline: the server's `routes.invoke`. */
@@ -683,8 +726,22 @@ export interface ServerBundles {
683
726
  ): Promise<Response | undefined>
684
727
  /** The bundles' site routes, for the server's route table, each given its bundle's capabilities. */
685
728
  siteRoutes(): DeclaredRoute[]
729
+ /** What a bundle's job is given: its capabilities for no caller, as on a public route (story 187). */
730
+ jobContext(bundleId: string): Pick<BundleHost, BundleCapability> | undefined
686
731
  }
687
732
 
733
+ const JOB_CALLER: BundleCaller = Object.freeze({ kind: 'job' })
734
+
735
+ /** Who queued a job, for administrators to read: it grants nothing. */
736
+ const queuedByOf = (caller: BundleCaller): string | null =>
737
+ caller.kind === 'member'
738
+ ? `member ${caller.member.username}`
739
+ : caller.kind === 'backoffice'
740
+ ? `user ${caller.principal.email}`
741
+ : caller.kind === 'job'
742
+ ? 'a job'
743
+ : 'a visitor'
744
+
688
745
  const freezeMember = (member: RequestMember): BundleMember =>
689
746
  Object.freeze({
690
747
  key: member.key,
@@ -728,39 +785,64 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
728
785
  }
729
786
  })
730
787
 
731
- // Built once per bundle, each over that bundle's schema alone.
732
- const tables = new Map(
733
- options.bundles
734
- .filter((bundle) => bundle.capabilities.includes('tables'))
735
- .map((bundle) => [bundle.id, options.tables?.(bundle)]),
736
- )
788
+ // Made once per bundle, at its first request, each on its own tables alone.
789
+ const databases = new Map<string, TablesDatabase>()
790
+ const databaseOf = (bundle: ServerBundle): TablesDatabase | undefined => {
791
+ if (!bundle.tables) return undefined
792
+ let opened = databases.get(bundle.id)
793
+ if (!opened) {
794
+ opened = options.database?.(bundle)
795
+ if (!opened) return undefined
796
+ databases.set(bundle.id, opened)
797
+ }
798
+ return opened
799
+ }
737
800
  /** Only the declared capabilities, frozen, so a handler cannot reach further. */
738
801
  const contextFor = (
739
802
  bundle: ServerBundle,
740
803
  caller: BundleCaller,
741
804
  ): Pick<BundleHost, BundleCapability> => {
742
805
  const host: Record<string, unknown> = {}
806
+ const declared = declaredPermissions(owners.get(bundle.id))
743
807
  for (const capability of bundle.capabilities) {
744
- const forCaller = capability === 'tables' ? undefined : options.callerHost?.[capability]
745
- host[capability] = forCaller
808
+ const forCaller = options.callerHost?.[capability]
809
+ const given = forCaller
746
810
  ? forCaller(caller, bundle)
747
811
  : capability === 'log'
748
812
  ? (logs.get(bundle.id) as BundleLog)
749
- : capability === 'tables'
750
- ? tables.get(bundle.id)
751
- : options.host[capability]
813
+ : options.host[capability]
814
+ // Only what its declared permissions allow (story 222).
815
+ host[capability] = given ? gated(bundle.id, capability, given, declared) : given
752
816
  }
817
+ const database = databaseOf(bundle)
818
+ if (database) host.database = database
819
+ if (bundle.jobs && options.jobs) host.jobs = options.jobs(bundle.id, queuedByOf(caller))
753
820
  return Object.freeze(host) as Pick<BundleHost, BundleCapability>
754
821
  }
755
822
 
823
+ /** A site route that answers as waiting while its bundle is off. */
824
+ const whileOn = (bundleId: string, route: SiteRoute): SiteRoute => {
825
+ const isOn = options.isOn
826
+ if (!isOn) return route
827
+ const handlers: SiteRoute['handlers'] = {}
828
+ for (const [method, handler] of Object.entries(route.handlers))
829
+ handlers[method as RouteMethod] = (request, context) =>
830
+ isOn(bundleId) ? handler(request, context) : waitingResponse(bundleId)
831
+ return { ...route, handlers }
832
+ }
833
+
756
834
  return {
757
835
  mounted,
758
836
  basePath,
837
+ jobContext(bundleId) {
838
+ const bundle = byId.get(bundleId)
839
+ return bundle ? contextFor(bundle, JOB_CALLER) : undefined
840
+ },
759
841
  siteRoutes() {
760
842
  return options.bundles.flatMap((bundle) =>
761
843
  (bundle.routes ?? []).filter(onSite).map(
762
844
  (route): DeclaredRoute => ({
763
- route: route as SiteRoute,
845
+ route: whileOn(bundle.id, route as SiteRoute),
764
846
  owner: `the bundle ${bundle.id}`,
765
847
  extra: ({ member, via }) => {
766
848
  const caller: BundleCaller = member
@@ -792,6 +874,7 @@ export function createServerBundles(options: ServerBundlesOptions): ServerBundle
792
874
  for (const route of (bundle.routes ?? []).filter((candidate) => !onSite(candidate))) {
793
875
  const params = matchRoute(route.path, requested)
794
876
  if (!params) continue
877
+ if (options.isOn && !options.isOn(bundle.id)) return waitingResponse(bundle.id)
795
878
  const caller: BundleCaller = Object.freeze({ kind: 'backoffice', principal })
796
879
  return invoke(
797
880
  { route: route as SiteRoute, owner: `the bundle ${bundle.id}` },
@@ -4,7 +4,7 @@
4
4
  * `<Breadcrumb model={model} nav={nav} />`. `Empty` is also the skeleton a new
5
5
  * component starts with.
6
6
  */
7
- import type { Snippet } from '@crombolo/api-management'
7
+ import type { Snippet } from '@crombolo/api-management/domain'
8
8
 
9
9
  const IMPORTS = "import type { PageProps } from '@crombolo/crombolo'\n\n"
10
10
 
package/src/components.ts CHANGED
@@ -245,7 +245,10 @@ export function withAwaitHint(line: string): string {
245
245
  * `typescript` is not a dependency of crombolo — a site that has not installed
246
246
  * it is told so rather than being made to carry one.
247
247
  */
248
- async function checkTypes(siteDir: string): Promise<ComponentCheckReport['types']> {
248
+ export async function checkTypes(
249
+ siteDir: string,
250
+ options: { signal?: AbortSignal } = {},
251
+ ): Promise<ComponentCheckReport['types']> {
249
252
  const tsc = join(siteDir, 'node_modules', 'typescript', 'bin', 'tsc')
250
253
  if (!existsSync(tsc))
251
254
  return {
@@ -261,6 +264,8 @@ async function checkTypes(siteDir: string): Promise<ComponentCheckReport['types'
261
264
  stdout: 'pipe',
262
265
  stderr: 'pipe',
263
266
  })
267
+ // A newer change has made this check's answer stale (story 214).
268
+ options.signal?.addEventListener('abort', () => proc.kill(), { once: true })
264
269
  const [out, err] = await Promise.all([
265
270
  new Response(proc.stdout).text(),
266
271
  new Response(proc.stderr).text(),
package/src/config.ts CHANGED
@@ -22,8 +22,10 @@ import type { GitConfig } from './git-routes.ts'
22
22
  import { checkHost, type HostConfig } from './host-token.ts'
23
23
  import { checkIdentityProviders, type IdentityProvider } from './identity-providers.ts'
24
24
  import type { MediaStore } from './media-store.ts'
25
+ import type { JobSchedule } from './owner-jobs.ts'
25
26
  import type { SchemaStore } from './schema-store.ts'
26
27
  import { setting } from './settings.ts'
28
+ import type { SiteDatabaseConfig, SiteQueryModules } from './site-queries.ts'
27
29
 
28
30
  /**
29
31
  * Runtime settings for a site. Umbraco's equivalents live in appsettings.json;
@@ -31,7 +33,7 @@ import { setting } from './settings.ts'
31
33
  * `loadConfig` fills anything unset from the environment.
32
34
  */
33
35
  /** What a process serves; see `CromboloConfig.role`. */
34
- export const SERVER_ROLES = ['all', 'api', 'web'] as const
36
+ export const SERVER_ROLES = ['all', 'api', 'web', 'worker'] as const
35
37
 
36
38
  export type ServerRole = (typeof SERVER_ROLES)[number]
37
39
 
@@ -121,6 +123,12 @@ export interface CromboloConfig {
121
123
  */
122
124
  signalRSkipNegotiation: boolean
123
125
  development: boolean
126
+ /**
127
+ * Open pages reload when the views, the schema or the content change, and
128
+ * show the background type check's findings (story 214). On in development,
129
+ * except under `bun test`.
130
+ */
131
+ liveReload: boolean
124
132
  /**
125
133
  * Whether the cache-busted asset path may be cached immutably. Defaults to
126
134
  * `!development`.
@@ -233,12 +241,20 @@ export interface CromboloConfig {
233
241
  * neither migrates nor seeds, and refuses to boot against a database that
234
242
  * has not been migrated yet — that is `api`'s job.
235
243
  *
236
- * Both halves still hold a database connection and stay coherent through
244
+ * - `worker` runs the background jobs and nothing else (story 223): no
245
+ * pages, back office or APIs, only `/health`. Like `web` it never migrates.
246
+ *
247
+ * Every split node holds a database connection and stays coherent through
237
248
  * `cache_instruction`, exactly as a load-balanced set already does. Splitting
238
249
  * needs Postgres: `locks.ts`'s SQLite manager is an in-process queue, so it
239
250
  * coordinates nothing between processes.
240
251
  */
241
252
  role: ServerRole
253
+ /**
254
+ * Whether an `all` or `api` node runs the background jobs (`CROMBOLO_JOBS`).
255
+ * False leaves them to a `worker`; the node still queues them.
256
+ */
257
+ runJobs: boolean
242
258
  /**
243
259
  * Where the schema files live, when not in `schemaDir` on this disk. Unset means
244
260
  * the directory, which is what a repository checkout wants. Set — with
@@ -414,6 +430,25 @@ export interface CromboloConfig {
414
430
  * (`bundles.ts`, `docs/bundles.md`).
415
431
  */
416
432
  bundles: ServerBundle[]
433
+ /**
434
+ * The site's own tables (story 189): `defineSiteTables` steps, migrated with
435
+ * crombolo's, and what an anonymised export may carry of each table.
436
+ * docs/data-model.md, "Custom tables".
437
+ */
438
+ database?: SiteDatabaseConfig
439
+ /**
440
+ * The site's named queries (story 189): modules, each export a query run as
441
+ * `site().queries.<module>.<export>(…)` against the site's own tables.
442
+ */
443
+ queries?: SiteQueryModules
444
+ /**
445
+ * The site's background jobs (story 187): modules, each export a job queued
446
+ * as `site().jobs.enqueue('<module>.<export>', payload)` and run on a node
447
+ * that owns writes. docs/rendering.md, "Background jobs".
448
+ */
449
+ jobs?: SiteQueryModules
450
+ /** When the site's jobs run by themselves: cron expressions in a timezone. */
451
+ schedules?: JobSchedule[]
417
452
  /**
418
453
  * Package names this installation provides to every site it runs, rather
419
454
  * than the site choosing them (story 177): a whole-site file leaves them out
@@ -533,6 +568,22 @@ function roleFromEnvironment(value: string | undefined): ServerRole {
533
568
  return value
534
569
  }
535
570
 
571
+ function jobsFromEnvironment(value: string | undefined): boolean {
572
+ if (value === undefined || value === '' || value === 'on') return true
573
+ if (value === 'off') return false
574
+ throw new Error(`CROMBOLO_JOBS must be on or off, not '${value}'.`)
575
+ }
576
+
577
+ /** A node told to leave jobs alone, or a worker on a database it cannot share, is refused. */
578
+ function assertJobs(config: Pick<CromboloConfig, 'role' | 'runJobs' | 'dialect'>): void {
579
+ if (!config.runJobs && (config.role === 'web' || config.role === 'worker'))
580
+ throw new Error(
581
+ `CROMBOLO_JOBS=off applies to an api or all node; a ${config.role} node ${config.role === 'web' ? 'never runs jobs' : 'only runs jobs'}.`,
582
+ )
583
+ if (config.role === 'worker' && config.dialect !== 'postgres')
584
+ throw new Error('A worker needs Postgres: SQLite cannot be shared between processes.')
585
+ }
586
+
536
587
  /** Which page answers an address nothing else does, optionally for one hostname or language. */
537
588
  export interface NotFoundRule {
538
589
  /** The page's key. */
@@ -672,6 +723,7 @@ export function loadConfig(
672
723
  schemaRevision: setting('CROMBOLO_SCHEMA_REVISION') ?? DEFAULTS.schemaRevision,
673
724
  nodeId: setting('CROMBOLO_NODE_ID') ?? `${hostname()}:${process.pid}`,
674
725
  role: roleFromEnvironment(setting('CROMBOLO_ROLE')),
726
+ runJobs: jobsFromEnvironment(setting('CROMBOLO_JOBS')),
675
727
  git: undefined,
676
728
  schemaStore: undefined,
677
729
  schemaCacheDir: setting('CROMBOLO_SCHEMA_CACHE_DIR') ?? join(tmpdir(), 'crombolo-schema'),
@@ -755,6 +807,7 @@ export function loadConfig(
755
807
  runtimeInstalls: setting('CROMBOLO_RUNTIME_INSTALLS') !== 'false',
756
808
  // Resolved again below, once it is known whether this is development.
757
809
  errors: { showDetails: envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ?? false },
810
+ liveReload: envFlag(setting('CROMBOLO_LIVE_RELOAD')) ?? false,
758
811
  seo: stripUndefined({
759
812
  sitemap: envFlag(setting('CROMBOLO_SITEMAP')),
760
813
  indexable: envFlag(setting('CROMBOLO_INDEXABLE')),
@@ -813,6 +866,10 @@ export function loadConfig(
813
866
  envFlag(setting('CROMBOLO_SHOW_ERROR_DETAILS')) ??
814
867
  merged.development,
815
868
  }
869
+ merged.liveReload =
870
+ overrides.liveReload ??
871
+ envFlag(setting('CROMBOLO_LIVE_RELOAD')) ??
872
+ (merged.development && setting('NODE_ENV') !== 'test')
816
873
  checkApiClient(merged.apiClient)
817
874
  checkHost(merged.host)
818
875
  // The key itself is refused, so a config left over from before says so rather
@@ -873,6 +930,7 @@ export function loadConfig(
873
930
  // Checked on the merged value, so a typo in `crombolo.config.ts` is refused on
874
931
  // the same terms as one in the environment.
875
932
  assertRole(merged.role)
933
+ assertJobs(merged)
876
934
  return merged
877
935
  }
878
936
 
@@ -918,7 +976,7 @@ export function describeDatabase(
918
976
  }
919
977
  }
920
978
 
921
- export const VERSION = '0.37.0'
979
+ export const VERSION = '0.38.1'
922
980
 
923
981
  /** A whole number of seconds from the environment; undefined when unset or not one. */
924
982
  /** A positive number from a setting, else the default. */
@@ -9,7 +9,7 @@
9
9
  * publish arrive as one e-mail, and a background job on the nodes that run
10
10
  * jobs sends them; each person's rows are claimed by one node.
11
11
  */
12
- import type { RaisedContentChange } from '@crombolo/api-management'
12
+ import type { RaisedContentChange } from '@crombolo/api-management/domain'
13
13
  import { hasPathAccess, isValidEmail, ObjectTypes, permissionsForPath } from '@crombolo/core'
14
14
  import {
15
15
  type ContentNotification,
@@ -102,10 +102,13 @@ export function createContentNotifier(db: Db, options: ContentNotifierOptions):
102
102
  }
103
103
  let summary = detail ?? null
104
104
  if (change.withDescendants) {
105
- const [row] = await on.query<{ n: number }>(
106
- 'SELECT COUNT(*) AS n FROM node WHERE path LIKE ? AND node_object_type = ? AND trashed = ?',
107
- [`${node.path},%`, ObjectTypes.Document, on.dialect.boolValue(false)],
108
- )
105
+ const row = await on.q
106
+ .selectFrom('node')
107
+ .select((eb) => eb.fn.countAll().as('n'))
108
+ .where('path', 'like', `${node.path},%`)
109
+ .where('node_object_type', '=', ObjectTypes.Document)
110
+ .where('trashed', '=', on.dialect.boolValue(false) as boolean)
111
+ .executeTakeFirst()
109
112
  const under = Number(row?.n ?? 0)
110
113
  if (under > 0) summary = `and ${under} page${under === 1 ? '' : 's'} under it`
111
114
  }
@@ -136,10 +139,11 @@ export function createContentNotifier(db: Db, options: ContentNotifierOptions):
136
139
  (id) => id !== actorId,
137
140
  )
138
141
  if (userIds.length === 0) continue
139
- const keys = await on.query<{ key: string }>(
140
- `SELECT key FROM user_account WHERE id IN (${userIds.map(() => '?').join(', ')})`,
141
- userIds,
142
- )
142
+ const keys = await on.q
143
+ .selectFrom('user_account')
144
+ .select('key')
145
+ .where('id', 'in', userIds)
146
+ .execute()
143
147
  for (const { key } of keys)
144
148
  rows.push({
145
149
  recipientUserKey: String(key),
@@ -6,31 +6,17 @@
6
6
  * the running nodes instead.
7
7
  */
8
8
 
9
- import {
10
- createDocumentOperations,
11
- createMediaOperations,
12
- type DocumentOperations,
13
- type EventSink,
14
- type MediaOperations,
15
- } from '@crombolo/content'
16
- import {
17
- appendCacheInstruction,
18
- currentSchemaState,
19
- type Db,
20
- RedirectRepository,
21
- } from '@crombolo/data'
9
+ import type { DocumentOperations, EventSink, MediaOperations } from '@crombolo/content'
10
+ import { currentSchemaState, type Db } from '@crombolo/data'
22
11
  import { PublishedCache } from '@crombolo/render'
23
12
  import { createPublishedContentSource } from './adapters/documents.ts'
24
- import { createApprovals } from './approvals.ts'
13
+ import { backOfficeUrl } from './back-office-url.ts'
25
14
  import type { CromboloConfig } from './config.ts'
26
- import { createContentEventSink, createMediaEventSink } from './content-events.ts'
15
+ import { createContentEventSink } from './content-events.ts'
27
16
  import { createContentNotifier } from './content-notifications.ts'
28
- import { writeDomainsFor } from './domains.ts'
29
17
  import { resolveEmailPort } from './email.ts'
30
- import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
31
18
  import { MediaFileStore, mediaStoreFor } from './media-files.ts'
32
- import { approvalsGate, backOfficeUrl } from './ports.ts'
33
- import { createRedirectTracker } from './redirects.ts'
19
+ import { createNodeOperations } from './node-operations.ts'
34
20
  import { createWebhookService } from './webhooks.ts'
35
21
 
36
22
  export interface SiteOperations {
@@ -57,45 +43,21 @@ export async function siteDocumentOperations(
57
43
  // Recorded only: a running server's dispatcher sends what this records (story 171).
58
44
  const events = createContentEventSink({ webhooks, notifier })
59
45
  const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
60
- let operations: DocumentOperations | undefined
61
- const approvals = createApprovals({
46
+ // The routes a redirect is tracked from are read from this cache once a change
47
+ // has committed, so the change drops it first.
48
+ const { documents: operations } = createNodeOperations({
62
49
  db,
50
+ config,
51
+ cache,
63
52
  nodeState,
53
+ nodeId: config.nodeId,
54
+ instructedBy: `cli:${config.nodeId}`,
55
+ mediaFiles: new MediaFileStore(await mediaStoreFor(config)),
64
56
  email,
65
- backOfficeUrl: backOfficeUrl(config),
66
57
  notifier,
67
- publisher: {
68
- publish: (key, cultures, actor, approvedHead) =>
69
- (operations as DocumentOperations).publish(actor, key, {
70
- cultures,
71
- expectedHead: approvedHead,
72
- }),
73
- unpublish: (key, cultures, actor) =>
74
- (operations as DocumentOperations).unpublish(actor, key, cultures),
75
- },
76
- })
77
- operations = createDocumentOperations({
78
- db,
79
- repository: { nodeState, nodeId: config.nodeId },
80
- events,
81
- approvals: approvalsGate(approvals),
82
- redirects: createRedirectTracker({
83
- cache,
84
- redirects: new RedirectRepository(db),
85
- enabled: config.trackRedirects,
86
- instruct: () =>
87
- appendCacheInstruction(db, {
88
- kind: 'content',
89
- payload: { redirects: true },
90
- by: `cli:${config.nodeId}`,
91
- }),
92
- }),
93
- // The routes a redirect is tracked from are read from this cache once a change
94
- // has committed, so the change has to drop it first.
95
- onChange: () => cache.invalidate(),
96
- afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
97
- refusalReason: (error) =>
98
- error instanceof TemporaryFileMissingError ? error.message : undefined,
58
+ contentEvents: events,
59
+ webhooks,
60
+ backOfficeUrl: backOfficeUrl(config),
99
61
  })
100
62
  return { operations, events }
101
63
  }
@@ -118,16 +80,12 @@ export async function siteMediaOperations(
118
80
  secretKey: config.secretKey,
119
81
  bundles: config.bundles,
120
82
  })
121
- return createMediaOperations({
83
+ return createNodeOperations({
122
84
  db,
123
- repository: {
124
- nodeState: { version: state.version, revision: state.revision },
125
- nodeId: config.nodeId,
126
- valueIntake: createFileIntake(files),
127
- },
128
- events: createMediaEventSink({ webhooks }),
129
- files,
130
- refusalReason: (error) =>
131
- error instanceof TemporaryFileMissingError ? error.message : undefined,
132
- })
85
+ config,
86
+ nodeState: { version: state.version, revision: state.revision },
87
+ nodeId: config.nodeId,
88
+ mediaFiles: files,
89
+ webhooks,
90
+ }).media
133
91
  }