From bd2ec79a69637c2d3798728568c3f6037c17d26e Mon Sep 17 00:00:00 2001 From: Andreas Schneider Date: Tue, 1 Dec 2026 17:02:53 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Silence=20SignalDB=20warnings=20?= =?UTF-8?q?for=20reads=20outside=20reactive=20scopes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every read outside a reactive scope passed { reactive: false } and made Cursor.depend() log a warning. Such reads now use a silent reactivity adapter, and all, get, pendingCount and save release the cursor again with cleanup(), so nothing is registered and nothing leaks. Reads inside $derived or $effect stay reactive as before. Vitest now resolves the browser export of Svelte. Without it svelte/reactivity is the server stub, createSubscriber never starts and no effect re-runs after a write in tests. --- web/src/lib/db.svelte.ts | 53 ++++++++++++++++++++++++------- web/src/lib/db.test.ts | 59 +++++++++++++++++++++++++++++++++++ web/src/lib/testing.svelte.ts | 32 +++++++++++++++++++ web/vite.config.ts | 6 ++-- 4 files changed, 137 insertions(+), 13 deletions(-) create mode 100644 web/src/lib/testing.svelte.ts diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index c2d81eb..ea825e6 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -1,4 +1,12 @@ -import { Collection, DefaultDataAdapter } from '@signaldb/core'; +import { + Collection, + DefaultDataAdapter, + createReactivityAdapter, + type BaseItem, + type Cursor, + type ReactivityAdapter, + type Selector +} from '@signaldb/core'; import { SyncManager } from '@signaldb/sync'; import svelteReactivityAdapter from '@signaldb/svelte'; import prepareIndexedDB from '@signaldb/indexeddb'; @@ -109,10 +117,28 @@ export const status = $state({ }); const reactivity = svelteReactivityAdapter; +/** Reports a reactive scope where there is none, so a cursor reads silently and wakes nobody. */ +const silent: ReactivityAdapter = createReactivityAdapter({ + create: () => ({ depend() {}, notify() {} }), + isInScope: () => true +}); -/** Reactive when called inside a reactive scope, a plain read otherwise. */ -function readOptions(): { reactive: false } | undefined { - return reactivity.isInScope?.() ? undefined : { reactive: false }; +function inScope(): boolean { + return reactivity.isInScope ? reactivity.isInScope() : true; +} + +/** Reads outside a reactive scope: registers no dependency and releases the cursor's observer. */ +function readOnce( + c: Collection, + selector: Selector | undefined, + read: (cursor: Cursor) => R +): R { + const cursor = c.find(selector, { reactive: silent }); + try { + return read(cursor); + } finally { + cursor.cleanup(); + } } const cursorKey = (uid: string, name: string) => `wotra-cursor:${uid}:${name}`; @@ -134,7 +160,8 @@ function onSynced(name: string) { class WotraSync extends SyncManager, AnyDoc, string> { pending(): number { - return this.changes.find({}, readOptions()).count(); + const changes = this.changes; + return inScope() ? changes.find({}).count() : readOnce(changes, {}, (cursor) => cursor.count()); } /** Lets writes in flight finish, since the sync manager rejects them after dispose(). */ async settle(): Promise { @@ -358,14 +385,18 @@ export function pendingCount(): number { } export function all(name: K, includeDeleted = false): Doc[] { - if (!cols) return []; - const c = cols[name]; - return (includeDeleted ? c.find({}, readOptions()) : c.find({ deleted: false }, readOptions())).fetch() as unknown as Doc[]; + const c = cols?.[name]; + if (!c) return []; + const selector = includeDeleted ? {} : { deleted: false }; + const rows = inScope() ? c.find(selector).fetch() : readOnce(c, selector, (cursor) => cursor.fetch()); + return rows as unknown as Doc[]; } export function get(name: K, id: string): Doc | undefined { - if (!cols) return undefined; - return cols[name].findOne({ id }, readOptions()) as Doc | undefined; + const c = cols?.[name]; + if (!c) return undefined; + const row = inScope() ? c.findOne({ id }) : readOnce(c, { id }, (cursor) => cursor.fetch()[0]); + return row as Doc | undefined; } export async function save(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise { @@ -373,7 +404,7 @@ export async function save(name: K, id: string | null, const c = cols[name]; const rid = id ?? newId(); const now = Date.now(); - const prev = c.findOne({ id: rid }, { reactive: false }); + const prev = readOnce(c, { id: rid }, (cursor) => cursor.fetch()[0]); const cua = Math.max(now, (prev?.client_updated_at ?? 0) + 1); const rec: AnyDoc = { ...pick(name, data), diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index ca92620..82f9c39 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -1,5 +1,8 @@ +import { Collection } from '@signaldb/core'; +import { tick } from 'svelte'; import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { all, closeDb, get, openDb, pendingCount, remove, save, status, syncNow, toRecord, update } from './db.svelte'; +import { watch } from './testing.svelte'; const mocks = vi.hoisted(() => { const server = new Map>>(); @@ -44,6 +47,7 @@ vi.mock('$lib/pb', () => ({ let n = 0; const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays_mask: 31, timezone: 'UTC' }; +const settled = () => new Promise((resolve) => setTimeout(resolve, 0)); beforeEach(async () => { status.online = false; @@ -95,6 +99,61 @@ describe('local collections', () => { }); }); +describe('read scopes', () => { + it('event style reads neither warn nor keep an observer', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + let created = 0; + let disposed = 0; + const collection = Collection.getCollections().find((c) => c.name === 'balance_adjustments'); + if (!collection) throw new Error('collection missing'); + collection.on('observer.created', () => (created += 1)); + collection.on('observer.disposed', () => (disposed += 1)); + try { + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: '', effective_at: 1 }); + await update('balance_adjustments', id, { delta_ms: 2000 }); + expect(all('balance_adjustments')[0]?.delta_ms).toBe(2000); + expect(get('balance_adjustments', id)?.delta_ms).toBe(2000); + expect(pendingCount()).toBe(2); + await remove('balance_adjustments', id); + expect(all('balance_adjustments')).toHaveLength(0); + expect(get('balance_adjustments', id)?.deleted).toBe(true); + expect(pendingCount()).toBe(3); + await settled(); + expect(warn).not.toHaveBeenCalled(); + expect(created).toBeGreaterThan(0); + expect(disposed).toBe(created); + } finally { + warn.mockRestore(); + } + }); + + it('reads inside an effect update after every write', async () => { + const id = await save('balance_adjustments', null, { delta_ms: 1000, note: 'first', effective_at: 1 }); + const total = watch(() => all('balance_adjustments').reduce((sum, a) => sum + a.delta_ms, 0)); + const note = watch(() => get('balance_adjustments', id)?.note); + try { + await tick(); + expect(total.current).toBe(1000); + expect(note.current).toBe('first'); + await update('balance_adjustments', id, { delta_ms: 3000, note: 'second' }); + await tick(); + expect(total.current).toBe(3000); + expect(note.current).toBe('second'); + await remove('balance_adjustments', id); + await tick(); + expect(total.current).toBe(0); + expect(note.current).toBe('second'); + } finally { + total.dispose(); + note.dispose(); + } + const runs = total.runs; + await save('balance_adjustments', null, { delta_ms: 5, note: '', effective_at: 1 }); + await tick(); + expect(total.runs).toBe(runs); + }); +}); + describe('sync boundary', () => { it('toRecord turns end_time 0 into null and coerces the metadata', () => { const doc = toRecord('entries', { diff --git a/web/src/lib/testing.svelte.ts b/web/src/lib/testing.svelte.ts new file mode 100644 index 0000000..29721ab --- /dev/null +++ b/web/src/lib/testing.svelte.ts @@ -0,0 +1,32 @@ +export interface Watcher { + /** Last value the effect observed. */ + readonly current: T | undefined; + /** How often the effect ran. */ + readonly runs: number; + /** Every value the effect observed, in order. */ + readonly seen: T[]; + dispose(): void; +} + +/** Test helper: reads through a derived inside an effect, like a component template does. */ +export function watch(read: () => T): Watcher { + const value = $derived(read()); + const seen: T[] = []; + let runs = 0; + const dispose = $effect.root(() => { + $effect(() => { + seen.push(value); + runs += 1; + }); + }); + return { + get current() { + return seen.at(-1); + }, + get runs() { + return runs; + }, + seen, + dispose + }; +} diff --git a/web/vite.config.ts b/web/vite.config.ts index b83ce99..0002ade 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -8,7 +8,9 @@ import { VitePWA } from 'vite-plugin-pwa'; // generated — so we add it explicitly here instead. const buildId = Date.now().toString(); -export default defineConfig({ +export default defineConfig(({ mode }) => ({ + // Vitest resolves the `browser` export of Svelte, so effects re-run in tests like in the app. + resolve: { conditions: mode === 'test' ? ['browser'] : [] }, plugins: [ sveltekit(), VitePWA({ @@ -58,4 +60,4 @@ export default defineConfig({ include: ['src/**/*.test.ts'], setupFiles: ['./src/lib/test-setup.ts'] } -}); +}));