import { EventEmitter } from './event_emitter.ts'; import { stdbLogger } from './logger.ts'; import { AlgebraicType, deepEqual, type ComparablePrimitive, } from '../index.ts'; import type { EventContextInterface, TableDefForTableName } from './index.ts'; import type { RowType, TableIndexes, UntypedTableDef } from '../lib/table.ts'; import type { ClientTableCoreImplementable } from './client_table.ts'; import type { UntypedRemoteModule } from './spacetime_module.ts'; import type { TableNamesOf } from '../lib/schema.ts'; import type { ReadonlyIndex, ReadonlyIndexes, ReadonlyRangedIndex, ReadonlyUniqueIndex, } from '../lib/indexes.ts'; import type { Range } from '../server/range.ts'; import type { Prettify } from '../lib/type_util.ts'; export type Operation< RowType extends Record = Record, > = { type: 'insert' | 'delete'; // For tables with a primary key, this is the primary key value, as a primitive or string. // Otherwise, it is an encoding of the full row. rowId: ComparablePrimitive; row: RowType; }; export type TableUpdate = { tableName: string; operations: Operation>[]; }; export type PendingCallback = { type: 'insert' | 'delete' | 'update'; table: string; cb: () => void; }; // Strict scalar compare for index term values. const scalarCompare = (x: any, y: any): number => { if (x === y) return 0; // Compare booleans/numbers/bigints/strings with JS ordering. return x < y ? -1 : 1; }; const isRange = (arg: any): arg is Range => arg && typeof arg === 'object' && 'from' in arg && 'to' in arg; const inRange = (value: unknown, range: Range): boolean => { const { from, to } = range; if (from.tag !== 'unbounded') { const c = scalarCompare(value, from.value); if (c < 0) return false; if (c === 0 && from.tag === 'excluded') return false; } if (to.tag !== 'unbounded') { const c = scalarCompare(value, to.value); if (c > 0) return false; if (c === 0 && to.tag === 'excluded') return false; } return true; }; type IndexNode = { rows: Map; // Created on the first child: the leaves (every node of a single-column // index) then carry one Map, not two. children: Map> | null; }; const newIndexNode = (): IndexNode => ({ rows: new Map(), children: null, }); type IndexEntry = { add(rowId: ComparablePrimitive, row: Row): void; remove(rowId: ComparablePrimitive, row: Row): void; }; export type TableIndexView< RemoteModule extends UntypedRemoteModule, TableName extends TableNamesOf, > = ReadonlyIndexes< TableDefForTableName, TableIndexes> >; export type TableCache< RemoteModule extends UntypedRemoteModule, TableName extends TableNamesOf, > = TableCacheImpl & TableIndexView; /** * Builder to generate calls to query a `table` in the database */ export class TableCacheImpl< RemoteModule extends UntypedRemoteModule, TableName extends TableNamesOf, > implements ClientTableCoreImplementable { private readonly hasPrimaryKey: boolean; private rows: Map< ComparablePrimitive, [RowType>, number] >; private tableDef: TableDefForTableName; // Only the indexes built so far (see `#makeReadonlyIndex`). #indexes: IndexEntry< RowType> >[] = []; private emitter: EventEmitter<'insert' | 'delete' | 'update'>; /** * @param name the table name * @param primaryKeyCol column index designated as `#[primarykey]` * @param primaryKey column name designated as `#[primarykey]` * @param entityClass the entityClass */ constructor(tableDef: TableDefForTableName) { this.tableDef = tableDef; this.rows = new Map(); this.emitter = new EventEmitter(); this.hasPrimaryKey = Object.values(this.tableDef.columns).some( col => col.columnMetadata.isPrimaryKey === true ); // Build index views from the resolved runtime index metadata. // // We intentionally use `resolvedIndexes` rather than `indexes`: // - `indexes` is declarative table-level config (`IndexOpts`) used mainly for typing. // - `resolvedIndexes` is the runtime shape (`UntypedIndex`) that includes both // field-level and explicit table-level indexes. for (const idxDef of this.tableDef.resolvedIndexes) { const index = this.#makeReadonlyIndex(this.tableDef, idxDef); // IMPORTANT: for duplicate accessor names, client cache uses assignment // semantics and later entries overwrite earlier ones. This matches prior // behavior and is intentionally different from server runtime merge logic. (this as any)[idxDef.name] = index; } } #makeReadonlyIndex< I extends TableDefForTableName< RemoteModule, TableName >['resolvedIndexes'][number], >( tableDef: TableDefForTableName, idx: I ): ReadonlyIndex, I> { type TableDef = TableDefForTableName; type Row = Prettify>; // We do not yet support non-btree indexes if (idx.algorithm !== 'btree') { throw new Error('Only btree indexes are supported in TableCacheImpl'); } const columns = idx.columns; const keyFns = columns.map(c => { const ty = tableDef.columns[c].typeBuilder.algebraicType; return (value: unknown) => AlgebraicType.intoMapKey(ty, value); }); const getCol = (row: RowType, i: number) => (row as Record)[columns[i]]; // An index is unique if it shares all columns with a unique constraint const isUnique = tableDef.constraints.some(constraint => { if (constraint.constraint !== 'unique') { return false; } return deepEqual(constraint.columns, idx.columns); }); // A unique single-column index is a flat key -> row map. const flat = isUnique && columns.length === 1 ? new Map() : null; // Each level of the tree is keyed by the next index column, and each node // holds every row whose key starts with the path leading to it. const root = newIndexNode(); const entry: IndexEntry = flat ? { add: (_rowId, row) => { flat.set(keyFns[0](getCol(row, 0)), row); }, remove: (_rowId, row) => { // Within one transaction the cache can add the new row of a key // before it removes the old one. Remove only the row stored here. const key = keyFns[0](getCol(row, 0)); if (flat.get(key) === row) flat.delete(key); }, } : { add: (rowId, row) => { let node = root; for (let i = 0; i < columns.length; i++) { const key = keyFns[i](getCol(row, i)); node.children ??= new Map(); let child = node.children.get(key); if (!child) { child = newIndexNode(); node.children.set(key, child); } child.rows.set(rowId, row); node = child; } }, remove: (rowId, row) => { let node = root; for (let i = 0; i < columns.length; i++) { const key = keyFns[i](getCol(row, i)); const child = node.children?.get(key); if (!child) return; child.rows.delete(rowId); if (child.rows.size === 0) { node.children!.delete(key); return; } node = child; } }, }; // The index is built on its first lookup, not at insert time: most // indexes of a subscribed table are never read, and building all of them // can take many times the heap of the rows themselves. let built = false; const build = () => { if (built) return; built = true; const start = Date.now(); for (const [rowId, [row]] of this.rows) entry.add(rowId, row as Row); this.#indexes.push(entry as IndexEntry>); stdbLogger( 'debug', () => `built index ${tableDef.sourceName}.${idx.name}: ${this.rows.size} rows, ${Date.now() - start} ms` ); }; const lookup = (prefix: readonly unknown[]): IndexNode | undefined => { build(); let node: IndexNode | undefined = root; for (let i = 0; i < prefix.length && node; i++) { node = node.children?.get(keyFns[i](prefix[i])); } return node; }; // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; if (isUnique) { const impl: ReadonlyUniqueIndex = { find: (colVal: any): Row | null => { // For unique btree, caller supplies the *full* key (tuple if multi-col). const key = Array.isArray(colVal) ? colVal : [colVal]; if (flat) { build(); return flat.get(keyFns[0](key[0])) ?? null; } return lookup(key)?.rows.values().next().value ?? null; }, }; return impl as ReadonlyIndex; } else { const impl: ReadonlyRangedIndex = { // The server’s ranged scan fixes all prefix cols to equality and applies // the bound only to the *last* provided term. We mirror that. *filter(range: any): IteratorObject { const arr = Array.isArray(range) ? range : [range]; const last = arr[arr.length - 1]; if (!isRange(last)) { const node = lookup(arr); if (node) yield* node.rows.values(); return; } const candidates = arr.length === 1 ? self.iter() : (lookup(arr.slice(0, -1))?.rows.values() ?? []); for (const row of candidates) { if (inRange(getCol(row, arr.length - 1), last)) yield row; } }, }; return impl as ReadonlyIndex; } } /** * @returns number of rows in the table */ count(): bigint { return BigInt(this.rows.size); } /** * @returns The values of the rows in the table */ iter(): IteratorObject< Prettify>>, undefined > { function* generator( rows: Map< ComparablePrimitive, [RowType>, number] > ): IteratorObject< Prettify>>, undefined > { for (const [row] of rows.values()) { yield row as Prettify< RowType> >; } } return generator(this.rows); } /** * Allows iteration over the rows in the table * @returns An iterator over the rows in the table */ [Symbol.iterator](): IteratorObject< Prettify>>, undefined > { return this.iter(); } /** Delete every cached reference, including overlaps between subscriptions. */ snapshotDeleteOperations = (): Operation< RowType> >[] => { const operations: Operation< RowType> >[] = []; for (const [rowId, [row, refCount]] of this.rows) { for (let i = 0; i < refCount; i++) { operations.push({ type: 'delete', rowId, row }); } } return operations; }; applyOperations = ( operations: Operation< RowType> >[], ctx: EventContextInterface, options?: { /** Suppress unchanged rows during reconnect reconciliation. */ skipIdenticalUpdates?: boolean; } ): PendingCallback[] => { const pendingCallbacks: PendingCallback[] = []; // Event tables: fire on_insert callbacks but don't store rows in the cache. if (this.tableDef.isEvent) { for (const op of operations) { if (op.type === 'insert') { pendingCallbacks.push({ type: 'insert', table: this.tableDef.sourceName, cb: () => { this.emitter.emit('insert', ctx, op.row); }, }); } } return pendingCallbacks; } if (this.hasPrimaryKey || options?.skipIdenticalUpdates) { const insertMap = new Map< ComparablePrimitive, [ Operation>>, number, ] >(); const deleteMap = new Map< ComparablePrimitive, [ Operation>>, number, ] >(); for (const op of operations) { if (op.type === 'insert') { const [_, prevCount] = insertMap.get(op.rowId) || [op, 0]; insertMap.set(op.rowId, [op, prevCount + 1]); } else { const [_, prevCount] = deleteMap.get(op.rowId) || [op, 0]; deleteMap.set(op.rowId, [op, prevCount + 1]); } } for (const [primaryKey, [insertOp, refCount]] of insertMap) { const deleteEntry = deleteMap.get(primaryKey); if (deleteEntry) { const [_, deleteCount] = deleteEntry; // In most cases the refCountDelta will be either 0 or refCount, but if // an update moves a row in or out of the result set of different queries, then // other deltas are possible. const refCountDelta = refCount - deleteCount; const maybeCb = this.update( ctx, primaryKey, insertOp.row, refCountDelta, options?.skipIdenticalUpdates ); if (maybeCb) { pendingCallbacks.push(maybeCb); } deleteMap.delete(primaryKey); } else { const maybeCb = this.insert(ctx, insertOp, refCount); if (maybeCb) { pendingCallbacks.push(maybeCb); } } } for (const [deleteOp, refCount] of deleteMap.values()) { const maybeCb = this.delete(ctx, deleteOp, refCount); if (maybeCb) { pendingCallbacks.push(maybeCb); } } } else { for (const op of operations) { if (op.type === 'insert') { const maybeCb = this.insert(ctx, op); if (maybeCb) { pendingCallbacks.push(maybeCb); } } else { const maybeCb = this.delete(ctx, op); if (maybeCb) { pendingCallbacks.push(maybeCb); } } } } return pendingCallbacks; }; update = ( ctx: EventContextInterface, rowId: ComparablePrimitive, newRow: RowType>, refCountDelta: number = 0, skipIfIdentical: boolean = false ): PendingCallback | undefined => { const existingEntry = this.rows.get(rowId); if (!existingEntry) { // TODO: this should throw an error and kill the connection. stdbLogger( 'error', `Updating a row that was not present in the cache. Table: ${this.tableDef.sourceName}, RowId: ${rowId}` ); return undefined; } const [oldRow, previousCount] = existingEntry; const refCount = Math.max(1, previousCount + refCountDelta); if (previousCount + refCountDelta <= 0) { stdbLogger( 'error', `Negative reference count for in table ${this.tableDef.sourceName} row ${rowId} (${previousCount} + ${refCountDelta})` ); return undefined; } this.#setRow(rowId, newRow, refCount); if (skipIfIdentical && deepEqual(oldRow, newRow)) { // The row is unchanged; the reference count was adjusted above but no // callback fires. return undefined; } // This indicates something is wrong, so we could arguably crash here. if (previousCount === 0) { stdbLogger( 'error', `Updating a row id in table ${this.tableDef.sourceName} which was not present in the cache (rowId: ${rowId})` ); return { type: 'insert', table: this.tableDef.sourceName, cb: () => { this.emitter.emit('insert', ctx, newRow); }, }; } return { type: 'update', table: this.tableDef.sourceName, cb: () => { this.emitter.emit('update', ctx, oldRow, newRow); }, }; }; insert = ( ctx: EventContextInterface, operation: Operation< RowType> >, count: number = 1 ): PendingCallback | undefined => { const [existingRow, previousCount] = this.rows.get(operation.rowId) || [ operation.row, 0, ]; if (previousCount === 0) { this.#setRow(operation.rowId, operation.row, count); return { type: 'insert', table: this.tableDef.sourceName, cb: () => { this.emitter.emit('insert', ctx, operation.row); }, }; } // It's possible to get a duplicate insert because rows can be returned from multiple queries. this.rows.set(operation.rowId, [existingRow, previousCount + count]); return undefined; }; delete = ( ctx: EventContextInterface, operation: Operation< RowType> >, count: number = 1 ): PendingCallback | undefined => { const [existingRow, previousCount] = this.rows.get(operation.rowId) || [ operation.row, 0, ]; // This should never happen. if (previousCount === 0) { stdbLogger('warn', 'Deleting a row that was not present in the cache'); return undefined; } // If this was the last reference, we are actually deleting the row. if (previousCount <= count) { // TODO: Log a warning/error if previousCount is less than count. this.#deleteRow(operation.rowId); return { type: 'delete', table: this.tableDef.sourceName, cb: () => { this.emitter.emit('delete', ctx, operation.row); }, }; } this.rows.set(operation.rowId, [existingRow, previousCount - count]); return undefined; }; #setRow( rowId: ComparablePrimitive, row: RowType>, refCount: number ): void { const existing = this.rows.get(rowId); if (existing) { for (const index of this.#indexes) index.remove(rowId, existing[0]); } this.rows.set(rowId, [row, refCount]); for (const index of this.#indexes) index.add(rowId, row); } #deleteRow(rowId: ComparablePrimitive): void { const existing = this.rows.get(rowId); if (!existing) return; for (const index of this.#indexes) index.remove(rowId, existing[0]); this.rows.delete(rowId); } /** * Register a callback for when a row is newly inserted into the database. * * ```ts * ctx.db.user.onInsert((reducerEvent, user) => { * if (reducerEvent) { * console.log("New user on reducer", reducerEvent, user); * } else { * console.log("New user received during subscription update on insert", user); * } * }); * ``` * * @param cb Callback to be called when a new row is inserted */ onInsert = ( cb: ( ctx: EventContextInterface, row: Prettify>> ) => void ): void => { this.emitter.on('insert', cb); }; /** * Register a callback for when a row is deleted from the database. * * ```ts * ctx.db.user.onDelete((reducerEvent, user) => { * if (reducerEvent) { * console.log("Deleted user on reducer", reducerEvent, user); * } else { * console.log("Deleted user received during subscription update on update", user); * } * }); * ``` * * @param cb Callback to be called when a new row is inserted */ onDelete = ( cb: ( ctx: EventContextInterface, row: Prettify>> ) => void ): void => { this.emitter.on('delete', cb); }; /** * Register a callback for when a row is updated into the database. * * ```ts * ctx.db.user.onInsert((reducerEvent, oldUser, user) => { * if (reducerEvent) { * console.log("Updated user on reducer", reducerEvent, user); * } else { * console.log("Updated user received during subscription update on delete", user); * } * }); * ``` * * @param cb Callback to be called when a new row is inserted */ onUpdate = ( cb: ( ctx: EventContextInterface, oldRow: Prettify>>, row: Prettify>> ) => void ): void => { this.emitter.on('update', cb); }; /** * Remove a callback for when a row is newly inserted into the database. * * @param cb Callback to be removed */ removeOnInsert = ( cb: ( ctx: EventContextInterface, row: Prettify>> ) => void ): void => { this.emitter.off('insert', cb); }; /** * Remove a callback for when a row is deleted from the database. * * @param cb Callback to be removed */ removeOnDelete = ( cb: ( ctx: EventContextInterface, row: Prettify>> ) => void ): void => { this.emitter.off('delete', cb); }; /** * Remove a callback for when a row is updated into the database. * * @param cb Callback to be removed */ removeOnUpdate = ( cb: ( ctx: EventContextInterface, oldRow: Prettify>>, row: Prettify>> ) => void ): void => { this.emitter.off('update', cb); }; }