feat(offline): background-preload dictionaries for offline readiness
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 10s
CI / integration (pull_request) Successful in 15s
CI / ui (pull_request) Successful in 1m10s
CI / conformance (pull_request) Successful in 10s
CI / gate (pull_request) Successful in 0s
CI / deploy (pull_request) Successful in 1m41s

An installed PWA (standalone web + confirmed email) warms the dictionaries
for the player's enabled variants while online — on lobby entry and on a
variant-preference change — using the per-variant version the profile now
advertises, so a later switch to offline mode already has the data.

- dict/preload.ts: pure preloadDicts (retry + linear backoff, honours the
  session dictionary miss-breaker); node-tested.
- dict/preloadrun.ts: lazy browser orchestration (real getDawg), imported
  dynamically so the loader and move generator stay out of the main bundle.
- offline.svelte.ts: kickDictPreload, gated by the pure, tested
  offlinePreloadEligible, plus the reactive first-lobby preload warning.
- Header shows a poor-connection notice in the ad-banner slot on a
  first-lobby preload failure (offline.preloadWarning, en/ru).
- App-entry bundle budget 112->113 for the irreducible main-side wiring
  (documented in bundle-size.mjs); the heavy parts remain lazy chunks.

Docs: ARCHITECTURE offline-mode + dict-preload mechanism.
This commit is contained in:
Ilia Denisov
2026-07-06 10:39:55 +02:00
parent a692024b4e
commit 2f867b8e6c
13 changed files with 311 additions and 10 deletions
+86
View File
@@ -0,0 +1,86 @@
import { describe, it, expect } from 'vitest';
import { preloadDicts } from './preload';
import type { Variant } from '../model';
import type { Dawg } from './dawg';
// A non-null stand-in for a loaded reader — preloadDicts only checks getDawg's result for null.
const DAWG = {} as Dawg;
const noSleep = (): Promise<void> => Promise.resolve();
describe('preloadDicts', () => {
it('fetches every enabled variant that has a known version', async () => {
const calls: string[] = [];
const res = await preloadDicts({ scrabble_en: 'v1', scrabble_ru: 'v2', erudit_ru: 'v3' }, ['scrabble_en', 'erudit_ru'], {
getDawg: async (v: Variant, ver: string) => {
calls.push(`${v}@${ver}`);
return DAWG;
},
disabled: () => false,
sleep: noSleep,
});
expect(res.ok).toEqual(['scrabble_en', 'erudit_ru']);
expect(res.failed).toEqual([]);
expect(calls).toEqual(['scrabble_en@v1', 'erudit_ru@v3']);
});
it('marks a variant with no known version as failed without fetching it', async () => {
const calls: string[] = [];
const res = await preloadDicts({ scrabble_en: 'v1' }, ['scrabble_en', 'scrabble_ru'], {
getDawg: async (v: Variant) => {
calls.push(v);
return DAWG;
},
disabled: () => false,
sleep: noSleep,
});
expect(res.ok).toEqual(['scrabble_en']);
expect(res.failed).toEqual(['scrabble_ru']);
expect(calls).toEqual(['scrabble_en']);
});
it('retries a transient failure with linear backoff, then succeeds', async () => {
let attempts = 0;
const waits: number[] = [];
const res = await preloadDicts({ scrabble_en: 'v1' }, ['scrabble_en'], {
getDawg: async () => (++attempts >= 3 ? DAWG : null),
disabled: () => false,
sleep: async (ms: number) => void waits.push(ms),
retries: 3,
backoffMs: 100,
});
expect(res.ok).toEqual(['scrabble_en']);
expect(attempts).toBe(3);
expect(waits).toEqual([100, 200]);
});
it('gives up a persistent failure after the retry budget', async () => {
let attempts = 0;
const res = await preloadDicts({ scrabble_en: 'v1' }, ['scrabble_en'], {
getDawg: async () => {
attempts++;
return null;
},
disabled: () => false,
sleep: noSleep,
retries: 2,
});
expect(res.failed).toEqual(['scrabble_en']);
expect(res.ok).toEqual([]);
expect(attempts).toBe(3);
});
it('stops retrying once the session miss-breaker trips', async () => {
let attempts = 0;
const res = await preloadDicts({ scrabble_en: 'v1' }, ['scrabble_en'], {
getDawg: async () => {
attempts++;
return null;
},
disabled: () => true,
sleep: noSleep,
retries: 5,
});
expect(res.failed).toEqual(['scrabble_en']);
expect(attempts).toBe(1);
});
});
+68
View File
@@ -0,0 +1,68 @@
// Background dictionary preload for offline readiness. An installed PWA with a confirmed email
// warms the dictionaries for the player's enabled variants while online, so a later switch to
// deliberate offline mode has the data it needs. The pure preloadDicts here takes its side effects
// (getDawg, the session miss-breaker, sleep) as dependencies, so it unit-tests in the node env. The
// eligibility and once/online guard live in offline.svelte.ts (kickDictPreload); the browser
// orchestration that supplies the real side effects and raises the in-lobby warning lives in
// preloadrun.ts, which offline.svelte.ts imports dynamically so neither the loader nor the
// generator is pulled into the main bundle.
import type { Variant } from '../model';
import type { Dawg } from './dawg';
/** PreloadDeps injects preloadDicts's side effects so the logic stays pure and testable. */
export interface PreloadDeps {
/** getDawg resolves the (variant, version) reader, serving memory/IndexedDB before the network,
* or null on any miss — mirrors the in-game loader. */
getDawg: (variant: Variant, version: string) => Promise<Dawg | null>;
/** disabled reports whether the session dictionary miss-breaker has tripped (too many network
* misses this session); when it has, a network fetch will not recover, so retries stop. */
disabled: () => boolean;
/** sleep waits between retries; defaults to a real timer. */
sleep?: (ms: number) => Promise<void>;
/** retries is the number of extra attempts after the first (default 2). */
retries?: number;
/** backoffMs is the base linear backoff between attempts (default 800). */
backoffMs?: number;
}
/** PreloadResult reports which enabled variants ended up available (ok) and which are still
* missing (failed) after the preload — the caller surfaces a warning when failed is non-empty. */
export interface PreloadResult {
ok: Variant[];
failed: Variant[];
}
/**
* preloadDicts fetches, via getDawg, the dictionary for each enabled variant that has a known
* version, retrying transient misses with linear backoff. A variant with no known version, or one
* still missing after the retry budget, lands in failed; the rest in ok. It never throws and stops
* retrying a variant once the session miss-breaker (disabled) trips, since the network will not
* recover this session — a cached dictionary is still served by getDawg regardless.
*/
export async function preloadDicts(
versions: Partial<Record<Variant, string>>,
enabled: readonly Variant[],
deps: PreloadDeps,
): Promise<PreloadResult> {
const sleep = deps.sleep ?? ((ms) => new Promise<void>((r) => setTimeout(r, ms)));
const retries = deps.retries ?? 2;
const backoffMs = deps.backoffMs ?? 800;
const ok: Variant[] = [];
const failed: Variant[] = [];
for (const variant of enabled) {
const version = versions[variant];
if (!version) {
failed.push(variant);
continue;
}
let dawg: Dawg | null = null;
for (let attempt = 0; attempt <= retries; attempt++) {
dawg = await deps.getDawg(variant, version);
if (dawg || deps.disabled()) break;
if (attempt < retries) await sleep(backoffMs * (attempt + 1));
}
(dawg ? ok : failed).push(variant);
}
return { ok, failed };
}
+24
View File
@@ -0,0 +1,24 @@
// Browser-only orchestration for the offline dictionary preload. Kept apart from the pure
// preloadDicts (preload.ts) — which unit-tests in the node env — and lazily imported by
// offline.svelte.ts's kickDictPreload, so the dict loader/generator it pulls in stays out of the
// main bundle. It supplies the real side effects (getDawg, the session miss-breaker) and raises the
// in-lobby notice when a first-lobby preload cannot fetch every enabled variant's dictionary.
import type { Profile } from '../model';
import { preloadDicts } from './preload';
import { getDawg, dictLoadingDisabled } from '../dict';
import { setDictPreloadWarning } from '../offline.svelte';
/**
* runPreload warms the dictionaries for the profile's enabled variants (using the versions the
* profile advertises) via the real dict loader, so a later switch to offline mode has the data.
* When warnOnFail is set (the first lobby entry), it raises the in-lobby notice if a variant is
* still missing afterwards, and clears it on a run where every variant is available.
*/
export async function runPreload(prof: Profile, warnOnFail: boolean): Promise<void> {
const res = await preloadDicts(prof.dictVersions, prof.variantPreferences, {
getDawg,
disabled: dictLoadingDisabled,
});
if (warnOnFail) setDictPreloadWarning(res.failed.length > 0);
}