@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.
Files changed (80) 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 +250 -0
  30. package/src/bundle-install.ts +13 -2
  31. package/src/bundle-media.ts +12 -11
  32. package/src/bundles.ts +131 -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 +675 -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/routes.ts +18 -1
  61. package/src/schema.ts +8 -3
  62. package/src/seed/compile.ts +7 -5
  63. package/src/seed/export.ts +6 -4
  64. package/src/seo.ts +2 -2
  65. package/src/server.ts +328 -452
  66. package/src/settings.ts +18 -2
  67. package/src/site-data.ts +195 -0
  68. package/src/site-file.ts +30 -4
  69. package/src/site-queries.ts +140 -0
  70. package/src/site-replace.ts +25 -19
  71. package/src/site-sections.ts +1 -1
  72. package/src/site-services.ts +23 -6
  73. package/src/status-pages.ts +19 -5
  74. package/src/status.ts +11 -9
  75. package/src/url-settings.ts +1 -2
  76. package/src/webhook-files.ts +1 -1
  77. package/src/webhooks.ts +31 -23
  78. package/src/worker-watch.ts +73 -0
  79. package/src/worker.ts +138 -0
  80. package/src/bundle-tables.ts +0 -161
@@ -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.39.0'
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
  }
@@ -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,