@crombolo/server 0.45.0 → 0.47.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/src/server.ts CHANGED
@@ -6,8 +6,9 @@
6
6
  * API, the SPA shells, then the front-end site.
7
7
  */
8
8
 
9
- import { existsSync } from 'node:fs'
10
- import { join } from 'node:path'
9
+ import { timingSafeEqual } from 'node:crypto'
10
+ import { existsSync, readFileSync } from 'node:fs'
11
+ import { basename, join } from 'node:path'
11
12
  import {
12
13
  apiForm,
13
14
  corsPolicy,
@@ -40,6 +41,7 @@ import {
40
41
  expireCookie,
41
42
  isSafeMethod,
42
43
  isSameOrigin,
44
+ memberCookieName,
43
45
  REDACTED,
44
46
  readCookie,
45
47
  serializeCookie,
@@ -106,10 +108,15 @@ import {
106
108
  cacheControl,
107
109
  chosenLifetime,
108
110
  contentForNode,
111
+ contentHash,
112
+ DEFERRED_LOADER,
113
+ DEFERRED_LOADER_PATH,
114
+ DEFERRED_PATH,
109
115
  FORM_SCRIPT,
110
116
  FORM_SCRIPT_PATH,
111
117
  FORM_SUBMIT_PATH,
112
118
  formAction,
119
+ hashedAddress,
113
120
  ISLAND_LOADER_PATH,
114
121
  ISLAND_LOADER_SCRIPT,
115
122
  ISLANDS_PATH,
@@ -118,15 +125,25 @@ import {
118
125
  LIVE_RELOAD_SCRIPT_PATH,
119
126
  type Lifetime,
120
127
  lifetimeFor,
128
+ notModified,
121
129
  type PageOutcome,
122
130
  PRIVATE_NO_STORE,
123
131
  PublishedCache,
124
132
  type PublishedContent,
133
+ publishedEtag,
134
+ type RememberedAnswer,
135
+ RememberedAnswers,
125
136
  type Renderer,
126
137
  type RequestMember,
138
+ readDeferredAddress,
139
+ rememberedHeaders,
127
140
  resolveCacheSettings,
128
141
  type SnapshotStatus,
142
+ setAssetResolver,
143
+ splitHashedAddress,
144
+ unchanged,
129
145
  type ViewSnapshots,
146
+ validatorFor,
130
147
  withLiveReload,
131
148
  } from '@crombolo/render'
132
149
  import type { SyncReport } from '@crombolo/schema'
@@ -209,13 +226,29 @@ import {
209
226
  } from './preview-tokens.ts'
210
227
  import { provenanceProblem } from './provenance.ts'
211
228
  import { createRemote, type RestartOutcome } from './remote.ts'
229
+ import { SiteAssets } from './site-assets.ts'
212
230
  import { unknownHostProvided } from './site-file.ts'
231
+ import {
232
+ activeSpan,
233
+ inSpan,
234
+ isTrustedProxy,
235
+ noteOnSpan,
236
+ recordRender,
237
+ recordRequest,
238
+ requestContext,
239
+ routeOf,
240
+ SpanKind,
241
+ stopTelemetry,
242
+ } from './telemetry.ts'
213
243
  import { handleTransferAction, pendingTransfers } from './transfer-dashboard.ts'
214
244
  import { changeUrlOptions, urlSettingEditable } from './url-settings.ts'
215
245
  import type { JobsStatus } from './worker-watch.ts'
216
246
 
217
247
  export { PREVIEW_COOKIE }
218
248
 
249
+ /** The member a back-office user previews as (story 264). */
250
+ export const PREVIEW_MEMBER_COOKIE = 'crombolo-preview-member'
251
+
219
252
  import { ACTIONS_PATH, type SiteRoute } from '@crombolo/common'
220
253
  import { backofficeAudience } from './backoffice-external.ts'
221
254
  import { createExternalSignIn } from './external-sign-in.ts'
@@ -234,7 +267,7 @@ import {
234
267
  requestCookies,
235
268
  runStage,
236
269
  } from './middleware.ts'
237
- import type { JobRunner } from './owner-jobs.ts'
270
+ import { CORE_JOB_OWNER, type JobRunner } from './owner-jobs.ts'
238
271
  import { callerAddress } from './rate-limit.ts'
239
272
  import { syncConfiguredRedirects } from './redirects.ts'
240
273
  import { createRoutes, type DeclaredRoute, siteRouteProblems } from './routes.ts'
@@ -796,6 +829,105 @@ export async function createServer(
796
829
  nodeId: schema.nodeId,
797
830
  })
798
831
  const caching = resolveCacheSettings(config.cache)
832
+ // Story 259: `check` with checks answered by rendering costs a render a floor, where `published` costs none.
833
+ if (
834
+ caching.mode === 'check' &&
835
+ (caching.validator === 'body' || [...caching.validators.values()].includes('body'))
836
+ )
837
+ renderLog.info(
838
+ "Copies are checked back with the site, and pages whose ETag is over their body are rendered for each check, at most every {floor} seconds per cache. Where no page shows the time, cache.validator = 'published' answers checks without rendering.",
839
+ { floor: caching.checkFloor },
840
+ )
841
+ // Story 260: the generated scripts and the site's own files, each also at an address naming its content.
842
+ const generatedBodies: Array<[string, string]> = [
843
+ [ISLAND_LOADER_PATH, ISLAND_LOADER_SCRIPT],
844
+ [DEFERRED_LOADER_PATH, DEFERRED_LOADER],
845
+ [FORM_SCRIPT_PATH, FORM_SCRIPT],
846
+ [BUNDLE_SCRIPT_PATH, BUNDLE_SCRIPT],
847
+ ]
848
+ const generatedPaths = new Map(
849
+ generatedBodies.map(([path, body]) => [path, hashedAddress(path, contentHash(body))]),
850
+ )
851
+ const generatedScripts = new Map(
852
+ generatedBodies.map(([path, body]) => [generatedPaths.get(path) as string, body]),
853
+ )
854
+ const siteAssets = new SiteAssets([
855
+ { prefix: '/css', dir: config.stylesheetsDir, extension: '.css' },
856
+ { prefix: '/scripts', dir: config.scriptsDir, extension: '.js' },
857
+ ])
858
+ siteAssets.start()
859
+ const missingAssets = new Set<string>()
860
+ setAssetResolver((path) => {
861
+ const found = generatedPaths.get(path) ?? siteAssets.address(path)
862
+ if (found) return found
863
+ if (config.development && !missingAssets.has(path)) {
864
+ missingAssets.add(path)
865
+ renderLog.warning(
866
+ 'asset({path}) names a file the site does not have, so it keeps its plain address.',
867
+ { path },
868
+ )
869
+ }
870
+ return path
871
+ })
872
+ // Story 263: a part's address is signed, so a visitor cannot change what it renders.
873
+ const deferredKey = `deferred|${formSecret}`
874
+ const signDeferred = (data: string) =>
875
+ new Bun.CryptoHasher('sha256', deferredKey).update(data).digest('base64url')
876
+ const verifyDeferred = (data: string, signature: string) => {
877
+ const expected = Buffer.from(signDeferred(data))
878
+ const given = Buffer.from(signature)
879
+ return expected.length === given.length && timingSafeEqual(expected, given)
880
+ }
881
+ const MEMBER_VARY = 'X-Crombolo-Member'
882
+ // Story 264: the member a user previews as, signed with their key so it is theirs alone.
883
+ const signPreviewMember = (member: string, user: string) =>
884
+ `${member}.${signDeferred(`preview-member|${member}|${user}`)}`
885
+ const readPreviewMember = (value: string | undefined, user: string) => {
886
+ const [member, signature] = (value ?? '').split('.')
887
+ if (!member || !signature) return undefined
888
+ return verifyDeferred(`preview-member|${member}|${user}`, signature) ? member : undefined
889
+ }
890
+ const notedMemberFiles = new Set<string>()
891
+ /** Development: why a page is rendered for each member, once per page. */
892
+ const noteMemberFiles = (content: PublishedContent, files: readonly string[]) => {
893
+ const note = `${content.key}|${files.join(',')}`
894
+ if (notedMemberFiles.has(note)) return
895
+ notedMemberFiles.add(note)
896
+ renderLog.info(
897
+ '{page} is rendered for each signed-in member, as {files} mentions member. A "use deferred" part would let it be shared.',
898
+ { page: content.name, files: files.join(', ') },
899
+ )
900
+ }
901
+ // Story 258: what a page's ETag is made from, when it is not its body.
902
+ const installed = Bun.hash(
903
+ ['package.json', 'bun.lock']
904
+ .map((name) => {
905
+ try {
906
+ return readFileSync(join(config.siteDir, name), 'utf8')
907
+ } catch {
908
+ return ''
909
+ }
910
+ })
911
+ .join('\u0000'),
912
+ ).toString(36)
913
+ /** What every answer's ETag shares, taken before it is made; nothing before the first snapshot. */
914
+ const validatorBasis = (views: boolean): string | undefined => {
915
+ const checkpoint = cache.served()?.checkpoint
916
+ const generation = views ? snapshots.status().hash : ''
917
+ if (checkpoint === undefined || generation === undefined) return undefined
918
+ return `${checkpoint}|${generation}|${installed}|${VERSION}`
919
+ }
920
+ const publishedValidator =
921
+ caching.validator === 'published' || [...caching.validators.values()].includes('published')
922
+ const rememberedPages = new RememberedAnswers<
923
+ RememberedAnswer & { key: string; culture: string | null }
924
+ >()
925
+ const personalCookies = [
926
+ memberCookieName({ siteName: config.siteName, securePrefix: config.secureCookies }),
927
+ PREVIEW_COOKIE,
928
+ FORM_FLASH_COOKIE,
929
+ ACTION_FLASH_COOKIE,
930
+ ]
799
931
  const deliveryPrefix = DELIVERY_API_PREFIX
800
932
  const deliveryMembers = createDeliveryMemberSecurity({
801
933
  db,
@@ -831,6 +963,54 @@ export async function createServer(
831
963
  ),
832
964
  })
833
965
  const mediaAccessPath = `${paths.pluginPath}/api/media-access`
966
+ const pageSharingPath = `${paths.pluginPath}/api/page-sharing`
967
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
968
+ const previewMemberPath = `${paths.pluginPath}/api/preview-member`
969
+
970
+ /**
971
+ * Which member this user previews as (story 264): `GET` says, and whether
972
+ * they may choose; `PUT` with `{ member }` chooses one, or none with null.
973
+ * Only a user who can open Members may, and each choice is in the audit log.
974
+ */
975
+ async function choosePreviewMember(request: Request, principal: Principal) {
976
+ const allowed = hasSection(principal, 'members')
977
+ if (request.method === 'GET') {
978
+ const chosen = allowed ? await previewMember(request, principal) : undefined
979
+ return Response.json(
980
+ { allowed, member: chosen ? { key: chosen.key, name: chosen.name } : null },
981
+ { headers: { 'cache-control': 'no-store' } },
982
+ )
983
+ }
984
+ if (request.method !== 'PUT') return new Response('Method Not Allowed', { status: 405 })
985
+ if (!allowed) return new Response('Forbidden', { status: 403 })
986
+ const body = (await request.json().catch(() => ({}))) as { member?: unknown }
987
+ const key = typeof body.member === 'string' ? body.member : null
988
+ const chosen = key ? await members.byKey(key) : undefined
989
+ if (key && !chosen)
990
+ return Response.json({ message: 'That member could not be found.' }, { status: 404 })
991
+ await recordAudit(db, {
992
+ category: 'member',
993
+ action: chosen ? 'preview as' : 'preview signed out',
994
+ source: 'request',
995
+ userKey: principal.id,
996
+ userName: principal.name,
997
+ entityType: chosen ? 'member' : null,
998
+ entityKey: chosen?.key ?? null,
999
+ entityName: chosen?.name ?? null,
1000
+ ...clientAddress(request),
1001
+ })
1002
+ const cookie = chosen
1003
+ ? serializeCookie({
1004
+ name: PREVIEW_MEMBER_COOKIE,
1005
+ value: signPreviewMember(chosen.key, principal.id),
1006
+ secure: config.secureCookies,
1007
+ })
1008
+ : expireCookie(PREVIEW_MEMBER_COOKIE, config.secureCookies)
1009
+ return Response.json(
1010
+ { allowed, member: chosen ? { key: chosen.key, name: chosen.name } : null },
1011
+ { headers: { 'set-cookie': cookie, 'cache-control': 'no-store' } },
1012
+ )
1013
+ }
834
1014
  for (const problem of previewProblems(deliverySettings))
835
1015
  log.warning('Delivery API: {problem}', { problem })
836
1016
 
@@ -880,6 +1060,7 @@ export async function createServer(
880
1060
  settings: deliverySettings,
881
1061
  cache,
882
1062
  caching,
1063
+ validatorBasis: () => validatorBasis(false),
883
1064
  prefix: deliveryPrefix,
884
1065
  // Asked only at request time, by which point the SEO host below exists.
885
1066
  seo: async (content, request) => ({ ...(await seo.details(content, request)) }),
@@ -1208,6 +1389,9 @@ export async function createServer(
1208
1389
  // credentials anywhere near it.
1209
1390
  const auditPath = `${paths.pluginPath}/api/audit`
1210
1391
  const jobsPath = `${paths.pluginPath}/api/jobs`
1392
+ const mediaJobsPath = `${paths.pluginPath}/api/media-jobs`
1393
+ /** What an open back office hears when a media change is queued (story 246); its key is the job's id. */
1394
+ const MEDIA_JOB_QUEUED_EVENT = { eventSource: 'Crombolo:MediaJob', eventType: 'Queued' } as const
1211
1395
  const hostTokenPath = `${paths.pluginPath}/api/host-token`
1212
1396
  const contentQueryPath = `${paths.pluginPath}/api/content-query`
1213
1397
  const bundleInstallPaths = new Set(
@@ -1243,12 +1427,39 @@ export async function createServer(
1243
1427
  * address it is answered with points back at the new paths.
1244
1428
  */
1245
1429
  async function fetch(request: Request): Promise<Response> {
1246
- const response = await answer(request)
1247
- // Readers are answered from the previous cache while it rebuilds (story
1248
- // 175), so a change is in it before the request that made it is answered.
1249
- if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
1250
- await cache.fresh().catch(() => {})
1251
- return response
1430
+ // Story 262: every request a span, continuing a trace only from a trusted proxy.
1431
+ const pathname = new URL(request.url).pathname
1432
+ const route = routeOf(pathname, paths.backOfficePath)
1433
+ const method = request.method
1434
+ const started = performance.now()
1435
+ const parent = requestContext(
1436
+ request,
1437
+ isTrustedProxy(peers.get(request), config.trustedProxies),
1438
+ )
1439
+ return inSpan(
1440
+ `${method} ${route}`,
1441
+ {
1442
+ 'http.request.method': method,
1443
+ 'http.route': route,
1444
+ 'url.path': pathname,
1445
+ 'crombolo.node.role': config.role,
1446
+ },
1447
+ async (span) => {
1448
+ const response = await answer(request)
1449
+ // Readers are answered from the previous cache while it rebuilds (story
1450
+ // 175), so a change is in it before the request that made it is answered.
1451
+ if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
1452
+ await cache.fresh().catch(() => {})
1453
+ span.setAttribute('http.response.status_code', response.status)
1454
+ recordRequest((performance.now() - started) / 1000, {
1455
+ 'http.request.method': method,
1456
+ 'http.route': route,
1457
+ 'http.response.status_code': response.status,
1458
+ })
1459
+ return response
1460
+ },
1461
+ { kind: SpanKind.SERVER, parent },
1462
+ )
1252
1463
  }
1253
1464
 
1254
1465
  async function answer(request: Request): Promise<Response> {
@@ -1293,7 +1504,7 @@ export async function createServer(
1293
1504
  // Umbraco's Delivery API, below the backoffice path but served wherever the
1294
1505
  // site is, from the published cache: it scales with rendering.
1295
1506
  if (deliveryApi && pathname.startsWith(`${deliveryPrefix}/`)) {
1296
- const response = await deliveryApi.handle(request)
1507
+ const response = await inSpan('delivery api', {}, () => deliveryApi.handle(request))
1297
1508
  if (response) return response
1298
1509
  }
1299
1510
 
@@ -1307,6 +1518,10 @@ export async function createServer(
1307
1518
  const response = await serveBackOffice(request, url)
1308
1519
  if (response) {
1309
1520
  if (response.ok) await auditPluginWrite(request, pathname)
1521
+ // A media change too large for the request is queued (story 246): open back
1522
+ // offices hear its id from the node that took it, wherever the job runs.
1523
+ const job = response.headers.get('crombolo-job')
1524
+ if (job) events.broadcast('notify', [{ ...MEDIA_JOB_QUEUED_EVENT, key: job }])
1310
1525
  return response
1311
1526
  }
1312
1527
  }
@@ -1324,26 +1539,24 @@ export async function createServer(
1324
1539
  : new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
1325
1540
  }
1326
1541
 
1542
+ // Story 260: a generated script at the address that names its content, or nothing.
1543
+ const generated = generatedScripts.get(pathname)
1544
+ if (generated) return keptScript(generated)
1545
+ const hashedPlain = splitHashedAddress(pathname)?.path
1546
+ if (hashedPlain && generatedPaths.has(hashedPlain))
1547
+ return new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
1548
+
1327
1549
  // Islands (story 209): the loader, and each generation's browser code.
1328
- if (pathname === ISLAND_LOADER_PATH)
1329
- return new Response(ISLAND_LOADER_SCRIPT, {
1330
- headers: {
1331
- 'content-type': 'text/javascript; charset=utf-8',
1332
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1333
- },
1334
- })
1550
+ if (pathname === ISLAND_LOADER_PATH) return siteScript(ISLAND_LOADER_SCRIPT)
1551
+ // Deferred parts (story 263): the loader, and each part for the visitor.
1552
+ if (pathname === DEFERRED_LOADER_PATH) return siteScript(DEFERRED_LOADER)
1553
+ if (pathname === DEFERRED_PATH && config.role !== 'api') return deferredPart(request, url)
1335
1554
  if (pathname.startsWith(`${ISLANDS_PATH}/`))
1336
1555
  return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1337
1556
 
1338
1557
  // The progressive-enhancement script. A site adds it to a layout; a form
1339
1558
  // works without it, so nothing emits it automatically.
1340
- if (pathname === FORM_SCRIPT_PATH)
1341
- return new Response(FORM_SCRIPT, {
1342
- headers: {
1343
- 'content-type': 'text/javascript; charset=utf-8',
1344
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1345
- },
1346
- })
1559
+ if (pathname === FORM_SCRIPT_PATH) return siteScript(FORM_SCRIPT)
1347
1560
 
1348
1561
  // A visitor posting a form. Before the renderer, which would otherwise try
1349
1562
  // to resolve `/crombolo/forms/...` as a page.
@@ -1356,16 +1569,10 @@ export async function createServer(
1356
1569
  : new Response('Method Not Allowed', { status: 405, headers: { allow: 'POST' } })
1357
1570
  }
1358
1571
 
1359
- // The script that calls the site's routes as a member, wherever the site is served.
1360
- if (config.role !== 'api') {
1361
- if (pathname === BUNDLE_SCRIPT_PATH)
1362
- return new Response(BUNDLE_SCRIPT, {
1363
- headers: {
1364
- 'content-type': 'text/javascript; charset=utf-8',
1365
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
1366
- },
1367
- })
1368
- }
1572
+ // The script that calls the site's routes as a member: on every node, as the
1573
+ // other site scripts are, so a proxy that sends `/crombolo/*` to the api node
1574
+ // still serves it (story 220).
1575
+ if (pathname === BUNDLE_SCRIPT_PATH) return siteScript(BUNDLE_SCRIPT)
1369
1576
 
1370
1577
  // Not on an `api` node, which serves no public site to describe.
1371
1578
  if ((pathname === '/sitemap.xml' || pathname === '/robots.txt') && config.role !== 'api')
@@ -1450,6 +1657,27 @@ export async function createServer(
1450
1657
  }
1451
1658
  }
1452
1659
 
1660
+ /** One of the scripts a site's pages load, answered alike on every node. */
1661
+ function siteScript(body: string): Response {
1662
+ return new Response(body, {
1663
+ headers: {
1664
+ 'content-type': 'text/javascript; charset=utf-8',
1665
+ // Asked again each time at its plain address; `asset()` gives the one kept for a year (story 260).
1666
+ 'cache-control': 'no-cache',
1667
+ },
1668
+ })
1669
+ }
1670
+
1671
+ /** A generated script at its hashed address: the same bytes for as long as the address lasts. */
1672
+ function keptScript(body: string): Response {
1673
+ return new Response(body, {
1674
+ headers: {
1675
+ 'content-type': 'text/javascript; charset=utf-8',
1676
+ 'cache-control': 'public, max-age=31536000, immutable',
1677
+ },
1678
+ })
1679
+ }
1680
+
1453
1681
  /** The site's stylesheets and scripts, or its pages. */
1454
1682
  async function siteFiles(request: Request, run?: ChainRun): Promise<Response> {
1455
1683
  const url = new URL(request.url)
@@ -1459,8 +1687,10 @@ export async function createServer(
1459
1687
  const routed = await siteRoutes.handle(request, url)
1460
1688
  if (routed) return routed
1461
1689
  }
1462
- if (pathname.startsWith('/css/')) return serveSiteFile(config.stylesheetsDir, pathname, '.css')
1463
- if (pathname.startsWith('/scripts/')) return serveSiteFile(config.scriptsDir, pathname, '.js')
1690
+ if (pathname.startsWith('/css/'))
1691
+ return serveSiteFile(request, config.stylesheetsDir, pathname, '.css')
1692
+ if (pathname.startsWith('/scripts/'))
1693
+ return serveSiteFile(request, config.scriptsDir, pathname, '.js')
1464
1694
  return renderSite(request, pathname, url.host, run)
1465
1695
  }
1466
1696
 
@@ -1616,6 +1846,23 @@ export async function createServer(
1616
1846
  if (response) return response
1617
1847
  }
1618
1848
 
1849
+ // Non-contract, signed in: whether a page's copies are shared (story 264).
1850
+ if (pathname.startsWith(`${pageSharingPath}/`)) {
1851
+ const principal = await authenticate(request)
1852
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1853
+ if (request.method !== 'GET') return new Response('Method Not Allowed', { status: 405 })
1854
+ const key = pathname.slice(pageSharingPath.length + 1)
1855
+ if (!UUID_PATTERN.test(key)) return new Response('Not Found', { status: 404 })
1856
+ return pageSharing(request, key, principal)
1857
+ }
1858
+
1859
+ // Non-contract, Members: which member a preview renders as (story 264).
1860
+ if (pathname === previewMemberPath) {
1861
+ const principal = await authenticate(request)
1862
+ if (!principal) return new Response('Unauthorized', { status: 401 })
1863
+ return choosePreviewMember(request, principal)
1864
+ }
1865
+
1619
1866
  // Non-contract, Media: who may read and change a media folder or item (story 196).
1620
1867
  if (pathname.startsWith(`${mediaAccessPath}/`)) {
1621
1868
  const principal = await authenticate(request)
@@ -2240,6 +2487,27 @@ export async function createServer(
2240
2487
  if (response) return response
2241
2488
  }
2242
2489
 
2490
+ // Non-contract, Media: how a large branch's queued trash, move or delete is
2491
+ // getting on (story 246), for anyone with the Media section, media jobs only.
2492
+ const mediaJob = /^\/([0-9a-f-]{36})$/i.exec(
2493
+ pathname.startsWith(mediaJobsPath) ? pathname.slice(mediaJobsPath.length) : '',
2494
+ )
2495
+ if (mediaJob && request.method === 'GET') {
2496
+ const principal = await authenticate(request)
2497
+ if (!principal) return new Response('Unauthorized', { status: 401 })
2498
+ if (!hasSection(principal, 'media')) return new Response('Forbidden', { status: 403 })
2499
+ const job = await new JobRepository(db).get(mediaJob[1] as string)
2500
+ if (!job || job.owner !== CORE_JOB_OWNER || !job.name.startsWith('media.'))
2501
+ return new Response('Not Found', { status: 404 })
2502
+ return Response.json({
2503
+ id: job.id,
2504
+ state: job.state,
2505
+ progress: job.progress,
2506
+ error: job.lastError,
2507
+ finishedAt: job.finishedAt?.toISOString() ?? null,
2508
+ })
2509
+ }
2510
+
2243
2511
  // Non-contract, Settings: every owner's background jobs, and retrying a
2244
2512
  // failed one by hand (story 187).
2245
2513
  if (pathname === jobsPath || pathname.startsWith(`${jobsPath}/`)) {
@@ -2586,17 +2854,56 @@ export async function createServer(
2586
2854
  }
2587
2855
 
2588
2856
  /** A stylesheet or script the Settings section edits, from its folder; nothing else from there. */
2589
- async function serveSiteFile(root: string, pathname: string, extension: string) {
2590
- const segments = decodeURIComponent(pathname).split('/').slice(2)
2591
- const safe =
2592
- segments.length > 0 &&
2593
- segments.every((s) => s !== '' && s !== '.' && s !== '..' && !s.includes('\\')) &&
2594
- segments.at(-1)?.toLowerCase().endsWith(extension)
2595
- const file = safe ? Bun.file(join(root, ...segments)) : undefined
2596
- if (!file || !(await file.exists())) return new Response('Not Found', { status: 404 })
2597
- const headers = { 'cache-control': 'no-cache', 'content-type': file.type }
2598
- // Bun.serve answers an empty file body 204, and an empty stylesheet is still one
2599
- return new Response(file.size === 0 ? '' : file, { status: 200, headers })
2857
+ /**
2858
+ * A stylesheet or script of the site's: at its plain address, asked again
2859
+ * each time; at its hashed address (story 260), kept for a year when the hash
2860
+ * is of the bytes sent, and nothing when it is not.
2861
+ */
2862
+ async function serveSiteFile(
2863
+ request: Request,
2864
+ root: string,
2865
+ pathname: string,
2866
+ extension: string,
2867
+ ) {
2868
+ const fileOf = (path: string) => {
2869
+ const segments = decodeURIComponent(path).split('/').slice(2)
2870
+ const safe =
2871
+ segments.length > 0 &&
2872
+ segments.every((s) => s !== '' && s !== '.' && s !== '..' && !s.includes('\\')) &&
2873
+ segments.at(-1)?.toLowerCase().endsWith(extension)
2874
+ return safe ? Bun.file(join(root, ...segments)) : undefined
2875
+ }
2876
+ const notFound = (headers: Record<string, string> = {}) =>
2877
+ new Response('Not Found', { status: 404, headers })
2878
+ const own = fileOf(pathname)
2879
+ if (own && (await own.exists())) {
2880
+ const bytes = await own.bytes()
2881
+ return withNoCache(
2882
+ cacheable(request, siteFileResponse(own.type, bytes), bytes, { lifetime: undefined }),
2883
+ )
2884
+ }
2885
+ const hashed = splitHashedAddress(pathname)
2886
+ const file = hashed ? fileOf(hashed.path) : undefined
2887
+ if (!hashed || !file || !(await file.exists())) return notFound()
2888
+ const bytes = await file.bytes()
2889
+ // Hashed from the bytes about to be sent, so a change the watcher missed is never kept under this address.
2890
+ if (contentHash(bytes) !== hashed.hash) return notFound({ 'cache-control': 'no-store' })
2891
+ const response = siteFileResponse(file.type, bytes)
2892
+ response.headers.set('cache-control', 'public, max-age=31536000, immutable')
2893
+ return response
2894
+ }
2895
+
2896
+ function siteFileResponse(type: string, bytes: Uint8Array): Response {
2897
+ // Bun.serve answers an empty file body 204, and an empty stylesheet is still one.
2898
+ return new Response(bytes.length === 0 ? '' : (bytes as BodyInit), {
2899
+ status: 200,
2900
+ headers: { 'content-type': type },
2901
+ })
2902
+ }
2903
+
2904
+ function withNoCache(response: Response): Response {
2905
+ response.headers.set('cache-control', 'no-cache')
2906
+ return response
2600
2907
  }
2601
2908
 
2602
2909
  /**
@@ -2743,11 +3050,13 @@ export async function createServer(
2743
3050
  if (!key) return undefined
2744
3051
  const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
2745
3052
  if (!draft) return undefined
3053
+ // The previewing editor is the visitor: signed out, or a member they chose (story 264).
3054
+ const member = await previewMember(request, principal)
2746
3055
  return renderer.renderModel(draft.content, draft.culture, {
2747
3056
  ...(await pageRequest(request)),
2748
- search: siteSearchFor(db, cache, undefined),
2749
- // The previewing editor is the visitor, with no member.
2750
- site: siteServicesFor(undefined),
3057
+ member,
3058
+ search: siteSearchFor(db, cache, member),
3059
+ site: siteServicesFor(member),
2751
3060
  // Blocks with no component say so here, and only here (story 184).
2752
3061
  preview: true,
2753
3062
  })
@@ -2966,6 +3275,136 @@ export async function createServer(
2966
3275
  })
2967
3276
  }
2968
3277
 
3278
+ function pageEtag(basis: string, content: PublishedContent, host: string, search: string) {
3279
+ return publishedEtag([basis, content.key, content.culture, host, search])
3280
+ }
3281
+
3282
+ /**
3283
+ * A `304` for a page a cache already holds, without rendering it (story
3284
+ * 258): only to a visitor nothing personal is shown to, for the ETag this
3285
+ * server last answered the address with, while it is still the page's and
3286
+ * the page is still public.
3287
+ */
3288
+ async function unchangedPage(
3289
+ request: Request,
3290
+ pathname: string,
3291
+ host: string,
3292
+ ): Promise<Response | undefined> {
3293
+ if (rememberedPages.size === 0 || !request.headers.has('if-none-match')) return undefined
3294
+ if (personalCookies.some((name) => readCookie(request, name))) return undefined
3295
+ const search = new URL(request.url).search
3296
+ const answer = rememberedPages.get(`${host}${pathname}${search}`)
3297
+ if (!answer || !notModified(request, answer.etag)) return undefined
3298
+ const content = await cache.byKey(answer.key, answer.culture)
3299
+ const basis = validatorBasis(true)
3300
+ if (!basis || !content || pageEtag(basis, content, host, search) !== answer.etag)
3301
+ return undefined
3302
+ // Public access is not in the snapshot, and this server may not have caught up with a change to it.
3303
+ if ((await members.decide(content, undefined)).status !== 'allowed') return undefined
3304
+ return unchanged(answer.headers)
3305
+ }
3306
+
3307
+ /**
3308
+ * A `'use deferred'` part for the visitor (story 263): the page it sits on,
3309
+ * as they may see it, rendered down to that part. Never kept, and nothing
3310
+ * for an address this site did not sign or a page they may not see.
3311
+ */
3312
+ async function deferredPart(request: Request, url: URL): Promise<Response> {
3313
+ const unkept = { 'cache-control': PRIVATE_NO_STORE }
3314
+ const part = readDeferredAddress(url.searchParams, verifyDeferred)
3315
+ const content = part ? await cache.byKey(part.key, part.culture) : undefined
3316
+ if (!part || !content) return new Response(null, { status: 404, headers: unkept })
3317
+ const session = await members.session(request)
3318
+ const member = session?.member
3319
+ if ((await members.decide(content, member)).status !== 'allowed')
3320
+ return new Response(null, { status: 404, headers: unkept })
3321
+ const result = await renderer.renderModel(content, part.culture, {
3322
+ member,
3323
+ antiforgery: session?.antiforgery,
3324
+ part,
3325
+ signDeferred,
3326
+ search: siteSearchFor(db, cache, member),
3327
+ site: siteServicesFor(member),
3328
+ ...(await pageRequest(request)),
3329
+ })
3330
+ if (result.status !== 'ok') return new Response(null, { status: 404, headers: unkept })
3331
+ return new Response(result.html, {
3332
+ headers: { 'content-type': 'text/html; charset=utf-8', ...unkept },
3333
+ })
3334
+ }
3335
+
3336
+ /**
3337
+ * The member a preview renders as (story 264): the one this user chose, while
3338
+ * they can still open Members. The cookie names the user too, so it is
3339
+ * nobody else's.
3340
+ */
3341
+ async function previewMember(request: Request, principal: Principal) {
3342
+ const chosen = readPreviewMember(readCookie(request, PREVIEW_MEMBER_COOKIE), principal.id)
3343
+ if (!chosen || !hasSection(principal, 'members')) return undefined
3344
+ return members.byKey(chosen)
3345
+ }
3346
+
3347
+ /**
3348
+ * Whether a published page's copies are shared, and what stops it (story
3349
+ * 264): rendered as a signed-out visitor and sent nowhere, for the Info panel.
3350
+ */
3351
+ async function pageSharing(request: Request, key: string, principal: Principal) {
3352
+ if (!(await canReadDocument(principal, key, nodeLookup)))
3353
+ return new Response('Not Found', { status: 404 })
3354
+ const culture = new URL(request.url).searchParams.get('culture') || null
3355
+ const content = await cache.byKey(key, culture)
3356
+ if (!content) return Response.json({ status: 'unpublished' })
3357
+ if ((await members.decide(content, undefined)).status !== 'allowed')
3358
+ return Response.json({ status: 'membersOnly' })
3359
+ const address = new URL(content.url, publicOrigin(request, config))
3360
+ const page = new Request(address)
3361
+ let personal = false
3362
+ const result = await renderer.renderModel(content, content.culture, {
3363
+ access: async (shown) => {
3364
+ const decision = await members.decide(shown, undefined)
3365
+ if (decision.status !== 'allowed') personal = true
3366
+ return decision
3367
+ },
3368
+ search: siteSearchFor(db, cache, undefined),
3369
+ site: siteServicesFor(undefined),
3370
+ signDeferred,
3371
+ ...(await pageRequest(page)),
3372
+ })
3373
+ if (result.status !== 'ok')
3374
+ return Response.json({
3375
+ status: 'notRendered',
3376
+ message: result.status === 'error' ? result.error.message : undefined,
3377
+ })
3378
+ const views = `${basename(config.componentsDir)}/`
3379
+ const memberFiles = (result.memberFiles ?? []).map((file) =>
3380
+ file.startsWith(views) ? `/${file.slice(views.length)}` : file,
3381
+ )
3382
+ const lifetime = pageLifetime(result)
3383
+ return Response.json({
3384
+ status: personal || result.personal ? 'notShared' : 'shared',
3385
+ keptFor: lifetime === undefined ? null : lifetime === 'none' ? 0 : lifetime.maxAge,
3386
+ checkedWithoutRendering:
3387
+ publishedValidator && validatorFor(caching, [content.contentType.alias]) === 'published',
3388
+ memberFiles,
3389
+ })
3390
+ }
3391
+
3392
+ /** A page's lifetime: its own "Keep copies for", its template's `revalidate`, its type's, the site's. */
3393
+ function pageLifetime(result: { content: PublishedContent; revalidate?: number | false }) {
3394
+ const item = {
3395
+ typeAlias: result.content.contentType.alias,
3396
+ value: (alias: string) => result.content.value(alias),
3397
+ }
3398
+ // A page's own "Keep copies for" still wins over its template's `revalidate`.
3399
+ return (
3400
+ (result.revalidate === undefined
3401
+ ? undefined
3402
+ : chosenLifetime(result.content.value(CACHE_KEEP_FOR_ALIAS))) ??
3403
+ revalidateLifetime(result.revalidate, caching.staleIfError) ??
3404
+ lifetimeFor(caching, item)
3405
+ )
3406
+ }
3407
+
2969
3408
  /** A page, and an action's flash cleared once it has been read (story 219). */
2970
3409
  async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
2971
3410
  const response = await renderPageOnce(request, pathname, host)
@@ -2985,6 +3424,14 @@ export async function createServer(
2985
3424
  pathname: string,
2986
3425
  host: string,
2987
3426
  ): Promise<Response> {
3427
+ const kept = await unchangedPage(request, pathname, host)
3428
+ if (kept) {
3429
+ noteOnSpan({ 'crombolo.render.skipped': true })
3430
+ return kept
3431
+ }
3432
+ // The render reads the snapshot anyway: built first, so a fresh server's first page has a basis.
3433
+ if (publishedValidator) await cache.snapshot()
3434
+ const basis = publishedValidator ? validatorBasis(true) : undefined
2988
3435
  const preview = await renderPreview(request, pathname, host)
2989
3436
  // An `api` node renders for preview and nothing else. The backoffice opens a
2990
3437
  // site URL to preview a draft, so the renderer has to be here; serving the
@@ -3010,20 +3457,36 @@ export async function createServer(
3010
3457
  // Whether the page itself read anything personal, the member included, it
3011
3458
  // says in its result (story 206).
3012
3459
  let personal = Boolean(preview || submission || cookie || actionCookie)
3460
+ const rendering = performance.now()
3461
+ const requestSpan = activeSpan()
3013
3462
  const result =
3014
3463
  preview ??
3015
- (await renderer.render(pathname, host, {
3016
- member,
3017
- antiforgery: session?.antiforgery,
3018
- submission,
3019
- actions: { idOf: actionList.idOf, flash: actionFlash },
3020
- access: async (content) => {
3021
- if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
3022
- return members.decide(content, member)
3023
- },
3024
- search: siteSearchFor(db, cache, member),
3025
- site: siteServicesFor(member),
3026
- ...(await pageRequest(request)),
3464
+ (await inSpan('render', {}, async (span) => {
3465
+ const rendered = await renderer.render(pathname, host, {
3466
+ member,
3467
+ antiforgery: session?.antiforgery,
3468
+ submission,
3469
+ actions: { idOf: actionList.idOf, flash: actionFlash },
3470
+ access: async (content) => {
3471
+ if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
3472
+ return members.decide(content, member)
3473
+ },
3474
+ search: siteSearchFor(db, cache, member),
3475
+ site: siteServicesFor(member),
3476
+ signDeferred,
3477
+ ...(await pageRequest(request)),
3478
+ })
3479
+ if ('content' in rendered) {
3480
+ const template = rendered.content.componentAlias ?? ''
3481
+ span.setAttributes({
3482
+ 'crombolo.template': template,
3483
+ 'crombolo.content.type': rendered.content.contentType.alias,
3484
+ 'crombolo.render.status': rendered.status,
3485
+ })
3486
+ requestSpan?.setAttribute('crombolo.content.type', rendered.content.contentType.alias)
3487
+ recordRender((performance.now() - rendering) / 1000, { 'crombolo.template': template })
3488
+ }
3489
+ return rendered
3027
3490
  }))
3028
3491
  const cleared: Record<string, string> = cookie
3029
3492
  ? { 'set-cookie': expireCookie(FORM_FLASH_COOKIE, config.secureCookies) }
@@ -3033,26 +3496,37 @@ export async function createServer(
3033
3496
  const response = new Response(result.html, {
3034
3497
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
3035
3498
  })
3499
+ // Story 263: shared with every visitor unless a file it rendered shows the member.
3500
+ if (result.memberFiles) {
3501
+ response.headers.append('vary', MEMBER_VARY)
3502
+ if (config.development && member) noteMemberFiles(result.content, result.memberFiles)
3503
+ }
3036
3504
  if (personal || result.personal) {
3037
3505
  response.headers.set('cache-control', PRIVATE_NO_STORE)
3038
3506
  return response
3039
3507
  }
3040
3508
  const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
3041
- const item = {
3042
- typeAlias: result.content.contentType.alias,
3043
- value: (alias: string) => result.content.value(alias),
3044
- }
3045
- return cacheable(request, response, result.html, {
3046
- // A page's own "Keep copies for" still wins over its template's `revalidate`.
3047
- lifetime:
3048
- (result.revalidate === undefined
3049
- ? undefined
3050
- : chosenLifetime(result.content.value(CACHE_KEEP_FOR_ALIAS))) ??
3051
- revalidateLifetime(result.revalidate) ??
3052
- lifetimeFor(caching, item),
3509
+ const item = { typeAlias: result.content.contentType.alias }
3510
+ const search = new URL(request.url).search
3511
+ const etag =
3512
+ basis && validatorFor(caching, [item.typeAlias]) === 'published'
3513
+ ? pageEtag(basis, result.content, host, search)
3514
+ : undefined
3515
+ const answer = cacheable(request, response, result.html, {
3516
+ lifetime: pageLifetime(result),
3053
3517
  tags: [result.content.key, ...ancestors.map((a) => a.key)],
3054
3518
  tagHeader: caching.tagHeader,
3519
+ etag,
3520
+ checkFloor: caching.checkFloor,
3055
3521
  })
3522
+ if (etag)
3523
+ rememberedPages.set(`${host}${pathname}${search}`, {
3524
+ etag,
3525
+ headers: rememberedHeaders(answer.headers, caching.tagHeader),
3526
+ key: result.content.key,
3527
+ culture: result.content.culture,
3528
+ })
3529
+ return answer
3056
3530
  }
3057
3531
  case 'redirect':
3058
3532
  // Umbraco's `umbracoRedirect` answers 302: the page may stop redirecting.
@@ -3353,11 +3827,13 @@ export async function createServer(
3353
3827
  previewHub.stop()
3354
3828
  watcher?.close()
3355
3829
  viewWatcher?.close()
3830
+ siteAssets.close()
3356
3831
  typeWatch?.stop()
3357
3832
  live?.close()
3358
3833
  poller.stop()
3359
3834
  await closeTables(chains)
3360
3835
  await db.close()
3836
+ await stopTelemetry()
3361
3837
  },
3362
3838
  }
3363
3839
  }
@@ -3382,9 +3858,13 @@ function errorReference(): string {
3382
3858
  }
3383
3859
 
3384
3860
  /** A template's `revalidate` as a lifetime: seconds, or false for as long as it is unchanged. */
3385
- function revalidateLifetime(revalidate: number | false | undefined): Lifetime {
3861
+ function revalidateLifetime(
3862
+ revalidate: number | false | undefined,
3863
+ staleIfError?: number,
3864
+ ): Lifetime {
3386
3865
  if (revalidate === undefined) return undefined
3387
- if (revalidate === false) return { maxAge: 31_536_000 }
3866
+ const onError = staleIfError ? { staleIfError } : {}
3867
+ if (revalidate === false) return { maxAge: 31_536_000, ...onError }
3388
3868
  if (!Number.isFinite(revalidate) || revalidate < 0) return undefined
3389
- return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate) }
3869
+ return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate), ...onError }
3390
3870
  }