import type { DbConnectionImpl } from './db_connection_impl.ts'; import { INTERNAL_REMOTE_MODULE } from './internal.ts'; import type { ErrorContextInterface, SubscriptionEventContextInterface, } from './event_context.ts'; import { EventEmitter } from './event_emitter.ts'; import type { UntypedRemoteModule } from './spacetime_module.ts'; import { isRowTypedQuery, toSql, type NamespacedQueryBuilder, type RowTypedQuery, } from '../lib/query.ts'; import type { UntypedSchemaDef } from '../lib/schema.ts'; export class SubscriptionBuilderImpl { #onApplied?: (ctx: SubscriptionEventContextInterface) => void = undefined; #onError?: (ctx: ErrorContextInterface) => void = undefined; constructor(private db: DbConnectionImpl) {} /** * Registers `callback` to run when this query is successfully added to our subscribed set, * I.e. when its `SubscriptionApplied` message is received. * * The database state exposed via the `&EventContext` argument * includes all the rows added to the client cache as a result of the new subscription. * * The event in the `&EventContext` argument is `Event::SubscribeApplied`. * * Multiple `on_applied` callbacks for the same query may coexist. * No mechanism for un-registering `on_applied` callbacks is exposed. * * @param cb - Callback to run when the subscription is applied. * @returns The current `SubscriptionBuilder` instance. */ onApplied( cb: (ctx: SubscriptionEventContextInterface) => void ): SubscriptionBuilderImpl { this.#onApplied = cb; return this; } /** * Registers `callback` to run when this query either: * - Fails to be added to our subscribed set. * - Is unexpectedly removed from our subscribed set. * * If the subscription had previously started and has been unexpectedly removed, * the database state exposed via the `&EventContext` argument contains no rows * from any subscriptions removed within the same error event. * As proposed, it must therefore contain no rows. * * The event in the `&EventContext` argument is `Event::SubscribeError`, * containing a dynamic error object with a human-readable description of the error * for diagnostic purposes. * * Multiple `on_error` callbacks for the same query may coexist. * No mechanism for un-registering `on_error` callbacks is exposed. * * @param cb - Callback to run when there is an error in subscription. * @returns The current `SubscriptionBuilder` instance. */ onError( cb: (ctx: ErrorContextInterface) => void ): SubscriptionBuilderImpl { this.#onError = cb; return this; } /** * Subscribe to a single query. The results of the query will be merged into the client * cache and deduplicated on the client. * * @param query_sql A `SQL` query to subscribe to. * * @example * * ```ts * const subscription = connection.subscriptionBuilder().onApplied(() => { * console.log("SDK client cache initialized."); * }).subscribe("SELECT * FROM User"); * * subscription.unsubscribe(); * ``` */ subscribe( query_sql: string | RowTypedQuery ): SubscriptionHandleImpl; subscribe( query_sql: Array> ): SubscriptionHandleImpl; /** * @param queryFn - Receives the query builder for all tables (root and namespaced), e.g. * `tables => tables.players.build()` or, for a submodule table, * `tables => tables.inventory.items.build()`. May return multiple queries as an array. */ subscribe( queryFn: ( tables: NamespacedQueryBuilder ) => RowTypedQuery | RowTypedQuery[] ): SubscriptionHandleImpl; subscribe( query_sql: | string | RowTypedQuery | Array> | ((tables: any) => RowTypedQuery | RowTypedQuery[]) ): SubscriptionHandleImpl { let queries: Array>; if (typeof query_sql === 'function') { const tables = this.db.getFromBuilder(); const result = query_sql(tables); queries = Array.isArray(result) ? result : [result]; } else { queries = Array.isArray(query_sql) ? query_sql : [query_sql]; } if (queries.length === 0) { throw new Error('Subscriptions must have at least one query'); } const queryStrings = queries.map(q => { if (typeof q === 'string') return q; if (isRowTypedQuery(q)) return toSql(q); throw new Error('Subscriptions must be SQL strings or typed queries'); }); return new SubscriptionHandleImpl( this.db, queryStrings, this.#onApplied, this.#onError ); } /** * Subscribes to all rows from all tables. * * This method is intended as a convenience * for applications where client-side memory use and network bandwidth are not concerns. * Applications where these resources are a constraint * should register more precise queries via `subscribe` * in order to replicate only the subset of data which the client needs to function. * * This method should not be combined with `subscribe` on the same `DbConnection`. * A connection may either `subscribe` to particular queries, * or `subscribeToAllTables`, but not both. * Attempting to call `subscribe` * on a `DbConnection` that has previously used `subscribeToAllTables`, * or vice versa, may misbehave in any number of ways, * including dropping subscriptions, corrupting the client cache, or throwing errors. * * Views that take arguments are left out, as there are no arguments to pass them. */ subscribeToAllTables(): void { const remoteModule = this.db[INTERNAL_REMOTE_MODULE](); const viewsWithArgs = new Set(remoteModule.viewsWithArgs); const queries = Object.values(remoteModule.tables) .filter(table => !viewsWithArgs.has(table.sourceName)) .map(table => `SELECT * FROM ${table.sourceName}`); this.subscribe(queries); } } export type SubscribeEvent = 'applied' | 'error' | 'end'; export type SubscriptionEntry = { handle: SubscriptionHandleImpl; emitter: EventEmitter; querySql: string[]; unsubscribeRequested?: boolean; }; export class SubscriptionManager { subscriptions: Map> = new Map(); } export class SubscriptionHandleImpl { #querySetId: number; #unsubscribeCalled: boolean = false; #endedState: boolean = false; #activeState: boolean = false; #emitter: EventEmitter void> = new EventEmitter(); constructor( private db: DbConnectionImpl, querySql: string[], onApplied?: (ctx: SubscriptionEventContextInterface) => void, onError?: (ctx: ErrorContextInterface, error: Error) => void ) { this.#emitter.on( 'applied', (ctx: SubscriptionEventContextInterface) => { this.#activeState = true; if (onApplied) { onApplied(ctx); } } ); this.#emitter.on( 'error', (ctx: ErrorContextInterface, error: Error) => { this.#activeState = false; this.#endedState = true; if (onError) { onError(ctx, error); } } ); this.#querySetId = this.db.registerSubscription( this, this.#emitter, querySql ); } /** @internal Rebind the retained handle to its replayed query set. */ rebindQuerySetId(querySetId: number): void { this.#querySetId = querySetId; } /** * Consumes self and issues an `Unsubscribe` message, * removing this query from the client's set of subscribed queries. * It is only valid to call this method if `is_active()` is `true`. */ unsubscribe(): void { if (this.#unsubscribeCalled) { throw new Error('Unsubscribe has already been called'); } this.#unsubscribeCalled = true; this.#emitter.on( 'end', (_ctx: SubscriptionEventContextInterface) => { this.#endedState = true; this.#activeState = false; } ); this.db.unregisterSubscription(this.#querySetId); } /** * Unsubscribes and also registers a callback to run upon success. * I.e. when an `UnsubscribeApplied` message is received. * * If `Unsubscribe` returns an error, * or if the `on_error` callback(s) are invoked before this subscription would end normally, * the `on_end` callback is not invoked. * * @param onEnd - Callback to run upon successful unsubscribe. */ unsubscribeThen( onEnd: (ctx: SubscriptionEventContextInterface) => void ): void { if (this.#endedState) { throw new Error('Subscription has already ended'); } if (this.#unsubscribeCalled) { throw new Error('Unsubscribe has already been called'); } this.#unsubscribeCalled = true; this.#emitter.on( 'end', (ctx: SubscriptionEventContextInterface) => { this.#endedState = true; this.#activeState = false; onEnd(ctx); } ); this.db.unregisterSubscription(this.#querySetId); } /** * True if this `SubscriptionHandle` has ended, * either due to an error or a call to `unsubscribe`. * * This is initially false, and becomes true when either the `on_end` or `on_error` callback is invoked. * A subscription which has not yet been applied is not active, but is also not ended. */ isEnded(): boolean { return this.#endedState; } /** * True if this `SubscriptionHandle` is active, meaning it has been successfully applied * and has not since ended, either due to an error or a complete `unsubscribe` request-response pair. * * This corresponds exactly to the interval bounded at the start by the `on_applied` callback * and at the end by either the `on_end` or `on_error` callback. */ isActive(): boolean { return this.#activeState; } }