🐛 Surface storage errors and ignore a late gate resolution

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.
This commit is contained in:
2026-12-01 19:07:11 +01:00
parent d387854329
commit d5b21c431e
6 changed files with 227 additions and 33 deletions
+37 -7
View File
@@ -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<CollectionName, string[]> = {
entries: ['start_time', 'end_time'],
@@ -264,14 +266,29 @@ let syncing: Promise<void> | null = null;
let beforeSync: (() => Promise<void>) | null = null;
const cleanups: (() => void)[] = [];
const roundListeners = new Set<() => void>();
let opening: Promise<void> | 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<void> } | null = null;
export function openDb(uid: string): Promise<void> {
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;
});
return opening;
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<CollectionName, AnyCollection>): Promise<void> {
let timer: ReturnType<typeof setTimeout> | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new Error('the browser blocked it or did not answer')), OPEN_TIMEOUT);
});
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<void> {
@@ -284,10 +301,23 @@ async function doOpenDb(uid: string): Promise<void> {
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<CollectionName, AnyCollection>;
for (const name of COLLECTIONS) c[name] = new Collection<AnyDoc, string>(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;
+20 -2
View File
@@ -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<string, Map<string, Record<string, unknown>>>();
@@ -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<void>((resolve, reject) => {
+38 -18
View File
@@ -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<void> {
}
}
async function activate(): Promise<void> {
/** Opens the database and activates the session, unless the user signed out or signed in anew while it opened. */
async function activate(): Promise<boolean> {
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<void> {
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<Gate> {
session.error = null;
try {
await refreshAuth();
if (!pb.authStore.isValid || !pb.authStore.record) {
session.userId = '';
session.email = '';
session.checked = true;
if (!pb.authStore.isValid || !pb.authStore.record || !(await activate())) {
clearSession();
return 'login';
}
await activate();
} catch (e) {
resetSession();
session.error = `The local database could not be opened: ${errorMessage(e)}`;
return 'error';
}
void removeLegacyStorage();
return 'app';
}
@@ -87,11 +106,12 @@ export async function signup(email: string, password: string): Promise<void> {
export async function logout(): Promise<void> {
const uid = session.userId || pb.authStore.record?.id || currentUserId();
await closeDb();
clearSession();
session.error = null;
try {
if (uid) await wipeLocal(uid);
pb.authStore.clear();
session.userId = '';
session.email = '';
else await closeDb();
} catch {}
}
export function safeNext(url: URL, fallback = '/today'): string {
+66 -1
View File
@@ -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');
});
});
+30
View File
@@ -30,3 +30,33 @@ export function watch<T>(read: () => T): Watcher<T> {
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<void>; release: () => void } {
const open = indexedDB.open.bind(indexedDB);
let enter!: () => void;
let release!: () => void;
const entered = new Promise<void>((resolve) => (enter = resolve));
const gate = new Promise<void>((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 };
}
+33 -2
View File
@@ -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<Gate | null>(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 @@
<div class="auth-wrap">
{@render children()}
</div>
{:else if gate === 'error'}
<div class="gate-error">
<p role="alert">{session.error}</p>
<button onclick={retry}>Retry</button>
</div>
{:else}
<p class="loading">Loading…</p>
{/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;