import { EventSubscriber } from '@verdant-web/common'; import type { Context } from '../context/context.js'; import { Entity } from '../entities/Entity.js'; import { Disposable } from '../utils/Disposable.js'; import { getDiagnosticResult, QueryDiagnostic, QueryRun, QueryTiming, } from './diagnostics.js'; import { enqueueQueryRun } from './QueryBatcher.js'; import { filterResultSet } from './utils.js'; export type BaseQueryEvents = { change: (value: any) => void; statusChange: (status: QueryStatus) => void; }; export type BaseQueryOptions = { context: Context; initial: T; collection: string; key: string; shouldUpdate?: (updatedCollections: string[]) => boolean; }; export type QueryStatus = 'initial' | 'initializing' | 'revalidating' | 'ready'; export const ON_ALL_UNSUBSCRIBED = Symbol('ON_ALL_UNSUBSCRIBED'); export const UPDATE = Symbol('UPDATE'); const REVALIDATION_DEBOUNCE = 50; export abstract class BaseQuery extends Disposable { private _rawValue; private _value; private _events; private _internalUnsubscribes: (() => void)[] = []; private _allUnsubscribedHandler?: (query: BaseQuery) => void; private _status: QueryStatus = 'initial'; private _executionPromise: Promise | null = null; private _timing: QueryTiming = { sweep: null, hydration: null, total: null, }; private _startedAt: number | null = null; private _timingHistory: QueryRun[] = []; private _revalidationTimeout: ReturnType | undefined; private _needsTrailingRevalidation = false; protected context; readonly collection; readonly key; readonly isListQuery; readonly type; constructor({ initial, context, collection, key, shouldUpdate, }: BaseQueryOptions) { super(); this._rawValue = initial; this._value = initial; this.isListQuery = Array.isArray(initial); this._events = new EventSubscriber( (event: keyof BaseQueryEvents) => { if (event === 'change') { this._allUnsubscribedHandler?.(this); } }, ); this.context = context; this.key = key; this.collection = collection; this.type = this.constructor.name; this.addDispose(() => clearTimeout(this._revalidationTimeout)); const shouldUpdateFn = shouldUpdate || ((collections: string[]) => collections.includes(collection)); this.addDispose( this.context.entityEvents.subscribe( 'collectionsChanged', (collections) => { if (shouldUpdateFn(collections)) { this.revalidate(); } }, ), ); // TODO: subscribe to document changes and update if necessary. } private revalidate = () => { if (this._revalidationTimeout !== undefined) { this._needsTrailingRevalidation = true; clearTimeout(this._revalidationTimeout); } else { this.execute(); } this._revalidationTimeout = setTimeout(() => { this._revalidationTimeout = undefined; if (this._needsTrailingRevalidation) { this._needsTrailingRevalidation = false; this.execute(); } }, REVALIDATION_DEBOUNCE); }; get current() { return this._value; } get resolved() { if (this.status === 'ready') return Promise.resolve(this._value); return this._executionPromise ?? this.execute(); } get subscribed() { return this._events.totalSubscriberCount() > 0; } get status() { return this._status; } private set status(v: QueryStatus) { if (this._status === v) return; this._status = v; this._events.emit('statusChange', this._status); } get hasDeleted() { if (this.isListQuery) { return (this._rawValue as any[]).length !== (this._value as any[]).length; } return !!this._rawValue && !this._value; } /** * Subscribe to changes in the query value. * * @deprecated use the two parameter form instead */ subscribe(callback: (value: T) => void): () => void; /** * Subscribe to changes in the query value. */ subscribe(event: 'change', callback: (value: T) => void): () => void; /** * Subscribe to changes in the query state. */ subscribe( event: 'statusChange', callback: (status: QueryStatus) => void, ): () => void; subscribe(eventOrCallback: any, callback?: any) { // change subscription has special behavior... if (callback === undefined && typeof eventOrCallback === 'function') { // accessing for side effects... eh this.resolved; return this._events.subscribe('change', eventOrCallback); } else if (eventOrCallback === 'change' && callback !== undefined) { // accessing for side effects... eh this.resolved; return this._events.subscribe('change', callback); } else if ( eventOrCallback === 'statusChange' && typeof callback === 'function' ) { return this._events.subscribe(eventOrCallback, callback); } else { throw new Error('Invalid invocation of Query.subscribe'); } } protected setValue = (value: T) => { this._rawValue = value; this.subscribeToDeleteAndRestore(this._rawValue); const filtered = filterResultSet(value); // prevent excess change notifications by diffing // value by identity for single-value queries, // and by item identity for multi-value let changed = true; // always fire change when going from initial to ready if (this.status === 'initializing' || this.status === 'initial') { changed = true; } else { // compare values by identity, after filtering. if (this.isListQuery) { if ( (this._value as any[]).length === (filtered as any[]).length && (this._value as any[]).every((v, i) => v === (filtered as any[])[i]) ) { changed = false; } } else { if (this._value === filtered) { changed = false; } } } this._value = filtered; if (changed) { this.context.log('debug', 'Query value changed', this.key); this._events.emit('change', this._value); } this.status = 'ready'; }; // re-applies filtering if results have changed protected refreshValue = () => { this.setValue(this._rawValue); }; private subscribeToDeleteAndRestore = (value: T) => { while (this._internalUnsubscribes.length) { this._internalUnsubscribes.pop()?.(); } if (Array.isArray(value)) { value.forEach((entity: any) => { if (entity instanceof Entity) { this._internalUnsubscribes.push( entity.subscribe('delete', this.refreshValue), ); this._internalUnsubscribes.push( entity.subscribe('restore', this.refreshValue), ); } }); } else if (value instanceof Entity) { this._internalUnsubscribes.push( value.subscribe('delete', this.refreshValue), ); this._internalUnsubscribes.push( value.subscribe('restore', () => { this.refreshValue(); }), ); } }; execute = () => { const startTime = performance.now(); this._startedAt = Date.now(); this.context.log('debug', 'Executing query', this.key); if (this.status === 'initial') { this.status = 'initializing'; } else if (this.status === 'ready') { this.status = 'revalidating'; } // no status change needed if already in a 'running' status. this._executionPromise = enqueueQueryRun(this.context, this.run) .then(() => this._value) .catch((err) => { if (err instanceof Error) { if ( err.name === 'InvalidStateError' || err.name === 'InvalidAccessError' ) { // possibly accessing db while it's closed. not much we can do. return this._value; } throw err; } else { throw new Error('Unknown error executing query'); } }) .finally(() => { const duration = performance.now() - startTime; this._timing.total = duration; this._timingHistory = [ ...this._timingHistory, { startedAt: this._startedAt ?? Date.now(), ...this._timing }, ].slice(-100); this.context.log( 'debug', 'Query executed', this.key, `Duration: ${duration}ms`, ); }); return this._executionPromise; }; protected measureSweep = async (work: () => Promise): Promise => { const start = performance.now(); try { return await work(); } finally { this._timing.sweep = performance.now() - start; } }; protected measureHydration = async ( work: () => Promise, ): Promise => { const start = performance.now(); try { return await work(); } finally { this._timing.hydration = performance.now() - start; } }; getDiagnostic = (active: boolean): QueryDiagnostic => ({ key: this.key, startedAt: this._startedAt, collection: this.collection, type: this.type, status: this.status, active, result: getDiagnosticResult(this.current), timing: { ...this._timing }, runs: this._timingHistory.map((run) => ({ ...run })), }); protected abstract run(): Promise; [ON_ALL_UNSUBSCRIBED] = (handler: (query: BaseQuery) => void) => { this._allUnsubscribedHandler = handler; }; get __rawValue() { return this._rawValue; } }