From d5b21c431e53f6bcf04c1763e5217eaa705e1264 Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 1 Dec 2026 19:07:11 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Surface=20storage=20errors=20and?= =?UTF-8?q?=20ignore=20a=20late=20gate=20resolution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When IndexedDB rejected or blocked the open, resolveGate() rejected, the gate stayed null and the app showed "Loading…" forever. A failed open now cleans up and rejects with a reason, a blocked open gives up after eight seconds, and resolveGate() turns that into an error gate: the layout shows the message with a Retry button instead of the loading line, and the sign-in itself is kept. logout() clears the auth store and the session before it closes and wipes the local data, and swallows a failing wipe, so the user is never left half logged out. activate() sets the session only after the database is open and only if the auth store is still valid with the same token, so a resolution that finishes after a logout or another sign-in no longer reopens the app for the wrong user. openDb() hands out an in-flight open only to the same user; another user's open waits for it and then replaces it. --- web/src/lib/db.svelte.ts | 44 +++++++++++++++++++---- web/src/lib/db.test.ts | 22 ++++++++++-- web/src/lib/session.svelte.ts | 62 +++++++++++++++++++++----------- web/src/lib/session.test.ts | 67 ++++++++++++++++++++++++++++++++++- web/src/lib/testing.svelte.ts | 30 ++++++++++++++++ web/src/routes/+layout.svelte | 35 ++++++++++++++++-- 6 files changed, 227 insertions(+), 33 deletions(-) diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index 85aa363..13c98ba 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -41,6 +41,8 @@ const SYNC_ID = 'wotra'; const SCHEMA_VERSION = 1; /** Changes per push request; the server rejects more than 500. */ const PUSH_BATCH = 200; +/** Upper bound for opening the local database in milliseconds. */ +const OPEN_TIMEOUT = 8000; const NUMBER_FIELDS: Record = { entries: ['start_time', 'end_time'], @@ -264,14 +266,29 @@ let syncing: Promise | null = null; let beforeSync: (() => Promise) | null = null; const cleanups: (() => void)[] = []; const roundListeners = new Set<() => void>(); -let opening: Promise | null = null; +/** An open in flight and the user it is for; an open for another user waits for it. */ +let opening: { uid: string; done: Promise } | null = null; export function openDb(uid: string): Promise { - if (opening) return opening; - opening = doOpenDb(uid).finally(() => { - opening = null; + if (opening?.uid === uid) return opening.done; + const settled = opening?.done.catch(() => {}) ?? Promise.resolve(); + const done = settled + .then(() => doOpenDb(uid)) + .finally(() => { + if (opening?.done === done) opening = null; + }); + opening = { uid, done }; + return done; +} + +/** Resolves once every collection is ready; rejects when the database cannot be opened or a blocked open does not answer in time. */ +function ready(c: Record): Promise { + let timer: ReturnType | undefined; + const timeout = new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('the browser blocked it or did not answer')), OPEN_TIMEOUT); }); - return opening; + const all = Promise.all(COLLECTIONS.map((n) => c[n].ready())).then(() => undefined); + return Promise.race([all, timeout]).finally(() => clearTimeout(timer)); } async function doOpenDb(uid: string): Promise { @@ -284,10 +301,23 @@ async function doOpenDb(uid: string): Promise { pushedChanges.clear(); applying.clear(); const idb = prepareIndexedDB({ databaseName: localDbName(uid), version: SCHEMA_VERSION, schema: schema() }); - const adapter = new DefaultDataAdapter({ storage: (name) => idb(name) }); + let opened = false; + const adapter = new DefaultDataAdapter({ + storage: (name) => idb(name), + onError: (e) => { + if (opened) console.error(e); + } + }); const c = {} as Record; for (const name of COLLECTIONS) c[name] = new Collection(name, adapter, { reactivity }); - await Promise.all(COLLECTIONS.map((n) => c[n].ready())); + try { + await ready(c); + } catch (e) { + await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {}))); + userId = ''; + throw e; + } + opened = true; if (gen !== epoch) { await Promise.all(Object.values(c).map((col) => col.dispose().catch(() => {}))); return; diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index 0c57701..5103079 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -1,8 +1,8 @@ import { Collection } from '@signaldb/core'; import { tick } from 'svelte'; import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { all, closeDb, get, onSessionExpired, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; -import { watch } from './testing.svelte'; +import { all, closeDb, currentUserId, get, onSessionExpired, openDb, pendingCount, remove, removeLegacyStorage, save, status, syncNow, toRecord, update } from './db.svelte'; +import { holdNextOpen, watch } from './testing.svelte'; const mocks = vi.hoisted(() => { const server = new Map>>(); @@ -189,6 +189,24 @@ describe('read scopes', () => { }); }); +describe('open', () => { + it('an open for another user while one is in flight ends with the database of that user', async () => { + const hold = holdNextOpen(); + const first = openDb('user-a'); + await hold.entered; + const second = openDb('user-b'); + hold.release(); + await first; + await second; + expect(currentUserId()).toBe('user-b'); + const id = await save('settings_history', null, settingsRow); + expect(get('settings_history', id)?.hours_per_week).toBe(40); + await closeDb(); + await openDb('user-a'); + expect(all('settings_history')).toEqual([]); + }); +}); + describe('legacy storage', () => { const open = (name: string) => new Promise((resolve, reject) => { diff --git a/web/src/lib/session.svelte.ts b/web/src/lib/session.svelte.ts index efb3314..1336123 100644 --- a/web/src/lib/session.svelte.ts +++ b/web/src/lib/session.svelte.ts @@ -4,14 +4,28 @@ import { errorMessage, pb } from '$lib/pb'; export const session = $state({ userId: '' as string, email: '' as string, - checked: false + checked: false, + /** Why the app could not start; shown instead of the loading line. */ + error: null as string | null }); -export type Gate = 'login' | 'app'; +export type Gate = 'login' | 'app' | 'error'; /** Whether the layout must resolve the gate again: nothing is resolved, the login page is up, or the session ended. */ export function gateStale(gate: Gate | null): boolean { - return gate === null || gate === 'login' || !session.userId || !pb.authStore.isValid; + if (gate === null || gate === 'login') return true; + return gate === 'app' && (!session.userId || !pb.authStore.isValid); +} + +function resetSession(): void { + session.userId = ''; + session.email = ''; + session.checked = true; +} + +function clearSession(): void { + pb.authStore.clear(); + resetSession(); } /** First field error PocketBase sent, else the general message of the error. */ @@ -32,36 +46,41 @@ export async function refreshAuth(): Promise { } } -async function activate(): Promise { +/** Opens the database and activates the session, unless the user signed out or signed in anew while it opened. */ +async function activate(): Promise { const r = pb.authStore.record; if (!r) throw new Error('Not signed in'); + const token = pb.authStore.token; + await openDb(r.id); + if (!pb.authStore.isValid || pb.authStore.token !== token) return false; session.userId = r.id; session.email = String(r.email ?? ''); - await openDb(r.id); session.checked = true; + return true; } /** Ends the session unless one refresh of the token saves it. */ async function expire(): Promise { await refreshAuth(); if (pb.authStore.isValid && pb.authStore.record) return; - pb.authStore.clear(); - session.userId = ''; - session.email = ''; - session.checked = true; + clearSession(); } onSessionExpired(() => void expire()); export async function resolveGate(): Promise { - await refreshAuth(); - if (!pb.authStore.isValid || !pb.authStore.record) { - session.userId = ''; - session.email = ''; - session.checked = true; - return 'login'; + session.error = null; + try { + await refreshAuth(); + if (!pb.authStore.isValid || !pb.authStore.record || !(await activate())) { + clearSession(); + return 'login'; + } + } catch (e) { + resetSession(); + session.error = `The local database could not be opened: ${errorMessage(e)}`; + return 'error'; } - await activate(); void removeLegacyStorage(); return 'app'; } @@ -87,11 +106,12 @@ export async function signup(email: string, password: string): Promise { export async function logout(): Promise { const uid = session.userId || pb.authStore.record?.id || currentUserId(); - await closeDb(); - if (uid) await wipeLocal(uid); - pb.authStore.clear(); - session.userId = ''; - session.email = ''; + clearSession(); + session.error = null; + try { + if (uid) await wipeLocal(uid); + else await closeDb(); + } catch {} } export function safeNext(url: URL, fallback = '/today'): string { diff --git a/web/src/lib/session.test.ts b/web/src/lib/session.test.ts index 51a983a..780704b 100644 --- a/web/src/lib/session.test.ts +++ b/web/src/lib/session.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { closeDb, save, status, syncNow, update } from './db.svelte'; -import { gateStale, resolveGate, session } from './session.svelte'; +import { gateStale, logout, resolveGate, safeNext, session } from './session.svelte'; +import { holdNextOpen } from './testing.svelte'; const mocks = vi.hoisted(() => ({ legacy: vi.fn(), @@ -115,3 +116,67 @@ describe('session expiry', () => { expect(gateStale('app')).toBe(true); }); }); + +describe('gate resolution', () => { + it('a database that cannot be opened shows its error instead of loading, and Retry resolves again', async () => { + vi.stubGlobal('indexedDB', { + open: () => { + const request = new EventTarget() as EventTarget & { error: DOMException }; + request.error = new DOMException('Access is denied', 'UnknownError'); + setTimeout(() => request.dispatchEvent(new Event('error')), 0); + return request; + } + }); + try { + mocks.record = { id: 'blocked-user', email: 'me@example.com' }; + expect(await resolveGate()).toBe('error'); + expect(session).toMatchObject({ userId: '', email: '', error: 'The local database could not be opened: Access is denied' }); + expect(status.ready).toBe(false); + expect(mocks.legacy).not.toHaveBeenCalled(); + } finally { + vi.unstubAllGlobals(); + } + expect(await resolveGate()).toBe('app'); + expect(session).toMatchObject({ userId: 'blocked-user', error: null }); + expect(status.ready).toBe(true); + }); + + it('a resolution that finishes after logout does not activate the session', async () => { + mocks.record = { id: 'slow-user', email: 'me@example.com' }; + const hold = holdNextOpen(); + const resolving = resolveGate(); + await hold.entered; + await logout(); + hold.release(); + expect(await resolving).toBe('login'); + expect(session).toMatchObject({ userId: '', email: '', error: null }); + expect(status.ready).toBe(false); + expect(mocks.record).toBeNull(); + expect(mocks.legacy).not.toHaveBeenCalled(); + }); + + it('logout leaves nothing of the session behind when the wipe fails', async () => { + mocks.record = { id: 'wipe-user' }; + await resolveGate(); + const wipe = vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => { + throw new Error('QuotaExceededError'); + }); + try { + await expect(logout()).resolves.toBeUndefined(); + } finally { + wipe.mockRestore(); + } + expect(session).toMatchObject({ userId: '', email: '', error: null }); + expect(mocks.record).toBeNull(); + expect(status.ready).toBe(false); + }); +}); + +describe('safeNext', () => { + const next = (query: string) => safeNext(new URL(`http://localhost/login?next=${query}`)); + it('keeps a local path and falls back for anything else', () => { + expect(next(encodeURIComponent('/week?day=2026-06-15'))).toBe('/week?day=2026-06-15'); + expect(next('https://evil.example')).toBe('/today'); + expect(next('')).toBe('/today'); + }); +}); diff --git a/web/src/lib/testing.svelte.ts b/web/src/lib/testing.svelte.ts index 29721ab..ab06e60 100644 --- a/web/src/lib/testing.svelte.ts +++ b/web/src/lib/testing.svelte.ts @@ -30,3 +30,33 @@ export function watch(read: () => T): Watcher { dispose }; } + +/** Lets the next IndexedDB open go through only once release() is called; entered resolves when the request is out. */ +export function holdNextOpen(): { entered: Promise; release: () => void } { + const open = indexedDB.open.bind(indexedDB); + let enter!: () => void; + let release!: () => void; + const entered = new Promise((resolve) => (enter = resolve)); + const gate = new Promise((resolve) => (release = resolve)); + indexedDB.open = ((name: string, version?: number) => { + indexedDB.open = open; + const request = open(name, version); + const add = request.addEventListener.bind(request); + const defer = (type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions) => { + if (type !== 'success') return add(type, listener, options); + add( + type, + async (event) => { + enter(); + await gate; + if (typeof listener === 'function') listener.call(request, event); + else listener?.handleEvent(event); + }, + options + ); + }; + request.addEventListener = defer; + return request; + }) as typeof indexedDB.open; + return { entered, release }; +} diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte index 515a0bb..780f151 100644 --- a/web/src/routes/+layout.svelte +++ b/web/src/routes/+layout.svelte @@ -3,10 +3,10 @@ import { goto } from '$app/navigation'; import { page } from '$app/state'; import { pendingCount, status, syncNow } from '$lib/db.svelte'; - import { gateStale, resolveGate, safeNext, session } from '$lib/session.svelte'; + import { gateStale, resolveGate, safeNext, session, type Gate } from '$lib/session.svelte'; let { children } = $props(); - let gate = $state<'login' | 'app' | null>(null); + let gate = $state(null); async function route() { if (gateStale(gate)) gate = await resolveGate(); @@ -21,6 +21,11 @@ } } + function retry() { + gate = null; + void route(); + } + $effect(() => { page.url.pathname; session.userId; @@ -100,6 +105,11 @@
{@render children()}
+{:else if gate === 'error'} +
+

{session.error}

+ +
{:else}

Loading…

{/if} @@ -196,6 +206,27 @@ justify-content: center; padding: 1rem; } + .gate-error { + min-height: 100dvh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 1rem; + margin: 0; + padding: 1rem; + color: #6c757d; + text-align: center; + } + .gate-error button { + padding: 0.55rem 1.4rem; + background: #1a1a2e; + color: #fff; + border: none; + border-radius: 6px; + font-size: 0.95rem; + font-weight: 600; + } .loading { min-height: 100dvh; display: flex;