Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Sean/safari cache fixes (#8472)

Sean Aye19b0ab4cab94
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 4e91881fbb..d7f6dcf4e8 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -10,6 +10,9 @@
- The app does not register a service worker. Keep `public/sw.js` as a retirement
endpoint for existing installations; see the [startup bundle rule](../../.agents/rules/web/startup-bundle.md).
Loro uses async WASM loading and HTML preloads independently of service workers.
+- Web asset publication and cache headers are covered by
+ [web-app delivery](../../infra/stacks/web-app/README.md); its publisher tests
+ are backend-free, and its Pulumi tests must not run real staging/cloud commands.
## Verifying a change in a real browser
@@ -96,6 +99,9 @@ ownership. Cancel, logout, and the ten-minute timeout retire pending callbacks.
shared HttpOnly dev cookies are not visible to JavaScript or localStorage.
- Disable GraphQL cache sessions and clear login hints on confirmed auth 401s,
even with retained user data; preserve session state on transient failures.
+- Treat a repeated worker-ready frame as a coordinator restart: retire the old
+ engine and re-register in place, preserving durable storage and never replaying
+ uncertain enqueues. See `docs/graphql-normalized-cache-plan.md`.
- Mobile dock customization shares the navigation island’s measured capacity; persist ordering per user with `mobile-dock-order.ts`, preserve gated destinations, and keep Search and More fixed. Reorder handles drag without a hold delay; the rest of each row scrolls.
- Share sidebar and mobile dock unread presence through `components/app/use-navigation-unread.ts`; keep badges reactive to read/done changes and avoid fetching extra pages for counts.
- Mobile dock search owns transient category/mode state in `features/command/mobile`; reuse the shared entity source and explicit full-text adapter rather than overlaying the dock query on view tabs or saved facets. See `docs/agent-guide/search.md` at the repository root.
diff --git a/apps/web/docs/graphql-normalized-cache-plan.md b/apps/web/docs/graphql-normalized-cache-plan.md
index c8985dde3f..0757c66629 100644
--- a/apps/web/docs/graphql-normalized-cache-plan.md
+++ b/apps/web/docs/graphql-normalized-cache-plan.md
@@ -211,6 +211,18 @@ heartbeat without changing epochs or touching storage. A released lock confirms
silent worker termination and triggers the usual fenced recovery. Read deadlines
still bound callers waiting on an unresponsive engine.
+Safari can recreate the SharedWorker global while retaining a page's MessagePort,
+including when another tab closes. A second Effect ready frame is a transport
+reset, not a duplicate initial handshake: the page retires its orphanable engine
+and connection, then re-registers and initializes against the new coordinator.
+The same host and subscribers survive. Pending operations reject without replay;
+an admitted optimistic enqueue is reported as uncertain so it cannot fall through
+to a second API write. Durable storage and the cache scope are preserved, while
+live-query dependencies and revision checkpoints are invalidated after reconnect.
+Restarted startup is bounded by the registration retry budget; exhaustion uses
+the normal session fallback without quarantining a healthy database. The
+`graphql_cache.owner` event records `ownerEvent: coordinator-restarted`.
+
Protocol v6 separates startup into asset loading, taking the database owner
lock, and database opening. The engine loads/compiles WASM without touching OPFS
and reports `engine-assets-ready`. It then takes the owner lock only if it is
diff --git a/apps/web/scripts/cache-wasm/upload-brotli-to-s3.test.ts b/apps/web/scripts/cache-wasm/upload-brotli-to-s3.test.ts
index 815d029484..46ff0e4962 100644
--- a/apps/web/scripts/cache-wasm/upload-brotli-to-s3.test.ts
+++ b/apps/web/scripts/cache-wasm/upload-brotli-to-s3.test.ts
@@ -20,35 +20,6 @@ afterEach(() => {
});
describe('cache WASM S3 upload', () => {
- it('production generic sync excludes cache raw/sidecar but not unrelated WASM', () => {
- const infrastructure = readFileSync(
- resolve(import.meta.dirname, '../../../../infra/stacks/web-app/index.ts'),
- 'utf8'
- );
- expect(infrastructure).toContain(
- '--exclude "*cache_wasm_bg*.wasm" --exclude "*cache_wasm_bg*.wasm.br"'
- );
- expect(infrastructure).not.toContain('--exclude "*.wasm"');
- const uploadIndex = infrastructure.indexOf('upload-brotli-to-s3.sh');
- const syncIndex = infrastructure.indexOf('aws s3 sync ./output');
- const indexPublishIndex = infrastructure.indexOf(
- 'index-html-object-metadata-command'
- );
- const pruneIndex = infrastructure.indexOf(
- 'prune-old-brotli-from-s3.sh'
- );
- expect(uploadIndex).toBeLessThan(syncIndex);
- expect(syncIndex).toBeLessThan(indexPublishIndex);
- expect(indexPublishIndex).toBeLessThan(pruneIndex);
- expect(infrastructure.slice(uploadIndex, syncIndex)).toContain('&&');
- expect(infrastructure).toContain(
- 'dependsOn: [webAppAssets, syncAssetsCommand]'
- );
- expect(infrastructure).toContain(
- 'dependsOn: [indexHtmlObjectMetadataCommand]'
- );
- });
-
it('keeps sidecars in web delivery but excludes them from native/OTA packaging', () => {
const webJustfile = readFileSync(
resolve(import.meta.dirname, '../../justfile'),
@@ -68,7 +39,9 @@ describe('cache WASM S3 upload', () => {
expect(infrastructure).toContain(
`find ${'${shellQuote(appArchiveOutputPath)}'} -type f -name 'cache_wasm_bg*.wasm.br' -delete`
);
- expect(infrastructure).toContain('--exclude "app-archive/*"');
+ expect(infrastructure).toContain(
+ 'publish-web-assets.sh assets ./output/app'
+ );
});
it('uploads only sidecar bytes at the original WASM key with exact metadata', () => {
@@ -178,10 +151,7 @@ describe('cache WASM S3 upload', () => {
mkdirSync(bin);
const rawPath = join(assets, 'cache_wasm_bg-current.wasm');
writeFileSync(rawPath, Buffer.from('current cache wasm'.repeat(100)));
- writeFileSync(
- `${rawPath}.br`,
- brotliCompressSync(readFileSync(rawPath))
- );
+ writeFileSync(`${rawPath}.br`, brotliCompressSync(readFileSync(rawPath)));
const argumentsPath = join(directory, 'aws-arguments.txt');
const fakeAws = join(bin, 'aws');
writeFileSync(
diff --git a/apps/web/scripts/publish-web-assets.sh b/apps/web/scripts/publish-web-assets.sh
new file mode 100755
index 0000000000..2ba5f20359
--- /dev/null
+++ b/apps/web/scripts/publish-web-assets.sh
@@ -0,0 +1,35 @@
+#!/usr/bin/env bash
+# Publish immutable objects before mutable entrypoints. Pulumi owns the ordering
+# between these two phases and the routing Lambda update.
+set -euo pipefail
+
+phase="${1:?expected assets or entrypoints}"
+dist="${2:?expected build directory}"
+destination="${3:?expected s3://bucket/prefix}"
+script_dir="$(\cd "$(dirname "$0")" && pwd)"
+
+# These URLs name the current build, rather than a content-hashed object.
+entrypoints=('*.html' '*.json' '*.txt' 'sw.js')
+filters=(--exclude 'app-archive.zip')
+
+case "$phase" in
+ assets)
+ bash "$script_dir/cache-wasm/upload-brotli-to-s3.sh" "$dist" "$destination" public-read
+ filters+=(--exclude '*cache_wasm_bg*.wasm' --exclude '*cache_wasm_bg*.wasm.br')
+ for pattern in "${entrypoints[@]}"; do filters+=(--exclude "$pattern"); done
+ # Unlike sync, cp also repairs metadata on unchanged objects from older
+ # builds, whose long lifetime previously came only from CloudFront.
+ aws s3 cp "$dist" "$destination" --recursive --acl public-read \
+ --cache-control 'public, max-age=31536000, immutable' "${filters[@]}"
+ ;;
+ entrypoints)
+ filters+=(--exclude '*')
+ for pattern in "${entrypoints[@]}"; do filters+=(--include "$pattern"); done
+ aws s3 cp "$dist" "$destination" --recursive --acl public-read \
+ --cache-control 'no-store' "${filters[@]}"
+ ;;
+ *)
+ echo "unknown publishing phase: $phase" >&2
+ exit 64
+ ;;
+esac
diff --git a/apps/web/scripts/publish-web-assets.test.ts b/apps/web/scripts/publish-web-assets.test.ts
new file mode 100644
index 0000000000..6804c8b965
--- /dev/null
+++ b/apps/web/scripts/publish-web-assets.test.ts
@@ -0,0 +1,194 @@
+import { spawnSync } from 'node:child_process';
+import {
+ chmodSync,
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { brotliCompressSync } from 'node:zlib';
+import { afterEach, describe, expect, it } from 'vitest';
+
+const temporaryDirectories: string[] = [];
+afterEach(() => {
+ for (const path of temporaryDirectories.splice(0))
+ rmSync(path, { recursive: true, force: true });
+});
+
+function publishingFixture() {
+ const root = mkdtempSync(join(tmpdir(), 'web-publishing-'));
+ temporaryDirectories.push(root);
+ const dist = join(root, 'dist');
+ const bucket = join(root, 'bucket');
+ const bin = join(root, 'bin');
+ const log = join(root, 'uploads.jsonl');
+ mkdirSync(bin);
+ mkdirSync(join(bucket, 'app'), { recursive: true });
+ for (const [path, content] of Object.entries({
+ 'index.html': '<script src="app-abcdefgh.js"></script>',
+ 'pipedream-connect.html': '<script src="app-abcdefgh.js"></script>',
+ 'manifest.json': '{"name":"Macro"}',
+ 'bundle-manifest.json': '{"bundleBuild":123}',
+ 'semver.txt': '1.0.0',
+ 'sw.js': 'self.registration.unregister()',
+ 'app-abcdefgh.js': 'export const ready = true;',
+ 'assets/font-abcdefgh.woff2': 'font',
+ 'assets/other-abcdefgh.wasm': 'unrelated wasm',
+ 'app-archive.zip': 'must not overwrite the managed archive',
+ })) {
+ mkdirSync(dirname(join(dist, path)), { recursive: true });
+ writeFileSync(join(dist, path), content);
+ }
+ const compressed = brotliCompressSync(Buffer.from('cache wasm'));
+ writeFileSync(join(dist, 'assets/cache_wasm_bg-hash.wasm'), 'cache wasm');
+ writeFileSync(join(dist, 'assets/cache_wasm_bg-hash.wasm.br'), compressed);
+ writeFileSync(join(bucket, 'app/index.html'), 'previous entrypoint');
+ writeFileSync(join(bucket, 'app/app-archive.zip'), 'managed archive');
+ writeFileSync(join(bucket, 'app/retained-old.js'), 'old build');
+ writeFileSync(log, '');
+ copyFileSync(
+ resolve(import.meta.dirname, 'tests/fake-asset-upload.mjs'),
+ join(bin, 'aws')
+ );
+ chmodSync(join(bin, 'aws'), 0o755);
+ return {
+ dist,
+ bucket,
+ compressed,
+ uploads: () =>
+ readFileSync(log, 'utf8')
+ .trim()
+ .split('\n')
+ .filter(Boolean)
+ .map((line) => JSON.parse(line)),
+ run: (phase: string, failAssets = false) =>
+ spawnSync(
+ 'bash',
+ [
+ resolve(import.meta.dirname, 'publish-web-assets.sh'),
+ phase,
+ dist,
+ 's3://example/app',
+ ],
+ {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ PATH: `${bin}:${process.env.PATH}`,
+ FAKE_AWS_LOG: log,
+ FAKE_S3_ROOT: bucket,
+ FAIL_ASSETS: String(failAssets),
+ },
+ }
+ ),
+ };
+}
+
+describe('web build publication', () => {
+ it('publishes immutable assets first without exposing new HTML or mutable metadata', () => {
+ const fixture = publishingFixture();
+ const result = fixture.run('assets');
+ expect(result.status, result.stderr).toBe(0);
+ expect(readFileSync(join(fixture.bucket, 'app/index.html'), 'utf8')).toBe(
+ 'previous entrypoint'
+ );
+ expect(existsSync(join(fixture.bucket, 'app/pipedream-connect.html'))).toBe(
+ false
+ );
+ expect(existsSync(join(fixture.bucket, 'app/bundle-manifest.json'))).toBe(
+ false
+ );
+ expect(existsSync(join(fixture.bucket, 'app/semver.txt'))).toBe(false);
+ expect(existsSync(join(fixture.bucket, 'app/sw.js'))).toBe(false);
+ expect(
+ readFileSync(join(fixture.bucket, 'app/assets/cache_wasm_bg-hash.wasm'))
+ ).toEqual(fixture.compressed);
+ expect(
+ existsSync(join(fixture.bucket, 'app/assets/cache_wasm_bg-hash.wasm.br'))
+ ).toBe(false);
+ expect(
+ readFileSync(
+ join(fixture.bucket, 'app/assets/other-abcdefgh.wasm'),
+ 'utf8'
+ )
+ ).toBe('unrelated wasm');
+ expect(
+ readFileSync(join(fixture.bucket, 'app/app-archive.zip'), 'utf8')
+ ).toBe('managed archive');
+ expect(
+ readFileSync(join(fixture.bucket, 'app/retained-old.js'), 'utf8')
+ ).toBe('old build');
+ expect(
+ fixture
+ .uploads()
+ .every(
+ (upload) =>
+ upload.cacheControl === 'public, max-age=31536000, immutable'
+ )
+ ).toBe(true);
+ });
+
+ it('publishes HTML, manifests, version, and retirement script with no-store only after assets', () => {
+ const fixture = publishingFixture();
+ expect(fixture.run('assets').status).toBe(0);
+ const result = fixture.run('entrypoints');
+ expect(result.status, result.stderr).toBe(0);
+ const uploads = fixture.uploads();
+ const entrypoints = uploads.filter(
+ (upload) => upload.cacheControl === 'no-store'
+ );
+ expect(entrypoints.map((upload) => upload.key).sort()).toEqual([
+ 'app/bundle-manifest.json',
+ 'app/index.html',
+ 'app/manifest.json',
+ 'app/pipedream-connect.html',
+ 'app/semver.txt',
+ 'app/sw.js',
+ ]);
+ expect(
+ uploads
+ .slice(0, -entrypoints.length)
+ .every((upload) => upload.cacheControl.includes('immutable'))
+ ).toBe(true);
+ expect(readFileSync(join(fixture.bucket, 'app/index.html'), 'utf8')).toBe(
+ '<script src="app-abcdefgh.js"></script>'
+ );
+ expect(
+ readFileSync(join(fixture.bucket, 'app/app-archive.zip'), 'utf8')
+ ).toBe('managed archive');
+ });
+
+ it('repairs cache metadata even when immutable bytes did not change', () => {
+ const fixture = publishingFixture();
+ copyFileSync(
+ join(fixture.dist, 'app-abcdefgh.js'),
+ join(fixture.bucket, 'app/app-abcdefgh.js')
+ );
+ expect(fixture.run('assets').status).toBe(0);
+ expect(fixture.uploads()).toContainEqual(
+ expect.objectContaining({
+ key: 'app/app-abcdefgh.js',
+ cacheControl: 'public, max-age=31536000, immutable',
+ })
+ );
+ });
+
+ it('fails the asset phase without publishing an entrypoint or removing old objects', () => {
+ const fixture = publishingFixture();
+ expect(fixture.run('assets', true).status).toBe(42);
+ expect(readFileSync(join(fixture.bucket, 'app/index.html'), 'utf8')).toBe(
+ 'previous entrypoint'
+ );
+ expect(
+ readFileSync(join(fixture.bucket, 'app/retained-old.js'), 'utf8')
+ ).toBe('old build');
+ expect(
+ fixture.uploads().some((upload) => upload.key.endsWith('.html'))
+ ).toBe(false);
+ });
+});
diff --git a/apps/web/scripts/retain-recent-builds.test.ts b/apps/web/scripts/retain-recent-builds.test.ts
index fcd03a30ce..2c8aa4114a 100644
--- a/apps/web/scripts/retain-recent-builds.test.ts
+++ b/apps/web/scripts/retain-recent-builds.test.ts
@@ -112,39 +112,6 @@ process.exit(1);
const manifest = (build: number) =>
JSON.stringify({ schemaVersion: 3, bundleBuild: build });
-describe('retention wiring', () => {
- const infrastructure = readFileSync(
- resolve(import.meta.dirname, '../../../infra/stacks/web-app/index.ts'),
- 'utf8'
- );
-
- it('does not let the generic sync delete a superseded build', () => {
- const sync = infrastructure.slice(
- infrastructure.indexOf('aws s3 sync ./output')
- );
- expect(sync.slice(0, sync.indexOf('`'))).not.toContain('--delete');
- });
-
- it('prunes last, after every publishing step has succeeded', () => {
- const sync = infrastructure.indexOf('aws s3 sync ./output');
- const indexPublish = infrastructure.indexOf(
- 'index-html-object-metadata-command'
- );
- // Anchored on the invocations: both scripts are named in comments too.
- const cacheWasmPrune = infrastructure.indexOf(
- 'bash ../../../apps/web/scripts/cache-wasm/prune-old-brotli-from-s3.sh'
- );
- const retain = infrastructure.indexOf(
- 'bash ../../../apps/web/scripts/retain-recent-builds.sh'
- );
- expect(sync).toBeLessThan(indexPublish);
- expect(indexPublish).toBeLessThan(cacheWasmPrune);
- expect(cacheWasmPrune).toBeLessThan(retain);
- // Serialized behind the other prune so a failure above retires nothing.
- expect(infrastructure).toContain('dependsOn: [pruneOldCacheWasmCommand]');
- });
-});
-
describe('retaining recent builds', () => {
it('keeps what recent builds still refer to and drops what none do', () => {
const { result, deleted } = run(
diff --git a/apps/web/scripts/tests/fake-asset-upload.mjs b/apps/web/scripts/tests/fake-asset-upload.mjs
new file mode 100644
index 0000000000..039b2101b2
--- /dev/null
+++ b/apps/web/scripts/tests/fake-asset-upload.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env bun
+// Local-only stand-in for the S3 cp commands exercised by publishing tests.
+import {
+ appendFileSync,
+ copyFileSync,
+ mkdirSync,
+ readdirSync,
+ statSync,
+} from 'node:fs';
+import { basename, dirname, join } from 'node:path';
+
+const [service, operation, source, destination, ...options] =
+ process.argv.slice(2);
+if (service !== 's3' || operation !== 'cp') process.exit(64);
+const target = new URL(destination);
+if (target.hostname !== 'example') process.exit(64);
+const cacheControl = options[options.indexOf('--cache-control') + 1];
+const recursive = options.includes('--recursive');
+if (
+ process.env.FAIL_ASSETS === 'true' &&
+ recursive &&
+ cacheControl.includes('immutable')
+) {
+ process.exit(42);
+}
+const filters = [];
+for (let index = 0; index < options.length; index += 1) {
+ if (options[index] !== '--include' && options[index] !== '--exclude')
+ continue;
+ filters.push({
+ include: options[index] === '--include',
+ pattern: options[++index],
+ });
+}
+const files = recursive
+ ? readdirSync(source, { recursive: true }).filter((file) =>
+ statSync(join(source, file)).isFile()
+ )
+ : [basename(source)];
+for (const file of files) {
+ let included = true;
+ for (const filter of filters) {
+ const glob = new Bun.Glob(`**/${filter.pattern}`);
+ if (glob.match(file)) included = filter.include;
+ }
+ if (!included) continue;
+ const key = recursive
+ ? join(target.pathname.slice(1), file)
+ : target.pathname.slice(1);
+ const path = join(process.env.FAKE_S3_ROOT, key);
+ mkdirSync(dirname(path), { recursive: true });
+ copyFileSync(recursive ? join(source, file) : source, path);
+ appendFileSync(
+ process.env.FAKE_AWS_LOG,
+ JSON.stringify({ key, cacheControl, options }) + '\n'
+ );
+}
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.integration.test.ts b/apps/web/src/lib/graphql-cache/host/worker-host.integration.test.ts
index 95f1477d19..f510521cab 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.integration.test.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.integration.test.ts
@@ -12,6 +12,7 @@ import type { CacheRequest, CacheResponse } from '../protocol';
import { installCacheCoordinatorWorker } from '../worker/cache-coordinator-runtime';
import { installCacheEngineWorker } from '../worker/cache-engine-runtime';
import { CoordinatorRouter } from '../worker/coordinator-router';
+import { EFFECT_WORKER_CLOSE_FRAME } from '../worker/effect-worker-transport';
import type { CacheHost } from './types';
import { createWorkerCacheHost } from './worker-host';
@@ -25,13 +26,22 @@ const STANDBY_MUTATION = gql`
holdStandby
}
`;
+const COORDINATOR_RESTART_MUTATION = gql`
+ mutation HoldCoordinatorRestart {
+ holdCoordinatorRestart
+ }
+`;
const RETIREMENT_FAILURE_MUTATION = gql`
mutation HoldRetirementFailure {
holdRetirementFailure
}
`;
-function exchangeHarness(host: CacheHost, operation: Operation) {
+function exchangeHarness(
+ host: CacheHost,
+ operation: Operation,
+ onResult?: (result: OperationResult) => void
+) {
const operations = makeSubject<Operation>();
const network = makeSubject<OperationResult>();
const forwarded: Operation[] = [];
@@ -50,7 +60,10 @@ function exchangeHarness(host: CacheHost, operation: Operation) {
client,
dispatchDebug: () => undefined,
})(operations.source),
- subscribe((result) => results.push(result))
+ subscribe((result) => {
+ results.push(result);
+ onResult?.(result);
+ })
);
operations.next(operation);
return { forwarded, results };
@@ -117,6 +130,8 @@ type RuntimeLog = {
query?: string;
};
+const requestObservers = new Set<(entry: RuntimeLog) => void>();
+
type Deferred = { promise: Promise<void>; resolve: () => void };
const deferred = (): Deferred => {
let resolve!: () => void;
@@ -142,12 +157,14 @@ class IntegrationCore {
port: { postMessage(message: unknown): void },
request: CacheRequest
): Promise<void> {
- this.logs.push({
+ const entry = {
epoch: this.epoch,
kind: request.kind,
id: request.id,
query: 'query' in request ? request.query : undefined,
- });
+ };
+ this.logs.push(entry);
+ for (const observer of requestObservers) observer(entry);
if (request.kind === 'init') {
// Like WASM: hold the owner lock and get the storage grant, then open.
if (request.id === 0) await this.onOwnerLockAcquired?.();
@@ -256,6 +273,22 @@ class IntegrationSharedWorker {
});
}
+ restart(router: CoordinatorRouter): void {
+ // Safari preserves the page endpoint but reconnects it to a fresh global.
+ const previous = this.port.peer;
+ previous?.close();
+ previous?.dispatchEvent(
+ new MessageEvent('message', { data: EFFECT_WORKER_CLOSE_FRAME })
+ );
+ const endpoint = new LinkedMessagePort();
+ endpoint.peer = this.port;
+ this.port.peer = endpoint;
+ installCacheCoordinatorWorker({
+ endpoint: endpoint as unknown as MessagePort,
+ router,
+ });
+ }
+
fail(message: string): void {
this.onerror?.call(
{} as AbstractWorker,
@@ -271,6 +304,7 @@ describe('worker CacheHost coordinator integration', () => {
const activationGates = new Map<number, Promise<void>>();
const hostInitGates = new Map<number, Promise<void>>();
const enqueueGates = new Map<string, Promise<void>>();
+ let router: CoordinatorRouter;
beforeEach(() => {
localStorage.clear();
@@ -280,7 +314,8 @@ describe('worker CacheHost coordinator integration', () => {
activationGates.clear();
hostInitGates.clear();
enqueueGates.clear();
- const router = new CoordinatorRouter({
+ requestObservers.clear();
+ router = new CoordinatorRouter({
verifyTabLockHeld: async () => true,
watchTabLock: () => () => undefined,
});
@@ -363,6 +398,229 @@ describe('worker CacheHost coordinator integration', () => {
vi.restoreAllMocks();
});
+ it('re-registers after the coordinator restarts on the existing port without replaying old reads', async () => {
+ localStorage.setItem('graphql-cache:scope', 'integration-scope');
+ const onInitializationError = vi.fn();
+ const record = vi.fn();
+ const host = createWorkerCacheHost({
+ scope: 'integration-scope',
+ requestTimeoutMs: 1_000,
+ onInitializationError,
+ telemetry: { record, flush: vi.fn() },
+ });
+ const clientId = host.clientId;
+ await host.readQuery({ opKey: 7, query: 'query Seven { seven }' });
+ const observed = Promise.withResolvers<void>();
+ requestObservers.add((entry) => {
+ if (entry.query === 'query Slow { slow }') observed.resolve();
+ });
+ const pending = host.readQuery({ opKey: 9, query: 'query Slow { slow }' });
+ const rejected = expect(pending).rejects.toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ await observed.promise;
+ const affected = Promise.withResolvers<number[]>();
+ const generations: unknown[] = [];
+ host.onOpsAffected((keys) => affected.resolve(keys));
+ host.onCacheGenerationChanged((change) => generations.push(change));
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => undefined,
+ });
+ sharedWorkers[0]?.restart(router);
+ await rejected;
+ expect(await affected.promise).toEqual([7, 9]);
+ await expect(
+ host.readQuery({ opKey: 7, query: 'query Seven { seven }' })
+ ).resolves.toEqual({ kind: 'miss' });
+ expect(host.clientId).toBe(clientId);
+ expect(generations).toEqual([{ storage: 'reset' }]);
+ expect(record).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: 'graphql_cache.owner',
+ ownerEvent: 'coordinator-restarted',
+ errorCode: 'transport',
+ })
+ );
+ expect(dedicatedWorkers.map((worker) => worker.epoch)).toEqual([1, 1]);
+ expect(dedicatedWorkers[0]?.terminated).toBe(true);
+ expect(logs.filter((entry) => entry.query?.includes('Slow'))).toHaveLength(
+ 1
+ );
+ expect(localStorage.getItem('graphql-cache:scope')).toBe(
+ 'integration-scope'
+ );
+ expect(onInitializationError).not.toHaveBeenCalled();
+ host.dispose();
+ });
+
+ it('retries registration when the coordinator restarts before acknowledging it', async () => {
+ const registering = Promise.withResolvers<void>();
+ const gate = deferred();
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => {
+ registering.resolve();
+ await gate.promise;
+ return true;
+ },
+ watchTabLock: () => () => undefined,
+ });
+ const onInitializationError = vi.fn();
+ const host = createWorkerCacheHost({
+ scope: 'integration-scope',
+ onInitializationError,
+ });
+ const read = host.readQuery({ query: 'query First { first }' });
+ await registering.promise;
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => undefined,
+ });
+ sharedWorkers[0]?.restart(router);
+ await expect(read).resolves.toEqual({ kind: 'miss' });
+ gate.resolve();
+ await host.readQuery({ query: 'query After { after }' });
+ expect(dedicatedWorkers).toHaveLength(1);
+ expect(onInitializationError).not.toHaveBeenCalled();
+ host.dispose();
+ });
+
+ it('fences an interrupted initialization and restores its active reads', async () => {
+ const initializing = Promise.withResolvers<void>();
+ const gate = deferred();
+ hostInitGates.set(1, gate.promise);
+ requestObservers.add((entry) => {
+ if (entry.kind === 'init' && entry.id !== 0) initializing.resolve();
+ });
+ const onInitializationError = vi.fn();
+ const host = createWorkerCacheHost({
+ scope: 'integration-scope',
+ onInitializationError,
+ });
+ const affected = Promise.withResolvers<number[]>();
+ host.onOpsAffected((keys) => affected.resolve(keys));
+ const read = host.readQuery({ opKey: 7, query: 'query First { first }' });
+ const rejected = expect(read).rejects.toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ await initializing.promise;
+ hostInitGates.clear();
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => undefined,
+ });
+ sharedWorkers[0]?.restart(router);
+ await rejected;
+ expect(await affected.promise).toEqual([7]);
+ gate.resolve();
+ await expect(
+ host.readQuery({ query: 'query After { after }' })
+ ).resolves.toEqual({
+ kind: 'miss',
+ });
+ expect(dedicatedWorkers[0]?.terminated).toBe(true);
+ expect(sharedWorkers).toHaveLength(2);
+ expect(onInitializationError).not.toHaveBeenCalled();
+ host.dispose();
+ });
+
+ it('bounds coordinator restarts that prevent initialization without quarantining storage', async () => {
+ const gate = deferred();
+ hostInitGates.set(1, gate.promise);
+ requestObservers.add((entry) => {
+ if (entry.kind !== 'init' || entry.id === 0) return;
+ queueMicrotask(() => {
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => undefined,
+ });
+ sharedWorkers.at(-1)?.restart(router);
+ });
+ });
+ localStorage.setItem('graphql-cache:scope', 'integration-scope');
+ const fallback = Promise.withResolvers<Error>();
+ const host = createWorkerCacheHost({
+ scope: 'integration-scope',
+ onInitializationError: fallback.resolve,
+ });
+ await expect(
+ host.readQuery({ query: 'query First { first }' })
+ ).rejects.toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ expect(await fallback.promise).toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ expect(sharedWorkers).toHaveLength(3);
+ expect(dedicatedWorkers.every((worker) => worker.terminated)).toBe(true);
+ expect(localStorage.getItem('graphql-cache:scope')).toBe(
+ 'integration-scope'
+ );
+ gate.resolve();
+ await expect(host.currentRevision()).rejects.toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ host.dispose();
+ });
+
+ it.each([false, true])(
+ 'never forwards or replays an admitted enqueue across coordinator restart (disposing: %s)',
+ async (disposing) => {
+ const admitted = Promise.withResolvers<void>();
+ const gate = deferred();
+ enqueueGates.set('HoldCoordinatorRestart', gate.promise);
+ requestObservers.add((entry) => {
+ if (entry.kind === 'enqueue-optimistic-mutation') admitted.resolve();
+ });
+ localStorage.setItem('graphql-cache:scope', 'integration-scope');
+ const onInitializationError = vi.fn();
+ const host = createWorkerCacheHost({
+ scope: 'integration-scope',
+ onInitializationError,
+ });
+ const recovered = Promise.withResolvers<void>();
+ host.onCacheGenerationChanged(() => recovered.resolve());
+ const completed = Promise.withResolvers<OperationResult>();
+ const { forwarded } = exchangeHarness(
+ host,
+ optimisticMutation(104, COORDINATOR_RESTART_MUTATION),
+ completed.resolve
+ );
+ await admitted.promise;
+ if (disposing) host.dispose();
+ router = new CoordinatorRouter({
+ verifyTabLockHeld: async () => true,
+ watchTabLock: () => () => undefined,
+ });
+ sharedWorkers[0]?.restart(router);
+ const result = await completed.promise;
+ expect(result.error?.networkError).toMatchObject({
+ errorCode: 'admitted-enqueue-uncertain',
+ });
+ expect(forwarded).toHaveLength(0);
+ expect(dedicatedWorkers[0]?.terminated).toBe(true);
+ gate.resolve();
+ if (disposing) {
+ await expect(host.currentRevision()).rejects.toMatchObject({
+ errorCode: 'owner-epoch-lost',
+ });
+ expect(sharedWorkers).toHaveLength(1);
+ } else {
+ await recovered.promise;
+ await host.currentRevision();
+ expect(sharedWorkers).toHaveLength(2);
+ }
+ expect(
+ logs.filter((entry) => entry.kind === 'enqueue-optimistic-mutation')
+ ).toHaveLength(1);
+ expect(localStorage.getItem('graphql-cache:scope')).toBe(
+ 'integration-scope'
+ );
+ expect(onInitializationError).not.toHaveBeenCalled();
+ host.dispose();
+ }
+ );
+
it('registers, replaces without replay or duplicate reread, and retires gracefully', async () => {
const host = createWorkerCacheHost({
scope: 'integration-scope',
diff --git a/apps/web/src/lib/graphql-cache/host/worker-host.ts b/apps/web/src/lib/graphql-cache/host/worker-host.ts
index c048a0b314..301eb8fc4c 100644
--- a/apps/web/src/lib/graphql-cache/host/worker-host.ts
+++ b/apps/web/src/lib/graphql-cache/host/worker-host.ts
@@ -61,6 +61,7 @@ import {
createCacheCoordinatorPageAdapter,
} from '../worker/coordinator-page-adapter';
import type { EngineOpenOutcome } from '../worker/coordinator-protocol';
+import { WorkerRestartedError } from '../worker/effect-worker-transport';
import { isUnambiguousCacheScope } from '../worker/stale-databases';
import {
CacheBootstrapExhaustedError,
@@ -250,7 +251,9 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
let state: HostState = 'idle';
let initialization: Promise<void> | undefined;
let initializationAttempt = 0;
- let navigationGeneration = 0;
+ let transportGeneration = 0;
+ let transportInterruption: Error | undefined;
+ let coordinatorRestarts = 0;
let suspension: Promise<void> | undefined;
let initializationError: Error | undefined;
let replacementError: CacheResponseError | undefined;
@@ -490,8 +493,9 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
onTerminalError: (error) => {
// start() also rejects; let the bounded registration loop retry before
// reporting a terminal failure or quarantining any cache scope.
- if (adapter === created && !registrationInProgress && !suspension)
- failTransport(error);
+ if (adapter !== created || registrationInProgress || suspension) return;
+ if (error instanceof WorkerRestartedError) reconnectCoordinator(error);
+ else failTransport(error);
},
onCacheUnavailable: (reason) => {
if (adapter === created) retireUnavailable(reason);
@@ -891,6 +895,53 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
await retirement;
}
+ function suspendTransport(error: Error): void {
+ state = 'suspended';
+ transportGeneration += 1;
+ transportInterruption = error;
+ initializationAttempt += 1;
+ beginRecoveryGeneration();
+ // All active operations need fresh dependencies after reconnect, including
+ // reads that never reached the old engine before the connection was lost.
+ for (const key of activeOpKeys) lostRegisteredOpKeys.add(key);
+ replacementReadOpKeys.clear();
+ cancelRegistration?.(error);
+ rejectPending(error, true);
+ if (adapter) adapter.onmessage = null;
+ suspension = finishSuspension(initialization, disposeAdapter(false, true));
+ finishTelemetry();
+ }
+
+ function reconnectCoordinator(cause: WorkerRestartedError): void {
+ if (state === 'failed' || state === 'suspended') return;
+ const error = new CacheResponseError(
+ 'cache coordinator transport restarted',
+ OWNER_EPOCH_LOST_ERROR_CODE,
+ { cause }
+ );
+ telemetry.record({
+ name: 'graphql_cache.owner',
+ operationCategory: 'lifecycle',
+ outcome: 'abrupt',
+ ownerEvent: 'coordinator-restarted',
+ errorCode: 'transport',
+ });
+ if (state === 'disposing' || state === 'disposed') {
+ stopForSession(error, { uncertain: true, preserveDatabase: true });
+ return;
+ }
+ // Bound restarts during startup just like registration retries. A completed
+ // handshake resets this budget; separate later restarts can recover again.
+ if (++coordinatorRestarts >= COORDINATOR_CONNECT_ATTEMPTS) {
+ stopStorageHealthSampling();
+ stopForSession(error, { uncertain: true, preserveDatabase: true });
+ reportFailure(error);
+ return;
+ }
+ suspendTransport(error);
+ fireAndForget(resumeTransport(), 'graphql-cache-host');
+ }
+
function onPagehide(event: PageTransitionEvent): void {
if (
!event.persisted ||
@@ -902,34 +953,22 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
return;
}
if (state === 'suspended') return;
- state = 'suspended';
- navigationGeneration += 1;
- initializationAttempt += 1;
- beginRecoveryGeneration();
- // All active operations need fresh dependencies after reconnect, including
- // reads that never reached the old engine before the page was frozen.
- for (const key of activeOpKeys) lostRegisteredOpKeys.add(key);
- replacementReadOpKeys.clear();
- cancelRegistration?.(new CacheNavigationError());
- rejectPending(new CacheNavigationError(), true);
- if (adapter) adapter.onmessage = null;
- suspension = finishSuspension(initialization, disposeAdapter(false, true));
- finishTelemetry();
+ suspendTransport(new CacheNavigationError());
}
- async function resumeAfterNavigation(): Promise<void> {
+ async function resumeTransport(): Promise<void> {
try {
- // Keep the host and all its subscribers alive; only the page transport is
- // replaced. Initialization waits for the suspended startup to unwind.
+ // Keep the host and subscribers; only the connection and engine epochs
+ // are replaced. Wait for the interrupted startup to unwind first.
await startInitialization();
} catch {
- // Non-navigation failures already invoke the normal product fallback.
+ // Initialization failures already invoke the normal product fallback.
}
}
function onPageshow(event: PageTransitionEvent): void {
if (!event.persisted || state !== 'suspended') return;
- fireAndForget(resumeAfterNavigation(), 'graphql-cache-host');
+ fireAndForget(resumeTransport(), 'graphql-cache-host');
}
function navigationError(): CacheNavigationError | undefined {
@@ -1111,6 +1150,7 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
return;
state = 'ready';
initialization = undefined;
+ coordinatorRestarts = 0;
if (suspended) {
// A surviving coordinator need not send engine-replaced to a late
// joiner. Resets while frozen are unknowable, so conservatively
@@ -1178,10 +1218,11 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
msg: DistributiveOmit<CacheRequest, 'id'>,
opKey?: number
): Promise<unknown> {
- const generation = navigationGeneration;
+ const generation = transportGeneration;
await ensureInitialized();
- // Do not admit an old-page operation to a newly restored transport.
- if (generation !== navigationGeneration) throw new CacheNavigationError();
+ // Never admit an interrupted operation to a different transport generation.
+ if (generation !== transportGeneration)
+ throw transportInterruption ?? new CacheNavigationError();
return await request(msg, opKey);
}
@@ -1204,9 +1245,8 @@ export function createWorkerCacheHost(options: WorkerHostOptions): CacheHost {
},
async currentStorageGeneration(): Promise<string> {
- await ensureInitialized();
return parseStorageGeneration(
- await request({ kind: 'current-storage-generation' })
+ await initializedRequest({ kind: 'current-storage-generation' })
);
},
diff --git a/apps/web/src/lib/graphql-cache/telemetry.ts b/apps/web/src/lib/graphql-cache/telemetry.ts
index 3a42ec369a..77900c0b74 100644
--- a/apps/web/src/lib/graphql-cache/telemetry.ts
+++ b/apps/web/src/lib/graphql-cache/telemetry.ts
@@ -130,6 +130,7 @@ export const CACHE_OWNER_EVENTS = [
'graceful-drain-started',
'graceful-drain-completed',
'navigation-departure',
+ 'coordinator-restarted',
'abrupt-loss',
'replacement',
'multiple-owner-detected',
diff --git a/apps/web/src/lib/graphql-cache/worker/coordinator-page-adapter.ts b/apps/web/src/lib/graphql-cache/worker/coordinator-page-adapter.ts
index 8bb1a9de47..236cf9af64 100644
--- a/apps/web/src/lib/graphql-cache/worker/coordinator-page-adapter.ts
+++ b/apps/web/src/lib/graphql-cache/worker/coordinator-page-adapter.ts
@@ -24,6 +24,7 @@ import {
import {
createEffectWorkerTransport,
type EffectWorkerTransport,
+ WorkerRestartedError,
} from './effect-worker-transport';
import {
listOpfsRootNames,
@@ -471,7 +472,11 @@ export class CacheCoordinatorPageAdapter {
},
onError: (error) => {
this.failTerminal(
- new Error(`coordinator Effect transport failed: ${error.message}`)
+ error instanceof WorkerRestartedError
+ ? error
+ : new Error(
+ `coordinator Effect transport failed: ${error.message}`
+ )
);
},
closeEndpoint: () => this.closePort(worker.port),
diff --git a/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.test.ts b/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.test.ts
index c9a606712f..b3a3cb2596 100644
--- a/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.test.ts
+++ b/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.test.ts
@@ -80,6 +80,42 @@ describe('Effect worker transport', () => {
await Effect.runPromise(transport.close());
});
+ it('reports a restarted runner on an already-ready port', async () => {
+ const endpoint = new FakeMessagePort();
+ const onError = vi.fn();
+ const transport = createEffectWorkerTransport({
+ endpoint: endpoint as unknown as MessagePort,
+ onMessage: vi.fn(),
+ onError,
+ });
+ try {
+ endpoint.ready();
+ await transport.ready;
+ endpoint.ready();
+ expect(onError).toHaveBeenCalledExactlyOnceWith(
+ expect.objectContaining({ name: 'WorkerRestartedError' })
+ );
+ } finally {
+ await Effect.runPromise(transport.close());
+ }
+ });
+
+ it('rejects startup when a second ready frame arrives before readiness settles', async () => {
+ const endpoint = new FakeMessagePort();
+ const transport = createEffectWorkerTransport({
+ endpoint: endpoint as unknown as MessagePort,
+ onMessage: vi.fn(),
+ onError: vi.fn(),
+ });
+ const rejected = expect(transport.ready).rejects.toMatchObject({
+ name: 'WorkerRestartedError',
+ });
+ endpoint.ready();
+ endpoint.ready();
+ await rejected;
+ await Effect.runPromise(transport.close());
+ });
+
it('does not start its protocol fiber when listener setup fails', () => {
const endpoint = new FakeMessagePort();
const addEventListener = endpoint.addEventListener.bind(endpoint);
diff --git a/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.ts b/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.ts
index ad2f424666..b2e5acf34b 100644
--- a/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.ts
+++ b/apps/web/src/lib/graphql-cache/worker/effect-worker-transport.ts
@@ -18,6 +18,14 @@ export const EFFECT_WORKER_RESPONSE_TAG = 1 as const;
/** Effect's parent-to-runner close frame. */
export const EFFECT_WORKER_CLOSE_FRAME = [EFFECT_WORKER_RESPONSE_TAG] as const;
+/** The browser replaced the runner global without replacing the page's port. */
+export class WorkerRestartedError extends Error {
+ constructor() {
+ super('Effect worker transport restarted');
+ this.name = 'WorkerRestartedError';
+ }
+}
+
export interface EffectWorkerTransportOptions<Inbound> {
/** Existing browser endpoint. Its lifetime remains owned by the caller. */
endpoint: BrowserWorkerEndpoint;
@@ -61,6 +69,7 @@ export function createEffectWorkerTransport<Inbound, Outbound>(
);
let readySettled = false;
+ let receivedReady = false;
let closed = false;
let resolveReady!: () => void;
let rejectReady!: (error: Error) => void;
@@ -85,7 +94,14 @@ export function createEffectWorkerTransport<Inbound, Outbound>(
}),
{
onSpawn: Effect.sync(() => {
- if (readySettled) return;
+ if (closed) return;
+ // Safari can reconnect this same port to an empty SharedWorker
+ // global. Its old registrations and engine route no longer exist.
+ if (receivedReady) {
+ reportFailure(new WorkerRestartedError());
+ return;
+ }
+ receivedReady = true;
// Effect invokes `onSpawn` before opening its private ready latch.
// Resolving synchronously here lets awaiters run before buffered sends
// flush (covered by the transport ordering test), so defer one task.
diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.md
index 4b4d5f3954..3d0c394663 100644
--- a/docs/agent-guide/navigation.md
+++ b/docs/agent-guide/navigation.md
@@ -48,6 +48,15 @@ queued mutations should resume promptly, without waiting for the old poll or
local retry timer; durable leases and server-retry deadlines still apply.
Switching tabs or navigating an in-app route is not a back/forward-cache restore.
+Safari can also restart the SharedWorker when its creating tab closes, leaving
+another tab's port alive but its coordinator registrations gone. The surviving
+page must re-register without a reload or cache wipe. Open two tabs, close the
+first, and verify that cached reads and live updates continue in the second.
+Repeat through another handoff and while requests are pending. Interrupted
+optimistic enqueues must not be sent twice. A `graphql_cache.owner` event with
+`ownerEvent: coordinator-restarted` distinguishes this from engine replacement
+or a BFCache restore.
+
## Android system navigation and sharing
In the Android app, Back first hides the keyboard, then dismisses the active
diff --git a/docs/development/infrastructure.md b/docs/development/infrastructure.md
index 0575f88489..02fecb7945 100644
--- a/docs/development/infrastructure.md
+++ b/docs/development/infrastructure.md
@@ -180,8 +180,13 @@ local resources.
- Raw `aws.sqs.Queue` instead of `Queue`; `createImage`; `createServiceRole`
(grants `dynamodb:*`).
- Lambda env vars holding resolved secret values.
-- `web-app` and `website` pin `@pulumi/aws` v6 and are excluded from `tsc`.
+- `web-app` and `website` pin `@pulumi/aws` v6. `bun run check` checks the
+ web-app in its separate TypeScript project, then runs the backend-free
+ web-delivery regressions in separate Bun processes.
+
+For web bundle publication order, asset/error cache policies, and backend-free
+checks, see [web-app delivery](../../infra/stacks/web-app/README.md) and
+[the website CDN](../../infra/stacks/website/README.md#app-cache-policy).
Stale docs to treat with suspicion: `SLACK_IMPORT_ROLLOUT.md` (the worker is on
-and receives `APP_SECRETS_JSON` now), `web-app/README.md` (`yarn`),
-`fusion-auth/README.md`.
+and receives `APP_SECRETS_JSON` now), `fusion-auth/README.md`.
diff --git a/infra/package.json b/infra/package.json
index 41b58b7ba4..811ea5f1ea 100644
--- a/infra/package.json
+++ b/infra/package.json
@@ -9,7 +9,8 @@
"preinstall": "node -e \"if (process.env.npm_execpath && !process.env.npm_execpath.includes('bun')) { console.error('Please use bun as the package manager'); process.exit(1); }\"",
"lint": "biome check .",
"format": "biome check --write .",
- "check": "tsc --noEmit"
+ "check": "tsc --noEmit && tsc --noEmit --skipLibCheck --project stacks/web-app/tsconfig.json && bun run test:web-delivery",
+ "test:web-delivery": "bun test stacks/web-app/publication.test.ts && bun test stacks/web-app/app-route.test.ts && bun test stacks/website/app-cache.test.ts"
},
"devDependencies": {
"@biomejs/biome": "2.4.12",
diff --git a/infra/stacks/web-app/README.md b/infra/stacks/web-app/README.md
index 4cddf6d41c..fbce844aeb 100644
--- a/infra/stacks/web-app/README.md
+++ b/infra/stacks/web-app/README.md
@@ -1,7 +1,70 @@
-# Macro Web App
+# Web app delivery
-This is Pulumi IaC for Macro Web App, deploying to AWS S3 and CloudFront Distribution with Route53 and ACM
+Pulumi project `macro-web-app` publishes the web bundle to S3 and supplies the
+routing Lambda used by the `website-infra` CloudFront distribution. Development
+is served at `https://dev.macro.com/app`; production is `https://macro.com/app`.
+Deployment requires explicit authorization; tests below do not contact AWS.
-## Dev Environment
-1. Run `just build-dev` from `apps/web/`.
-2. Run `$ yarn run deploy:dev` from this directory or `$ yarn workspace @macro-inc/infra-web-app run deploy:dev` from root directory to deploy the build artifact from `apps/web/dist` to https://app-dev.macro.com
+## Publication order
+
+The resource dependency graph, not TypeScript declaration order, enforces:
+
+```text
+immutable assets + native archive
+ ↓
+HTML, manifests, version files, and service-worker retirement script
+ ↓
+routing Lambda with the new HTML
+ ↓
+old WASM pruning → retained-build pruning
+```
+
+`apps/web/scripts/publish-web-assets.sh` owns the two S3 publishing phases:
+
+- `assets`: upload compressed cache WASM at its original key, then static assets
+ with `public, max-age=31536000, immutable`. Copy rather than sync so unchanged
+ objects also receive the correct metadata after earlier deployments that relied
+ on CloudFront headers. Do not delete previous builds during upload.
+- `entrypoints`: publish `*.html`, `*.json`, `*.txt`, and `sw.js` with `no-store`,
+ only after the assets and managed native archive are ready. The stable
+ `app-archive.zip` is managed separately with `no-store`.
+
+The routing Lambda depends on entrypoint publication. Updating it independently
+could expose HTML naming an asset that still returns 403. Every Lambda HTML
+response, including preview failures, uses `no-store`. Pruning waits for the
+Lambda too; a failed publication must leave the previous build reachable.
+
+The existing `sync-assets-command` and `index-html-object-metadata-command`
+resource identities are retained even though publication now copies entrypoint
+bytes with their final headers instead of patching metadata afterward.
+
+## CDN policy
+
+[The website stack](../website/README.md#app-cache-policy) owns browser and edge
+cache policy. Static errors default to `no-store`; only successful objects with
+explicit metadata receive a long lifetime. Prefer deploying this publisher before
+the CDN policy so existing objects already have their metadata. Neither change is
+deployed by running the checks below.
+
+Policy changes cannot evict a failed response already cached in a browser with
+one-year freshness. Such sessions need a new asset URL/build or targeted browser
+revalidation; a CloudFront invalidation alone cannot clear browser caches.
+
+## Checks
+
+From the repository root:
+
+```sh
+\cd apps/web
+bun run test --project scripts scripts/publish-web-assets.test.ts scripts/cache-wasm/upload-brotli-to-s3.test.ts scripts/retain-recent-builds.test.ts
+\cd ../../infra
+bun run check # Type-checks both projects and runs the web-delivery tests.
+```
+
+The publisher tests use a local fake S3 CLI, including failure and unchanged-byte
+cases. The Pulumi mock monitor verifies actual resource dependency edges; source
+order assertions are not sufficient. `publication.test.ts` suppresses local staging
+commands and does not execute cloud commands. `bun run test:web-delivery` runs
+just these infrastructure regressions. It keeps Pulumi mock files in separate
+processes because their runtime configuration is process-global; CI invokes it
+through `bun run check`.
diff --git a/infra/stacks/web-app/app-route.test.ts b/infra/stacks/web-app/app-route.test.ts
new file mode 100644
index 0000000000..ab435c63f5
--- /dev/null
+++ b/infra/stacks/web-app/app-route.test.ts
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import * as fs from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const readFileSync = fs.readFileSync;
+const templatePath = fileURLToPath(
+ new URL('./appRouteLambda/index.html', import.meta.url)
+);
+mock.module('fs', () => ({
+ ...fs,
+ readFileSync: (...args: Parameters<typeof readFileSync>) =>
+ args[0] === templatePath
+ ? '<html><head></head><body>fixture</body></html>'
+ : Reflect.apply(readFileSync, fs, args),
+}));
+const { handler } = await import('./appRouteLambda/index.mjs');
+afterEach(() => mock.restore());
+
+describe('app entry HTML cache headers', () => {
+ test('channel entry HTML cannot be cached as an immutable asset', async () => {
+ const response = await handler({
+ rawPath: '/app/channel/test-channel',
+ requestContext: { http: { path: '/app/channel/test-channel' } },
+ });
+ expect(response).toMatchObject({
+ statusCode: '200',
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ });
+
+ test('file-route errors are non-cacheable', async () => {
+ const response = await handler({ rawPath: '/app/missing.js' });
+ expect(response).toMatchObject({
+ statusCode: '404',
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ });
+
+ test('successful document previews keep HTML non-cacheable', async () => {
+ spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(
+ JSON.stringify({ previews: [{ document_name: 'Document' }] })
+ )
+ );
+ const response = await handler({
+ rawPath: '/app/md/test-document',
+ requestContext: { http: { path: '/app/md/test-document' } },
+ });
+ expect(response).toMatchObject({
+ statusCode: '200',
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ });
+
+ test('fallback HTML remains non-cacheable when the preview service fails', async () => {
+ spyOn(globalThis, 'fetch').mockRejectedValue(
+ new Error('preview unavailable')
+ );
+ spyOn(console, 'error').mockImplementation(() => {});
+ const response = await handler({
+ rawPath: '/app/md/test-document',
+ requestContext: { http: { path: '/app/md/test-document' } },
+ });
+ expect(response).toMatchObject({
+ statusCode: '200',
+ headers: { 'Cache-Control': 'no-store' },
+ });
+ });
+});
diff --git a/infra/stacks/web-app/appRouteLambda/index.mjs b/infra/stacks/web-app/appRouteLambda/index.mjs
index c14cafd840..1b3a68a067 100644
--- a/infra/stacks/web-app/appRouteLambda/index.mjs
+++ b/infra/stacks/web-app/appRouteLambda/index.mjs
@@ -7,6 +7,10 @@ const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const template = readFileSync(join(__dirname, 'index.html'), 'utf-8');
const PREVIEW_URL = process.env.PREVIEW_URL;
+const HTML_HEADERS = {
+ 'Content-Type': 'text/html',
+ 'Cache-Control': 'no-store',
+};
function escapeHtmlText(value) {
return String(value ?? '')
@@ -22,9 +26,7 @@ export const handler = async (event) => {
if ((!rawPath.includes('@') && fileName.includes('.') && fileName !== 'index.html') || !template) {
return {
statusCode: '404',
- headers: {
- 'Content-Type': 'text/html',
- },
+ headers: HTML_HEADERS,
body: 'Not Found',
};
}
@@ -36,9 +38,7 @@ export const handler = async (event) => {
if (blockName === 'chat' || blockName === 'channel') {
return {
statusCode: '200',
- headers: {
- 'Content-Type': 'text/html',
- },
+ headers: HTML_HEADERS,
body: template,
};
}
@@ -64,18 +64,14 @@ export const handler = async (event) => {
// Return the response
return {
statusCode: '200',
- headers: {
- 'Content-Type': 'text/html',
- },
+ headers: HTML_HEADERS,
body,
};
} catch (error) {
console.error('Error building response:', error);
return {
statusCode: '200',
- headers: {
- 'Content-Type': 'text/html',
- },
+ headers: HTML_HEADERS,
body: template,
};
}
diff --git a/infra/stacks/web-app/index.ts b/infra/stacks/web-app/index.ts
index 9607cc3deb..35c701deb3 100644
--- a/infra/stacks/web-app/index.ts
+++ b/infra/stacks/web-app/index.ts
@@ -94,13 +94,14 @@ execSync(
);
const appArchive = new pulumi.asset.FileArchive(appArchiveOutputPath);
-new aws.s3.BucketObjectv2(
+const appArchiveObject = new aws.s3.BucketObjectv2(
'app-archive',
{
bucket: webAppAssets.bucket,
key: 'app/app-archive.zip',
source: appArchive,
acl: 'public-read',
+ cacheControl: 'no-store',
},
{
dependsOn: [ownershipControls, publicAccessBlock],
@@ -115,17 +116,10 @@ execSync(
const syncAssetsCommand = new command.local.Command(
'sync-assets-command',
{
- // Source maps are intentionally public in production; the web client is open source.
- // Cache WASM is over CloudFront's automatic-compression size limit. Keep
- // raw bytes in dist/archive for Tauri and local preview, but exclude both
- // raw and sidecar from generic sync. The targeted uploader stores Brotli
- // bytes at the original .wasm key with application/wasm + Content-Encoding br.
- // No --delete: it removed the previous build's content-hashed files as
- // soon as a new build landed, and a tab still running that build fetches
- // most of itself lazily, so those chunks are asked for long afterwards.
- // `retain-recent-builds.sh` deletes what the last few builds no longer
- // refer to instead, once everything below has published.
- create: pulumi.interpolate`bash ../../../apps/web/scripts/cache-wasm/upload-brotli-to-s3.sh ./output/app s3://${webAppAssets.bucket}/app public-read && aws s3 sync ./output s3://${webAppAssets.bucket} --acl public-read --exclude "app/app-archive.zip" --exclude "app-archive/*" --exclude "*cache_wasm_bg*.wasm" --exclude "*cache_wasm_bg*.wasm.br"`,
+ // Publish assets and their cache metadata before any entrypoint can name
+ // them. Source maps remain public; the publisher keeps the special Brotli
+ // WASM upload and never deletes a still-open build's assets.
+ create: pulumi.interpolate`bash ../../../apps/web/scripts/publish-web-assets.sh assets ./output/app s3://${webAppAssets.bucket}/app`,
triggers: [Date.now()],
},
{
@@ -134,49 +128,16 @@ const syncAssetsCommand = new command.local.Command(
}
);
-// Using the bucket ID we will now update the index.html object metadata to include correct no-store header to disable caching
-// Use randomValue as part of the command so it's considered new on every deployment.
-const updateIndexHtmlObjectMetadataCommand = webAppAssets.id.apply(
- (bucketName) => {
- const object = `s3://${bucketName}/app/index.html`;
- return pulumi.interpolate`aws s3 cp ${object} ${object} --metadata-directive REPLACE --content-type "text/html" --cache-control "no-store" --acl public-read && echo "${Date.now()}"`;
- }
-);
-
-// Run the command to update the index.html object metadata
-const indexHtmlObjectMetadataCommand = new command.local.Command(
+// Keep the existing resource identity, but publish entrypoint bytes with their
+// final headers in one operation instead of publishing then patching metadata.
+const publishEntrypointsCommand = new command.local.Command(
'index-html-object-metadata-command',
{
- create: updateIndexHtmlObjectMetadataCommand,
- },
- { dependsOn: [webAppAssets, syncAssetsCommand], replaceOnChanges: ['*'] }
-);
-
-// Prune only after the current WASM, generic assets, index content, and index
-// metadata have all published. Any earlier failure preserves all prior keys.
-const pruneOldCacheWasmCommand = new command.local.Command(
- 'prune-old-cache-wasm-command',
- {
- create: pulumi.interpolate`bash ../../../apps/web/scripts/cache-wasm/prune-old-brotli-from-s3.sh ./output/app s3://${webAppAssets.bucket}/app ${cacheWasmRetentionDays}`,
+ create: pulumi.interpolate`bash ../../../apps/web/scripts/publish-web-assets.sh entrypoints ./output/app s3://${webAppAssets.bucket}/app`,
triggers: [Date.now()],
},
{
- dependsOn: [indexHtmlObjectMetadataCommand],
- replaceOnChanges: ['*'],
- }
-);
-
-// What the generic sync's --delete used to do, delayed by a few builds. Runs
-// last, and after the cache WASM prune, so a failure anywhere above leaves
-// every prior key in place rather than half-retiring a build.
-new command.local.Command(
- 'retain-recent-builds-command',
- {
- create: pulumi.interpolate`bash ../../../apps/web/scripts/retain-recent-builds.sh ./output/app s3://${webAppAssets.bucket}/app ${assetBuildRetention}`,
- triggers: [Date.now()],
- },
- {
- dependsOn: [pruneOldCacheWasmCommand],
+ dependsOn: [webAppAssets, syncAssetsCommand, appArchiveObject],
replaceOnChanges: ['*'],
}
);
@@ -210,21 +171,51 @@ const encodingLambdaEdgeFunction = new aws.lambda.Function(
const encodingLambdaVersion: pulumi.Output<String> =
encodingLambdaEdgeFunction.version.apply((v: string) => v);
-const appRouteLambda = new aws.lambda.Function('app-route-lambda', {
- code: new pulumi.asset.FileArchive('./appRouteLambda'),
- role: lambdaRole.arn,
- handler: 'index.handler',
- runtime: Runtime.NodeJS22dX,
- name: `app-route-lambda-${stack}`,
- // do not throttle prod
- reservedConcurrentExecutions: stack === 'prod' ? undefined : 100,
- publish: true,
- environment: {
- variables: {
- PREVIEW_URL: `https://${stack === 'dev' ? 'dev-' : ''}gateway.macro.com/dss/documents/preview`,
+const appRouteLambda = new aws.lambda.Function(
+ 'app-route-lambda',
+ {
+ code: new pulumi.asset.FileArchive('./appRouteLambda'),
+ role: lambdaRole.arn,
+ handler: 'index.handler',
+ runtime: Runtime.NodeJS22dX,
+ name: `app-route-lambda-${stack}`,
+ // do not throttle prod
+ reservedConcurrentExecutions: stack === 'prod' ? undefined : 100,
+ publish: true,
+ environment: {
+ variables: {
+ PREVIEW_URL: `https://${stack === 'dev' ? 'dev-' : ''}gateway.macro.com/dss/documents/preview`,
+ },
},
},
-});
+ { dependsOn: [publishEntrypointsCommand] }
+);
+
+// Prune only after every entrypoint, including Lambda-rendered HTML, has
+// published successfully. Failure must leave the preceding build reachable.
+const pruneOldCacheWasmCommand = new command.local.Command(
+ 'prune-old-cache-wasm-command',
+ {
+ create: pulumi.interpolate`bash ../../../apps/web/scripts/cache-wasm/prune-old-brotli-from-s3.sh ./output/app s3://${webAppAssets.bucket}/app ${cacheWasmRetentionDays}`,
+ triggers: [Date.now()],
+ },
+ {
+ dependsOn: [publishEntrypointsCommand, appRouteLambda],
+ replaceOnChanges: ['*'],
+ }
+);
+
+new command.local.Command(
+ 'retain-recent-builds-command',
+ {
+ create: pulumi.interpolate`bash ../../../apps/web/scripts/retain-recent-builds.sh ./output/app s3://${webAppAssets.bucket}/app ${assetBuildRetention}`,
+ triggers: [Date.now()],
+ },
+ {
+ dependsOn: [pruneOldCacheWasmCommand],
+ replaceOnChanges: ['*'],
+ }
+);
const appRouteFunctionUrl = new aws.lambda.FunctionUrl('app-route-lambda-url', {
functionName: appRouteLambda.name,
diff --git a/infra/stacks/web-app/publication.test.ts b/infra/stacks/web-app/publication.test.ts
new file mode 100644
index 0000000000..9c41cbe5d6
--- /dev/null
+++ b/infra/stacks/web-app/publication.test.ts
@@ -0,0 +1,123 @@
+import {
+ afterAll,
+ beforeAll,
+ describe,
+ expect,
+ mock,
+ spyOn,
+ test,
+} from 'bun:test';
+import * as childProcess from 'node:child_process';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import * as pulumi from '@pulumi/pulumi';
+import type { RegisterResourceRequest } from '@pulumi/pulumi/proto/resource_pb';
+import { MockMonitor } from '@pulumi/pulumi/runtime/mocks';
+
+const resources: pulumi.runtime.MockResourceArgs[] = [];
+const dependencies = new Map<string, string[]>();
+const dist = mkdtempSync(join(tmpdir(), 'web-publication-'));
+writeFileSync(join(dist, 'index.html'), '<html>fixture</html>');
+
+beforeAll(async () => {
+ // Staging commands must not run in a resource-graph test. The command
+ // resources themselves use Pulumi's real constructors and mock monitor.
+ mock.module('node:child_process', () => ({
+ ...childProcess,
+ execSync: mock(() => Buffer.from('')),
+ }));
+ const register = MockMonitor.prototype.registerResource;
+ spyOn(MockMonitor.prototype, 'registerResource').mockImplementation(function (
+ this: MockMonitor,
+ request: RegisterResourceRequest,
+ callback
+ ) {
+ dependencies.set(
+ request.getName(),
+ request.getDependenciesList().map((urn) => urn.split('::').at(-1) ?? urn)
+ );
+ return register.call(this, request, callback);
+ });
+ await pulumi.runtime.setMocks(
+ {
+ newResource(args) {
+ resources.push(args);
+ return {
+ id: args.name,
+ state: {
+ ...args.inputs,
+ arn: `arn:aws:test:us-east-1:123456789012:${args.name}`,
+ bucket: args.inputs.bucket ?? args.name,
+ websiteEndpoint: 'assets.example.test',
+ version: '1',
+ functionUrl: 'https://route.example.test/',
+ },
+ };
+ },
+ call(args) {
+ return { ...args.inputs, partition: 'aws', dnsSuffix: 'amazonaws.com' };
+ },
+ },
+ 'macro-web-app',
+ 'dev',
+ false
+ );
+ pulumi.runtime.setAllConfig({
+ 'macro-web-app:path': dist,
+ 'aws:region': 'us-east-1',
+ });
+ await import('./index');
+ await pulumi.runtime.waitForRPCs();
+});
+
+afterAll(() => {
+ mock.restore();
+ rmSync(dist, { recursive: true, force: true });
+});
+
+function dependsOn(resource: string, predecessor: string): boolean {
+ return (dependencies.get(resource) ?? []).some(
+ (dependency) =>
+ dependency === predecessor || dependsOn(dependency, predecessor)
+ );
+}
+
+describe('web publication resource ordering', () => {
+ test('the routing Lambda cannot publish HTML before the new assets', () => {
+ expect(dependsOn('app-route-lambda', 'sync-assets-command')).toBe(true);
+ });
+
+ test('mutable entrypoints wait for both assets and the native archive', () => {
+ expect(
+ dependsOn('index-html-object-metadata-command', 'sync-assets-command')
+ ).toBe(true);
+ expect(dependsOn('index-html-object-metadata-command', 'app-archive')).toBe(
+ true
+ );
+ expect(
+ resources.find(
+ (resource) => resource.name === 'index-html-object-metadata-command'
+ )?.inputs.create
+ ).toContain('publish-web-assets.sh entrypoints');
+ });
+
+ test('a failed HTML publication prevents pruning any retained build', () => {
+ expect(dependsOn('retain-recent-builds-command', 'app-route-lambda')).toBe(
+ true
+ );
+ expect(
+ dependsOn(
+ 'retain-recent-builds-command',
+ 'index-html-object-metadata-command'
+ )
+ ).toBe(true);
+ });
+
+ test('the stable archive URL is not cached as an immutable asset', () => {
+ expect(
+ resources.find((resource) => resource.name === 'app-archive')?.inputs
+ .cacheControl
+ ).toBe('no-store');
+ });
+});
diff --git a/infra/stacks/website/README.md b/infra/stacks/website/README.md
index 8ec35d4adb..ff221d56cc 100644
--- a/infra/stacks/website/README.md
+++ b/infra/stacks/website/README.md
@@ -16,6 +16,37 @@ uncovered chat hostname would block unrelated website deploys.
Moved from `macro-inc/solid-site/infra`; project and stack names are unchanged,
so this program manages the existing resources.
+## App cache policy
+
+`/app/*.*` respects the web-app objects' S3 cache metadata. Its response-header
+policy supplies `Cache-Control: no-store` only when the origin did not supply a
+cache policy, so missing assets cannot acquire an immutable success lifetime.
+The existing `Cross-Origin-Opener-Policy: same-origin-allow-popups` is preserved.
+The app's edge policy has zero default/minimum TTL and a one-year maximum; common
+403/404/5xx responses also have zero error-cache TTL. The marketing site's success
+cache policy is unchanged.
+
+The [web-app publisher](../web-app/README.md) sets long-lived metadata on static
+assets and `no-store` on mutable HTML, manifests, version files, and the archive.
+It publishes assets before entrypoints. Updating CloudFront alone does not repair
+already-cached browser errors; affected clients need a new asset URL or browser
+revalidation.
+
+Verify after an authorized deployment: entry HTML (including `/app/index.html`)
+and missing-asset responses must not receive a one-year lifetime, while a hashed
+JavaScript response retains its explicit immutable lifetime. A later published
+asset must be reachable without clearing the browser's entire cache.
+
+Backend-free checks, from `infra/`:
+
+```sh
+bun test stacks/website/app-cache.test.ts # Focused CDN policy check.
+bun run check # Includes every web-delivery regression.
+```
+
+The mock test constructs the real stack resources without uploading assets or
+contacting AWS and checks the policies attached to the app's actual behavior.
+
## Deploy
`.github/workflows/deploy_website.yml` deploys dev on pushes to `main` that touch
diff --git a/infra/stacks/website/app-cache.test.ts b/infra/stacks/website/app-cache.test.ts
new file mode 100644
index 0000000000..01e8b2896a
--- /dev/null
+++ b/infra/stacks/website/app-cache.test.ts
@@ -0,0 +1,117 @@
+import { afterAll, beforeAll, describe, expect, mock, test } from 'bun:test';
+import * as childProcess from 'node:child_process';
+import * as fs from 'node:fs';
+import * as pulumi from '@pulumi/pulumi';
+
+const resources: pulumi.runtime.MockResourceArgs[] = [];
+
+beforeAll(async () => {
+ mock.module('node:child_process', () => ({
+ ...childProcess,
+ execSync: mock(() => Buffer.from('')),
+ }));
+ const readFileSync = fs.readFileSync;
+ mock.module('fs', () => ({
+ ...fs,
+ readFileSync: (...args: Parameters<typeof readFileSync>) =>
+ args[0] === './wwwRedirect/handler.js'
+ ? 'function handler(event) { return event.request; }'
+ : Reflect.apply(readFileSync, fs, args),
+ }));
+ mock.module('../../packages/utils', () => ({ hasItems: () => true }));
+ await pulumi.runtime.setMocks(
+ {
+ newResource(args) {
+ resources.push(args);
+ return {
+ id: args.name,
+ state: {
+ ...args.inputs,
+ arn: `arn:aws:test:us-east-1:123456789012:${args.name}`,
+ bucket: args.name,
+ websiteEndpoint: 'site.example.test',
+ domainName: 'cdn.example.test',
+ hostedZoneId: 'zone-id',
+ outputs: {
+ macroWebAppBucketArn: 'arn:aws:s3:::web-app-test',
+ macroWebAppBucketWebsiteEndpoint: 'assets.example.test',
+ appRouteLambdaId: 'route-lambda',
+ appRouteUrl: 'https://route.example.test/',
+ },
+ },
+ };
+ },
+ call(args) {
+ return {
+ ...args.inputs,
+ id: 'test-id',
+ arn: 'arn:aws:test',
+ zoneId: 'test-zone',
+ };
+ },
+ },
+ 'website-infra',
+ 'dev',
+ false
+ );
+ pulumi.runtime.setAllConfig({
+ 'aws:region': 'us-east-1',
+ 'website-infra:certArn':
+ 'arn:aws:acm:us-east-1:123456789012:certificate/test',
+ 'website-infra:domain': 'example.test',
+ 'website-infra:subdomain': 'dev',
+ 'website-infra:oidcBucketArn': 'arn:aws:s3:::oidc-test',
+ 'website-infra:oidcBucketWebsiteEndpoint': 'oidc.example.test',
+ });
+ await import('./index');
+ await pulumi.runtime.waitForRPCs();
+});
+
+afterAll(() => mock.restore());
+
+function resource(resourceName: string): pulumi.runtime.MockResourceArgs {
+ const result = resources.find((entry) => entry.name === resourceName);
+ if (!result) throw new Error(`Missing resource ${resourceName}`);
+ return result;
+}
+
+describe('app asset caching', () => {
+ test('missing asset responses default to no-store without overriding successful object metadata', () => {
+ const policy = resource('website-infra-app-asset-headers-dev').inputs;
+ expect(policy.customHeadersConfig.items).toContainEqual({
+ header: 'Cache-Control',
+ value: 'no-store',
+ override: false,
+ });
+ expect(policy.customHeadersConfig.items).toContainEqual({
+ header: 'Cross-Origin-Opener-Policy',
+ value: 'same-origin-allow-popups',
+ override: true,
+ });
+ });
+
+ test('the static app behavior actually uses safe viewer and edge policies', () => {
+ const distribution = resource('cdn-dev').inputs;
+ const assets = distribution.orderedCacheBehaviors.find(
+ (behavior: { pathPattern: string }) => behavior.pathPattern === '/app/*.*'
+ );
+ expect(assets.responseHeadersPolicyId).toBe(
+ 'website-infra-app-asset-headers-dev'
+ );
+ expect(assets.cachePolicyId).toBe('website-infra-app-asset-cache-dev');
+ expect(resource('website-infra-app-asset-cache-dev').inputs).toMatchObject({
+ minTtl: 0,
+ defaultTtl: 0,
+ maxTtl: 31536000,
+ });
+ });
+
+ test('transient asset failures are not retained as edge errors after publication', () => {
+ expect(resource('cdn-dev').inputs.customErrorResponses).toEqual(
+ [403, 404, 500, 502, 503, 504].map((errorCode) => ({
+ errorCode,
+ errorCachingMinTtl: 0,
+ }))
+ );
+ });
+});
diff --git a/infra/stacks/website/index.ts b/infra/stacks/website/index.ts
index 94a3a0cd65..c2466ba3f5 100644
--- a/infra/stacks/website/index.ts
+++ b/infra/stacks/website/index.ts
@@ -5,6 +5,7 @@ import * as pulumi from '@pulumi/pulumi';
import { hasItems } from '../../packages/utils';
const config = new pulumi.Config();
+const BASE_NAME = pulumi.getProject();
const certArn = config.require('certArn');
const domain = config.require('domain');
@@ -148,8 +149,6 @@ const wwwRedirectFn = new aws.cloudfront.Function(
}
);
-const SHARED_ARRAY_RESPONSE_HEADERS_MAX_AGE_CACHE_CONTROL =
- '78ba335f-4e54-45a3-85d5-1d9933b1363d';
const SHARED_ARRAY_RESPONSE_HEADERS_NO_CACHE_CONTROL =
'c9d6f215-ca3d-4c29-8eb4-41ee30fb2129';
const CACHING_DISABLED = '4135ea2d-6df8-44a3-9df3-4b5a84be39ad';
@@ -207,24 +206,46 @@ const bookingPageHeadersPolicy = new aws.cloudfront.ResponseHeadersPolicy(
}
);
+const compressedCacheKey = {
+ enableAcceptEncodingGzip: true,
+ enableAcceptEncodingBrotli: true,
+ cookiesConfig: { cookieBehavior: 'none' },
+ headersConfig: { headerBehavior: 'none' },
+ queryStringsConfig: { queryStringBehavior: 'none' },
+};
+
const compressibleCachePolicy = new aws.cloudfront.CachePolicy(
`cache-policy-${stack}`,
+ { parametersInCacheKeyAndForwardedToOrigin: compressedCacheKey }
+);
+
+// Immutable objects carry their lifetime in S3 metadata. Missing objects and
+// mutable entrypoints must never inherit a one-year browser or edge lifetime.
+const appAssetHeadersPolicy = new aws.cloudfront.ResponseHeadersPolicy(
+ `${BASE_NAME}-app-asset-headers-${stack}`,
{
- parametersInCacheKeyAndForwardedToOrigin: {
- enableAcceptEncodingGzip: true,
- enableAcceptEncodingBrotli: true,
- cookiesConfig: {
- cookieBehavior: 'none',
- },
- headersConfig: {
- headerBehavior: 'none',
- },
- queryStringsConfig: {
- queryStringBehavior: 'none',
- },
+ name: `${BASE_NAME}-app-asset-headers-${stack}`,
+ customHeadersConfig: {
+ items: [
+ {
+ header: 'Cross-Origin-Opener-Policy',
+ value: 'same-origin-allow-popups',
+ override: true,
+ },
+ { header: 'Cache-Control', value: 'no-store', override: false },
+ ],
},
}
);
+const appAssetCachePolicy = new aws.cloudfront.CachePolicy(
+ `${BASE_NAME}-app-asset-cache-${stack}`,
+ {
+ minTtl: 0,
+ defaultTtl: 0,
+ maxTtl: 31536000,
+ parametersInCacheKeyAndForwardedToOrigin: compressedCacheKey,
+ }
+);
const ghostOriginId = `macro.ghost.io-${stack}`;
@@ -334,13 +355,12 @@ const cdn = new aws.cloudfront.Distribution(`cdn-${stack}`, {
},
{
pathPattern: '/app/*.*',
- responseHeadersPolicyId:
- SHARED_ARRAY_RESPONSE_HEADERS_MAX_AGE_CACHE_CONTROL,
+ responseHeadersPolicyId: appAssetHeadersPolicy.id,
targetOriginId: macroWebAppBucketArn,
viewerProtocolPolicy: 'redirect-to-https',
allowedMethods: ['GET', 'HEAD', 'OPTIONS'],
cachedMethods: ['GET', 'HEAD', 'OPTIONS'],
- cachePolicyId: compressibleCachePolicy.id,
+ cachePolicyId: appAssetCachePolicy.id,
compress: true,
},
...['/app/book/*', '/app/booking/*'].map((pathPattern) => ({
@@ -393,6 +413,11 @@ const cdn = new aws.cloudfront.Distribution(`cdn-${stack}`, {
},
},
],
+ // A transient missing upload must not remain an edge error after publication.
+ customErrorResponses: [403, 404, 500, 502, 503, 504].map((errorCode) => ({
+ errorCode,
+ errorCachingMinTtl: 0,
+ })),
restrictions: {
geoRestriction: {
restrictionType: 'none',