@crombolo/server 0.23.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.
package/src/server.ts CHANGED
@@ -57,6 +57,7 @@ import {
57
57
  resolveStaticFile,
58
58
  serveStaticFile,
59
59
  } from '@crombolo/backoffice-host'
60
+ import type { DocumentOperations } from '@crombolo/content'
60
61
  import { servedContract } from '@crombolo/contracts'
61
62
  import {
62
63
  CHOICE_SOURCE_KINDS,
@@ -131,6 +132,7 @@ import {
131
132
  type ServerRole,
132
133
  VERSION,
133
134
  } from './config.ts'
135
+ import { createContentDispatcher } from './content-dispatch.ts'
134
136
  import { createContentEventSink } from './content-events.ts'
135
137
  import { createContentNotificationRunner, createContentNotifier } from './content-notifications.ts'
136
138
  import { attachDatabase, bootstrapDatabase } from './database.ts'
@@ -945,8 +947,15 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
945
947
  if (event.eventSource === 'Umbraco:CMS:Document' && event.eventType !== 'Deleted')
946
948
  previewHub.broadcast('refreshed', [event.key])
947
949
  }
948
- // Document writes announce themselves through this, from every entry point (story 170).
949
- const contentEvents = createContentEventSink({ db, webhooks, notifier, live: announce })
950
+ // Recorded content events become deliveries and notifications here (story 171).
951
+ const dispatcher = createContentDispatcher({ db, webhooks, notifier })
952
+ // Document writes record and announce themselves through this, from every entry point.
953
+ const contentEvents = createContentEventSink({
954
+ webhooks,
955
+ notifier,
956
+ live: announce,
957
+ nudge: () => dispatcher.nudge(),
958
+ })
950
959
 
951
960
  const managementDeps = createDeps({
952
961
  config,
@@ -955,6 +964,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
955
964
  db,
956
965
  webhooks,
957
966
  contentEvents,
967
+ nudgeEvents: () => dispatcher.nudge(),
958
968
  cache,
959
969
  previewInApp: appPreview,
960
970
  schema,
@@ -994,10 +1004,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
994
1004
  onNotImplemented: config.development
995
1005
  ? (operation, request) => notImplemented.record(operation, request)
996
1006
  : undefined,
997
- // Queued after the response, so a slow receiver never holds an editor up.
998
- onWebhookEvent: (event) => {
999
- void webhooks.raise(event)
1000
- },
1001
1007
  // After the response too: the subscribers are worked out and queued, and sent a minute later.
1002
1008
  onContentChange: (change, principal) => {
1003
1009
  void notifier.raise(change, principal ? { key: principal.id, name: principal.name } : null)
@@ -1041,7 +1047,9 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1041
1047
  db,
1042
1048
  cache,
1043
1049
  approvals: managementDeps.approvals as Approvals | undefined,
1044
- operations: managementDeps.documentOperations,
1050
+ operations: managementDeps.documentOperations as DocumentOperations,
1051
+ dispatcher,
1052
+ eventRetentionDays: config.eventRetentionDays,
1045
1053
  nodeState: schema.nodeState,
1046
1054
  nodeId: schema.nodeId,
1047
1055
  versionCleanup: config.versionCleanup,
@@ -1066,7 +1074,6 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1066
1074
  url: config.applicationUrl,
1067
1075
  }),
1068
1076
  }),
1069
- notifier,
1070
1077
  contentNotifications: email
1071
1078
  ? createContentNotificationRunner({
1072
1079
  db,
package/src/settings.ts CHANGED
@@ -194,6 +194,14 @@ const DECLARED = [
194
194
  section: 'Database',
195
195
  description: 'How many days the audit log keeps an entry. `0` keeps them all.',
196
196
  },
197
+ {
198
+ env: 'CROMBOLO_EVENT_RETENTION_DAYS',
199
+ kind: 'number',
200
+ default: '30',
201
+ section: 'Database',
202
+ description:
203
+ 'How many days delivered webhooks, their log, and sent change events are kept. Failed ones stay until retried. `0` keeps them all.',
204
+ },
197
205
 
198
206
  // Sign-in and secrets
199
207
  {
package/src/webhooks.ts CHANGED
@@ -8,7 +8,6 @@ import { join } from 'node:path'
8
8
  import { type RaisedWebhookEvent, WEBHOOK_EVENT_ALIASES } from '@crombolo/api-management'
9
9
  import {
10
10
  type Db,
11
- fromDbBool,
12
11
  type WebhookDelivery,
13
12
  WebhookDeliveryRepository,
14
13
  type WebhookLogEntry,
@@ -143,6 +142,11 @@ export interface WebhookServiceOptions {
143
142
  now?: () => Date
144
143
  }
145
144
 
145
+ /** An event as a webhook delivers it, with the item's type as it was when it happened. */
146
+ export interface WebhookFacts extends RaisedWebhookEvent {
147
+ contentTypeKey?: string
148
+ }
149
+
146
150
  export interface WebhookService {
147
151
  /** Which stores a new or moved webhook may use on this node. */
148
152
  stores(): { files: boolean; database: boolean }
@@ -152,7 +156,11 @@ export interface WebhookService {
152
156
  update(key: string, definition: WebhookDefinition): Promise<WebhookWriteResult>
153
157
  remove(key: string): Promise<boolean>
154
158
  move(key: string, store: WebhookStore): Promise<WebhookWriteResult>
155
- /** Queues an event for everyone listening. Never throws into the caller. */
159
+ /** What a delivery needs to know about the item, read on `db` — the change's transaction. */
160
+ factsFor(db: Db, event: RaisedWebhookEvent): Promise<WebhookFacts>
161
+ /** Queues a delivery per subscriber, once per event however often it is repeated. */
162
+ enqueueFor(db: Db, eventId: string | undefined, facts: WebhookFacts): Promise<number>
163
+ /** Facts and queue at once, outside any outbox. Never throws into the caller. */
156
164
  raise(event: RaisedWebhookEvent): Promise<number>
157
165
  runDue(now?: Date, limit?: number): Promise<WorkflowRunReport>
158
166
  logs(
@@ -288,6 +296,8 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
288
296
  'Webhook-Retry-Count': String(delivery.attempts - 1),
289
297
  'Webhook-Id': webhook.key,
290
298
  'Webhook-Delivery': delivery.id,
299
+ // The change itself, the same for every webhook it reaches (story 171).
300
+ ...(delivery.eventId ? { 'Webhook-Event-Id': delivery.eventId } : {}),
291
301
  }
292
302
  // The log shows which headers were sent, never what their values were.
293
303
  const logged = JSON.stringify({
@@ -458,21 +468,27 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
458
468
  else await rows.remove(existing.key)
459
469
  return written
460
470
  },
471
+ async factsFor(db, event) {
472
+ const contentTypeKey = await itemType(db, event.key)
473
+ return contentTypeKey ? { ...event, contentTypeKey } : { ...event }
474
+ },
475
+ async enqueueFor(db, eventId, facts) {
476
+ const subscribers = subscribersFor(facts, facts.contentTypeKey, await all(), bundles)
477
+ if (subscribers.length === 0) return 0
478
+ const queued = await new WebhookDeliveryRepository(db).enqueue(
479
+ subscribers.map((subscriber) => ({
480
+ subscriber,
481
+ eventAlias: facts.alias,
482
+ payload: { Id: facts.key },
483
+ eventId,
484
+ })),
485
+ now(),
486
+ )
487
+ return queued.length
488
+ },
461
489
  async raise(event) {
462
490
  try {
463
- const facts = await itemFacts(options.db, event.key)
464
- if (!eventHappened(event.alias, facts.published)) return 0
465
- const subscribers = subscribersFor(event, facts.contentTypeKey, await all(), bundles)
466
- if (subscribers.length === 0) return 0
467
- await deliveries.enqueue(
468
- subscribers.map((subscriber) => ({
469
- subscriber,
470
- eventAlias: event.alias,
471
- payload: { Id: event.key },
472
- })),
473
- now(),
474
- )
475
- return subscribers.length
491
+ return await this.enqueueFor(options.db, undefined, await this.factsFor(options.db, event))
476
492
  } catch (error) {
477
493
  log.error('Could not queue {event} for {key}: {error}', { ...event, error })
478
494
  return 0
@@ -509,36 +525,14 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
509
525
  }
510
526
  }
511
527
 
512
- /**
513
- * Whether the change an event names really happened. A publish request that
514
- * only schedules one answers 200 too, and must not tell anyone the page is live
515
- * until the schedule makes it so. Pure; `published` is undefined for an item
516
- * that is gone or not a document.
517
- */
518
- export function eventHappened(alias: string, published: boolean | undefined): boolean {
519
- if (alias === 'Umbraco.ContentPublish') return published === true
520
- if (alias === 'Umbraco.ContentUnpublish') return published !== true
521
- return true
522
- }
523
-
524
- /** An item's type and whether it is published, while it still exists. */
525
- async function itemFacts(
526
- db: Db,
527
- key: string,
528
- ): Promise<{ contentTypeKey: string | undefined; published: boolean | undefined }> {
529
- const rows = await db.query<{ type_key: string; published: unknown }>(
530
- `SELECT tn.unique_id AS type_key, d.published FROM node n
528
+ /** An item's type, while it still exists. */
529
+ async function itemType(db: Db, key: string): Promise<string | undefined> {
530
+ const rows = await db.query<{ type_key: string }>(
531
+ `SELECT tn.unique_id AS type_key FROM node n
531
532
  JOIN content c ON c.node_id = n.id
532
533
  JOIN node tn ON tn.id = c.content_type_id
533
- LEFT JOIN document d ON d.node_id = n.id
534
534
  WHERE n.unique_id = ?`,
535
535
  [key],
536
536
  )
537
- const row = rows[0]
538
- if (!row) return { contentTypeKey: undefined, published: undefined }
539
- return {
540
- contentTypeKey: String(row.type_key).toLowerCase(),
541
- published:
542
- row.published === null || row.published === undefined ? undefined : fromDbBool(row.published),
543
- }
537
+ return rows[0] ? String(rows[0].type_key).toLowerCase() : undefined
544
538
  }