@crombolo/server 0.22.0 → 0.23.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.22.0",
3
+ "version": "0.23.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,17 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
33
- "@crombolo/api-delivery": "0.22.0",
34
- "@crombolo/api-management": "0.22.0",
35
- "@crombolo/assistant": "0.22.0",
36
- "@crombolo/auth": "0.22.0",
37
- "@crombolo/backoffice-host": "0.22.0",
38
- "@crombolo/contracts": "0.22.0",
39
- "@crombolo/core": "0.22.0",
40
- "@crombolo/data": "0.22.0",
41
- "@crombolo/render": "0.22.0",
42
- "@crombolo/schema": "0.22.0",
43
- "@crombolo/transfer": "0.22.0",
33
+ "@crombolo/api-delivery": "0.23.0",
34
+ "@crombolo/api-management": "0.23.0",
35
+ "@crombolo/assistant": "0.23.0",
36
+ "@crombolo/auth": "0.23.0",
37
+ "@crombolo/backoffice-host": "0.23.0",
38
+ "@crombolo/content": "0.23.0",
39
+ "@crombolo/contracts": "0.23.0",
40
+ "@crombolo/core": "0.23.0",
41
+ "@crombolo/data": "0.23.0",
42
+ "@crombolo/render": "0.23.0",
43
+ "@crombolo/schema": "0.23.0",
44
+ "@crombolo/transfer": "0.23.0",
44
45
  "@logtape/logtape": "^2.3.8"
45
46
  }
46
47
  }
package/src/approvals.ts CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import type { Principal } from '@crombolo/api-management'
13
+ import { type Actor, systemActor } from '@crombolo/content'
13
14
  import {
14
15
  approvalsNeeded,
15
16
  DocumentPermissions,
@@ -45,13 +46,16 @@ import type { EmailPort } from './email.ts'
45
46
 
46
47
  /** What publishing and unpublishing go through when approval says yes. */
47
48
  export interface ApprovalPublisher {
49
+ /** As the site, on the approver's behalf: the gate has been passed by approving. */
48
50
  publish(
49
51
  key: string,
50
52
  cultures: string[] | null,
53
+ actor: Actor,
51
54
  ): Promise<{ ok: true } | { ok: false; reason: string }>
52
55
  unpublish(
53
56
  key: string,
54
57
  cultures: string[] | null,
58
+ actor: Actor,
55
59
  ): Promise<{ ok: true } | { ok: false; reason: string }>
56
60
  }
57
61
 
@@ -135,24 +139,24 @@ export interface Approvals {
135
139
  workflows(): Promise<StoredWorkflow[]>
136
140
  /** Undefined when the caller may go ahead; otherwise why not. */
137
141
  publishRefusal(
138
- principal: Principal,
142
+ principal: Principal | undefined,
139
143
  key: string,
140
144
  action: ApprovalAction,
141
145
  ): Promise<string | undefined>
142
146
  /** A branch publish: the root and every page below it. */
143
- branchRefusal(principal: Principal, key: string): Promise<string | undefined>
147
+ branchRefusal(principal: Principal | undefined, key: string): Promise<string | undefined>
144
148
  /** For a page being created and published at once: by its parent and type. */
145
149
  newPageRefusal(
146
- principal: Principal,
150
+ principal: Principal | undefined,
147
151
  parentKey: string | null,
148
152
  contentTypeKey: string,
149
153
  ): Promise<string | undefined>
150
154
  /** Undefined when the save may go ahead; otherwise why not. */
151
- beforeSave(principal: Principal, key: string): Promise<string | undefined>
155
+ beforeSave(principal: Principal | undefined, key: string): Promise<string | undefined>
152
156
  /** What the save does to a waiting request, once it has gone through. */
153
- afterSave(principal: Principal, key: string): Promise<void>
157
+ afterSave(principal: Principal | undefined, key: string): Promise<void>
154
158
  /** A direct publish, schedule or unpublish by someone allowed to: a scheduled request ends. */
155
- afterDirectPublish(principal: Principal, key: string, what: string): Promise<void>
159
+ afterDirectPublish(principal: Principal | undefined, key: string, what: string): Promise<void>
156
160
  /** The schedule job fired one of a page's schedules: a scheduled request goes on or ends. */
157
161
  scheduleFired(
158
162
  key: string,
@@ -292,11 +296,17 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
292
296
  const groupAliases = async (principal: Principal): Promise<Set<string>> =>
293
297
  new Set((await groups.byKeys(principal.groupKeys)).map((g) => g.alias))
294
298
 
295
- const mayPublish = (principal: Principal, facts: PageFacts, action: ApprovalAction): boolean =>
296
- principal.isAdmin ||
297
- permissionsForPath(principal.groups, facts.chain).has(
298
- action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
299
- )
299
+ /** A local operator (no principal) holds no publishing rights of their own. */
300
+ const mayPublish = (
301
+ principal: Principal | undefined,
302
+ facts: PageFacts,
303
+ action: ApprovalAction,
304
+ ): boolean =>
305
+ principal !== undefined &&
306
+ (principal.isAdmin ||
307
+ permissionsForPath(principal.groups, facts.chain).has(
308
+ action === 'publish' ? DocumentPermissions.Publish : DocumentPermissions.Unpublish,
309
+ ))
300
310
 
301
311
  /**
302
312
  * Refuses, with a 403, a caller who cannot reach the page through their start
@@ -315,7 +325,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
315
325
  workflow !== undefined && (action === 'publish' || workflow.unpublish)
316
326
 
317
327
  const refusalFor = (
318
- principal: Principal,
328
+ principal: Principal | undefined,
319
329
  facts: PageFacts,
320
330
  workflow: SchemaWorkflow | undefined,
321
331
  action: ApprovalAction,
@@ -576,22 +586,22 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
576
586
  : undefined
577
587
  }
578
588
  if (cultures !== undefined) {
589
+ // As the site, on the approver's behalf; the publish raises the notification, with this note.
590
+ const actor = systemActor('Approval', {
591
+ source: principal ? 'request' : 'job',
592
+ user: principal ? { id: principal.id, name: principal.name } : undefined,
593
+ note: `approved through "${request.workflow.name}"`,
594
+ })
579
595
  const result =
580
596
  request.action === 'publish'
581
- ? await options.publisher.publish(request.nodeKey, cultures)
582
- : await options.publisher.unpublish(request.nodeKey, cultures)
597
+ ? await options.publisher.publish(request.nodeKey, cultures, actor)
598
+ : await options.publisher.unpublish(request.nodeKey, cultures, actor)
583
599
  if (!result.ok) return unpublishable(request, facts, result.reason)
584
600
  await repo.record(request.id, {
585
601
  kind: request.action === 'publish' ? 'published' : 'unpublished',
586
602
  userKey: principal?.id ?? null,
587
603
  comment: passed ? 'the requested time had passed when it was approved' : null,
588
604
  })
589
- if (request.action === 'publish')
590
- await options.notifier?.raise(
591
- { actions: ['Umb.Document.Publish'], key: request.nodeKey, keyKind: 'document' },
592
- principal ? { key: principal.id, name: principal.name } : null,
593
- `approved through "${request.workflow.name}"`,
594
- )
595
605
  }
596
606
  if (later.length + expires.length > 0)
597
607
  await documents().setSchedule(request.nodeKey, [...later, ...expires])
@@ -774,7 +784,7 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
774
784
 
775
785
  async beforeSave(principal, key) {
776
786
  const request = await requests().openFor(key)
777
- if (!request || principal.isAdmin) return undefined
787
+ if (!request || principal?.isAdmin) return undefined
778
788
  const edit = request.workflow.onEdit
779
789
  if (request.state === 'scheduled') {
780
790
  if (edit === 'lock' || edit === 'lock-after-first-approval')
@@ -800,18 +810,18 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
800
810
  ?.head ?? null
801
811
  if (head === request.eventId) return
802
812
  // Administrators may always edit; the request goes on, on what they saved.
803
- if (!principal.isAdmin && request.workflow.onEdit === 'withdraw') {
813
+ if (!principal?.isAdmin && request.workflow.onEdit === 'withdraw') {
804
814
  await repo.setState(request.id, 'withdrawn')
805
815
  await repo.record(request.id, {
806
816
  kind: 'withdrawn',
807
- userKey: principal.id,
817
+ userKey: principal?.id ?? null,
808
818
  comment: 'the page was changed after it was sent',
809
819
  })
810
820
  if (request.state === 'scheduled') await clearSchedule(request)
811
821
  return
812
822
  }
813
823
  await repo.setEvent(request.id, head)
814
- await repo.record(request.id, { kind: 'edited', userKey: principal.id })
824
+ await repo.record(request.id, { kind: 'edited', userKey: principal?.id ?? null })
815
825
  },
816
826
 
817
827
  async send(principal, key, action, cultures, comment, schedule) {
@@ -1010,8 +1020,8 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
1010
1020
  await repo.setState(request.id, 'superseded')
1011
1021
  await repo.record(request.id, {
1012
1022
  kind: 'superseded',
1013
- userKey: principal.id,
1014
- comment: `${principal.name} ${what} directly`,
1023
+ userKey: principal?.id ?? null,
1024
+ comment: `${principal?.name ?? 'Someone at the command line'} ${what} directly`,
1015
1025
  })
1016
1026
  await auditStep(
1017
1027
  principal,
package/src/config.ts CHANGED
@@ -788,7 +788,7 @@ export function describeDatabase(
788
788
  }
789
789
  }
790
790
 
791
- export const VERSION = '0.22.0'
791
+ export const VERSION = '0.23.0'
792
792
 
793
793
  /** A whole number of seconds from the environment; undefined when unset or not one. */
794
794
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Where document operations announce what they did (story 170): the audit log,
3
+ * webhooks, the people subscribed to a page, and — on a server — the live
4
+ * backoffice. The command line wires the same sink without the live part, so a
5
+ * change records and raises the same things wherever it was started.
6
+ */
7
+ import {
8
+ actorName,
9
+ actorNote,
10
+ actorUserKey,
11
+ auditEntryFor,
12
+ type EventSink,
13
+ liveEventsFor,
14
+ notificationFor,
15
+ webhookFor,
16
+ } from '@crombolo/content'
17
+ import { AuditLog, type Db } from '@crombolo/data'
18
+ import { recordAudit } from './adapters/audit.ts'
19
+ import type { ContentNotifier } from './content-notifications.ts'
20
+ import { logger } from './logging.ts'
21
+ import type { WebhookService } from './webhooks.ts'
22
+
23
+ const log = logger('Content')
24
+
25
+ export interface ContentEventSinkOptions {
26
+ db: Db
27
+ webhooks?: Pick<WebhookService, 'raise'>
28
+ notifier?: Pick<ContentNotifier, 'raise'>
29
+ /** Tells an open backoffice what changed: a server's event hub; absent on the command line. */
30
+ live?(event: ReturnType<typeof liveEventsFor>[number]): void
31
+ }
32
+
33
+ export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
34
+ const audit = new AuditLog(options.db)
35
+ const nameOf = async (entityType: string, key: string) => {
36
+ try {
37
+ return await audit.describe(entityType, key)
38
+ } catch {
39
+ return { entityType, entityKey: key, entityName: null }
40
+ }
41
+ }
42
+ return {
43
+ async emit(event, actor) {
44
+ const entry = auditEntryFor(event, actor)
45
+ // A deleted page cannot be named after it went: the operation read its name first.
46
+ const subject =
47
+ event.type === 'deleted'
48
+ ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
49
+ : entry.entityKey
50
+ ? await nameOf(entry.entityType, entry.entityKey)
51
+ : undefined
52
+ await recordAudit(options.db, {
53
+ ...entry,
54
+ entityType: subject?.entityType ?? entry.entityType,
55
+ entityKey: subject?.entityKey ?? entry.entityKey,
56
+ entityName: subject?.entityName ?? null,
57
+ })
58
+ // Queued and sent after: a slow receiver or an e-mail never holds the change up.
59
+ const hook = webhookFor(event)
60
+ if (hook)
61
+ void options.webhooks
62
+ ?.raise(hook)
63
+ .catch((error: unknown) =>
64
+ log.error('Could not queue the {alias} webhook: {error}', { alias: hook.alias, error }),
65
+ )
66
+ const change = notificationFor(event)
67
+ if (change)
68
+ void options.notifier
69
+ ?.raise(change, { key: actorUserKey(actor), name: actorName(actor) }, actorNote(actor))
70
+ .catch((error: unknown) =>
71
+ log.error('Could not queue change notifications: {error}', { error }),
72
+ )
73
+ for (const live of liveEventsFor(event)) options.live?.(live)
74
+ },
75
+ }
76
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Document operations for a process that is not serving requests — the command
3
+ * line (story 170). The same rules and the same announcements as the server's:
4
+ * approvals, redirect tracking, the audit log, webhooks and change notifications.
5
+ * What it cannot do is refresh an open backoffice; its cache instructions tell
6
+ * the running nodes instead.
7
+ */
8
+
9
+ import {
10
+ createDocumentOperations,
11
+ type DocumentOperations,
12
+ type EventSink,
13
+ } from '@crombolo/content'
14
+ import { currentSchemaState, type Db, RedirectRepository } from '@crombolo/data'
15
+ import { PublishedCache } from '@crombolo/render'
16
+ import { createPublishedContentSource } from './adapters/documents.ts'
17
+ import { createApprovals } from './approvals.ts'
18
+ import type { CromboloConfig } from './config.ts'
19
+ import { createContentEventSink } from './content-events.ts'
20
+ import { createContentNotifier } from './content-notifications.ts'
21
+ import { writeDomainsFor } from './domains.ts'
22
+ import { resolveEmailPort } from './email.ts'
23
+ import { TemporaryFileMissingError } from './file-intake.ts'
24
+ import { approvalsGate, backOfficeUrl } from './ports.ts'
25
+ import { createRedirectTracker } from './redirects.ts'
26
+ import { createWebhookService } from './webhooks.ts'
27
+
28
+ export interface SiteOperations {
29
+ operations: DocumentOperations
30
+ /** The sink they announce through, for a caller that adds its own steps. */
31
+ events: EventSink
32
+ }
33
+
34
+ export async function siteDocumentOperations(
35
+ db: Db,
36
+ config: CromboloConfig,
37
+ ): Promise<SiteOperations> {
38
+ const state = await currentSchemaState(db)
39
+ const nodeState = { version: state.version, revision: state.revision }
40
+ const email = resolveEmailPort(config)
41
+ const notifier = createContentNotifier(db, { canSend: Boolean(email) })
42
+ const webhooks = createWebhookService({
43
+ db,
44
+ schemaDir: config.schemaDir,
45
+ filesWritable: config.schemaWritable,
46
+ secretKey: config.secretKey,
47
+ bundles: config.bundles,
48
+ })
49
+ const events = createContentEventSink({ db, webhooks, notifier })
50
+ const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
51
+ let operations: DocumentOperations | undefined
52
+ const approvals = createApprovals({
53
+ db,
54
+ nodeState,
55
+ email,
56
+ backOfficeUrl: backOfficeUrl(config),
57
+ notifier,
58
+ publisher: {
59
+ publish: (key, cultures, actor) =>
60
+ (operations as DocumentOperations).publish(actor, key, { cultures }),
61
+ unpublish: (key, cultures, actor) =>
62
+ (operations as DocumentOperations).unpublish(actor, key, cultures),
63
+ },
64
+ })
65
+ operations = createDocumentOperations({
66
+ db,
67
+ repository: { nodeState, nodeId: config.nodeId },
68
+ events,
69
+ approvals: approvalsGate(approvals),
70
+ redirects: createRedirectTracker({
71
+ cache,
72
+ redirects: new RedirectRepository(db),
73
+ enabled: config.trackRedirects,
74
+ }),
75
+ afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
76
+ refusalReason: (error) =>
77
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
78
+ })
79
+ return { operations, events }
80
+ }
package/src/domains.ts CHANGED
@@ -16,9 +16,11 @@ import { existsSync, readFileSync } from 'node:fs'
16
16
  import { join } from 'node:path'
17
17
  import { ObjectTypes } from '@crombolo/core'
18
18
  import {
19
+ appendCacheInstruction,
19
20
  type Db,
20
21
  DocumentRepository,
21
22
  DomainRepository,
23
+ type DomainRow,
22
24
  describeRefFailure,
23
25
  LanguageRepository,
24
26
  NodeRepository,
@@ -307,6 +309,7 @@ export async function syncDomainsFile(
307
309
  else byNode.set(declaration.node, [declaration])
308
310
  }
309
311
 
312
+ const boundBefore = bindingsOf(await domains.all())
310
313
  const kept = new Set<number>()
311
314
  const namedBy = new Map<number, string>()
312
315
  for (const [node, declarations] of byNode) {
@@ -368,9 +371,24 @@ export async function syncDomainsFile(
368
371
  removed += before.domains.length + (before.defaultIsoCode ? 1 : 0)
369
372
  }
370
373
 
374
+ // Hostnames are part of every node's published cache, and this runs from the
375
+ // CLI as often as from a server. Unsigned, so every node rebuilds its routing,
376
+ // the one this ran in included; only when something changed, so a boot that
377
+ // re-applies the same file tells nobody anything.
378
+ if (bindingsOf(await domains.all()) !== boundBefore)
379
+ await appendCacheInstruction(db, { kind: 'content', payload: { domains: true } })
380
+
371
381
  return { action: 'applied', applied, removed, problems }
372
382
  }
373
383
 
384
+ /** The bindings as a comparable string: page, hostname and culture, in a stable order. */
385
+ function bindingsOf(rows: readonly DomainRow[]): string {
386
+ return rows
387
+ .map((row) => `${row.nodeId}|${row.domainName}|${row.isoCode ?? ''}|${row.isWildcard}`)
388
+ .sort()
389
+ .join('\n')
390
+ }
391
+
374
392
  function describeSetFailure(result: { status: string; domainName?: string; isoCode?: string }) {
375
393
  switch (result.status) {
376
394
  case 'invalidLanguage':
@@ -383,3 +401,36 @@ function describeSetFailure(result: { status: string; domainName?: string; isoCo
383
401
  return result.status
384
402
  }
385
403
  }
404
+
405
+ /**
406
+ * After a page's hostnames were saved in the backoffice: a site that keeps
407
+ * `domains.toml` keeps them in the file, since the next boot converges onto it
408
+ * and a change saved only in the database would be undone. Only this page's
409
+ * entries are rewritten, so `${VAR}` in the others survives. Answers the file it
410
+ * wrote, or undefined for a site without one.
411
+ */
412
+ export async function writeDomainsFor(
413
+ db: Db,
414
+ siteDir: string | undefined,
415
+ node: NodeRow,
416
+ assignment: {
417
+ defaultIsoCode: string | null
418
+ domains: Array<{ domainName: string; isoCode: string }>
419
+ },
420
+ ): Promise<string | undefined> {
421
+ const declarations = siteDir ? readDomainsFile(siteDir) : undefined
422
+ if (!siteDir || !declarations) return undefined
423
+ await writeDomains(
424
+ siteDir,
425
+ replaceNodeDeclarations(
426
+ declarations.declarations,
427
+ await nodeReferenceFor(db, declarations.declarations, node),
428
+ assignment.domains.map((domain) => ({
429
+ host: domain.domainName,
430
+ culture: domain.isoCode || undefined,
431
+ })),
432
+ assignment.defaultIsoCode ?? undefined,
433
+ ),
434
+ )
435
+ return DOMAINS_FILE
436
+ }
@@ -11,6 +11,7 @@
11
11
  * why), and Slack is `sendToUrl` with a webhook URL rather than a type of its
12
12
  * own.
13
13
  */
14
+ import { type DocumentOperations, systemActor } from '@crombolo/content'
14
15
  import {
15
16
  allFormFields,
16
17
  type FormValueToStore,
@@ -66,6 +67,11 @@ export interface WorkflowDeps {
66
67
  nodeId?: string
67
68
  /** Told when a workflow published something, so the cache is dropped. */
68
69
  onContentChanged?: () => void
70
+ /**
71
+ * Saves a submission as a page as the site (story 170), recorded and announced
72
+ * as any page made in the backoffice is. Without them it writes directly.
73
+ */
74
+ operations?: DocumentOperations
69
75
  /** The workflow types wired bundles add, by type. */
70
76
  bundleWorkflows?: ReadonlyMap<string, FormWorkflowTypeDefinition>
71
77
  /** Renders a `template` component to HTML; absent, a workflow naming one cannot send. */
@@ -358,6 +364,36 @@ async function saveAsContent(
358
364
  (nameField ? firstValue(context.values, nameField) : '') ||
359
365
  `${context.form.name} ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`
360
366
 
367
+ const input = {
368
+ key: crypto.randomUUID(),
369
+ contentTypeKey: type.key,
370
+ componentKey: null,
371
+ // `root` or nothing both mean the top of the tree.
372
+ parentKey: parent && parent !== 'root' ? parent : null,
373
+ values: Object.entries(map).map(([fieldAlias, propertyAlias]) => ({
374
+ alias: propertyAlias,
375
+ culture: null,
376
+ segment: null,
377
+ value: firstValue(context.values, fieldAlias),
378
+ })),
379
+ variants: [{ culture: null, segment: null, name }],
380
+ }
381
+ if (deps.operations) {
382
+ const actor = systemActor(`The form "${context.form.name}"`, {
383
+ note: `from a submission to "${context.form.name}"`,
384
+ })
385
+ const result =
386
+ settings.publish === true
387
+ ? await deps.operations.createAndPublish(actor, input, null)
388
+ : await deps.operations.create(actor, input)
389
+ if (result.ok) return { ok: true, detail: result.key }
390
+ // A node behind the schema, or a parent not yet published, resolves on its own: worth retrying.
391
+ return {
392
+ ok: false,
393
+ retry: result.kind === 'conflict' || result.kind === 'blocked',
394
+ error: result.reason,
395
+ }
396
+ }
361
397
  const documents = new DocumentRepository(deps.db, {
362
398
  nodeState: deps.nodeState,
363
399
  nodeId: deps.nodeId,
package/src/index.ts CHANGED
@@ -25,7 +25,9 @@ export * from './bundles.ts'
25
25
  export * from './busy.ts'
26
26
  export * from './components.ts'
27
27
  export * from './config.ts'
28
+ export * from './content-events.ts'
28
29
  export * from './content-notifications.ts'
30
+ export * from './content-operations.ts'
29
31
  export * from './content-type-udt.ts'
30
32
  export * from './database.ts'
31
33
  export * from './diagnostics.ts'
package/src/jobs.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * it runs once.
9
9
  */
10
10
 
11
+ import { type DocumentOperations, systemActor } from '@crombolo/content'
11
12
  import type { NodeSchemaState } from '@crombolo/data'
12
13
  import {
13
14
  AuditLog,
@@ -64,6 +65,11 @@ export interface JobsOptions {
64
65
  notifier?: ContentNotifier
65
66
  /** Told what scheduled publishing did, for the approval requests waiting on it (story 029). */
66
67
  approvals?: Pick<Approvals, 'scheduleFired' | 'sweepScheduled'>
68
+ /**
69
+ * Publishes what a schedule says, as the site (story 170): recorded, tracked and
70
+ * announced as an editor's publish is. Without them the job writes directly.
71
+ */
72
+ operations?: DocumentOperations
67
73
  }
68
74
 
69
75
  export interface ScheduledRun {
@@ -110,8 +116,25 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
110
116
  for (const due of await documents.dueSchedules(now)) {
111
117
  if (!(await documents.claimSchedule(due.id))) continue
112
118
  const cultures = due.culture ? [due.culture] : null
119
+ const release = due.action === 'Release'
120
+ if (options.operations) {
121
+ const actor = systemActor('The schedule', {
122
+ note: `scheduled${due.culture ? ` (${due.culture})` : ''}`,
123
+ })
124
+ const result = release
125
+ ? await options.operations.publish(actor, due.key, { cultures })
126
+ : await options.operations.unpublish(actor, due.key, cultures)
127
+ if (result.ok) (release ? run.published : run.unpublished).push(due.key)
128
+ else run.failed.push({ key: due.key, reason: result.reason })
129
+ await options.approvals?.scheduleFired(
130
+ due.key,
131
+ due.culture,
132
+ due.action,
133
+ result.ok ? { ok: true } : { ok: false, reason: result.reason },
134
+ )
135
+ continue
136
+ }
113
137
  try {
114
- const release = due.action === 'Release'
115
138
  const changed = release
116
139
  ? await documents.publish(due.key, cultures)
117
140
  : await documents.unpublish(due.key, cultures)
@@ -137,6 +160,8 @@ export function createBackgroundJobs(options: JobsOptions): BackgroundJobs {
137
160
  }
138
161
  }
139
162
  await options.approvals?.sweepScheduled(now.getTime())
163
+ // The operations announced and refreshed what they did themselves.
164
+ if (options.operations) return run
140
165
  if (run.published.length + run.unpublished.length > 0) options.cache.invalidate()
141
166
  for (const key of run.published) {
142
167
  await options.webhooks?.raise({ alias: 'Umbraco.ContentPublish', key })
package/src/ports.ts CHANGED
@@ -23,6 +23,14 @@ import {
23
23
  type ExtensionRegistry,
24
24
  toResponseModels,
25
25
  } from '@crombolo/backoffice-host'
26
+ import {
27
+ type ApprovalsGate,
28
+ type ContentPrincipal,
29
+ createDocumentOperations,
30
+ type DocumentOperations,
31
+ type EventSink,
32
+ SILENT,
33
+ } from '@crombolo/content'
26
34
  import {
27
35
  CORE_SECTION_ALIASES,
28
36
  DEFAULT_UPLOAD_SETTINGS,
@@ -72,12 +80,13 @@ import { createTemplateFileStore } from './adapters/template-files.ts'
72
80
  import { createTemplateQueryPort } from './adapters/template-query.ts'
73
81
  import { avatarUrls, createUserPorts } from './adapters/users.ts'
74
82
  import { createWebhookPort } from './adapters/webhooks.ts'
75
- import { createApprovals } from './approvals.ts'
83
+ import { type Approvals, createApprovals } from './approvals.ts'
76
84
  import { COMPONENT_SNIPPETS } from './component-snippets.ts'
77
85
  import { type CromboloConfig, type UserLinkSender, VERSION } from './config.ts'
78
86
  import type { ContentNotifier } from './content-notifications.ts'
87
+ import { writeDomainsFor } from './domains.ts'
79
88
  import { type EmailPort, resolveEmailPort } from './email.ts'
80
- import { createFileIntake } from './file-intake.ts'
89
+ import { createFileIntake, TemporaryFileMissingError } from './file-intake.ts'
81
90
  import { formTypesFor } from './form-types.ts'
82
91
  import { createLogViewerPort } from './log-viewer.ts'
83
92
  import { logger } from './logging.ts'
@@ -387,6 +396,8 @@ export interface DepsOptions {
387
396
  extensions: ExtensionRegistry
388
397
  /** Omitted only by tests that exercise the contract without a database. */
389
398
  db?: Db
399
+ /** Where document operations announce what they did; nothing hears them when absent. */
400
+ contentEvents?: EventSink
390
401
  /** The site's webhooks, shared with the delivery job and the event source. */
391
402
  webhooks?: WebhookService
392
403
  /** Required alongside `db` to serve documents, which invalidate the cache. */
@@ -638,6 +649,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
638
649
  deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
639
650
  onChange: () => options.cache?.invalidate(),
640
651
  })
652
+ const tracker = options.cache
653
+ ? createRedirectTracker({
654
+ cache: options.cache,
655
+ redirects: new RedirectRepository(options.db),
656
+ enabled: options.config.trackRedirects,
657
+ })
658
+ : undefined
641
659
  if (options.cache)
642
660
  deps.documents = createDocumentPort(
643
661
  options.db,
@@ -647,29 +665,47 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
647
665
  nodeId: options.schema?.nodeId,
648
666
  valueIntake,
649
667
  },
650
- createRedirectTracker({
651
- cache: options.cache,
652
- redirects: new RedirectRepository(options.db),
653
- enabled: options.config.trackRedirects,
654
- }),
668
+ tracker,
655
669
  options.config.siteDir,
656
670
  Boolean(email),
657
671
  )
658
672
  if (deps.documents) {
659
- const documents = deps.documents
660
- deps.approvals = createApprovals({
661
- db: options.db,
673
+ const db = options.db
674
+ // Every document write, whoever starts it (story 170). Approvals publish
675
+ // through it too, so what an approval publishes is cached, tracked and
676
+ // announced as any publish is.
677
+ let operations: DocumentOperations | undefined
678
+ const approvals = createApprovals({
679
+ db,
662
680
  nodeState: options.schema?.nodeState,
663
681
  email,
664
682
  backOfficeUrl: backOfficeUrl(options.config),
665
683
  notifier: options.notifier,
666
- // Through the same port an editor's publish takes, so what approval
667
- // publishes is cached, tracked and announced as any publish is.
668
684
  publisher: {
669
- publish: (key, cultures) => documents.publish(key, cultures),
670
- unpublish: (key, cultures) => documents.unpublish(key, cultures),
685
+ publish: (key, cultures, actor) =>
686
+ (operations as DocumentOperations).publish(actor, key, { cultures }),
687
+ unpublish: (key, cultures, actor) =>
688
+ (operations as DocumentOperations).unpublish(actor, key, cultures),
671
689
  },
672
690
  })
691
+ deps.approvals = approvals
692
+ operations = createDocumentOperations({
693
+ db,
694
+ repository: {
695
+ nodeState: options.schema?.nodeState,
696
+ nodeId: options.schema?.nodeId,
697
+ valueIntake,
698
+ },
699
+ events: options.contentEvents ?? SILENT,
700
+ approvals: approvalsGate(approvals),
701
+ redirects: tracker,
702
+ onChange: () => options.cache?.invalidate(),
703
+ afterDomains: (node, assignment) =>
704
+ writeDomainsFor(db, options.config.siteDir, node, assignment),
705
+ refusalReason: (error) =>
706
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
707
+ })
708
+ deps.documentOperations = operations
673
709
  }
674
710
  }
675
711
  return deps
@@ -715,3 +751,20 @@ function userTwoFactorPort(service: TwoFactorService): UserTwoFactorPort {
715
751
  reset: (userKey) => service.reset(userKey, provider),
716
752
  }
717
753
  }
754
+
755
+ /**
756
+ * The approval workflows as the document operations meet them. A user's principal
757
+ * is the backoffice's own, passed straight through; a local operator has none.
758
+ */
759
+ export function approvalsGate(approvals: Approvals): ApprovalsGate {
760
+ const as = (who: ContentPrincipal | undefined) => who as Principal | undefined
761
+ return {
762
+ publishRefusal: (who, key, action) => approvals.publishRefusal(as(who), key, action),
763
+ branchRefusal: (who, key) => approvals.branchRefusal(as(who), key),
764
+ newPageRefusal: (who, parentKey, typeKey) =>
765
+ approvals.newPageRefusal(as(who), parentKey, typeKey),
766
+ beforeSave: (who, key) => approvals.beforeSave(as(who), key),
767
+ afterSave: (who, key) => approvals.afterSave(as(who), key),
768
+ afterDirectPublish: (who, key, what) => approvals.afterDirectPublish(as(who), key, what),
769
+ }
770
+ }
package/src/remote.ts CHANGED
@@ -48,6 +48,11 @@ export interface RemoteOptions {
48
48
  db: Db
49
49
  config: CromboloConfig
50
50
  authenticate(request: Request): Promise<Principal | undefined>
51
+ /**
52
+ * Told once a push has landed, so this node's published cache is rebuilt: the
53
+ * import's cache instruction carries this node's id, and a node skips its own.
54
+ */
55
+ onApplied?(): void
51
56
  }
52
57
 
53
58
  export interface Remote {
@@ -307,6 +312,7 @@ export function createRemote(options: RemoteOptions): Remote {
307
312
  })
308
313
  return
309
314
  }
315
+ options.onApplied?.()
310
316
  await jobs.update(job.id, {
311
317
  state: 'done',
312
318
  stage:
package/src/server.ts CHANGED
@@ -29,6 +29,7 @@ import {
29
29
  createManagementApiRouter,
30
30
  hasSection,
31
31
  type Principal,
32
+ type ServerEvent,
32
33
  } from '@crombolo/api-management'
33
34
  import {
34
35
  AuthService,
@@ -130,6 +131,7 @@ import {
130
131
  type ServerRole,
131
132
  VERSION,
132
133
  } from './config.ts'
134
+ import { createContentEventSink } from './content-events.ts'
133
135
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
134
136
  import { attachDatabase, bootstrapDatabase } from './database.ts'
135
137
  import { createDeliveryMemberSecurity } from './delivery-members.ts'
@@ -741,7 +743,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
741
743
  },
742
744
  )
743
745
  : undefined
744
- const remote = createRemote({ db, config, authenticate })
746
+ const remote = createRemote({ db, config, authenticate, onApplied: () => cache.invalidate() })
745
747
  const members = createMemberAuth(db, config, {
746
748
  nodeState: schema.nodeState,
747
749
  nodeId: schema.nodeId,
@@ -932,12 +934,27 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
932
934
  }
933
935
  : undefined,
934
936
  })
937
+ /**
938
+ * What an open backoffice hears of a change: the event hub drops its cached
939
+ * copy, whatever was queued gets indexed now, and an open preview reloads.
940
+ * Called only once requests are served, by which time the hubs below exist.
941
+ */
942
+ function announce(event: ServerEvent): void {
943
+ events.broadcast('notify', [event])
944
+ jobs.kickSearchIndexing()
945
+ if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
946
+ previewHub.broadcast('refreshed', [event.key])
947
+ }
948
+ // Document writes announce themselves through this, from every entry point (story 170).
949
+ const contentEvents = createContentEventSink({ db, webhooks, notifier, live: announce })
950
+
935
951
  const managementDeps = createDeps({
936
952
  config,
937
953
  paths,
938
954
  extensions,
939
955
  db,
940
956
  webhooks,
957
+ contentEvents,
941
958
  cache,
942
959
  previewInApp: appPreview,
943
960
  schema,
@@ -985,14 +1002,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
985
1002
  onContentChange: (change, principal) => {
986
1003
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
987
1004
  },
988
- onServerEvent: (event) => {
989
- events.broadcast('notify', [event])
990
- // Saves, deletes and moves all announce themselves; whatever they queued gets indexed now.
991
- jobs.kickSearchIndexing()
992
- // An open preview of the document reloads when it changes.
993
- if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
994
- previewHub.broadcast('refreshed', [event.key])
995
- },
1005
+ onServerEvent: announce,
996
1006
  })
997
1007
 
998
1008
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
@@ -1031,6 +1041,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1031
1041
  db,
1032
1042
  cache,
1033
1043
  approvals: managementDeps.approvals as Approvals | undefined,
1044
+ operations: managementDeps.documentOperations,
1034
1045
  nodeState: schema.nodeState,
1035
1046
  nodeId: schema.nodeId,
1036
1047
  versionCleanup: config.versionCleanup,
@@ -1047,6 +1058,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1047
1058
  nodeState: schema.nodeState,
1048
1059
  nodeId: schema.nodeId,
1049
1060
  onContentChanged: () => cache.invalidate(),
1061
+ operations: managementDeps.documentOperations,
1050
1062
  bundleWorkflows: formTypes.workflows,
1051
1063
  renderEmail: (alias, props) => renderer.renderEmail(alias, props),
1052
1064
  site: async () => ({