Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/deploy/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ The game is served at https://opencoaster.noriagentic.com/ over HTTPS. `public/C
- Production builds use a relative Vite base (`./`) by default, so `dist/` works at the domain root and under a subpath such as `/opencoaster/`. Set `OC_BASE` (e.g. `OC_BASE=/opencoaster/ pnpm build`) to pin an absolute base instead.
- `pnpm smoke:subpath` builds `dist/`, serves it under `/opencoaster/` with no cross-origin isolation headers (`tools/serve-subpath.mjs`), and runs the smoke suite against it. GitHub Pages sends no COOP/COEP headers, so this matches production.

## Service worker precache

The production service worker precaches only what the game requests at runtime, a few files at a time, and resumes a failed install instead of restarting it ([src/pwa](../../src/pwa/docs.md)). `dist/` still contains the per-sprite atlas inputs copied from `public/sprites/`; precaching them all once caused GitHub Pages to answer with 503s and every reload to re-flood the site, so keep the precache list small.

Dev and preview builds keep the root base and the COOP/COEP headers the Vite dev server sends.
1 change: 1 addition & 0 deletions smoke/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Path: @/smoke
- The visual check captures the starter park before and after enabling gridlines.
- [mobile-fps.spec.ts](mobile-fps.spec.ts) emulates a Pixel 8 (4Γ— CPU throttle, device scale factor 2.6) with 2,000 and 5,000 guests and prints median FPS, p95 frame time and render scale. Budgets (55 and 30 FPS median) are soft: a miss adds a `soft-budget-miss` annotation and a warning, not a failure, because SwiftShader timing varies by host.
- [no-4xx.spec.ts](no-4xx.spec.ts) loads the game, opens every toolbar window and fails on any 4xx network response; under `pnpm smoke:subpath` it runs against the production build served at `/opencoaster/`.
- [returning-visitor.spec.ts](returning-visitor.spec.ts) runs only under `pnpm smoke:subpath`. It seeds an earlier build's worker cache, an IndexedDB save, and settings, then checks the production worker installs without downloading the whole of `public/`, reloads stay controlled and fetch nothing but the navigation, the old cache is removed, and the save still appears under Load game ([src/pwa](../src/pwa/docs.md)).
- Playwright screenshots are stored in `.local/playwright-results/` (dev) and `.local/playwright-results-subpath/` (subpath).
- Specs navigate with `page.goto('./')` so the same spec runs at the origin root and under the subpath.

Expand Down
112 changes: 112 additions & 0 deletions smoke/returning-visitor.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { expect, test } from '@playwright/test';

const SAVE = { id: 'returning-park', name: 'Returning park', bytes: [7, 1, 2, 3] };

// The production worker installs once, then repeat visits load from it. The dev server's worker
// only precaches the shell, so this runs against the production build (pnpm smoke:subpath).
test('a returning visitor reloads from the installed worker and keeps their saved parks', async ({
page,
context,
baseURL,
}) => {
test.skip(new URL(baseURL ?? '/').pathname === '/', 'production build only');
test.setTimeout(90_000);
const base = new URL(baseURL ?? '/');

// A visitor from an earlier build: a saved park, settings and that build's worker cache.
await page.goto(base.origin);
await page.evaluate(
async ({ save, scope }) => {
localStorage.setItem('opencoaster.settings.v1', '{"returning":true}');
const old = await caches.open('opencoaster-static-old');
await old.put(new URL(scope, location.href).href, new Response('old shell'));
await new Promise<void>((resolve, reject) => {
const open = indexedDB.open('opencoaster-saves', 1);
open.onupgradeneeded = () => open.result.createObjectStore('slots', { keyPath: 'id' });
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const tx = open.result.transaction('slots', 'readwrite');
tx.objectStore('slots').put({
id: save.id,
name: save.name,
savedAt: Date.now(),
scenarioId: 'sandbox',
tick: 0,
cash: 0,
loan: 0,
bytes: new Uint8Array(save.bytes),
});
tx.oncomplete = () => resolve();
tx.onerror = () => reject(tx.error);
};
});
},
{ save: SAVE, scope: base.pathname },
);

const workerDownloads: string[] = [];
const pageNetworkLoads: string[] = [];
const failures: string[] = [];
context.on('request', (request) => {
if (request.serviceWorker()) workerDownloads.push(request.url());
});
context.on('response', (response) => {
if (response.status() >= 400) failures.push(`${response.status()} ${response.url()}`);
const request = response.request();
if (
!request.serviceWorker() &&
request.resourceType() !== 'document' &&
!response.fromServiceWorker()
)
pageNetworkLoads.push(response.url());
});

await page.goto(base.href);
await expect
.poll(() => page.evaluate(() => Boolean(navigator.serviceWorker.controller)), {
timeout: 60_000,
})
.toBe(true);
// The precache holds the bundle, shell, atlas and icons, not the per-sprite packer inputs.
expect(workerDownloads).toContain(`${base.href}sprites/manifest.json`);
expect(workerDownloads.length).toBeLessThan(1000);

await page.waitForLoadState('networkidle');
for (let reload = 0; reload < 3; reload++) {
workerDownloads.length = 0;
pageNetworkLoads.length = 0;
await page.reload();
await expect(page.getByRole('button', { name: 'Load game' })).toBeVisible();
await page.waitForLoadState('networkidle');
expect(await page.evaluate(() => Boolean(navigator.serviceWorker.controller))).toBe(true);
expect(workerDownloads.filter((url) => url !== base.href)).toEqual([]);
expect(pageNetworkLoads.filter((url) => !url.endsWith('/service-worker.js'))).toEqual([]);
}

const storage = await page.evaluate(async (id) => {
const save = await new Promise<{ name: string; bytes: Uint8Array } | undefined>(
(resolve, reject) => {
const open = indexedDB.open('opencoaster-saves');
open.onerror = () => reject(open.error);
open.onsuccess = () => {
const get = open.result.transaction('slots').objectStore('slots').get(id);
get.onerror = () => reject(get.error);
get.onsuccess = () => resolve(get.result as { name: string; bytes: Uint8Array });
};
},
);
return {
save: save && { name: save.name, bytes: [...save.bytes] },
settings: localStorage.getItem('opencoaster.settings.v1'),
caches: (await caches.keys()).filter((key) => key.startsWith('opencoaster-static-')).length,
};
}, SAVE.id);
expect(storage).toEqual({
save: { name: SAVE.name, bytes: SAVE.bytes },
settings: '{"returning":true}',
caches: 1,
});
await page.getByRole('button', { name: 'Load game' }).click();
await expect(page.getByText(SAVE.name)).toBeVisible();
expect(failures.filter((failure) => !failure.endsWith(`${base.origin}/`))).toEqual([]);
});
18 changes: 11 additions & 7 deletions src/pwa/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,33 @@ Path: @/src/pwa
### Overview

- Registers the browser service worker that supplies the offline app shell.
- The worker precaches the app shell and built assets, then caches same-origin GET responses as they are used.
- In production the worker precaches the built bundle, the page shell, and the public files the game requests at runtime, then caches other same-origin GET responses as they are used.
- PWA metadata and icons live in the public web root and are linked from [index.html](../../index.html).
- Every URL is relative to the deploy base, so the app works at the origin root (dev) and under a subpath such as GitHub Pages' `/opencoaster/`.

### How it fits into the larger codebase

- [src/main.ts](../main.ts) registers the worker during app startup; browser support or registration failure does not prevent the game from starting.
- [vite.config.ts](../../vite.config.ts) serves a development worker and emits a production worker. Production builds default to a relative base (`./`, overridable with `OC_BASE`), and the worker's precache list is relative to the worker script, so the worker's scope is the deploy base.
- [register.ts](register.ts) and the sprite fetches in [webgl2-renderer.ts](../render/webgl2-renderer.ts) prefix `import.meta.env.BASE_URL`; the deploy workflow is described in [docs/deploy](../../docs/deploy/README.md).
- [src/app/bootstrap/index.ts](../app/bootstrap/index.ts) calls `registerPwa` during app startup; browser support or registration failure does not prevent the game from starting.
- [vite.config.ts](../../vite.config.ts) serves a development worker (precaching only `/`) and emits a production worker. Production builds default to a relative base (`./`, overridable with `OC_BASE`), and the worker's precache list is relative to the worker script, so the worker's scope is the deploy base.
- The production precache list comes from [tools/pwa/precache-urls.ts](../../tools/pwa/precache-urls.ts): bundle files, `index.html`, `./`, and the files under `public/`, except `CNAME` and any `sprites/` file other than the sprite manifest, atlas pages, and UI icons. The rest of `public/sprites/` is per-sprite packer input from [tools/art](../../tools/art/README.md) that the game never requests.
- [register.ts](register.ts), the atlas loader in [sprite-pages.ts](../render/sprite-pages.ts), and the UI icon URLs in [icons.ts](../ui/icons.ts) prefix `import.meta.env.BASE_URL`; the deploy workflow is described in [docs/deploy](../../docs/deploy/README.md).
- The worker caches JavaScript modules, worker chunks, and other same-origin requests used by the client. This allows the simulation worker to start when the app is reopened offline after its assets have been cached.
- The web app remains responsible for simulation state and save persistence; service-worker caches hold application resources rather than park saves.
- The web app remains responsible for simulation state and save persistence; the worker never touches IndexedDB or `localStorage`, so park saves and settings survive worker updates.

### Core Implementation

- [register.ts](register.ts) calls `navigator.serviceWorker.register` when the API exists and reports registration errors through the browser console.
- [service-worker.js](service-worker.js) installs a cache named for the build (`opencoaster-static-<build stamp>`, filled in by [vite.config.ts](../../vite.config.ts)) from the build-generated URL list, removes older OpenCoaster static caches on activation, and claims controlled clients.
- Page navigations go to the network first (`cache: 'no-cache'`, so the browser HTTP cache cannot supply an old shell naming old assets) and update the cache; offline they fall back to the cached page or the shell at the worker's scope. Every other same-origin GET is served from the cache first, otherwise fetched and stored. Install precaches with `cache: 'reload'` for the same reason.
- [service-worker.js](service-worker.js) installs into a cache named for the build (`opencoaster-static-<build stamp>`, filled in by [vite.config.ts](../../vite.config.ts)), removes older OpenCoaster static caches on activation, and claims controlled clients.
- Install downloads the precache list with a small fixed number of downloads in flight, storing each response with `cache.put`. URLs already present in this build's cache are skipped, so an install retried after a failure only downloads what is missing. The first failed or non-OK download empties the queue so no new downloads start, and install rejects once in-flight downloads settle; the worker activates only once the whole list is cached.
- Page navigations go to the network first (`cache: 'no-cache'`, so the browser HTTP cache cannot supply an old shell naming old assets) and update the cache; offline they fall back to the cached page or the shell at the worker's scope. Every other same-origin GET is served from the cache first, otherwise fetched and stored. Install downloads use `cache: 'reload'` for the same reason.
- [manifest.webmanifest](../../public/manifest.webmanifest) describes standalone launch, orientation, theme colors, and scalable/raster app icons.

### Things to Know

- Offline startup requires one successful online load so the worker can install and cache the shell and requested assets.
- The precache list must stay small. Precaching all of `public/` (tens of thousands of per-sprite packer files) in one atomic `cache.addAll` made GitHub Pages answer with 503s; one failed response discarded the whole install, so the page was never controlled and every reload restarted the full download, re-flooding the origin. The filtered list, bounded concurrency, stop-on-first-failure, and resumable install exist to prevent that loop. A new runtime-requested file outside the allowed `sprites/` paths must be added to [precache-urls.ts](../../tools/pwa/precache-urls.ts), or it is only cached on first use.
- Each build has its own cache, and activation removes the caches of earlier builds. A page that is already open keeps running the build it loaded until it is reloaded; the next navigation gets the new build. A browser still running the previous cache-first worker serves its old shell once more before the new worker takes over.
- [returning-visitor.spec.ts](../../smoke/returning-visitor.spec.ts) covers install and repeat visits against the production build (`pnpm smoke:subpath` only): an earlier build's cache is removed, reloads stay controlled, and seeded saves and settings remain intact.
- The PWA layer does not cache or migrate game saves; save slots remain in the save subsystem's IndexedDB or its in-memory fallback.

Created and maintained by Nori.
40 changes: 32 additions & 8 deletions src/pwa/service-worker.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,39 @@
const CACHE_NAME = 'opencoaster-static-' + self.__CACHE_VERSION__;
const PRECACHE_URLS = self.__PRECACHE_URLS__;
const PRECACHE_CONCURRENCY = 6;

/**
* Downloads the precache list a few files at a time into this build's cache, skipping files a
* failed earlier attempt already stored, so a retried install fetches only what is missing.
* The first failed download stops the queue, so a throttled server is not sent the rest.
*/
async function precache() {
const cache = await caches.open(CACHE_NAME);
const pending = [];
for (const url of PRECACHE_URLS) {
const request = new Request(url, { cache: 'reload' });
if (!(await cache.match(request))) pending.push(request);
}
const store = async (request) => {
const response = await fetch(request);
if (!response.ok) throw new Error(`Precache of ${request.url} failed: ${response.status}`);
await cache.put(request, response);
};
const download = async () => {
for (let request = pending.shift(); request; request = pending.shift()) {
await store(request).catch((error) => {
pending.length = 0;
throw error;
});
}
};
const results = await Promise.allSettled(Array.from({ length: PRECACHE_CONCURRENCY }, download));
const failure = results.find((result) => result.status === 'rejected');
if (failure) throw failure.reason;
}

self.addEventListener('install', (event) => {
event.waitUntil(
caches
.open(CACHE_NAME)
.then((cache) =>
cache.addAll(PRECACHE_URLS.map((url) => new Request(url, { cache: 'reload' }))),
)
.then(() => self.skipWaiting()),
);
event.waitUntil(precache().then(() => self.skipWaiting()));
});

self.addEventListener('activate', (event) => {
Expand Down
Loading
Loading