fix(sync): bound the wait on the persisted settings before the inbox repair
zustand's persist never finishes a failed load (a storage that throws, or corrupted JSON under simpl-liste-settings): onFinishHydration is never called and hasHydrated stays false. whenSettingsHydrated waited for it without bound, so repairInbox never settled and the splash screen stayed up at every launch (review of PR #164). - onRehydrateStorage records the load error. - whenSettingsHydrated goes through waitForHydration (src/lib/hydration.ts, pure, node-tested), which rejects on that error or after 5 s. The rejection skips the repair through the existing catch of prepareInbox, and ensureInbox and the startup go on. - tests/hydration.test.mjs also pins the failure mode against the zustand persist middleware of the repo; the smoke test locks the store wiring (mutation R6 of the review now fails it). Refs #152 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0156aee011
commit
3cf8be3dcf
5 changed files with 297 additions and 11 deletions
|
|
@ -4,7 +4,7 @@
|
|||
"version": "1.6.6",
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs",
|
||||
"test": "node tests/smoke.test.cjs && node --test --disable-warning=ExperimentalWarning --disable-warning=MODULE_TYPELESS_PACKAGE_JSON tests/feedback.test.mjs tests/syncRules.test.mjs tests/hydration.test.mjs",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web",
|
||||
|
|
|
|||
55
src/lib/hydration.ts
Normal file
55
src/lib/hydration.ts
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
// Bounded wait for a persisted store to finish loading.
|
||||
//
|
||||
// This module MUST stay import-free and use only erasable TypeScript syntax:
|
||||
// tests/hydration.test.mjs loads it with Node's native type stripping. The
|
||||
// smoke test locks the zero-import rule.
|
||||
|
||||
/** Upper bound of the wait for the persisted settings, in milliseconds. */
|
||||
export const HYDRATION_TIMEOUT_MS = 5000;
|
||||
|
||||
/** What waitForHydration reads from a persisted store. */
|
||||
export interface HydrationSource {
|
||||
hasHydrated: () => boolean;
|
||||
/** Error of a failed load, null when there is none (yet). */
|
||||
error: () => unknown;
|
||||
/** Called once the load succeeds; returns an unsubscribe function. */
|
||||
onFinish: (cb: () => void) => () => void;
|
||||
/** Called when the load fails; returns an unsubscribe function. */
|
||||
onError: (cb: (error: unknown) => void) => () => void;
|
||||
}
|
||||
|
||||
export interface Timers {
|
||||
setTimeout: (cb: () => void, ms: number) => unknown;
|
||||
clearTimeout: (handle: unknown) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves once the store has loaded, rejects when its load failed or after
|
||||
* timeoutMs. zustand's persist never finishes a failed load (a storage that
|
||||
* throws, or corrupted JSON): onFinishHydration is never called and
|
||||
* hasHydrated stays false, so an unbounded wait would hang forever (#152,
|
||||
* review of PR #164).
|
||||
*/
|
||||
export function waitForHydration(source: HydrationSource, timeoutMs: number, timers: Timers): Promise<void> {
|
||||
if (source.hasHydrated()) return Promise.resolve();
|
||||
const failed = source.error();
|
||||
if (failed != null) return Promise.reject(failed);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
let done = false;
|
||||
const settle = (fn: () => void) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
offFinish();
|
||||
offError();
|
||||
timers.clearTimeout(timer);
|
||||
fn();
|
||||
};
|
||||
const offFinish = source.onFinish(() => settle(resolve));
|
||||
const offError = source.onError((error) => settle(() => reject(error)));
|
||||
const timer = timers.setTimeout(
|
||||
() => settle(() => reject(new Error(`settings not loaded after ${timeoutMs} ms`))),
|
||||
timeoutMs
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { create } from 'zustand';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
import { HYDRATION_TIMEOUT_MS, waitForHydration } from '@/src/lib/hydration';
|
||||
|
||||
type ThemeMode = 'light' | 'dark' | 'system';
|
||||
|
||||
|
|
@ -25,6 +26,10 @@ interface SettingsState {
|
|||
setUserId: (userId: string | null) => void;
|
||||
}
|
||||
|
||||
// Error of a failed settings load, and who waits for it (whenSettingsHydrated)
|
||||
let hydrationError: unknown = null;
|
||||
const hydrationErrorListeners = new Set<(error: unknown) => void>();
|
||||
|
||||
export const useSettingsStore = create<SettingsState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
|
|
@ -50,21 +55,35 @@ export const useSettingsStore = create<SettingsState>()(
|
|||
{
|
||||
name: 'simpl-liste-settings',
|
||||
storage: createJSONStorage(() => AsyncStorage),
|
||||
// A failed load is never finished by persist: record it for
|
||||
// whenSettingsHydrated, which would otherwise wait for nothing.
|
||||
onRehydrateStorage: () => (_state, error) => {
|
||||
if (error == null) return;
|
||||
hydrationError = error;
|
||||
hydrationErrorListeners.forEach((cb) => cb(error));
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* Resolves once the persisted settings are loaded from AsyncStorage. Before
|
||||
* that, syncEnabled reads as its default false: a startup write that depends
|
||||
* on it waits for this (#152).
|
||||
* Resolves once the persisted settings are loaded from AsyncStorage, rejects
|
||||
* when the load failed or after HYDRATION_TIMEOUT_MS. Before the load,
|
||||
* syncEnabled reads as its default false: a startup write that depends on it
|
||||
* waits for this, and is skipped when it rejects (#152).
|
||||
*/
|
||||
export function whenSettingsHydrated(): Promise<void> {
|
||||
if (useSettingsStore.persist.hasHydrated()) return Promise.resolve();
|
||||
return new Promise((resolve) => {
|
||||
const unsubscribe = useSettingsStore.persist.onFinishHydration(() => {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
return waitForHydration(
|
||||
{
|
||||
hasHydrated: () => useSettingsStore.persist.hasHydrated(),
|
||||
error: () => hydrationError,
|
||||
onFinish: (cb) => useSettingsStore.persist.onFinishHydration(cb),
|
||||
onError: (cb) => {
|
||||
hydrationErrorListeners.add(cb);
|
||||
return () => hydrationErrorListeners.delete(cb);
|
||||
},
|
||||
},
|
||||
HYDRATION_TIMEOUT_MS,
|
||||
{ setTimeout, clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>) }
|
||||
);
|
||||
}
|
||||
|
|
|
|||
185
tests/hydration.test.mjs
Normal file
185
tests/hydration.test.mjs
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
// Execution tests for the bounded wait on the persisted settings (#152,
|
||||
// review of PR #164). Runs on plain node via the built-in test runner +
|
||||
// native TS type-stripping:
|
||||
//
|
||||
// node --test tests/hydration.test.mjs
|
||||
//
|
||||
// The unit tests drive waitForHydration with a fake source and fake timers.
|
||||
// The last tests run it against the zustand persist middleware of the repo,
|
||||
// with the same onRehydrateStorage hook as src/stores/useSettingsStore.ts
|
||||
// (locked by the smoke test), to pin the failure mode it guards against.
|
||||
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createStore } from 'zustand/vanilla';
|
||||
import { persist, createJSONStorage } from 'zustand/middleware';
|
||||
import { HYDRATION_TIMEOUT_MS, waitForHydration } from '../src/lib/hydration.ts';
|
||||
|
||||
function fakeSource({ hydrated = false, error = null } = {}) {
|
||||
const finish = new Set();
|
||||
const errors = new Set();
|
||||
return {
|
||||
finish,
|
||||
errors,
|
||||
source: {
|
||||
hasHydrated: () => hydrated,
|
||||
error: () => error,
|
||||
onFinish: (cb) => {
|
||||
finish.add(cb);
|
||||
return () => finish.delete(cb);
|
||||
},
|
||||
onError: (cb) => {
|
||||
errors.add(cb);
|
||||
return () => errors.delete(cb);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeTimers() {
|
||||
const pending = new Map();
|
||||
let next = 1;
|
||||
return {
|
||||
pending,
|
||||
fire: () => [...pending.values()].forEach((t) => t.cb()),
|
||||
timers: {
|
||||
setTimeout: (cb, ms) => {
|
||||
const id = next++;
|
||||
pending.set(id, { cb, ms });
|
||||
return id;
|
||||
},
|
||||
clearTimeout: (id) => pending.delete(id),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Settled state of a promise after the microtask queue drains
|
||||
async function state(promise) {
|
||||
let s = 'pending';
|
||||
promise.then(() => (s = 'resolved'), (e) => (s = `rejected: ${e && e.message ? e.message : e}`));
|
||||
await new Promise((r) => setImmediate(r));
|
||||
return s;
|
||||
}
|
||||
|
||||
test('HYDRATION_TIMEOUT_MS is a few seconds', () => {
|
||||
assert.equal(HYDRATION_TIMEOUT_MS, 5000);
|
||||
});
|
||||
|
||||
test('waitForHydration: an already loaded store resolves at once, without a timer', async () => {
|
||||
const { source } = fakeSource({ hydrated: true });
|
||||
const t = fakeTimers();
|
||||
assert.equal(await state(waitForHydration(source, 5000, t.timers)), 'resolved');
|
||||
assert.equal(t.pending.size, 0);
|
||||
});
|
||||
|
||||
test('waitForHydration: a load that already failed rejects at once', async () => {
|
||||
const { source } = fakeSource({ error: new Error('bad json') });
|
||||
const t = fakeTimers();
|
||||
assert.equal(await state(waitForHydration(source, 5000, t.timers)), 'rejected: bad json');
|
||||
assert.equal(t.pending.size, 0);
|
||||
});
|
||||
|
||||
test('waitForHydration: waits for the load, then resolves and clears its timer and listeners', async () => {
|
||||
const f = fakeSource();
|
||||
const t = fakeTimers();
|
||||
const p = waitForHydration(f.source, 5000, t.timers);
|
||||
assert.equal(await state(p), 'pending');
|
||||
assert.equal(t.pending.size, 1);
|
||||
assert.equal([...t.pending.values()][0].ms, 5000);
|
||||
[...f.finish].forEach((cb) => cb());
|
||||
assert.equal(await state(p), 'resolved');
|
||||
assert.equal(t.pending.size, 0);
|
||||
assert.equal(f.finish.size, 0);
|
||||
assert.equal(f.errors.size, 0);
|
||||
});
|
||||
|
||||
test('waitForHydration: a load that fails later rejects with its error', async () => {
|
||||
const f = fakeSource();
|
||||
const t = fakeTimers();
|
||||
const p = waitForHydration(f.source, 5000, t.timers);
|
||||
[...f.errors].forEach((cb) => cb(new Error('storage down')));
|
||||
assert.equal(await state(p), 'rejected: storage down');
|
||||
assert.equal(t.pending.size, 0);
|
||||
assert.equal(f.finish.size, 0);
|
||||
});
|
||||
|
||||
test('waitForHydration: a load that never ends rejects at the timeout', async () => {
|
||||
const f = fakeSource();
|
||||
const t = fakeTimers();
|
||||
const p = waitForHydration(f.source, 5000, t.timers);
|
||||
t.fire();
|
||||
assert.equal(await state(p), 'rejected: settings not loaded after 5000 ms');
|
||||
assert.equal(f.finish.size, 0);
|
||||
assert.equal(f.errors.size, 0);
|
||||
});
|
||||
|
||||
test('waitForHydration: settles once, a late finish after the timeout changes nothing', async () => {
|
||||
const f = fakeSource();
|
||||
const t = fakeTimers();
|
||||
const finishers = () => [...f.finish];
|
||||
const p = waitForHydration(f.source, 5000, t.timers);
|
||||
const late = finishers();
|
||||
t.fire();
|
||||
late.forEach((cb) => cb());
|
||||
assert.match(await state(p), /^rejected/);
|
||||
});
|
||||
|
||||
// --- Against the zustand persist middleware of the repo ---
|
||||
|
||||
function settingsStore(raw) {
|
||||
let error = null;
|
||||
const errorListeners = new Set();
|
||||
const store = createStore()(
|
||||
persist(() => ({ syncEnabled: false }), {
|
||||
name: 'simpl-liste-settings',
|
||||
storage: createJSONStorage(() => ({
|
||||
getItem: async () => raw,
|
||||
setItem: async () => {},
|
||||
removeItem: async () => {},
|
||||
})),
|
||||
// Same hook as useSettingsStore.ts
|
||||
onRehydrateStorage: () => (_state, e) => {
|
||||
if (e == null) return;
|
||||
error = e;
|
||||
errorListeners.forEach((cb) => cb(e));
|
||||
},
|
||||
}),
|
||||
);
|
||||
const source = {
|
||||
hasHydrated: () => store.persist.hasHydrated(),
|
||||
error: () => error,
|
||||
onFinish: (cb) => store.persist.onFinishHydration(cb),
|
||||
onError: (cb) => {
|
||||
errorListeners.add(cb);
|
||||
return () => errorListeners.delete(cb);
|
||||
},
|
||||
};
|
||||
return { store, source };
|
||||
}
|
||||
|
||||
const realTimers = { setTimeout, clearTimeout };
|
||||
|
||||
test('zustand persist never finishes a load of corrupted JSON (the hang of the review)', async () => {
|
||||
const { store } = settingsStore('{not json');
|
||||
let finished = false;
|
||||
store.persist.onFinishHydration(() => (finished = true));
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
assert.equal(store.persist.hasHydrated(), false);
|
||||
assert.equal(finished, false);
|
||||
});
|
||||
|
||||
test('waitForHydration rejects on corrupted settings, whether it starts before or after the failure', async () => {
|
||||
const early = settingsStore('{not json');
|
||||
const p = waitForHydration(early.source, 1000, realTimers);
|
||||
await assert.rejects(p);
|
||||
|
||||
const late = settingsStore('{not json');
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
await assert.rejects(waitForHydration(late.source, 1000, realTimers));
|
||||
});
|
||||
|
||||
test('waitForHydration resolves on valid settings, with the stored syncEnabled', async () => {
|
||||
const { store, source } = settingsStore(JSON.stringify({ state: { syncEnabled: true }, version: 0 }));
|
||||
await waitForHydration(source, 1000, realTimers);
|
||||
assert.equal(store.getState().syncEnabled, true);
|
||||
});
|
||||
|
|
@ -275,6 +275,33 @@ check('syncClient.ts wires the #149-#151 sync rules', () => {
|
|||
assert.match(push, /\.where\(inArray\(syncOutbox\.id, markIds\)\);\s*\/\/[^\n]*\s*syncWidgetData\(\)/);
|
||||
});
|
||||
|
||||
// The bounded wait on the persisted settings (review of PR #164) is executed
|
||||
// by tests/hydration.test.mjs through node's type stripping: hydration.ts
|
||||
// stays import-free, and useSettingsStore.ts (React Native, not loadable
|
||||
// under node) must feed it the load error and the timeout.
|
||||
check('hydration.ts stays import-free and useSettingsStore.ts bounds its wait', () => {
|
||||
assert.deepEqual(staticImportsOf('src/lib/hydration.ts'), [], 'hydration.ts must have zero imports');
|
||||
const src = fs.readFileSync(path.join(__dirname, '..', 'src/stores/useSettingsStore.ts'), 'utf8');
|
||||
// persist never finishes a failed load: the hook records the error
|
||||
assert.match(
|
||||
src,
|
||||
/onRehydrateStorage: \(\) => \(_state, error\) => \{\s*if \(error == null\) return;\s*hydrationError = error;\s*hydrationErrorListeners\.forEach\(\(cb\) => cb\(error\)\);\s*\}/
|
||||
);
|
||||
const start = src.indexOf('export function whenSettingsHydrated(');
|
||||
assert.ok(start >= 0, 'whenSettingsHydrated not found');
|
||||
const body = src.slice(start);
|
||||
assert.match(body, /^[^]*?\{\s*return waitForHydration\(/, 'whenSettingsHydrated must return waitForHydration(...)');
|
||||
for (const piece of [
|
||||
'hasHydrated: () => useSettingsStore.persist.hasHydrated()',
|
||||
'error: () => hydrationError',
|
||||
'onFinish: (cb) => useSettingsStore.persist.onFinishHydration(cb)',
|
||||
'hydrationErrorListeners.add(cb)',
|
||||
'HYDRATION_TIMEOUT_MS,',
|
||||
]) {
|
||||
assert.ok(body.includes(piece), `whenSettingsHydrated misses ${piece}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Wiring of the Inbox repair (#152) in lists.ts and app/_layout.tsx, which
|
||||
// node cannot load: planInboxRepair and pickInboxId are executed by
|
||||
// tests/syncRules.test.mjs, this check locks how they are called.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue