@crombolo/server 0.46.1 → 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'
@@ -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)) }),
@@ -1246,12 +1427,39 @@ export async function createServer(
1246
1427
  * address it is answered with points back at the new paths.
1247
1428
  */
1248
1429
  async function fetch(request: Request): Promise<Response> {
1249
- const response = await answer(request)
1250
- // Readers are answered from the previous cache while it rebuilds (story
1251
- // 175), so a change is in it before the request that made it is answered.
1252
- if (request.method !== 'GET' && request.method !== 'HEAD' && cache.stale)
1253
- await cache.fresh().catch(() => {})
1254
- 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
+ )
1255
1463
  }
1256
1464
 
1257
1465
  async function answer(request: Request): Promise<Response> {
@@ -1296,7 +1504,7 @@ export async function createServer(
1296
1504
  // Umbraco's Delivery API, below the backoffice path but served wherever the
1297
1505
  // site is, from the published cache: it scales with rendering.
1298
1506
  if (deliveryApi && pathname.startsWith(`${deliveryPrefix}/`)) {
1299
- const response = await deliveryApi.handle(request)
1507
+ const response = await inSpan('delivery api', {}, () => deliveryApi.handle(request))
1300
1508
  if (response) return response
1301
1509
  }
1302
1510
 
@@ -1331,8 +1539,18 @@ export async function createServer(
1331
1539
  : new Response('Not Found', { status: 404, headers: { 'cache-control': 'no-store' } })
1332
1540
  }
1333
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
+
1334
1549
  // Islands (story 209): the loader, and each generation's browser code.
1335
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)
1336
1554
  if (pathname.startsWith(`${ISLANDS_PATH}/`))
1337
1555
  return islandFile(pathname.slice(ISLANDS_PATH.length + 1))
1338
1556
 
@@ -1444,7 +1662,18 @@ export async function createServer(
1444
1662
  return new Response(body, {
1445
1663
  headers: {
1446
1664
  'content-type': 'text/javascript; charset=utf-8',
1447
- 'cache-control': config.development ? 'no-cache' : 'public, max-age=3600',
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',
1448
1677
  },
1449
1678
  })
1450
1679
  }
@@ -1458,8 +1687,10 @@ export async function createServer(
1458
1687
  const routed = await siteRoutes.handle(request, url)
1459
1688
  if (routed) return routed
1460
1689
  }
1461
- if (pathname.startsWith('/css/')) return serveSiteFile(config.stylesheetsDir, pathname, '.css')
1462
- 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')
1463
1694
  return renderSite(request, pathname, url.host, run)
1464
1695
  }
1465
1696
 
@@ -1615,6 +1846,23 @@ export async function createServer(
1615
1846
  if (response) return response
1616
1847
  }
1617
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
+
1618
1866
  // Non-contract, Media: who may read and change a media folder or item (story 196).
1619
1867
  if (pathname.startsWith(`${mediaAccessPath}/`)) {
1620
1868
  const principal = await authenticate(request)
@@ -2606,17 +2854,56 @@ export async function createServer(
2606
2854
  }
2607
2855
 
2608
2856
  /** A stylesheet or script the Settings section edits, from its folder; nothing else from there. */
2609
- async function serveSiteFile(root: string, pathname: string, extension: string) {
2610
- const segments = decodeURIComponent(pathname).split('/').slice(2)
2611
- const safe =
2612
- segments.length > 0 &&
2613
- segments.every((s) => s !== '' && s !== '.' && s !== '..' && !s.includes('\\')) &&
2614
- segments.at(-1)?.toLowerCase().endsWith(extension)
2615
- const file = safe ? Bun.file(join(root, ...segments)) : undefined
2616
- if (!file || !(await file.exists())) return new Response('Not Found', { status: 404 })
2617
- const headers = { 'cache-control': 'no-cache', 'content-type': file.type }
2618
- // Bun.serve answers an empty file body 204, and an empty stylesheet is still one
2619
- 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
2620
2907
  }
2621
2908
 
2622
2909
  /**
@@ -2763,11 +3050,13 @@ export async function createServer(
2763
3050
  if (!key) return undefined
2764
3051
  const draft = await draftModel(key, new URL(request.url).searchParams.get('culture'), principal)
2765
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)
2766
3055
  return renderer.renderModel(draft.content, draft.culture, {
2767
3056
  ...(await pageRequest(request)),
2768
- search: siteSearchFor(db, cache, undefined),
2769
- // The previewing editor is the visitor, with no member.
2770
- site: siteServicesFor(undefined),
3057
+ member,
3058
+ search: siteSearchFor(db, cache, member),
3059
+ site: siteServicesFor(member),
2771
3060
  // Blocks with no component say so here, and only here (story 184).
2772
3061
  preview: true,
2773
3062
  })
@@ -2986,6 +3275,136 @@ export async function createServer(
2986
3275
  })
2987
3276
  }
2988
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
+
2989
3408
  /** A page, and an action's flash cleared once it has been read (story 219). */
2990
3409
  async function renderPage(request: Request, pathname: string, host: string): Promise<Response> {
2991
3410
  const response = await renderPageOnce(request, pathname, host)
@@ -3005,6 +3424,14 @@ export async function createServer(
3005
3424
  pathname: string,
3006
3425
  host: string,
3007
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
3008
3435
  const preview = await renderPreview(request, pathname, host)
3009
3436
  // An `api` node renders for preview and nothing else. The backoffice opens a
3010
3437
  // site URL to preview a draft, so the renderer has to be here; serving the
@@ -3030,20 +3457,36 @@ export async function createServer(
3030
3457
  // Whether the page itself read anything personal, the member included, it
3031
3458
  // says in its result (story 206).
3032
3459
  let personal = Boolean(preview || submission || cookie || actionCookie)
3460
+ const rendering = performance.now()
3461
+ const requestSpan = activeSpan()
3033
3462
  const result =
3034
3463
  preview ??
3035
- (await renderer.render(pathname, host, {
3036
- member,
3037
- antiforgery: session?.antiforgery,
3038
- submission,
3039
- actions: { idOf: actionList.idOf, flash: actionFlash },
3040
- access: async (content) => {
3041
- if ((await members.decide(content, undefined)).status !== 'allowed') personal = true
3042
- return members.decide(content, member)
3043
- },
3044
- search: siteSearchFor(db, cache, member),
3045
- site: siteServicesFor(member),
3046
- ...(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
3047
3490
  }))
3048
3491
  const cleared: Record<string, string> = cookie
3049
3492
  ? { 'set-cookie': expireCookie(FORM_FLASH_COOKIE, config.secureCookies) }
@@ -3053,26 +3496,37 @@ export async function createServer(
3053
3496
  const response = new Response(result.html, {
3054
3497
  headers: { 'content-type': 'text/html; charset=utf-8', ...cleared },
3055
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
+ }
3056
3504
  if (personal || result.personal) {
3057
3505
  response.headers.set('cache-control', PRIVATE_NO_STORE)
3058
3506
  return response
3059
3507
  }
3060
3508
  const ancestors = (await cache.navigation(result.content.culture)).ancestors(result.content)
3061
- const item = {
3062
- typeAlias: result.content.contentType.alias,
3063
- value: (alias: string) => result.content.value(alias),
3064
- }
3065
- return cacheable(request, response, result.html, {
3066
- // A page's own "Keep copies for" still wins over its template's `revalidate`.
3067
- lifetime:
3068
- (result.revalidate === undefined
3069
- ? undefined
3070
- : chosenLifetime(result.content.value(CACHE_KEEP_FOR_ALIAS))) ??
3071
- revalidateLifetime(result.revalidate) ??
3072
- 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),
3073
3517
  tags: [result.content.key, ...ancestors.map((a) => a.key)],
3074
3518
  tagHeader: caching.tagHeader,
3519
+ etag,
3520
+ checkFloor: caching.checkFloor,
3075
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
3076
3530
  }
3077
3531
  case 'redirect':
3078
3532
  // Umbraco's `umbracoRedirect` answers 302: the page may stop redirecting.
@@ -3373,11 +3827,13 @@ export async function createServer(
3373
3827
  previewHub.stop()
3374
3828
  watcher?.close()
3375
3829
  viewWatcher?.close()
3830
+ siteAssets.close()
3376
3831
  typeWatch?.stop()
3377
3832
  live?.close()
3378
3833
  poller.stop()
3379
3834
  await closeTables(chains)
3380
3835
  await db.close()
3836
+ await stopTelemetry()
3381
3837
  },
3382
3838
  }
3383
3839
  }
@@ -3402,9 +3858,13 @@ function errorReference(): string {
3402
3858
  }
3403
3859
 
3404
3860
  /** A template's `revalidate` as a lifetime: seconds, or false for as long as it is unchanged. */
3405
- function revalidateLifetime(revalidate: number | false | undefined): Lifetime {
3861
+ function revalidateLifetime(
3862
+ revalidate: number | false | undefined,
3863
+ staleIfError?: number,
3864
+ ): Lifetime {
3406
3865
  if (revalidate === undefined) return undefined
3407
- if (revalidate === false) return { maxAge: 31_536_000 }
3866
+ const onError = staleIfError ? { staleIfError } : {}
3867
+ if (revalidate === false) return { maxAge: 31_536_000, ...onError }
3408
3868
  if (!Number.isFinite(revalidate) || revalidate < 0) return undefined
3409
- return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate) }
3869
+ return revalidate === 0 ? 'none' : { maxAge: Math.floor(revalidate), ...onError }
3410
3870
  }