@crombolo/server 0.24.1 → 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.24.1",
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.24.1",
34
- "@crombolo/api-management": "0.24.1",
35
- "@crombolo/assistant": "0.24.1",
36
- "@crombolo/auth": "0.24.1",
37
- "@crombolo/backoffice-host": "0.24.1",
38
- "@crombolo/content": "0.24.1",
39
- "@crombolo/contracts": "0.24.1",
40
- "@crombolo/core": "0.24.1",
41
- "@crombolo/data": "0.24.1",
42
- "@crombolo/render": "0.24.1",
43
- "@crombolo/schema": "0.24.1",
44
- "@crombolo/transfer": "0.24.1",
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,10 +4,13 @@
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,
@@ -72,6 +75,36 @@ const GROUPS: HealthCheckGroup[] = [
72
75
  },
73
76
  ]
74
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
+
75
108
  const QUEUE_LABELS = {
76
109
  changes: 'change(s) waiting to be passed on',
77
110
  webhooks: 'webhook delivery(ies)',
@@ -250,9 +283,16 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
250
283
  const results = live.map((node) =>
251
284
  result(
252
285
  'Info',
253
- `${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}`}.`,
254
287
  ),
255
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
+ }
256
296
  const releases = new Set(live.map((node) => node.cromboloVersion ?? 'unknown'))
257
297
  const schemas = new Set(live.map((node) => `${node.version}/${node.revision}`))
258
298
  if (releases.size > 1)
@@ -273,6 +313,7 @@ export function createDiagnosticsPort(options: HealthCheckOptions): DiagnosticsP
273
313
  results.unshift(
274
314
  result('Success', `${live.length} server(s) running Crombolo ${[...releases][0]}.`),
275
315
  )
316
+ results.unshift(...freshnessResults(live, latest, since, at))
276
317
  return results
277
318
  }
278
319
 
@@ -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
  },
@@ -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
@@ -798,7 +798,7 @@ export function describeDatabase(
798
798
  }
799
799
  }
800
800
 
801
- export const VERSION = '0.24.1'
801
+ export const VERSION = '0.25.0'
802
802
 
803
803
  /** A whole number of seconds from the environment; undefined when unset or not one. */
804
804
  function numberSetting(name: Parameters<typeof setting>[0]): number | undefined {
@@ -11,7 +11,12 @@ import {
11
11
  type DocumentOperations,
12
12
  type EventSink,
13
13
  } from '@crombolo/content'
14
- import { currentSchemaState, type Db, RedirectRepository } from '@crombolo/data'
14
+ import {
15
+ appendCacheInstruction,
16
+ currentSchemaState,
17
+ type Db,
18
+ RedirectRepository,
19
+ } from '@crombolo/data'
15
20
  import { PublishedCache } from '@crombolo/render'
16
21
  import { createPublishedContentSource } from './adapters/documents.ts'
17
22
  import { createApprovals } from './approvals.ts'
@@ -75,6 +80,12 @@ export async function siteDocumentOperations(
75
80
  cache,
76
81
  redirects: new RedirectRepository(db),
77
82
  enabled: config.trackRedirects,
83
+ instruct: () =>
84
+ appendCacheInstruction(db, {
85
+ kind: 'content',
86
+ payload: { redirects: true },
87
+ by: `cli:${config.nodeId}`,
88
+ }),
78
89
  }),
79
90
  afterDomains: (node, assignment) => writeDomainsFor(db, config.siteDir, node, assignment),
80
91
  refusalReason: (error) =>
package/src/ports.ts CHANGED
@@ -39,6 +39,7 @@ import {
39
39
  permissionsForPath,
40
40
  } from '@crombolo/core'
41
41
  import {
42
+ appendCacheInstruction,
42
43
  ContentEventRepository,
43
44
  ContentTypeRepository,
44
45
  type Db,
@@ -638,6 +639,7 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
638
639
  deps.redirects = createRedirectPort(options.db, options.cache, {
639
640
  isTracking: options.config.trackRedirects,
640
641
  onChange: () => options.cache?.invalidate(),
642
+ nodeId: options.schema?.nodeId,
641
643
  })
642
644
  deps.packages = createPackagePort(options.db, {
643
645
  siteName: options.config.siteName,
@@ -668,12 +670,20 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
668
670
  }
669
671
  deps.dictionary = createDictionaryPort(options.db, mediaFiles, {
670
672
  onChange: () => options.cache?.invalidate(),
673
+ nodeId: options.schema?.nodeId,
671
674
  })
675
+ const db = options.db
672
676
  const tracker = options.cache
673
677
  ? createRedirectTracker({
674
678
  cache: options.cache,
675
- redirects: new RedirectRepository(options.db),
679
+ redirects: new RedirectRepository(db),
676
680
  enabled: options.config.trackRedirects,
681
+ instruct: () =>
682
+ appendCacheInstruction(db, {
683
+ kind: 'content',
684
+ payload: { redirects: true },
685
+ by: options.schema?.nodeId,
686
+ }),
677
687
  })
678
688
  : undefined
679
689
  if (options.cache)
package/src/redirects.ts CHANGED
@@ -39,6 +39,12 @@ export function createRedirectTracker(options: {
39
39
  cache: PublishedCache
40
40
  redirects: RedirectRepository
41
41
  enabled: boolean
42
+ /**
43
+ * Tells every node a redirect was written (story 174). The routes it compares
44
+ * are read from the published cache once the change has committed, so this
45
+ * moves the checkpoint just after the change rather than inside it.
46
+ */
47
+ instruct?: () => Promise<unknown>
42
48
  }): RedirectTracker {
43
49
  if (!options.enabled) return NO_REDIRECT_TRACKING
44
50
  const { cache, redirects } = options
@@ -99,7 +105,10 @@ export function createRedirectTracker(options: {
99
105
  // The rules are part of the cache's snapshot, and reading the new routes
100
106
  // above has just rebuilt it — so without this the redirect just written
101
107
  // would not answer until something else dropped the cache.
102
- if (wrote) cache.invalidate()
108
+ if (wrote) {
109
+ await options.instruct?.()
110
+ cache.invalidate()
111
+ }
103
112
  },
104
113
  }
105
114
  }
package/src/schema.ts CHANGED
@@ -19,6 +19,7 @@ import {
19
19
  type Finding,
20
20
  Locks,
21
21
  latestCacheInstructionId,
22
+ latestCheckpoint,
22
23
  latestLedgerId,
23
24
  type NodeSchemaState,
24
25
  readWritesPaused,
@@ -247,14 +248,27 @@ export interface CachePollerOptions {
247
248
  role?: string
248
249
  /** Called for instructions other nodes appended. */
249
250
  onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
251
+ /**
252
+ * The published cache's freshness (story 174). With it, content and schema
253
+ * instructions only wake the poll: the node compares the latest committed
254
+ * checkpoint with the one it serves, and is told it is behind. Being ordered
255
+ * by commit, the checkpoint cannot skip a change that committed late.
256
+ */
257
+ content?: {
258
+ served(): { checkpoint: number | undefined; builtAt: Date } | undefined
259
+ behind(latest: number): void
260
+ }
250
261
  }
251
262
 
263
+ /** A rebuild asked for and not yet served is asked for again after this long. */
264
+ const REASK_AFTER_MS = 30_000
265
+
252
266
  /**
253
267
  * Polls `cache_instruction` from where this node came in; own instructions are
254
268
  * skipped. Where the database can notify, a write wakes it at once and the
255
269
  * timer is only the fallback.
256
270
  */
257
- /** How far behind its cursor the poller looks for a row that committed late. */
271
+ /** How far behind its cursor the poller looks for a views instruction that committed late. */
258
272
  const CURSOR_WINDOW = 100
259
273
 
260
274
  export class CacheInstructionPoller {
@@ -272,6 +286,14 @@ export class CacheInstructionPoller {
272
286
  #bootLedgerId = 0
273
287
  #readsUnsafe = false
274
288
  #paused: WritesPaused | undefined
289
+ /** The checkpoint this node last asked its cache to catch up to, and when. */
290
+ #asked: { checkpoint: number; at: number } | undefined
291
+ #latest: number | undefined
292
+
293
+ /** The latest committed content checkpoint, as of the last poll. */
294
+ get latestCheckpoint(): number | undefined {
295
+ return this.#latest
296
+ }
275
297
 
276
298
  /** True once an upgrade has moved the database past this node: reads only. */
277
299
  get behind(): boolean {
@@ -349,15 +371,22 @@ export class CacheInstructionPoller {
349
371
  this.#seen.add(instruction.id)
350
372
  this.#cursor = Math.max(this.#cursor, instruction.id)
351
373
  if (instruction.createdBy === nodeId) continue
352
- onInstruction(instruction.kind, instruction.payload)
353
374
  applied += 1
375
+ // The checkpoint below decides; an instruction about content only woke us.
376
+ if (this.#options.content && instruction.checkpoint !== null) continue
377
+ onInstruction(instruction.kind, instruction.payload)
354
378
  }
355
379
  for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
380
+ const served = await this.#catchUp()
356
381
  await touchServer(db, {
357
382
  nodeId,
358
383
  ...nodeState,
359
384
  role: this.#options.role,
360
385
  cromboloVersion: VERSION,
386
+ served:
387
+ served?.checkpoint === undefined
388
+ ? undefined
389
+ : { checkpoint: served.checkpoint, at: served.builtAt },
361
390
  })
362
391
  const current = await currentSchemaState(db)
363
392
  const behind = compareStates(nodeState, current) < 0
@@ -371,6 +400,27 @@ export class CacheInstructionPoller {
371
400
  return applied
372
401
  }
373
402
 
403
+ /**
404
+ * Tells the cache it is behind when the latest committed checkpoint is past
405
+ * the one it serves. A cache that has not been built yet is left to build on
406
+ * its first read. A request not served within a while is made again, so a
407
+ * failed rebuild is retried.
408
+ */
409
+ async #catchUp() {
410
+ const content = this.#options.content
411
+ if (!content) return undefined
412
+ const latest = await latestCheckpoint(this.#options.db)
413
+ this.#latest = latest
414
+ const served = content.served()
415
+ if (served?.checkpoint === undefined || served.checkpoint >= latest) return served
416
+ const asked = this.#asked
417
+ if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
418
+ this.#asked = { checkpoint: latest, at: Date.now() }
419
+ content.behind(latest)
420
+ }
421
+ return served
422
+ }
423
+
374
424
  stop(): void {
375
425
  if (this.#timer) clearInterval(this.#timer)
376
426
  this.#timer = undefined
package/src/server.ts CHANGED
@@ -571,6 +571,12 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
571
571
  cache,
572
572
  redirects: new RedirectRepository(db),
573
573
  enabled: config.trackRedirects,
574
+ instruct: () =>
575
+ appendCacheInstruction(db, {
576
+ kind: 'content',
577
+ payload: { redirects: true },
578
+ by: schema.nodeId,
579
+ }),
574
580
  }),
575
581
  }
576
582
  const afterSync = async (report: SyncReport | undefined) => {
@@ -710,6 +716,19 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
710
716
  // of the bytes this node reads, so a superseded one is harmless.
711
717
  snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
712
718
  },
719
+ // Behind the latest committed checkpoint: rebuilt now rather than on the next
720
+ // read, so an idle node catches up and says so (story 174).
721
+ content: {
722
+ served: () => cache.served(),
723
+ behind: () => {
724
+ cache.invalidate()
725
+ void cache
726
+ .snapshot()
727
+ .catch((error: unknown) =>
728
+ renderLog.error('Could not rebuild the published cache: {error}', { error }),
729
+ )
730
+ },
731
+ },
713
732
  })
714
733
  await poller.start(config.development ? 2_000 : 5_000)
715
734
  const watcher =
@@ -1014,6 +1033,23 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1014
1033
  // Fixed by the contract and the client's SDK, wherever the editor is mounted.
1015
1034
  const apiPrefix = MANAGEMENT_API_PREFIX
1016
1035
 
1036
+ /**
1037
+ * Which committed changes this node's published cache holds (story 174):
1038
+ * numbers and times only. `latest` is as of the last poll; `behind` is null
1039
+ * until both are known.
1040
+ */
1041
+ const contentFreshness = () => {
1042
+ const served = cache.served()
1043
+ const latest = poller.latestCheckpoint
1044
+ const checkpoint = served?.checkpoint
1045
+ return {
1046
+ checkpoint: checkpoint ?? null,
1047
+ latest: latest ?? null,
1048
+ behind: checkpoint === undefined || latest === undefined ? null : checkpoint < latest,
1049
+ builtAt: served?.builtAt.toISOString() ?? null,
1050
+ }
1051
+ }
1052
+
1017
1053
  const health = () => {
1018
1054
  const paused = poller.paused
1019
1055
  const readOnly = schema.compatibilityMode || poller.behind || paused !== undefined
@@ -1037,6 +1073,7 @@ export async function createServer(config: CromboloConfig = loadConfig()): Promi
1037
1073
  revision: schema.nodeState.revision,
1038
1074
  nodeId: schema.nodeId,
1039
1075
  role: config.role,
1076
+ content: contentFreshness(),
1040
1077
  components: snapshots.status(),
1041
1078
  }
1042
1079
  }
@@ -43,8 +43,19 @@ export async function redirectAfterUrlChange(
43
43
  ctx: UrlChangeContext,
44
44
  before: UrlOptions,
45
45
  ): Promise<void> {
46
+ const withBefore = (source: PublishedContentSource): PublishedContentSource => ({
47
+ ...source,
48
+ loadUrlOptions: async () => before,
49
+ })
50
+ // The snapshot hands the build a source of its own, so the old setting goes on that too.
51
+ const snapshot = ctx.source.withSnapshot?.bind(ctx.source)
46
52
  const old = new PublishedCache(
47
- { ...ctx.source, loadUrlOptions: async () => before },
53
+ {
54
+ ...withBefore(ctx.source),
55
+ withSnapshot: snapshot
56
+ ? (fn) => snapshot((scoped, checkpoint) => fn(withBefore(scoped), checkpoint))
57
+ : undefined,
58
+ },
48
59
  ctx.cacheOptions,
49
60
  )
50
61
  const captured: DocumentRoute[] = []