🐛 Silence SignalDB warnings for reads outside reactive scopes
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.
This commit is contained in:
+42
-11
@@ -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<T extends BaseItem, R>(
|
||||
c: Collection<T, string>,
|
||||
selector: Selector<T> | undefined,
|
||||
read: (cursor: Cursor<T, T>) => 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<Record<string, unknown>, 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<void> {
|
||||
@@ -358,14 +385,18 @@ export function pendingCount(): number {
|
||||
}
|
||||
|
||||
export function all<K extends CollectionName>(name: K, includeDeleted = false): Doc<PayloadMap[K]>[] {
|
||||
if (!cols) return [];
|
||||
const c = cols[name];
|
||||
return (includeDeleted ? c.find({}, readOptions()) : c.find({ deleted: false }, readOptions())).fetch() as unknown as Doc<PayloadMap[K]>[];
|
||||
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<PayloadMap[K]>[];
|
||||
}
|
||||
|
||||
export function get<K extends CollectionName>(name: K, id: string): Doc<PayloadMap[K]> | undefined {
|
||||
if (!cols) return undefined;
|
||||
return cols[name].findOne({ id }, readOptions()) as Doc<PayloadMap[K]> | 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<PayloadMap[K]> | undefined;
|
||||
}
|
||||
|
||||
export async function save<K extends CollectionName>(name: K, id: string | null, data: PayloadMap[K], deleted = false): Promise<string> {
|
||||
@@ -373,7 +404,7 @@ export async function save<K extends CollectionName>(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),
|
||||
|
||||
@@ -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<string, Map<string, Record<string, unknown>>>();
|
||||
@@ -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<void>((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', {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface Watcher<T> {
|
||||
/** 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<T>(read: () => T): Watcher<T> {
|
||||
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
|
||||
};
|
||||
}
|
||||
+4
-2
@@ -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']
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user