@crombolo/server 0.23.0 → 0.25.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.23.0",
3
+ "version": "0.25.0",
4
4
  "description": "The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -30,18 +30,18 @@
30
30
  "access": "public"
31
31
  },
32
32
  "dependencies": {
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",
33
+ "@crombolo/api-delivery": "0.25.0",
34
+ "@crombolo/api-management": "0.25.0",
35
+ "@crombolo/assistant": "0.25.0",
36
+ "@crombolo/auth": "0.25.0",
37
+ "@crombolo/backoffice-host": "0.25.0",
38
+ "@crombolo/content": "0.25.0",
39
+ "@crombolo/contracts": "0.25.0",
40
+ "@crombolo/core": "0.25.0",
41
+ "@crombolo/data": "0.25.0",
42
+ "@crombolo/render": "0.25.0",
43
+ "@crombolo/schema": "0.25.0",
44
+ "@crombolo/transfer": "0.25.0",
45
45
  "@logtape/logtape": "^2.3.8"
46
46
  }
47
47
  }
@@ -1,6 +1,6 @@
1
1
  /** The dictionary port over the repository, with `.udt` import and export. */
2
2
  import type { DictionaryPort } from '@crombolo/api-management'
3
- import { type Db, DictionaryRepository } from '@crombolo/data'
3
+ import { appendCacheInstruction, type Db, DictionaryRepository } from '@crombolo/data'
4
4
  import { importDictionaryUdt } from '../dictionary-transfer.ts'
5
5
  import type { MediaFileStore } from '../media-files.ts'
6
6
  import { readUdt, type UdtItem, writeUdt } from '../udt.ts'
@@ -8,10 +8,22 @@ import { readUdt, type UdtItem, writeUdt } from '../udt.ts'
8
8
  export function createDictionaryPort(
9
9
  db: Db,
10
10
  files: MediaFileStore,
11
- options: { onChange?: () => void } = {},
11
+ options: { onChange?: () => void; nodeId?: string } = {},
12
12
  ): DictionaryPort {
13
13
  const repo = new DictionaryRepository(db)
14
- const changed = <T>(result: T): T => {
14
+ /** Every node is told in the change's own transaction (story 174). */
15
+ const instruct = (on: Db) =>
16
+ appendCacheInstruction(on, {
17
+ kind: 'content',
18
+ payload: { dictionary: true },
19
+ by: options.nodeId,
20
+ })
21
+ const write = async <T>(change: (tx: DictionaryRepository) => Promise<T>): Promise<T> => {
22
+ const result = await db.transaction(async (tx) => {
23
+ const done = await change(new DictionaryRepository(tx))
24
+ if (done === 'Success') await instruct(tx)
25
+ return done
26
+ })
15
27
  if (result === 'Success') options.onChange?.()
16
28
  return result
17
29
  }
@@ -34,10 +46,10 @@ export function createDictionaryPort(
34
46
  items: (keys) => repo.many(keys),
35
47
  children: (parentKey) => repo.children(parentKey),
36
48
  ancestry: (key) => repo.ancestry(key),
37
- create: async (item) => changed(await repo.create(item)),
38
- update: async (key, change) => changed(await repo.update(key, change)),
39
- move: async (key, parentKey) => changed(await repo.move(key, parentKey)),
40
- delete: async (key) => changed(await repo.delete(key)),
49
+ create: (item) => write((tx) => tx.create(item)),
50
+ update: (key, change) => write((tx) => tx.update(key, change)),
51
+ move: (key, parentKey) => write((tx) => tx.move(key, parentKey)),
52
+ delete: (key) => write((tx) => tx.delete(key)),
41
53
 
42
54
  async export(key, includeChildren) {
43
55
  const item = await toUdt(key, includeChildren)
@@ -69,6 +81,7 @@ export function createDictionaryPort(
69
81
  status: 'Invalid',
70
82
  reason: 'No item in the file could be imported: its name is already in use.',
71
83
  }
84
+ await instruct(db)
72
85
  options.onChange?.()
73
86
  return { ok: true, key: items[0]?.key as string }
74
87
  },
@@ -24,6 +24,7 @@ import {
24
24
  DomainRepository,
25
25
  InvalidParentError,
26
26
  LanguageRepository,
27
+ latestCheckpoint,
27
28
  NOTIFIABLE_ACTIONS,
28
29
  type NodeRow,
29
30
  NotificationRepository,
@@ -607,6 +608,16 @@ export function createPublishedContentSource(
607
608
  source: row.source,
608
609
  }))
609
610
  },
611
+
612
+ /**
613
+ * Every load in one read snapshot, the checkpoint read first inside it
614
+ * (story 174), so the snapshot holds exactly the changes up to that number.
615
+ */
616
+ withSnapshot: (fn) =>
617
+ db.readSnapshot(async (reader) => {
618
+ const checkpoint = await latestCheckpoint(reader)
619
+ return fn(createPublishedContentSource(reader, options), checkpoint)
620
+ }),
610
621
  }
611
622
  }
612
623
 
@@ -4,13 +4,18 @@
4
4
  */
5
5
  import type { DiagnosticsPort, HealthCheckGroup, HealthCheckResult } from '@crombolo/api-management'
6
6
  import {
7
+ changedSince,
7
8
  compareStates,
8
9
  cromboloPlan,
9
10
  currentSchemaState,
10
11
  type Db,
12
+ type LiveNode,
13
+ latestCheckpoint,
11
14
  liveNodes,
12
15
  type NodeSchemaState,
13
16
  pendingMigrations,
17
+ type QueueCounts,
18
+ queueCounts,
14
19
  } from '@crombolo/data'
15
20
  import { BundleConfigurationError, bundleChainsFor, pendingBundleSteps } from '../bundle-tables.ts'
16
21
  import { type CromboloConfig, describeDatabase, VERSION } from '../config.ts'
@@ -29,8 +34,12 @@ const CHECKS = {
29
34
  media: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000003', name: 'Media storage' },
30
35
  email: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000004', name: 'E-mail delivery' },
31
36
  nodes: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000005', name: 'Servers' },
37
+ outgoing: { id: '6f1d4a8e-0047-4c1a-9e7d-000000000006', name: 'Outgoing changes' },
32
38
  } as const
33
39
 
40
+ /** Waiting longer than this means nothing is sending: no server is running its jobs, or one is stuck. */
41
+ export const BACKLOG_AFTER_MS = 10 * 60_000
42
+
34
43
  const GROUPS: HealthCheckGroup[] = [
35
44
  {
36
45
  name: 'Database',
@@ -57,10 +66,79 @@ const GROUPS: HealthCheckGroup[] = [
57
66
  ...CHECKS.nodes,
58
67
  description: 'The servers running this site, and whether they run the same release.',
59
68
  },
69
+ {
70
+ ...CHECKS.outgoing,
71
+ description:
72
+ 'Whether changes are reaching webhooks and the people who asked to hear of them.',
73
+ },
60
74
  ],
61
75
  },
62
76
  ]
63
77
 
78
+ /** Behind the latest content for longer than this, a node is worth a warning: it is not catching up. */
79
+ export const CONTENT_STALE_AFTER_MS = 60_000
80
+
81
+ /**
82
+ * Which nodes serve older published content than the latest committed, and for
83
+ * how long (story 174). Pure: `since` is when the first change a node lacks was
84
+ * recorded. Numbers and times only, never content.
85
+ */
86
+ export function freshnessResults(
87
+ nodes: ReadonlyArray<Pick<LiveNode, 'nodeId' | 'servedCheckpoint'>>,
88
+ latest: number,
89
+ since: ReadonlyMap<string, Date>,
90
+ at: Date,
91
+ ): HealthCheckResult[] {
92
+ const results: HealthCheckResult[] = []
93
+ for (const node of nodes) {
94
+ if (node.servedCheckpoint === null) continue
95
+ if (node.servedCheckpoint >= latest) continue
96
+ const from = since.get(node.nodeId)
97
+ if (from && at.getTime() - from.getTime() > CONTENT_STALE_AFTER_MS)
98
+ results.push(
99
+ result(
100
+ 'Warning',
101
+ `${node.nodeId} serves published content as of change ${node.servedCheckpoint}; the latest is ${latest}, since ${from.toISOString()}. It is not catching up: check it can reach the database, or restart it.`,
102
+ ),
103
+ )
104
+ }
105
+ return results
106
+ }
107
+
108
+ const QUEUE_LABELS = {
109
+ changes: 'change(s) waiting to be passed on',
110
+ webhooks: 'webhook delivery(ies)',
111
+ notifications: 'change e-mail(s)',
112
+ } as const
113
+
114
+ /** What the outgoing queues say about delivery, worst first (story 171). Pure. */
115
+ export function outgoingResults(
116
+ queues: Record<keyof typeof QUEUE_LABELS, QueueCounts>,
117
+ at: Date,
118
+ ): HealthCheckResult[] {
119
+ const results: HealthCheckResult[] = []
120
+ for (const [name, counts] of Object.entries(queues) as Array<
121
+ [keyof typeof QUEUE_LABELS, QueueCounts]
122
+ >) {
123
+ if (counts.failed > 0)
124
+ results.push(
125
+ result(
126
+ 'Warning',
127
+ `${counts.failed} ${QUEUE_LABELS[name]} failed. \`crombolo events failed\` says why; \`crombolo events retry --all\` sends them again.`,
128
+ ),
129
+ )
130
+ if (counts.oldestPending && at.getTime() - counts.oldestPending.getTime() > BACKLOG_AFTER_MS)
131
+ results.push(
132
+ result(
133
+ 'Warning',
134
+ `${counts.pending} ${QUEUE_LABELS[name]} waiting, the oldest since ${counts.oldestPending.toISOString()}. Check a server is running background jobs.`,
135
+ ),
136
+ )
137
+ }
138
+ if (results.length === 0) results.push(result('Success', 'Changes are going out as they happen.'))
139
+ return results
140
+ }
141
+
64
142
  export interface HealthCheckOptions {
65
143
  config: CromboloConfig
66
144
  db: Db
@@ -205,9 +283,16 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
205
283
  const results = live.map((node) =>
206
284
  result(
207
285
  'Info',
208
- `${node.nodeId}${node.role ? ` (${node.role})` : ''} runs Crombolo ${node.cromboloVersion ?? 'of an unknown release'} with schema ${node.version ?? '?'} revision ${node.revision ?? '?'}, last seen ${ago(node.lastSeen, at)}.`,
286
+ `${node.nodeId}${node.role ? ` (${node.role})` : ''} runs Crombolo ${node.cromboloVersion ?? 'of an unknown release'} with schema ${node.version ?? '?'} revision ${node.revision ?? '?'}, last seen ${ago(node.lastSeen, at)}${node.servedCheckpoint === null ? '' : `, serving published content as of change ${node.servedCheckpoint} of ${latest}`}.`,
209
287
  ),
210
288
  )
289
+ const latest = await latestCheckpoint(db)
290
+ const since = new Map<string, Date>()
291
+ for (const node of live)
292
+ if (node.servedCheckpoint !== null && node.servedCheckpoint < latest) {
293
+ const from = await changedSince(db, node.servedCheckpoint)
294
+ if (from) since.set(node.nodeId, from)
295
+ }
211
296
  const releases = new Set(live.map((node) => node.cromboloVersion ?? 'unknown'))
212
297
  const schemas = new Set(live.map((node) => `${node.version}/${node.revision}`))
213
298
  if (releases.size > 1)
@@ -228,6 +313,7 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
228
313
  results.unshift(
229
314
  result('Success', `${live.length} server(s) running Crombolo ${[...releases][0]}.`),
230
315
  )
316
+ results.unshift(...freshnessResults(live, latest, since, at))
231
317
  return results
232
318
  }
233
319
 
@@ -237,6 +323,15 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
237
323
  [CHECKS.media.id]: mediaStorage,
238
324
  [CHECKS.email.id]: email,
239
325
  [CHECKS.nodes.id]: nodes,
326
+ [CHECKS.outgoing.id]: async () =>
327
+ outgoingResults(
328
+ {
329
+ changes: await queueCounts(db, 'content_event'),
330
+ webhooks: await queueCounts(db, 'webhook_delivery'),
331
+ notifications: await queueCounts(db, 'content_notification'),
332
+ },
333
+ now(),
334
+ ),
240
335
  }
241
336
 
242
337
  return {
@@ -15,6 +15,7 @@ import {
15
15
  } from '@crombolo/core'
16
16
  import {
17
17
  appendCacheInstruction,
18
+ ContentEventRepository,
18
19
  ContentTypeRepository,
19
20
  DataTypeRepository,
20
21
  type Db,
@@ -27,6 +28,7 @@ import {
27
28
  } from '@crombolo/data'
28
29
  import { TemporaryFileMissingError } from '../file-intake.ts'
29
30
  import type { MediaFileStore } from '../media-files.ts'
31
+ import type { WebhookService } from '../webhooks.ts'
30
32
 
31
33
  /** The file path an item's `umbracoFile` holds, whether an upload or a cropper value. */
32
34
  export function mediaFileOf(media: DocumentAggregate): string | null {
@@ -45,18 +47,56 @@ export function createMediaPort(
45
47
  valueIntake?: ValueIntake
46
48
  /** Told after every change, so pages that show media refresh. */
47
49
  onChange?: () => void | Promise<void>
50
+ /** Reads what a `MediaSave` or `MediaDelete` delivery needs, inside the change. */
51
+ webhooks?: Pick<WebhookService, 'factsFor'>
52
+ /** Told after a commit that left an event in the outbox (story 171). */
53
+ nudge?: () => void
48
54
  } = {},
49
55
  ): MediaPort {
56
+ /** Every node is told inside the change's transaction; this node's pages refresh after. */
57
+ const instruct = (on: Db) =>
58
+ appendCacheInstruction(on, { kind: 'content', payload: { media: true }, by: options.nodeId })
50
59
  const changed = async () => {
51
- await appendCacheInstruction(db, {
52
- kind: 'content',
53
- payload: { media: true },
54
- by: options.nodeId,
55
- })
60
+ await instruct(db)
56
61
  await options.onChange?.()
57
62
  }
58
63
  const repo = new DocumentRepository(db, { ...options, kind: 'media' })
59
64
 
65
+ /**
66
+ * Writes a media change, its cache instruction and its webhook event in one
67
+ * transaction (story 171), so the event commits with the change or not at all.
68
+ */
69
+ const commit = async <T>(
70
+ write: (tx: DocumentRepository) => Promise<T>,
71
+ announce: (result: T) => { alias: string; key: string } | undefined,
72
+ principal?: Principal,
73
+ ): Promise<T> => {
74
+ let recorded = false
75
+ const result = await repo.atomically(async (tx, txDb) => {
76
+ const written = await write(tx)
77
+ const event = announce(written)
78
+ if (!event) return written
79
+ await instruct(txDb)
80
+ const webhook = await options.webhooks?.factsFor(txDb, event)
81
+ if (webhook) {
82
+ await new ContentEventRepository(txDb).record({
83
+ kind: event.alias === 'Umbraco.MediaDelete' ? 'mediaDeleted' : 'mediaSaved',
84
+ entityType: 'Media',
85
+ entityKey: event.key,
86
+ facts: { v: 1, webhook },
87
+ actor: principal
88
+ ? { kind: 'user', name: principal.name, userKey: principal.id }
89
+ : { kind: 'system', name: 'The site', userKey: null },
90
+ })
91
+ recorded = true
92
+ }
93
+ return written
94
+ })
95
+ if (announce(result)) await options.onChange?.()
96
+ if (recorded) options.nudge?.()
97
+ return result
98
+ }
99
+
60
100
  const userIdOf = async (principal: Principal): Promise<number | undefined> => {
61
101
  const rows = await db.query<{ id: number }>('SELECT id FROM user_account WHERE key = ?', [
62
102
  principal.id,
@@ -131,11 +171,12 @@ export function createMediaPort(
131
171
  }
132
172
  const removeBranch = async (key: string) => {
133
173
  const paths = await filesIn(key)
134
- const removed = await repo.delete(key)
135
- if (removed) {
136
- for (const path of paths) await files.remove(path)
137
- await changed()
138
- }
174
+ const removed = await commit(
175
+ (tx) => tx.delete(key),
176
+ (done) => (done ? { alias: 'Umbraco.MediaDelete', key } : undefined),
177
+ )
178
+ // The files go once the rows have: a failed delete leaves both.
179
+ if (removed) for (const path of paths) await files.remove(path)
139
180
  return removed
140
181
  }
141
182
 
@@ -145,12 +186,12 @@ export function createMediaPort(
145
186
 
146
187
  async create(input, principal) {
147
188
  try {
148
- const created = await repo.create({
149
- ...input,
150
- componentKey: null,
151
- userId: await userIdOf(principal),
152
- })
153
- await changed()
189
+ const userId = await userIdOf(principal)
190
+ const created = await commit(
191
+ (tx) => tx.create({ ...input, componentKey: null, userId }),
192
+ (doc) => ({ alias: 'Umbraco.MediaSave', key: doc.key }),
193
+ principal,
194
+ )
154
195
  return { ok: true as const, key: created.key }
155
196
  } catch (error) {
156
197
  return failure(error)
@@ -160,17 +201,16 @@ export function createMediaPort(
160
201
  async update(key, input, principal) {
161
202
  try {
162
203
  const before = await repo.byKey(key)
163
- const updated = await repo.update({
164
- ...input,
165
- key,
166
- componentKey: null,
167
- userId: await userIdOf(principal),
168
- })
204
+ const userId = await userIdOf(principal)
205
+ const updated = await commit(
206
+ (tx) => tx.update({ ...input, key, componentKey: null, userId }),
207
+ (doc) => (doc ? { alias: 'Umbraco.MediaSave', key } : undefined),
208
+ principal,
209
+ )
169
210
  if (!updated) return notFound()
170
211
  // A replaced file is no longer anyone's: Umbraco deletes it too.
171
212
  const was = before ? mediaFileOf(before) : null
172
213
  if (was && was !== mediaFileOf(updated)) await files.remove(was)
173
- await changed()
174
214
  return { ok: true as const }
175
215
  } catch (error) {
176
216
  return failure(error)
@@ -9,13 +9,18 @@
9
9
 
10
10
  import type { RedirectListing, RedirectPort } from '@crombolo/api-management'
11
11
  import type { Page } from '@crombolo/core'
12
- import { type Db, RedirectRepository, type RedirectRow } from '@crombolo/data'
12
+ import {
13
+ appendCacheInstruction,
14
+ type Db,
15
+ RedirectRepository,
16
+ type RedirectRow,
17
+ } from '@crombolo/data'
13
18
  import type { PublishedCache } from '@crombolo/render'
14
19
 
15
20
  export function createRedirectPort(
16
21
  db: Db,
17
22
  cache: PublishedCache | undefined,
18
- options: { isTracking: boolean; onChange?: () => void },
23
+ options: { isTracking: boolean; onChange?: () => void; nodeId?: string },
19
24
  ): RedirectPort {
20
25
  const redirects = new RedirectRepository(db)
21
26
 
@@ -62,9 +67,16 @@ export function createRedirectPort(
62
67
  const found = await redirects.byKey(key)
63
68
  if (!found) return 'notFound'
64
69
  if (found.source === 'config') return 'configured'
65
- await redirects.delete(key)
66
- // The rules live in the published cache's snapshot, so it has to be dropped
67
- // for the redirect to stop answering.
70
+ // The rules live in the published cache's snapshot: every node is told in
71
+ // the delete's own transaction (story 174), and this one drops its copy.
72
+ await db.transaction(async (tx) => {
73
+ await new RedirectRepository(tx).delete(key)
74
+ await appendCacheInstruction(tx, {
75
+ kind: 'content',
76
+ payload: { redirects: true },
77
+ by: options.nodeId,
78
+ })
79
+ })
68
80
  options.onChange?.()
69
81
  return 'deleted'
70
82
  },
package/src/approvals.ts CHANGED
@@ -51,7 +51,9 @@ export interface ApprovalPublisher {
51
51
  key: string,
52
52
  cultures: string[] | null,
53
53
  actor: Actor,
54
- ): Promise<{ ok: true } | { ok: false; reason: string }>
54
+ /** The event the request was approved on; anything later is not published (story 172). */
55
+ approvedHead?: number,
56
+ ): Promise<{ ok: true } | { ok: false; reason: string; kind?: string }>
55
57
  unpublish(
56
58
  key: string,
57
59
  cultures: string[] | null,
@@ -594,9 +596,21 @@ export function createApprovals(options: ApprovalsOptions): Approvals {
594
596
  })
595
597
  const result =
596
598
  request.action === 'publish'
597
- ? await options.publisher.publish(request.nodeKey, cultures, actor)
599
+ ? await options.publisher.publish(
600
+ request.nodeKey,
601
+ cultures,
602
+ actor,
603
+ request.eventId ?? undefined,
604
+ )
598
605
  : await options.publisher.unpublish(request.nodeKey, cultures, actor)
599
- if (!result.ok) return unpublishable(request, facts, result.reason)
606
+ if (!result.ok)
607
+ return unpublishable(
608
+ request,
609
+ facts,
610
+ 'kind' in result && result.kind === 'stale'
611
+ ? 'it was changed after it was approved, so it needs approving again'
612
+ : result.reason,
613
+ )
600
614
  await repo.record(request.id, {
601
615
  kind: request.action === 'publish' ? 'published' : 'unpublished',
602
616
  userKey: principal?.id ?? null,
package/src/assistant.ts CHANGED
@@ -161,13 +161,14 @@ export function createAssistantHost(options: AssistantHostOptions): AssistantHos
161
161
  const origin = new URL(source.url).origin
162
162
  const cookie = source.headers.get('cookie')
163
163
  const authorization = source.headers.get('authorization')
164
- return async ({ method, path, query, body }) => {
164
+ return async ({ method, path, query, body, headers: extra }) => {
165
165
  const url = new URL(path, origin)
166
166
  for (const [name, value] of Object.entries(query ?? {})) url.searchParams.set(name, value)
167
167
  const headers = new Headers({ accept: 'application/json' })
168
168
  if (cookie) headers.set('cookie', cookie)
169
169
  if (authorization) headers.set('authorization', authorization)
170
170
  if (body !== undefined) headers.set('content-type', 'application/json')
171
+ for (const [name, value] of Object.entries(extra ?? {})) headers.set(name, value)
171
172
  const response = await options.dispatch(
172
173
  new Request(url, {
173
174
  method: method.toUpperCase(),
@@ -184,7 +185,11 @@ export function createAssistantHost(options: AssistantHostOptions): AssistantHos
184
185
  // A non-JSON body is passed through as text; the tools report it as-is.
185
186
  }
186
187
  }
187
- return { status: response.status, body: parsed }
188
+ return {
189
+ status: response.status,
190
+ body: parsed,
191
+ etag: response.headers.get('etag') ?? undefined,
192
+ }
188
193
  }
189
194
  }
190
195
 
@@ -160,7 +160,12 @@ function locate(target: string, siteDir: string): { directory: string; dependenc
160
160
  * The bundle a path or a package name names, read whole, or a refusal: a
161
161
  * half-copied bundle must never be checked as though complete.
162
162
  */
163
- export function readBundle(target: string, siteDir: string, passphrase?: string): ResolvedBundle {
163
+ export function readBundle(
164
+ target: string,
165
+ siteDir: string,
166
+ passphrase?: string,
167
+ options: { withoutPeople?: boolean } = {},
168
+ ): ResolvedBundle {
164
169
  const { directory, dependency } = locate(target, siteDir)
165
170
  const json = readPackageJson(join(directory, 'package.json'))
166
171
  if (!json) {
@@ -199,9 +204,10 @@ export function readBundle(target: string, siteDir: string, passphrase?: string)
199
204
  people: undefined,
200
205
  openBlob: (_key, bytes) => bytes,
201
206
  }
202
- if (passphrase !== undefined && passphrase !== '')
207
+ const peopleOnly = options.withoutPeople && loaded.set.manifest.content !== 'sealed'
208
+ if ((passphrase !== undefined && passphrase !== '') || peopleOnly)
203
209
  try {
204
- opened = openBundle(loaded, passphrase)
210
+ opened = openBundle(loaded, passphrase || undefined, options)
205
211
  } catch (error) {
206
212
  if (error instanceof WrongPassphraseError)
207
213
  throw new PassphraseError(
@@ -269,6 +275,8 @@ export interface TransferInput extends SectionOptions {
269
275
  by?: string
270
276
  /** Opens what the bundle sealed; used for this request only, never stored. */
271
277
  passphrase?: string
278
+ /** Leave the file's members, users and their groups out: this site's own are untouched. */
279
+ excludePeople?: boolean
272
280
  }
273
281
 
274
282
  /**
@@ -312,6 +320,7 @@ export async function transferOptions(
312
320
  allowMissingBlobs: input.allowMissingBlobs ?? pending?.allowMissingBlobs ?? false,
313
321
  hasBlob: async (key: string) => Boolean(await store.get(key)),
314
322
  backOfficePath: config.backOfficePath,
323
+ ...(input.excludePeople ? { excludePeople: true } : {}),
315
324
  },
316
325
  under,
317
326
  problems: saved.problems,
@@ -341,7 +350,9 @@ export async function checkBundleContent(
341
350
  config: CromboloConfig,
342
351
  input: TransferInput,
343
352
  ): Promise<ContentCheckResult> {
344
- const bundle = readBundle(input.bundle, config.siteDir, input.passphrase)
353
+ const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
354
+ withoutPeople: input.excludePeople,
355
+ })
345
356
  const set = bundle.set
346
357
  const prepared = await transferOptions(db, config, bundle, input)
347
358
  const check = await checkBundle(db, set, prepared.options)
@@ -493,7 +504,9 @@ export async function installBundleContent(
493
504
  config: CromboloConfig,
494
505
  input: ContentImportInput,
495
506
  ): Promise<ContentImportResult> {
496
- const bundle = readBundle(input.bundle, config.siteDir, input.passphrase)
507
+ const bundle = readBundle(input.bundle, config.siteDir, input.passphrase, {
508
+ withoutPeople: input.excludePeople,
509
+ })
497
510
  const { set, blobs, carried } = bundle
498
511
  // Before the backup and the sections: nothing of a bundle that cannot be
499
512
  // opened is applied.
@@ -538,6 +551,10 @@ export async function installBundleContent(
538
551
  ])
539
552
  referencedPresent = true
540
553
  }
554
+ if (replace === 'replace-all' && input.excludePeople)
555
+ return refuse([
556
+ "--replace-all deletes the people the file lacks, so it cannot leave the file's people out; use --replace",
557
+ ])
541
558
  if (replace === 'replace-all' && !carriesAdministrator(set.people))
542
559
  return refuse([
543
560
  'this file carries no back-office administrator, so replacing everything would leave nobody able to sign in; export it with --with-users, or use --replace',
package/src/config.ts CHANGED
@@ -255,6 +255,11 @@ export interface CromboloConfig {
255
255
  }
256
256
  /** How many days the audit log keeps an entry; 0 keeps them forever. docs/audit-log.md. */
257
257
  auditRetentionDays: number
258
+ /**
259
+ * How many days delivered webhooks, their log and dispatched content events
260
+ * are kept; 0 keeps them forever. Failed work stays until retried. docs/webhooks.md.
261
+ */
262
+ eventRetentionDays: number
258
263
  /** Where uploaded media files live; served at `/media/`. */
259
264
  mediaDir: string
260
265
  /**
@@ -455,6 +460,7 @@ export const DEFAULTS = {
455
460
  keepAllVersionsNewerThanDays: 7,
456
461
  keepLatestVersionPerDayForDays: 90,
457
462
  auditRetentionDays: 365,
463
+ eventRetentionDays: 30,
458
464
  memberRegistrationType: 'Member',
459
465
  memberSessionMinutes: 60 * 24 * 14,
460
466
  maxFailedPasswordAttempts: 5,
@@ -598,6 +604,10 @@ export function loadConfig(
598
604
  setting('CROMBOLO_AUDIT_RETENTION_DAYS'),
599
605
  DEFAULTS.auditRetentionDays,
600
606
  ),
607
+ eventRetentionDays: nonNegative(
608
+ setting('CROMBOLO_EVENT_RETENTION_DAYS'),
609
+ DEFAULTS.eventRetentionDays,
610
+ ),
601
611
  mediaDir: setting('CROMBOLO_MEDIA_DIR') ?? DEFAULTS.mediaDir,
602
612
  mediaStore: undefined,
603
613
  logsDir: setting('CROMBOLO_LOGS_DIR') ?? DEFAULTS.logsDir,
@@ -788,7 +798,7 @@ export function describeDatabase(
788
798
  }
789
799
  }
790
800
 
791
- export const VERSION = '0.23.0'
801
+ export const VERSION = '0.25.0'
792
802
 
793
803
  /** A whole number of seconds from the environment; undefined when unset or not one. */
794
804
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {