@crombolo/server 0.51.0 → 0.51.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crombolo/server",
3
- "version": "0.51.0",
3
+ "version": "0.51.1",
4
4
  "description": "Internal to crombolo, with no compatibility promise: use @crombolo/crombolo. The crombolo HTTP server: routing, configuration, media stores and background jobs.",
5
5
  "license": "MIT",
6
6
  "author": "Crombolo",
@@ -31,18 +31,18 @@
31
31
  "access": "public"
32
32
  },
33
33
  "dependencies": {
34
- "@crombolo/api-delivery": "0.51.0",
35
- "@crombolo/api-management": "0.51.0",
36
- "@crombolo/auth": "0.51.0",
37
- "@crombolo/backoffice-host": "0.51.0",
38
- "@crombolo/common": "0.51.0",
39
- "@crombolo/content": "0.51.0",
40
- "@crombolo/contracts": "0.51.0",
41
- "@crombolo/core": "0.51.0",
42
- "@crombolo/data": "0.51.0",
43
- "@crombolo/render": "0.51.0",
44
- "@crombolo/schema": "0.51.0",
45
- "@crombolo/transfer": "0.51.0",
34
+ "@crombolo/api-delivery": "0.51.1",
35
+ "@crombolo/api-management": "0.51.1",
36
+ "@crombolo/auth": "0.51.1",
37
+ "@crombolo/backoffice-host": "0.51.1",
38
+ "@crombolo/common": "0.51.1",
39
+ "@crombolo/content": "0.51.1",
40
+ "@crombolo/contracts": "0.51.1",
41
+ "@crombolo/core": "0.51.1",
42
+ "@crombolo/data": "0.51.1",
43
+ "@crombolo/render": "0.51.1",
44
+ "@crombolo/schema": "0.51.1",
45
+ "@crombolo/transfer": "0.51.1",
46
46
  "@logtape/logtape": "^2.3.8",
47
47
  "@opentelemetry/api": "1.10.0",
48
48
  "@opentelemetry/context-async-hooks": "3.0.0",
@@ -66,9 +66,11 @@ import {
66
66
  revertCode,
67
67
  } from './bundle-code-install.ts'
68
68
  import {
69
+ announceFiles,
69
70
  type CarriedSections,
70
71
  carriedSections,
71
72
  carriesSections,
73
+ changedFileSections,
72
74
  keepDictionary,
73
75
  keptDictionary,
74
76
  planSections,
@@ -76,6 +78,7 @@ import {
76
78
  type RestoredFiles,
77
79
  replacementsNeedingPermission,
78
80
  restoreSectionFiles,
81
+ runFileSections,
79
82
  type SectionFile,
80
83
  type SectionOptions,
81
84
  type SectionPlan,
@@ -673,6 +676,11 @@ export async function installBundleContent(
673
676
  backup,
674
677
  )
675
678
 
679
+ const changedFiles = changedFileSections(config, carried, plan, {
680
+ ...effective,
681
+ replace: Boolean(replace),
682
+ })
683
+
676
684
  // ---- 1. Stage
677
685
  const runDir = stageBackups(config)
678
686
  const staged =
@@ -762,6 +770,7 @@ export async function installBundleContent(
762
770
  swapSections(config, staged)
763
771
  if (staged.next.schema && config.schemaStore)
764
772
  await publishSchema(config.schemaStore, config.schemaDir)
773
+ await announceFiles(db, config, changedFiles)
765
774
  }
766
775
  const kept = promoteStaged(config, runDir, runId)
767
776
  const codeInstalled =
@@ -836,7 +845,9 @@ export async function revertSections(
836
845
  runId: string,
837
846
  ): Promise<RevertedSections> {
838
847
  const swapped = swappedSections(config, runId)
848
+ const touched = runFileSections(config, runId)
839
849
  const files = restoreSectionFiles(config, runId)
850
+ await announceFiles(db, config, touched)
840
851
  let schema: string | undefined
841
852
  if (swapped.includes('schema')) {
842
853
  // A type the install brought has content only in the bin by now, which is
@@ -28,12 +28,13 @@ import {
28
28
  writeFileSync,
29
29
  } from 'node:fs'
30
30
  import { tmpdir } from 'node:os'
31
- import { dirname, join } from 'node:path'
32
- import type { Db } from '@crombolo/data'
31
+ import { dirname, join, sep } from 'node:path'
32
+ import { appendCacheInstruction, type Db } from '@crombolo/data'
33
33
  import type { BundleSection, LoadedBundle } from '@crombolo/transfer'
34
34
  import { BUNDLE_SECTIONS } from '@crombolo/transfer'
35
35
  import type { CromboloConfig } from './config.ts'
36
36
  import { importDictionaryUdt } from './dictionary-transfer.ts'
37
+ import { logger } from './logging.ts'
37
38
  import { checkSchemaDirectory, syncSchemaDirectory } from './schema.ts'
38
39
  import { publishSchema } from './schema-store.ts'
39
40
 
@@ -446,6 +447,80 @@ export function restoreSectionFiles(config: CromboloConfig, runId: string): Rest
446
447
  return { restored, removed }
447
448
  }
448
449
 
450
+ /**
451
+ * The file sections an install will change here, asked before it moves anything.
452
+ * The plan names what lands; a replace also takes out what the file lacks.
453
+ */
454
+ export function changedFileSections(
455
+ config: CromboloConfig,
456
+ carried: CarriedSections,
457
+ plan: SectionPlan | undefined,
458
+ options: SectionOptions & { replace?: boolean },
459
+ ): BundleSection[] {
460
+ if (options.withoutFiles) return []
461
+ const changed = new Set<BundleSection>()
462
+ for (const file of plan?.files ?? []) {
463
+ const section = sectionFor(file.path)
464
+ if (section && FILE_SECTIONS.includes(section) && file.action !== 'unchanged')
465
+ changed.add(section)
466
+ }
467
+ if (options.replace)
468
+ for (const section of FILE_SECTIONS) {
469
+ const dir = destinationOf(config, section) as string
470
+ if (!existsSync(dir)) continue
471
+ const kept = new Set(carried.carries[section] ?? [])
472
+ for (const path of new Bun.Glob('**/*').scanSync({ cwd: dir, onlyFiles: true, dot: true }))
473
+ if (!kept.has(`${BUNDLE_SECTIONS[section]}/${path.split(sep).join('/')}`)) {
474
+ changed.add(section)
475
+ break
476
+ }
477
+ }
478
+ return [...changed]
479
+ }
480
+
481
+ /** The file sections a run touched, for its revert to announce. */
482
+ export function runFileSections(config: CromboloConfig, runId: string): BundleSection[] {
483
+ const swapped = swappedSections(config, runId)
484
+ const record = join(config.siteDir, RUN_BACKUP_DIR, runId, RECORD_FILE)
485
+ const paths =
486
+ swapped.length === 0 && existsSync(record)
487
+ ? (JSON.parse(readFileSync(record, 'utf8')) as FileRecord[]).map((entry) => entry.path)
488
+ : []
489
+ const sections = [
490
+ ...swapped,
491
+ ...paths.flatMap((path) => {
492
+ const section = sectionFor(path)
493
+ return section ? [section] : []
494
+ }),
495
+ ]
496
+ return [...new Set(sections)].filter((section) => FILE_SECTIONS.includes(section))
497
+ }
498
+
499
+ /**
500
+ * Tells every node the site's files changed (story 285): the only way a view,
501
+ * a stylesheet or a public file reaches a node when the writer is another
502
+ * process, on a folder no watcher sees. Signed so that the node that ran it, if
503
+ * a node did, follows too. The files are in place by now, so a failure is said
504
+ * rather than thrown.
505
+ */
506
+ export async function announceFiles(
507
+ db: Db,
508
+ config: CromboloConfig,
509
+ sections: readonly BundleSection[],
510
+ ): Promise<void> {
511
+ const by = `import:${config.nodeId}`
512
+ try {
513
+ if (sections.some((section) => section !== 'public'))
514
+ await appendCacheInstruction(db, { kind: 'components', by })
515
+ if (sections.includes('public')) await appendCacheInstruction(db, { kind: 'public-files', by })
516
+ } catch (error) {
517
+ logger('transfer').warning(
518
+ 'The files are in place, but the running nodes could not be told; restart them, or import again: {error}',
519
+ { error: error instanceof Error ? error.message : String(error) },
520
+ )
521
+ }
522
+ }
523
+
449
524
  /** The section a bundle path belongs to, by its leading directory. */
450
525
  function sectionFor(path: string): BundleSection | undefined {
451
526
  if (path === `${BUNDLE_SECTIONS.dictionary}.udt`) return 'dictionary'
package/src/config.ts CHANGED
@@ -1091,7 +1091,7 @@ export function describeDatabase(
1091
1091
  }
1092
1092
  }
1093
1093
 
1094
- export const VERSION = '0.51.0'
1094
+ export const VERSION = '0.51.1'
1095
1095
 
1096
1096
  /** A whole number of seconds from the environment; undefined when unset or not one. */
1097
1097
  /** A positive number from a setting, else the default. */
package/src/core.ts CHANGED
@@ -88,6 +88,8 @@ import { createWorkerWatch } from './worker-watch.ts'
88
88
 
89
89
  /** What only the serving half of a node supplies; a worker leaves each out. */
90
90
  export interface CoreHooks {
91
+ /** A site's stylesheets and scripts, or its `public/` folder, changed elsewhere (story 285). */
92
+ onSiteFiles?: (change: 'assets' | 'public') => void
91
93
  /** The published cache was dropped: a server drops its drafts and reloads open pages. */
92
94
  onCacheInvalidate?: () => void
93
95
  /** A newer views generation replaced the one in use. */
@@ -509,10 +511,17 @@ export async function createCore(config: CromboloConfig, hooks: CoreHooks) {
509
511
  // definitions. `views` changes the code that renders it, which is a new
510
512
  // snapshot rather than anything in the published cache.
511
513
  onInstruction: (kind, payload) => {
514
+ if (kind === 'public-files') return hooks.onSiteFiles?.('public')
512
515
  if (kind !== 'components') return cache.invalidate()
513
516
  // The hash only says when to stop looking eagerly; the snapshot is always
514
517
  // of the bytes this node reads, so a superseded one is harmless.
515
518
  snapshots.announce(typeof payload.hash === 'string' ? payload.hash : undefined)
519
+ hooks.onSiteFiles?.('assets')
520
+ },
521
+ onMissed: () => {
522
+ snapshots.announce()
523
+ hooks.onSiteFiles?.('assets')
524
+ hooks.onSiteFiles?.('public')
516
525
  },
517
526
  // Behind the latest committed checkpoint: rebuilt now rather than on the next
518
527
  // read, so an idle node catches up and says so (story 174). A worker builds
package/src/index.ts CHANGED
@@ -108,6 +108,7 @@ export * from './server.ts'
108
108
  export * from './server-events.ts'
109
109
  export * from './settings.ts'
110
110
  export * from './setup.ts'
111
+ export * from './site-assets.ts'
111
112
  export * from './site-data.ts'
112
113
  export * from './site-file.ts'
113
114
  export * from './site-public.ts'
package/src/schema.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  latestCheckpoint,
25
25
  latestLedgerId,
26
26
  type NodeSchemaState,
27
+ oldestCacheInstructionId,
27
28
  readWritesPaused,
28
29
  touchServer,
29
30
  updateSchemaStateHash,
@@ -251,6 +252,11 @@ export interface CachePollerOptions {
251
252
  role?: string
252
253
  /** Called for instructions other nodes appended. */
253
254
  onInstruction(kind: CacheInstructionKind, payload: Record<string, unknown>): void
255
+ /**
256
+ * Instructions this node never read were pruned (story 285). What has a
257
+ * checkpoint catches up by it; what has none has to look again.
258
+ */
259
+ onMissed?(): void
254
260
  /**
255
261
  * The published cache's freshness (story 174). With it, content and schema
256
262
  * instructions only wake the poll: the node compares the latest committed
@@ -392,6 +398,10 @@ export class CacheInstructionPoller {
392
398
  const { db, nodeId, nodeState, onInstruction } = this.#options
393
399
  // Read first: every instruction numbered up to it has committed, and is visible below.
394
400
  const latest = await latestCheckpoint(db)
401
+ // Pruning keeps the newest row, so the log only starts past this node when
402
+ // it lost rows. A gap in ids makes this a false alarm, which costs a look.
403
+ const oldest = await oldestCacheInstructionId(db)
404
+ if (oldest !== undefined && oldest > this.#cursor + 1) this.#options.onMissed?.()
395
405
  // A row can commit after one with a higher id (Postgres hands ids out
396
406
  // before commit), so a short window behind the cursor is read again and
397
407
  // the ids already seen are skipped.
package/src/server.ts CHANGED
@@ -362,6 +362,8 @@ export interface ServerOptions {
362
362
  * (story 241); absent when nothing supervises this one.
363
363
  */
364
364
  restart?: () => Promise<RestartOutcome>
365
+ /** Off, a node hears of file changes only through instructions, as on a network folder. */
366
+ watchSiteFiles?: boolean
365
367
  }
366
368
 
367
369
  export async function createServer(
@@ -385,7 +387,11 @@ export async function createServer(
385
387
  // and a template error says which components were rendering.
386
388
  const live = config.liveReload ? createLiveReload() : undefined
387
389
  let drafts: { cache: PublishedCache; version: number } | undefined
390
+ // Set once they exist: a Postgres notification can wake the poller before then,
391
+ // and they read the disk as they start anyway.
392
+ let siteFilesChanged: ((change: 'assets' | 'public') => void) | undefined
388
393
  const core = await createCore(config, {
394
+ onSiteFiles: (change) => siteFilesChanged?.(change),
389
395
  onCacheInvalidate: () => {
390
396
  drafts = undefined
391
397
  live?.changed('content')
@@ -862,13 +868,19 @@ export async function createServer(
862
868
  const generatedScripts = new Map(
863
869
  generatedBodies.map(([path, body]) => [generatedPaths.get(path) as string, body]),
864
870
  )
865
- const siteAssets = new SiteAssets([
866
- { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
867
- { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
868
- ])
871
+ const siteAssets = new SiteAssets(
872
+ [
873
+ { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
874
+ { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
875
+ ],
876
+ { watch: serverOptions.watchSiteFiles },
877
+ )
869
878
  siteAssets.start()
870
- const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath)
879
+ const publicFiles = new PublicFiles(config.publicDir, config.backOfficePath, {
880
+ watch: serverOptions.watchSiteFiles,
881
+ })
871
882
  publicFiles.start()
883
+ siteFilesChanged = (change) => (change === 'public' ? publicFiles.changed() : siteAssets.rescan())
872
884
  // A file wins at its path (story 284), so a page it hides is worth saying once.
873
885
  if (config.role !== 'api' && publicFiles.paths().length > 0)
874
886
  void publicFiles
@@ -16,18 +16,21 @@ export interface AssetRoot {
16
16
 
17
17
  export class SiteAssets {
18
18
  readonly #roots: readonly AssetRoot[]
19
+ readonly #watch: boolean
19
20
  readonly #hashes = new Map<string, string>()
20
21
  readonly #watchers: FSWatcher[] = []
21
22
 
22
- constructor(roots: readonly AssetRoot[]) {
23
+ constructor(roots: readonly AssetRoot[], options: { watch?: boolean } = {}) {
23
24
  this.#roots = roots
25
+ this.#watch = options.watch !== false
24
26
  }
25
27
 
26
28
  /** Hashes every file, and watches each folder for changes. */
27
29
  start(): void {
30
+ this.rescan()
31
+ if (!this.#watch) return
28
32
  for (const root of this.#roots) {
29
33
  if (!existsSync(root.dir)) continue
30
- for (const file of filesIn(root.dir)) this.#hash(root, file)
31
34
  try {
32
35
  const watcher = watch(root.dir, { recursive: true }, (_event, name) => {
33
36
  if (name) this.#hash(root, join(root.dir, name.toString()))
@@ -40,6 +43,18 @@ export class SiteAssets {
40
43
  }
41
44
  }
42
45
 
46
+ /** Every file hashed again, and one that has gone forgotten: for a change no watcher saw. */
47
+ rescan(): void {
48
+ this.#hashes.clear()
49
+ for (const root of this.#roots) {
50
+ try {
51
+ if (existsSync(root.dir)) for (const file of filesIn(root.dir)) this.#hash(root, file)
52
+ } catch {
53
+ // A file that went while the folder was read: the next change says so.
54
+ }
55
+ }
56
+ }
57
+
43
58
  /** The hashed address of a file the site has, or undefined. */
44
59
  address(path: string): string | undefined {
45
60
  const hash = this.#hashes.get(path)
@@ -52,9 +67,13 @@ export class SiteAssets {
52
67
 
53
68
  #hash(root: AssetRoot, file: string): void {
54
69
  const path = `${root.prefix}/${relative(root.dir, file).split(sep).join('/')}`
55
- if (!file.toLowerCase().endsWith(root.extension)) return
56
70
  try {
57
- if (!statSync(file).isFile()) return
71
+ // A folder moved in reports only its own name.
72
+ if (statSync(file).isDirectory()) {
73
+ for (const inside of filesIn(file)) this.#hash(root, inside)
74
+ return
75
+ }
76
+ if (!file.toLowerCase().endsWith(root.extension)) return
58
77
  this.#hashes.set(path, contentHash(readFileSync(file)))
59
78
  } catch {
60
79
  this.#hashes.delete(path)
@@ -22,6 +22,11 @@ const WELL_KNOWN = '.well-known'
22
22
  /** What git needs to keep an empty folder: it travels with the folder, and is never served. */
23
23
  const FOLDER_KEEPER = '.gitkeep'
24
24
  const RESCAN_DELAY_MS = 25
25
+ /**
26
+ * After a node is told of a change, it lists the folder again at these delays:
27
+ * a shared folder can show another machine's write up to a minute late.
28
+ */
29
+ const RELIST_AFTER_MS = [5_000, 15_000, 30_000, 60_000, 90_000]
25
30
 
26
31
  /** Whether an address is the CMS's own, which no public file can take. */
27
32
  export function isReservedPublicPath(path: string, backOfficePath: string): boolean {
@@ -129,15 +134,25 @@ export class PublicFiles {
129
134
  #folder: FSWatcher | undefined
130
135
  #parent: FSWatcher | undefined
131
136
  #rescan: ReturnType<typeof setTimeout> | undefined
137
+ #relist: ReturnType<typeof setTimeout>[] = []
138
+ readonly #watch: boolean
139
+ readonly #relistAfter: readonly number[]
132
140
 
133
- constructor(root: string, backOfficePath: string) {
141
+ constructor(
142
+ root: string,
143
+ backOfficePath: string,
144
+ options: { watch?: boolean; relistAfterMs?: readonly number[] } = {},
145
+ ) {
134
146
  this.#root = root
135
147
  this.#backOfficePath = backOfficePath
148
+ this.#watch = options.watch !== false
149
+ this.#relistAfter = options.relistAfterMs ?? RELIST_AFTER_MS
136
150
  }
137
151
 
138
152
  /** Lists the folder and watches it, and watches for it being made or replaced. */
139
153
  start(): void {
140
154
  this.#list()
155
+ if (!this.#watch) return
141
156
  this.#watchFolder()
142
157
  try {
143
158
  const name = basename(this.#root)
@@ -152,8 +167,20 @@ export class PublicFiles {
152
167
  }
153
168
  }
154
169
 
170
+ /** The folder changed where no watcher can see: listed now, and again as it settles. */
171
+ changed(): void {
172
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
173
+ this.#list()
174
+ this.#relist = this.#relistAfter.map((delay) => {
175
+ const timer = setTimeout(() => this.#list(), delay)
176
+ timer.unref?.()
177
+ return timer
178
+ })
179
+ }
180
+
155
181
  close(): void {
156
182
  clearTimeout(this.#rescan)
183
+ for (const timer of this.#relist.splice(0)) clearTimeout(timer)
157
184
  this.#folder?.close()
158
185
  this.#parent?.close()
159
186
  }