@crombolo/server 0.34.0 → 0.36.2

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/index.ts CHANGED
@@ -21,6 +21,7 @@ export * from './boot-failure.ts'
21
21
  export * from './bundle-build.ts'
22
22
  export * from './bundle-code.ts'
23
23
  export * from './bundle-install.ts'
24
+ export * from './bundle-media.ts'
24
25
  export * from './bundle-reload.ts'
25
26
  export * from './bundle-sections.ts'
26
27
  export * from './bundle-tables.ts'
@@ -60,6 +61,7 @@ export * from './git-routes.ts'
60
61
  export * from './host-token.ts'
61
62
  export * from './identity-provider-overrides.ts'
62
63
  export * from './identity-providers.ts'
64
+ export * from './image-metadata.ts'
63
65
  export * from './imaging.ts'
64
66
  export * from './jobs.ts'
65
67
  export * from './listen.ts'
@@ -77,6 +79,7 @@ export * from './models-builder.ts'
77
79
  export * from './no-nodes.ts'
78
80
  export * from './oembed.ts'
79
81
  export * from './ports.ts'
82
+ export * from './rate-limit.ts'
80
83
  export * from './redirects.ts'
81
84
  export * from './remote.ts'
82
85
  export * from './remote-credentials.ts'
@@ -0,0 +1,337 @@
1
+ /**
2
+ * Who may read a media file, and the back office's permissions for media
3
+ * (story 196). docs/media.md, "Protected media".
4
+ *
5
+ * `/media/…` asks `mayRead` of a protected file: a member by their site
6
+ * cookie or a Delivery API member token, or a back-office user with the Media
7
+ * section within their start nodes. The back office's "Permissions" action
8
+ * reads and sets rules through `handle`, under
9
+ * `<backoffice>/crombolo/api/media-access/{key}`, which is not in the contract.
10
+ */
11
+ import { hasSection, type Principal } from '@crombolo/api-management'
12
+ import {
13
+ fallbackPermissions,
14
+ hasPathAccess,
15
+ isProtectedMedia,
16
+ MEDIA_POLICIES,
17
+ MEMBER_FILE_TYPES,
18
+ type MediaMember,
19
+ MediaPermissions,
20
+ type MediaPolicy,
21
+ memberMay,
22
+ NEW_MEDIA_READ,
23
+ NEW_MEDIA_WRITE,
24
+ type NewMediaRead,
25
+ type NewMediaWrite,
26
+ normaliseUuid,
27
+ ObjectTypes,
28
+ } from '@crombolo/core'
29
+ import {
30
+ appendCacheInstruction,
31
+ type Db,
32
+ type MediaAccessEntry,
33
+ type MediaAccessGroup,
34
+ type MediaAccessMember,
35
+ MediaAccessRepository,
36
+ type MediaByUrl,
37
+ MemberRepository,
38
+ NodeRepository,
39
+ ruleOf,
40
+ } from '@crombolo/data'
41
+
42
+ export interface MediaAccessDeps {
43
+ db: Db
44
+ /** The member a request's site cookie carries. */
45
+ member(request: Request): Promise<MediaMember | undefined>
46
+ /** The member a Delivery API token names, when member tokens are on. */
47
+ memberByToken?(token: string): Promise<MediaMember | undefined>
48
+ /** The back-office user a request carries. */
49
+ principal(request: Request): Promise<Principal | undefined>
50
+ /** Told after a rule or an item's setting changes, with its key, for the media cache here. */
51
+ onChange?(key: string): void | Promise<void>
52
+ /** This server's name, on the cache instruction an item's change appends. */
53
+ nodeId?: string
54
+ /** The folders wired bundles declare (story 198), by bundle name and node path. */
55
+ bundleFolders?(): ReadonlyArray<{ bundle: string; nodePath: string }>
56
+ }
57
+
58
+ const bearerOf = (request: Request): string | undefined => {
59
+ const header = request.headers.get('authorization')
60
+ return header?.toLowerCase().startsWith('bearer ') ? header.slice(7).trim() : undefined
61
+ }
62
+
63
+ const isUuid = (value: string) =>
64
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)
65
+
66
+ /** A rule as the back office sends and shows it. */
67
+ interface RuleBody {
68
+ publicRead: boolean
69
+ groups: MediaAccessGroup[]
70
+ members?: MediaAccessMember[]
71
+ newRead: NewMediaRead | null
72
+ newWrite: NewMediaWrite | null
73
+ /** File types members may upload below (story 198); empty is none. */
74
+ memberTypes: string[]
75
+ /** The largest file a member may upload below, in bytes; null sets none. */
76
+ memberMaxBytes: number | null
77
+ }
78
+
79
+ const ruleBody = (entry: MediaAccessEntry): RuleBody => ({
80
+ publicRead: entry.publicRead,
81
+ groups: entry.groups,
82
+ ...(entry.members?.length ? { members: [...entry.members] } : {}),
83
+ newRead: entry.newRead,
84
+ newWrite: entry.newWrite,
85
+ memberTypes: entry.memberTypes,
86
+ memberMaxBytes: entry.memberMaxBytes,
87
+ })
88
+
89
+ /** A rule from a request body; a string saying what is wrong otherwise. Pure. */
90
+ export function parseRuleBody(raw: unknown): RuleBody | string {
91
+ if (!raw || typeof raw !== 'object') return 'Send the permissions to set.'
92
+ const body = raw as Record<string, unknown>
93
+ const groups = Array.isArray(body.groups) ? body.groups : []
94
+ const parsed: MediaAccessGroup[] = []
95
+ for (const group of groups) {
96
+ const g = group as Record<string, unknown>
97
+ if (!g || typeof g.name !== 'string' || g.name.trim() === '') return 'Each group needs a name.'
98
+ parsed.push({ name: g.name.trim(), read: g.read === true, write: g.write === true })
99
+ }
100
+ const newRead = body.newRead ?? null
101
+ if (body.members !== undefined && !Array.isArray(body.members))
102
+ return 'Choose members from the member picker.'
103
+ const members: MediaAccessMember[] = []
104
+ for (const rawMember of (body.members ?? []) as unknown[]) {
105
+ const m = rawMember as Record<string, unknown> | null
106
+ if (!m || typeof m.key !== 'string' || !isUuid(m.key))
107
+ return 'Choose members from the member picker.'
108
+ members.push({ key: normaliseUuid(m.key), read: m.read === true, write: m.write === true })
109
+ }
110
+ if (newRead !== null && !NEW_MEDIA_READ.includes(newRead as NewMediaRead))
111
+ return 'Choose who may see new files.'
112
+ const newWrite = body.newWrite ?? null
113
+ if (newWrite !== null && !NEW_MEDIA_WRITE.includes(newWrite as NewMediaWrite))
114
+ return 'Choose who may change new files.'
115
+ const known = MEMBER_FILE_TYPES.map((type) => type.id)
116
+ const memberTypes = body.memberTypes ?? []
117
+ if (!Array.isArray(memberTypes) || memberTypes.some((t) => !known.includes(t as string)))
118
+ return 'Choose the file types members may upload from the list.'
119
+ const memberMaxBytes = body.memberMaxBytes ?? null
120
+ if (
121
+ memberMaxBytes !== null &&
122
+ (typeof memberMaxBytes !== 'number' || !Number.isInteger(memberMaxBytes) || memberMaxBytes <= 0)
123
+ )
124
+ return 'The largest file members may upload must be a size above nothing, or left empty.'
125
+ return {
126
+ publicRead: body.publicRead === true,
127
+ groups: parsed,
128
+ ...(members.length ? { members } : {}),
129
+ newRead: newRead as NewMediaRead | null,
130
+ newWrite: newWrite as NewMediaWrite | null,
131
+ memberTypes: [...new Set(memberTypes as string[])],
132
+ memberMaxBytes: memberMaxBytes as number | null,
133
+ }
134
+ }
135
+
136
+ export function createMediaAccess(deps: MediaAccessDeps) {
137
+ const { db } = deps
138
+ const repo = new MediaAccessRepository(db)
139
+ const nodes = new NodeRepository(db)
140
+
141
+ /** A node's media ancestors' keys then its own, root first. */
142
+ const chainOf = async (path: string): Promise<string[]> => {
143
+ const ids = path
144
+ .split(',')
145
+ .map(Number)
146
+ .filter((id) => id > 0)
147
+ const byId = new Map((await nodes.byIds(ids)).map((row) => [row.id, row]))
148
+ return ids.flatMap((id) => {
149
+ const row = byId.get(id)
150
+ return row && row.objectType === ObjectTypes.Media ? [row.key] : []
151
+ })
152
+ }
153
+
154
+ const mayView = async (principal: Principal, path: string, trashed: boolean) =>
155
+ hasSection(principal, 'media') &&
156
+ hasPathAccess(principal.startNodes.media, await chainOf(path), trashed)
157
+
158
+ /** The member a request carries: its site cookie, else a Delivery API member token. */
159
+ const memberOf = async (request: Request): Promise<MediaMember | undefined> => {
160
+ const fromCookie = await deps.member(request)
161
+ if (fromCookie) return fromCookie
162
+ const token = bearerOf(request)
163
+ return token && deps.memberByToken ? deps.memberByToken(token) : undefined
164
+ }
165
+
166
+ /**
167
+ * Whether this request may read a protected file. A file in the recycle bin
168
+ * has left the folder that protected it, so only a back-office user may.
169
+ */
170
+ async function mayRead(request: Request, item: MediaByUrl): Promise<boolean> {
171
+ if (!item.trashed) {
172
+ const member = await memberOf(request)
173
+ if (member && memberMay('read', item.access, item.rule, member)) return true
174
+ }
175
+ const principal = await deps.principal(request)
176
+ return principal ? mayView(principal, item.path, item.trashed) : false
177
+ }
178
+
179
+ /** Whether a file is closed to someone who is not signed in. */
180
+ const isProtected = (item: MediaByUrl) => item.trashed || isProtectedMedia(item.access, item.rule)
181
+
182
+ const memberGroups = async (): Promise<string[]> => {
183
+ const rows = await db.query<{ text: string | null }>(
184
+ 'SELECT text FROM node WHERE node_object_type = ? ORDER BY text',
185
+ [ObjectTypes.MemberGroup],
186
+ )
187
+ return rows.flatMap((row) => (row.text ? [String(row.text)] : []))
188
+ }
189
+
190
+ /**
191
+ * The bundles that use a folder: those declaring it, or one below it, so a
192
+ * rename, move or delete of it would break their path. Sorted, each once.
193
+ */
194
+ const usedBy = (id: number): string[] =>
195
+ [
196
+ ...new Set(
197
+ (deps.bundleFolders?.() ?? [])
198
+ .filter((folder) => `,${folder.nodePath},`.includes(`,${id},`))
199
+ .map((folder) => folder.bundle),
200
+ ),
201
+ ].sort()
202
+
203
+ /** Every folder a bundle's path runs through, with the bundles that use it. */
204
+ async function usedFolders(): Promise<Array<{ key: string; name: string; bundles: string[] }>> {
205
+ const ids = new Set<number>()
206
+ for (const folder of deps.bundleFolders?.() ?? [])
207
+ for (const id of folder.nodePath.split(',').map(Number)) if (id > 0) ids.add(id)
208
+ const rows = await nodes.byIds([...ids])
209
+ return rows
210
+ .filter((row) => row.objectType === ObjectTypes.Media)
211
+ .map((row) => ({ key: row.key, name: row.text ?? '', bundles: usedBy(row.id) }))
212
+ }
213
+
214
+ /** What the Permissions dialog shows for a folder or item. */
215
+ async function describe(key: string) {
216
+ const node = await nodes.byKey(key)
217
+ if (!node || node.objectType !== ObjectTypes.Media) return undefined
218
+ const own = await repo.byNodeKey(key)
219
+ const inherited = await repo.ruleFor(key, { above: true })
220
+ const item = (await repo.itemAccess(key)) ?? {
221
+ readPolicy: 'inherit' as const,
222
+ writePolicy: 'inherit' as const,
223
+ creatorMemberKey: null,
224
+ }
225
+ const fileRows = await db.query<{ file_url: string | null }>(
226
+ 'SELECT file_url FROM content WHERE node_id = ?',
227
+ [node.id],
228
+ )
229
+ const from = inherited ? await nodes.byKey(inherited.nodeKey) : undefined
230
+ const creator = item.creatorMemberKey
231
+ ? await new MemberRepository(db).byKey(item.creatorMemberKey)
232
+ : undefined
233
+ const effective = own ?? inherited
234
+ return {
235
+ key: node.key,
236
+ name: node.text ?? '',
237
+ hasParent: node.parentId > 0,
238
+ hasFile: Boolean(fileRows[0]?.file_url),
239
+ own: own ? ruleBody(own) : null,
240
+ inherited:
241
+ inherited && from
242
+ ? { from: { key: from.key, name: from.text ?? '' }, ...ruleBody(inherited) }
243
+ : null,
244
+ item: {
245
+ readPolicy: item.readPolicy,
246
+ writePolicy: item.writePolicy,
247
+ creator: item.creatorMemberKey
248
+ ? { key: item.creatorMemberKey, name: creator?.name ?? null }
249
+ : null,
250
+ },
251
+ protected: node.trashed || isProtectedMedia(item, effective ? ruleOf(effective) : undefined),
252
+ memberGroups: await memberGroups(),
253
+ memberFileTypes: MEMBER_FILE_TYPES.map((type) => ({ id: type.id, label: type.label })),
254
+ usedBy: usedBy(node.id),
255
+ }
256
+ }
257
+
258
+ /**
259
+ * `GET|PUT|DELETE /{key}`. A PUT sends `rule` (null takes the folder's or
260
+ * item's own rule off) and, for a file, `item` with its own policies.
261
+ */
262
+ async function handle(
263
+ request: Request,
264
+ subpath: string,
265
+ principal: Principal,
266
+ ): Promise<Response | undefined> {
267
+ const key = subpath.replace(/^\//, '')
268
+ if (key === 'used') {
269
+ if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
270
+ if (request.method !== 'GET') return new Response('Method Not Allowed', { status: 405 })
271
+ return Response.json(await usedFolders())
272
+ }
273
+ if (!isUuid(key)) return undefined
274
+ if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
275
+ const node = await nodes.byKey(key)
276
+ if (!node || node.objectType !== ObjectTypes.Media)
277
+ return new Response('Not Found', { status: 404 })
278
+ if (!(await mayView(principal, node.path, node.trashed)))
279
+ return new Response('Forbidden', { status: 403 })
280
+
281
+ if (request.method === 'GET') return Response.json(await describe(key))
282
+ if (request.method !== 'PUT' && request.method !== 'DELETE')
283
+ return new Response('Method Not Allowed', { status: 405 })
284
+ if (!fallbackPermissions(principal.groups).has(MediaPermissions.Update))
285
+ return new Response('Forbidden', { status: 403 })
286
+
287
+ if (request.method === 'DELETE') {
288
+ await repo.remove(key)
289
+ } else {
290
+ const body = (await request.json().catch(() => undefined)) as
291
+ | Record<string, unknown>
292
+ | undefined
293
+ if (!body) return Response.json({ reason: 'Send the permissions to set.' }, { status: 400 })
294
+ let item: { readPolicy: MediaPolicy; writePolicy: MediaPolicy } | undefined
295
+ if (body.item !== undefined) {
296
+ const raw = (body.item ?? {}) as Record<string, unknown>
297
+ const read = raw.readPolicy ?? 'inherit'
298
+ const write = raw.writePolicy ?? 'inherit'
299
+ if (!MEDIA_POLICIES.includes(read as MediaPolicy))
300
+ return Response.json({ reason: 'Choose who may see this file.' }, { status: 400 })
301
+ if (
302
+ !MEDIA_POLICIES.includes(write as MediaPolicy) ||
303
+ write === 'public' ||
304
+ write === 'members'
305
+ )
306
+ return Response.json({ reason: 'Choose who may change this file.' }, { status: 400 })
307
+ item = { readPolicy: read as MediaPolicy, writePolicy: write as MediaPolicy }
308
+ }
309
+ let rule: RuleBody | null | undefined
310
+ if (body.rule === null) rule = null
311
+ else if (body.rule !== undefined) {
312
+ const parsed = parseRuleBody(body.rule)
313
+ if (typeof parsed === 'string') return Response.json({ reason: parsed }, { status: 400 })
314
+ rule = parsed
315
+ }
316
+ await db.transaction(async (tx) => {
317
+ const writing = new MediaAccessRepository(tx)
318
+ if (rule === null) await writing.remove(key)
319
+ else if (rule) await writing.save({ nodeKey: key, ...rule })
320
+ if (item) await writing.setItemAccess(key, item)
321
+ // The item carries its own settings in every server's media cache (story 197).
322
+ if (item)
323
+ await appendCacheInstruction(tx, {
324
+ kind: 'content',
325
+ payload: { media: [normaliseUuid(key)] },
326
+ by: deps.nodeId,
327
+ })
328
+ })
329
+ }
330
+ await deps.onChange?.(normaliseUuid(key))
331
+ return Response.json(await describe(normaliseUuid(key)))
332
+ }
333
+
334
+ return { mayRead, isProtected, handle, describe }
335
+ }
336
+
337
+ export type MediaAccess = ReturnType<typeof createMediaAccess>
@@ -23,6 +23,7 @@
23
23
  * accounts is a decision a site makes, not one a framework makes for it.
24
24
  */
25
25
  import {
26
+ antiforgeryToken,
26
27
  expireCookie,
27
28
  hashPassword,
28
29
  isNativeHash,
@@ -35,6 +36,7 @@ import {
35
36
  serializeCookie,
36
37
  signMemberTicket,
37
38
  signShortLived,
39
+ verifyAntiforgery,
38
40
  verifyPassword,
39
41
  } from '@crombolo/auth'
40
42
  import {
@@ -77,9 +79,20 @@ export interface MemberAuthOptions {
77
79
  nodeId?: string
78
80
  }
79
81
 
82
+ /** A member signed in by the site's cookie, with that session's anti-forgery token. */
83
+ export interface MemberSession {
84
+ member: RequestMember
85
+ /** For `<AntiforgeryMeta />`. */
86
+ antiforgery: string
87
+ /** Whether a request's `Crombolo-Antiforgery` value belongs to this session. */
88
+ verify(token: string | null): Promise<boolean>
89
+ }
90
+
80
91
  export interface MemberAuth {
81
92
  /** The member this request carries, or undefined. */
82
93
  resolve(request: Request): Promise<RequestMember | undefined>
94
+ /** The member this request's cookie carries, and its anti-forgery token (story 186). */
95
+ session(request: Request): Promise<MemberSession | undefined>
83
96
  /**
84
97
  * Whether a member may see a page, and what to render instead when not. The
85
98
  * answer is Umbraco's: the login page for a visitor who is not signed in, the
@@ -269,8 +282,9 @@ export function createMemberAuth(
269
282
  },
270
283
  )
271
284
 
272
- const resolve: MemberAuth['resolve'] = async (request) => {
273
- const ticket = await readMemberTicket(await secret(), readCookie(request, cookie))
285
+ const session: MemberAuth['session'] = async (request) => {
286
+ const key = await secret()
287
+ const ticket = await readMemberTicket(key, readCookie(request, cookie))
274
288
  if (!ticket) return undefined
275
289
  const member = await members.byKey(ticket.id)
276
290
  if (!member) return undefined
@@ -278,9 +292,15 @@ export function createMemberAuth(
278
292
  // lockout rotates it, and every ticket issued before it is now worthless.
279
293
  if ((member.securityStamp ?? '') !== ticket.stamp) return undefined
280
294
  if (!member.isApproved || member.isLockedOut) return undefined
281
- return asRequestMember(member)
295
+ return {
296
+ member: asRequestMember(member),
297
+ antiforgery: await antiforgeryToken(key, ticket),
298
+ verify: (token) => verifyAntiforgery(key, ticket, token),
299
+ }
282
300
  }
283
301
 
302
+ const resolve: MemberAuth['resolve'] = async (request) => (await session(request))?.member
303
+
284
304
  const decide: MemberAuth['decide'] = async (content, member) => {
285
305
  const entry = await access.entryFor(content.key)
286
306
  if (!entry) return { status: 'allowed' }
@@ -562,6 +582,7 @@ export function createMemberAuth(
562
582
 
563
583
  return {
564
584
  resolve,
585
+ session,
565
586
  decide,
566
587
  signOutCookie: () => expireCookie(cookie, config.secureCookies),
567
588
  externalSignInUrl: (providerId, returnUrl) =>
package/src/ports.ts CHANGED
@@ -591,7 +591,8 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
591
591
  },
592
592
  events: createMediaEventSink({ webhooks: options.webhooks, nudge: options.nudgeEvents }),
593
593
  files: mediaFiles,
594
- onChange: () => options.cache?.invalidate(),
594
+ // Only the items it touched: a media change leaves the pages alone (story 197).
595
+ onChange: (change) => options.cache?.media?.apply(change),
595
596
  refusalReason: (error) =>
596
597
  error instanceof TemporaryFileMissingError ? error.message : undefined,
597
598
  })
@@ -672,9 +673,13 @@ export function createDeps(options: DepsOptions): ManagementApiDeps {
672
673
  })
673
674
  deps.searchIndex = createSearchIndexPort(options.db, options.onSearchQueued)
674
675
  deps.publishedCache = {
675
- reload: () => cache.invalidate(),
676
+ reload: () => {
677
+ cache.invalidate()
678
+ cache.media?.clear()
679
+ },
676
680
  rebuild: async () => {
677
681
  cache.invalidate()
682
+ cache.media?.clear()
678
683
  await cache.snapshot()
679
684
  },
680
685
  isRebuilding: () => false,
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Request limits for a bundle's member and public routes (story 186): counted
3
+ * per server, in memory, in a sliding window, as sign-in throttling counts
4
+ * failures (`AttemptLimiter`). Behind N servers a site allows up to N times
5
+ * the limit in total.
6
+ */
7
+
8
+ /** Keys held before the idle ones are swept, so a flood of addresses cannot grow the map for ever. */
9
+ const SWEEP_AT = 10_000
10
+
11
+ export class RateLimiter {
12
+ #hits = new Map<string, number[]>()
13
+ readonly #max: number
14
+ readonly #windowMs: number
15
+ readonly #now: () => number
16
+
17
+ constructor(options: { max: number; windowMs: number; now?: () => number }) {
18
+ this.#max = options.max
19
+ this.#windowMs = options.windowMs
20
+ this.#now = options.now ?? Date.now
21
+ }
22
+
23
+ /** Counts a request: undefined when it may go ahead, or the seconds until one may. */
24
+ take(key: string): number | undefined {
25
+ const now = this.#now()
26
+ const since = now - this.#windowMs
27
+ if (this.#hits.size >= SWEEP_AT)
28
+ for (const [held, times] of this.#hits)
29
+ if ((times.at(-1) ?? 0) <= since) this.#hits.delete(held)
30
+ const recent = (this.#hits.get(key) ?? []).filter((t) => t > since)
31
+ if (recent.length >= this.#max) {
32
+ this.#hits.set(key, recent)
33
+ return Math.max(1, Math.ceil(((recent[0] as number) + this.#windowMs - now) / 1000))
34
+ }
35
+ recent.push(now)
36
+ this.#hits.set(key, recent)
37
+ return undefined
38
+ }
39
+ }
40
+
41
+ const PRIVATE_ADDRESS =
42
+ /^(?:::ffff:)?(?:127\.|10\.|192\.168\.|172\.(?:1[6-9]|2\d|3[01])\.|169\.254\.)|^(?:::1|f[cd][0-9a-f]{2}:|fe80:)/i
43
+
44
+ /**
45
+ * The address a request came from. The socket's peer, unless that is a
46
+ * private address — a proxy or load balancer in front of the site — when the
47
+ * last `X-Forwarded-For` entry, the one that proxy added, is the caller.
48
+ * Earlier entries are the client's own to write, so they are never trusted.
49
+ */
50
+ export function callerAddress(peer: string | undefined, forwardedFor: string | null): string {
51
+ const forwarded = forwardedFor?.split(',').at(-1)?.trim()
52
+ if (forwarded && (!peer || PRIVATE_ADDRESS.test(peer))) return forwarded
53
+ return peer ?? 'unknown'
54
+ }
package/src/schema.ts CHANGED
@@ -16,6 +16,8 @@ import {
16
16
  ensureSystemContentTypes,
17
17
  ensureSystemMemberTypes,
18
18
  type Finding,
19
+ instructionEffects,
20
+ instructionsBetween,
19
21
  Locks,
20
22
  latestCacheInstructionId,
21
23
  latestCheckpoint,
@@ -251,12 +253,30 @@ export interface CachePollerOptions {
251
253
  content?: {
252
254
  served(): { checkpoint: number | undefined; builtAt: Date } | undefined
253
255
  behind(latest: number): void
256
+ /**
257
+ * Told that every change from the one it serves up to `checkpoint` left the
258
+ * pages alone — media only (story 197) — so its snapshot holds them too.
259
+ */
260
+ covered?(checkpoint: number): void
261
+ }
262
+ /**
263
+ * The media cache (story 197). Every change, this node's own included, is
264
+ * read in checkpoint order: a media change drops the items it names, and a
265
+ * change that empties caches empties it. A gap in the checkpoints, or being
266
+ * further behind than `MEDIA_REPLAY_LIMIT`, empties it too.
267
+ */
268
+ media?: {
269
+ apply(change: { keys: string[]; moved: string[] }): void
270
+ clear(): void
254
271
  }
255
272
  }
256
273
 
257
274
  /** A rebuild asked for and not yet served is asked for again after this long. */
258
275
  const REASK_AFTER_MS = 30_000
259
276
 
277
+ /** Further behind than this many changes, the media cache is emptied rather than replayed. */
278
+ export const MEDIA_REPLAY_LIMIT = 5_000
279
+
260
280
  /**
261
281
  * Polls `cache_instruction` from where this node came in; own instructions are
262
282
  * skipped. Where the database can notify, a write wakes it at once and the
@@ -283,6 +303,10 @@ export class CacheInstructionPoller {
283
303
  /** The checkpoint this node last asked its cache to catch up to, and when. */
284
304
  #asked: { checkpoint: number; at: number } | undefined
285
305
  #latest: number | undefined
306
+ /** The checkpoint whose changes have all been read for the caches; undefined before the start. */
307
+ #followed: number | undefined
308
+ /** Checkpoints read whose changes left the pages alone. */
309
+ #pagesFree = new Set<number>()
286
310
 
287
311
  /** The latest committed content checkpoint, as of the last poll. */
288
312
  get latestCheckpoint(): number | undefined {
@@ -318,6 +342,8 @@ export class CacheInstructionPoller {
318
342
  this.#paused = await readWritesPaused(this.#options.db)
319
343
  this.#cursor = await latestCacheInstructionId(this.#options.db)
320
344
  this.#origin = this.#cursor
345
+ // An empty media cache is current with whatever has committed so far.
346
+ this.#followed = await latestCheckpoint(this.#options.db)
321
347
  if (intervalMs > 0) {
322
348
  this.#timer = setInterval(() => void this.poll().catch(() => {}), intervalMs)
323
349
  this.#timer.unref()
@@ -355,6 +381,8 @@ export class CacheInstructionPoller {
355
381
 
356
382
  async #pollOnce(): Promise<number> {
357
383
  const { db, nodeId, nodeState, onInstruction } = this.#options
384
+ // Read first: every instruction numbered up to it has committed, and is visible below.
385
+ const latest = await latestCheckpoint(db)
358
386
  // A row can commit after one with a higher id (Postgres hands ids out
359
387
  // before commit), so a short window behind the cursor is read again and
360
388
  // the ids already seen are skipped.
@@ -371,7 +399,8 @@ export class CacheInstructionPoller {
371
399
  onInstruction(instruction.kind, instruction.payload)
372
400
  }
373
401
  for (const id of this.#seen) if (id <= this.#cursor - CURSOR_WINDOW) this.#seen.delete(id)
374
- const served = await this.#catchUp()
402
+ await this.#follow(latest)
403
+ const served = this.#catchUp(latest)
375
404
  await touchServer(db, {
376
405
  nodeId,
377
406
  ...nodeState,
@@ -394,19 +423,60 @@ export class CacheInstructionPoller {
394
423
  return applied
395
424
  }
396
425
 
426
+ /**
427
+ * Reads every change since the last checkpoint followed, in order: for the
428
+ * media cache, and to know which left the pages alone. Checkpoints count up
429
+ * by one per change, so a number with no instruction was pruned before this
430
+ * node read it, and the media cache cannot know what it missed.
431
+ */
432
+ async #follow(latest: number): Promise<void> {
433
+ const from = this.#followed
434
+ if (from === undefined || latest === from) return
435
+ const media = this.#options.media
436
+ this.#followed = latest
437
+ // Behind a reset count, or too far behind to replay: start the media again.
438
+ if (latest < from || latest - from > MEDIA_REPLAY_LIMIT) {
439
+ media?.clear()
440
+ this.#pagesFree.clear()
441
+ return
442
+ }
443
+ const missed = await instructionsBetween(this.#options.db, from, latest)
444
+ const numbered = new Set(missed.map((instruction) => instruction.checkpoint))
445
+ let gap = false
446
+ for (let checkpoint = from + 1; checkpoint <= latest && !gap; checkpoint++)
447
+ gap = !numbered.has(checkpoint)
448
+ if (gap) media?.clear()
449
+ for (const instruction of missed) {
450
+ const effects = instructionEffects(instruction.kind, instruction.payload)
451
+ if (!effects.pages && instruction.checkpoint !== null)
452
+ this.#pagesFree.add(instruction.checkpoint)
453
+ if (gap || !media || effects.media === 'keep') continue
454
+ if (effects.media === 'clear') media.clear()
455
+ else media.apply(effects.media)
456
+ }
457
+ }
458
+
397
459
  /**
398
460
  * Tells the cache it is behind when the latest committed checkpoint is past
399
- * the one it serves. A cache that has not been built yet is left to build on
400
- * its first read. A request not served within a while is made again, so a
401
- * failed rebuild is retried.
461
+ * the one it serves, and any changes between left pages alone. A cache that
462
+ * has not been built yet is left to build on its first read. A request not
463
+ * served within a while is made again, so a failed rebuild is retried.
402
464
  */
403
- async #catchUp() {
465
+ #catchUp(latest: number) {
404
466
  const content = this.#options.content
405
467
  if (!content) return undefined
406
- const latest = await latestCheckpoint(this.#options.db)
407
468
  this.#latest = latest
408
- const served = content.served()
409
- if (served?.checkpoint === undefined || served.checkpoint >= latest) return served
469
+ let served = content.served()
470
+ if (served?.checkpoint === undefined) return served
471
+ let covered = served.checkpoint
472
+ while (this.#pagesFree.has(covered + 1)) covered += 1
473
+ for (const checkpoint of this.#pagesFree)
474
+ if (checkpoint <= covered) this.#pagesFree.delete(checkpoint)
475
+ if (covered > served.checkpoint) {
476
+ content.covered?.(covered)
477
+ served = content.served() ?? served
478
+ }
479
+ if (covered >= latest) return served
410
480
  const asked = this.#asked
411
481
  if (!asked || asked.checkpoint < latest || Date.now() - asked.at > REASK_AFTER_MS) {
412
482
  this.#asked = { checkpoint: latest, at: Date.now() }