@crombolo/server 0.22.0 → 0.24.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.
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Where document operations record what they did (stories 170 and 171). Inside
3
+ * the change's own transaction: its audit entry, and — when anyone may hear of
4
+ * it — an outbox event holding the facts as they were. After the commit: the
5
+ * live backoffice, and a nudge so the dispatcher sends it now rather than at
6
+ * its next tick. The command line wires the same sink without the live part.
7
+ */
8
+ import {
9
+ type Actor,
10
+ actorName,
11
+ actorNote,
12
+ actorUserKey,
13
+ auditEntryFor,
14
+ type DocumentEvent,
15
+ type EventSink,
16
+ liveEventsFor,
17
+ notificationFor,
18
+ webhookFor,
19
+ } from '@crombolo/content'
20
+ import { AuditLog, ContentEventRepository, type Db } from '@crombolo/data'
21
+ import type { ContentNotifier } from './content-notifications.ts'
22
+ import type { WebhookService } from './webhooks.ts'
23
+
24
+ export interface ContentEventSinkOptions {
25
+ webhooks?: Pick<WebhookService, 'factsFor'>
26
+ notifier?: Pick<ContentNotifier, 'factsFor'>
27
+ /** Tells an open backoffice what changed: a server's event hub; absent on the command line. */
28
+ live?(event: ReturnType<typeof liveEventsFor>[number]): void
29
+ /** Called after a commit that left work in the outbox. */
30
+ nudge?(): void
31
+ }
32
+
33
+ /** The page an event is about, for the outbox row. */
34
+ const subjectOf = (event: DocumentEvent): string | null =>
35
+ 'key' in event ? event.key : 'parentKey' in event ? event.parentKey : null
36
+
37
+ /** Who made a change, as the outbox keeps it: enough to name them and leave them out. */
38
+ export const outboxActor = (actor: Actor) => ({
39
+ kind: actor.kind,
40
+ name: actorName(actor),
41
+ userKey: actorUserKey(actor),
42
+ })
43
+
44
+ export function createContentEventSink(options: ContentEventSinkOptions): EventSink {
45
+ return {
46
+ async record(tx: Db, event, actor) {
47
+ const entry = auditEntryFor(event, actor)
48
+ const audit = new AuditLog(tx)
49
+ // A deleted page cannot be named after it went: the operation read its name first.
50
+ const subject =
51
+ event.type === 'deleted'
52
+ ? { entityType: entry.entityType, entityKey: event.key, entityName: event.name }
53
+ : entry.entityKey
54
+ ? await audit.describe(entry.entityType, entry.entityKey)
55
+ : undefined
56
+ await audit.record({
57
+ ...entry,
58
+ entityType: subject?.entityType ?? entry.entityType,
59
+ entityKey: subject?.entityKey ?? entry.entityKey,
60
+ entityName: subject?.entityName ?? null,
61
+ })
62
+ const hook = webhookFor(event)
63
+ const change = notificationFor(event)
64
+ const webhook =
65
+ hook && options.webhooks ? await options.webhooks.factsFor(tx, hook) : undefined
66
+ const notification =
67
+ change && options.notifier
68
+ ? await options.notifier.factsFor(
69
+ tx,
70
+ change,
71
+ { key: actorUserKey(actor), name: actorName(actor) },
72
+ actorNote(actor),
73
+ )
74
+ : undefined
75
+ if (!webhook && !notification) return
76
+ await new ContentEventRepository(tx).record({
77
+ kind: event.type,
78
+ entityType: 'Document',
79
+ entityKey: subjectOf(event),
80
+ facts: { v: 1, ...(webhook ? { webhook } : {}), ...(notification ? { notification } : {}) },
81
+ actor: outboxActor(actor),
82
+ })
83
+ },
84
+ afterCommit(event) {
85
+ for (const live of liveEventsFor(event)) options.live?.(live)
86
+ if (webhookFor(event) || notificationFor(event)) options.nudge?.()
87
+ },
88
+ }
89
+ }
@@ -44,7 +44,33 @@ export interface ContentNotifierOptions {
44
44
  delayMs?: number
45
45
  }
46
46
 
47
+ /**
48
+ * What a change's notifications need, read when it commits (story 171): the
49
+ * page as it was, where its subscribers are looked up, and who made the change.
50
+ */
51
+ export interface NotificationFacts {
52
+ actions: string[]
53
+ nodeKey: string
54
+ nodeName: string
55
+ /** Node ids, root first: where the page is, or where it was before the recycle bin. */
56
+ path: number[]
57
+ detail: string | null
58
+ actorUserKey: string | null
59
+ actorName: string | null
60
+ occurredAt: string
61
+ }
62
+
47
63
  export interface ContentNotifier {
64
+ /** The facts for a change, read on `db` — the change's transaction; undefined when it notifies no one. */
65
+ factsFor(
66
+ db: Db,
67
+ change: RaisedContentChange,
68
+ actor: Actor | null,
69
+ detail?: string,
70
+ ): Promise<NotificationFacts | undefined>
71
+ /** Queues one row per subscriber, once per event however often it is repeated. */
72
+ enqueueFor(db: Db, eventId: string | undefined, facts: NotificationFacts): Promise<void>
73
+ /** Facts and queue at once, outside any outbox: for a change with no event to record. */
48
74
  raise(change: RaisedContentChange, actor: Actor | null, detail?: string): Promise<void>
49
75
  }
50
76
 
@@ -56,71 +82,90 @@ const pathIds = (path: string): number[] =>
56
82
  .filter((id) => Number.isFinite(id) && id > 0)
57
83
 
58
84
  export function createContentNotifier(db: Db, options: ContentNotifierOptions): ContentNotifier {
59
- const nodes = new NodeRepository(db)
60
- const documents = new DocumentRepository(db)
61
- const subscriptions = new NotificationRepository(db)
62
- const outbox = new ContentNotificationRepository(db)
85
+ const factsFor: ContentNotifier['factsFor'] = async (on, change, actor, detail) => {
86
+ const nodes = new NodeRepository(on)
87
+ const documents = new DocumentRepository(on)
88
+ const node =
89
+ change.keyKind === 'version'
90
+ ? await documents
91
+ .atVersion(change.key)
92
+ .then((version) => (version ? nodes.byKey(version.document.key) : undefined))
93
+ : await nodes.byKey(change.key)
94
+ if (!node || node.objectType !== ObjectTypes.Document) return undefined
95
+ // A trashed page sits under the recycle bin now; its subscribers are
96
+ // the ones where it was.
97
+ let path = pathIds(node.path)
98
+ if (node.trashed) {
99
+ const parentKey = await documents.originalParent(node.key)
100
+ const parent = parentKey ? await nodes.byKey(parentKey) : undefined
101
+ path = [...(parent ? pathIds(parent.path) : []), node.id]
102
+ }
103
+ let summary = detail ?? null
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
+ )
109
+ const under = Number(row?.n ?? 0)
110
+ if (under > 0) summary = `and ${under} page${under === 1 ? '' : 's'} under it`
111
+ }
112
+ return {
113
+ actions: [...change.actions],
114
+ nodeKey: node.key,
115
+ nodeName: node.text ?? node.key,
116
+ path,
117
+ detail: summary,
118
+ actorUserKey: actor?.key ?? null,
119
+ actorName: actor?.name ?? null,
120
+ occurredAt: new Date().toISOString(),
121
+ }
122
+ }
63
123
 
64
- const resolve = async (change: RaisedContentChange) => {
65
- if (change.keyKind === 'version') {
66
- const version = await documents.atVersion(change.key)
67
- return version ? nodes.byKey(version.document.key) : undefined
124
+ const enqueueFor: ContentNotifier['enqueueFor'] = async (on, eventId, facts) => {
125
+ // A site that cannot send e-mail queues nothing, so nothing piles up.
126
+ if (!options.canSend) return
127
+ const subscriptions = new NotificationRepository(on)
128
+ const actorId = facts.actorUserKey
129
+ ? (await new UserRepository(on).byKey(facts.actorUserKey))?.id
130
+ : undefined
131
+ const occurredAt = new Date(facts.occurredAt)
132
+ const runAfter = new Date(Date.now() + (options.delayMs ?? DIGEST_DELAY_MS))
133
+ const rows = []
134
+ for (const actionId of facts.actions) {
135
+ const userIds = (await subscriptions.subscribersFor(actionId, facts.path)).filter(
136
+ (id) => id !== actorId,
137
+ )
138
+ 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
+ )
143
+ for (const { key } of keys)
144
+ rows.push({
145
+ recipientUserKey: String(key),
146
+ actionId,
147
+ nodeKey: facts.nodeKey,
148
+ nodeName: facts.nodeName,
149
+ actorUserKey: facts.actorUserKey,
150
+ actorName: facts.actorName,
151
+ detail: facts.detail,
152
+ occurredAt,
153
+ runAfter,
154
+ eventId,
155
+ })
68
156
  }
69
- return nodes.byKey(change.key)
157
+ await new ContentNotificationRepository(on).enqueue(rows)
70
158
  }
71
159
 
72
160
  return {
161
+ factsFor,
162
+ enqueueFor,
73
163
  async raise(change, actor, detail) {
74
164
  if (!options.canSend) return
75
165
  try {
76
- const node = await resolve(change)
77
- if (!node || node.objectType !== ObjectTypes.Document) return
78
- // A trashed page sits under the recycle bin now; its subscribers are
79
- // the ones where it was.
80
- let path = pathIds(node.path)
81
- if (node.trashed) {
82
- const parentKey = await documents.originalParent(node.key)
83
- const parent = parentKey ? await nodes.byKey(parentKey) : undefined
84
- path = [...(parent ? pathIds(parent.path) : []), node.id]
85
- }
86
- let summary = detail ?? null
87
- if (change.withDescendants) {
88
- const [row] = await db.query<{ n: number }>(
89
- 'SELECT COUNT(*) AS n FROM node WHERE path LIKE ? AND node_object_type = ? AND trashed = ?',
90
- [`${node.path},%`, ObjectTypes.Document, db.dialect.boolValue(false)],
91
- )
92
- const under = Number(row?.n ?? 0)
93
- if (under > 0) summary = `and ${under} page${under === 1 ? '' : 's'} under it`
94
- }
95
- const actorId = actor?.key ? (await new UserRepository(db).byKey(actor.key))?.id : undefined
96
- const occurredAt = new Date()
97
- const runAfter = new Date(occurredAt.getTime() + (options.delayMs ?? DIGEST_DELAY_MS))
98
- const rows = []
99
- for (const actionId of change.actions) {
100
- const userIds = (await subscriptions.subscribersFor(actionId, path)).filter(
101
- (id) => id !== actorId,
102
- )
103
- if (userIds.length === 0) continue
104
- const keys = await db.query<{ key: string }>(
105
- `SELECT key FROM user_account WHERE id IN (${userIds.map(() => '?').join(', ')})`,
106
- userIds,
107
- )
108
- for (const { key } of keys)
109
- rows.push({
110
- recipientUserKey: String(key),
111
- actionId,
112
- nodeKey: node.key,
113
- nodeName: node.text ?? node.key,
114
- actorUserKey: actor?.key ?? null,
115
- actorName: actor?.name ?? null,
116
- detail: summary,
117
- occurredAt,
118
- runAfter,
119
- })
120
- }
121
- await outbox.enqueue(rows)
166
+ const facts = await factsFor(db, change, actor, detail)
167
+ if (facts) await enqueueFor(db, undefined, facts)
122
168
  } catch (error) {
123
- // Like the audit log: a notification that cannot be queued never costs the change.
124
169
  log.error('A content notification could not be queued: {error}', { error: String(error) })
125
170
  }
126
171
  },
@@ -0,0 +1,84 @@
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
+ // Recorded only: a running server's dispatcher sends what this records (story 171).
50
+ const events = createContentEventSink({ webhooks, notifier })
51
+ const cache = new PublishedCache(createPublishedContentSource(db, { nodeState }))
52
+ let operations: DocumentOperations | undefined
53
+ const approvals = createApprovals({
54
+ db,
55
+ nodeState,
56
+ email,
57
+ backOfficeUrl: backOfficeUrl(config),
58
+ notifier,
59
+ publisher: {
60
+ publish: (key, cultures, actor, approvedHead) =>
61
+ (operations as DocumentOperations).publish(actor, key, {
62
+ cultures,
63
+ expectedHead: approvedHead,
64
+ }),
65
+ unpublish: (key, cultures, actor) =>
66
+ (operations as DocumentOperations).unpublish(actor, key, cultures),
67
+ },
68
+ })
69
+ operations = createDocumentOperations({
70
+ db,
71
+ repository: { nodeState, nodeId: config.nodeId },
72
+ events,
73
+ approvals: approvalsGate(approvals),
74
+ redirects: createRedirectTracker({
75
+ cache,
76
+ redirects: new RedirectRepository(db),
77
+ enabled: config.trackRedirects,
78
+ }),
79
+ afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
80
+ refusalReason: (error) =>
81
+ error instanceof TemporaryFileMissingError ? error.message : undefined,
82
+ })
83
+ return { operations, events }
84
+ }
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,10 @@ 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-dispatch.ts'
29
+ export * from './content-events.ts'
28
30
  export * from './content-notifications.ts'
31
+ export * from './content-operations.ts'
29
32
  export * from './content-type-udt.ts'
30
33
  export * from './database.ts'
31
34
  export * from './diagnostics.ts'