// // Copyright 2022 DXOS.org // import { isNotUndefined } from 'effect/Predicate'; import { asyncTimeout, Event } from '@dxos/async'; import { Context } from '@dxos/context'; import { filterMatchObject } from '@dxos/echo-pipeline/filter'; import { type QueryAST } from '@dxos/echo-protocol'; import { type ObjectId } from '@dxos/echo-schema'; import { log } from '@dxos/log'; import type { QueryContext, QueryResultEntry, QueryRunOptions } from './query-result'; import { getTargetSpacesForQuery, isSimpleSelectionQuery } from './util'; import { type ItemsUpdatedEvent, type ObjectCore } from '../core-db'; import { type AnyLiveObject } from '../echo-handler'; import { prohibitSignalActions } from '../guarded-scope'; import { type EchoDatabaseImpl } from '../proxy-db'; export type GraphQueryContextParams = { // TODO(dmaretskyi): Make async. onStart: () => void; onStop: () => void; }; /** * Query data source. * Implemented by a space or a remote agent. * Each query has a separate instance. */ export interface QuerySource { // TODO(dmaretskyi): Update info? changed: Event; // TODO(dmaretskyi): Make async. open(): void; // TODO(dmaretskyi): Make async. close(): void; /** * Synchronous query. */ getResults(): QueryResultEntry[]; /** * One-shot query. */ run(query: QueryAST.Query): Promise; /** * Set the filter and trigger continuous updates. */ update(query: QueryAST.Query): void; } /** * Aggregates multiple query sources. */ export class GraphQueryContext implements QueryContext { private readonly _sources = new Set(); private _query?: QueryAST.Query = undefined; private _ctx?: Context = undefined; public changed = new Event(); constructor(private readonly _params: GraphQueryContextParams) {} get sources(): ReadonlySet { return this._sources; } start() { this._ctx = new Context(); this._params.onStart(); for (const source of this._sources) { if (this._query) { source.update(this._query); } // Subscribing after `update` means that we will intentionally skip any `changed` events generated by update. source.changed.on(this._ctx, () => { this.changed.emit(); }); } } stop() { void this._ctx?.dispose(); for (const source of this.sources) { source.close(); } this._params.onStop(); } getResults(): QueryResultEntry[] { if (!this._query) { return []; } return Array.from(this._sources).flatMap((source) => source.getResults()); } async run(query: QueryAST.Query, { timeout = 30_000 }: QueryRunOptions = {}): Promise { const runTasks = [...this._sources.values()].map(async (s) => { try { log('run query', { resolver: Object.getPrototypeOf(s).constructor.name }); const results = await asyncTimeout(s.run(query), timeout); log('run query results', { resolver: Object.getPrototypeOf(s).constructor.name, count: results.length }); return results; } catch (err) { log('run query error', { resolver: Object.getPrototypeOf(s).constructor.name, error: err }); throw err; } }); if (runTasks.length === 0) { return []; } const mergedResults = (await Promise.all(runTasks)).flatMap((r) => r ?? []); return mergedResults; } update(query: QueryAST.Query): void { this._query = query; for (const source of this._sources) { source.update(query); } } addQuerySource(querySource: QuerySource) { this._sources.add(querySource); if (this._ctx != null) { querySource.changed.on(this._ctx, () => { this.changed.emit(); }); } if (this._query) { querySource.update(this._query); } } } /** * Queries objects from the local working set. */ export class SpaceQuerySource implements QuerySource { public readonly changed = new Event(); private _ctx: Context = new Context(); private _query: QueryAST.Query | undefined = undefined; private _results?: QueryResultEntry>[] = undefined; constructor(private readonly _database: EchoDatabaseImpl) {} get spaceId() { return this._database.spaceId; } get spaceKey() { return this._database.spaceKey; } open(): void {} close() { this._results = undefined; void this._ctx.dispose().catch(() => {}); } private _onUpdate = (updateEvent: ItemsUpdatedEvent) => { if (!this._query) { return; } prohibitSignalActions(() => { // TODO(dmaretskyi): Could be optimized to recompute changed only to the relevant space. const changed = updateEvent.itemsUpdated.some(({ id: objectId }) => { const core = this._database.coreDatabase.getObjectCoreById(objectId, { load: false }); const trivial = isSimpleSelectionQuery(this._query!); if (!trivial) { return false; } const { filter, options } = trivial; return ( !this._results || this._results.find((result) => result.id === objectId) || (core && this._filterCore(core, filter, options)) ); }); if (changed) { this._results = undefined; this.changed.emit(); } }); }; async run(query: QueryAST.Query): Promise>[]> { if (!this._isValidSourceForQuery(query)) { return []; } const simple = isSimpleSelectionQuery(query); if (!simple) { return []; } const { filter, options } = simple; const results: QueryResultEntry>[] = []; if (isObjectIdFilter(filter)) { results.push( ...(await this._database._coreDatabase.batchLoadObjectCores((filter as QueryAST.FilterObject).id as ObjectId[])) .filter(isNotUndefined) .filter((core) => this._filterCore(core, filter, options)) .map((core) => this._mapCoreToResult(core)), ); } prohibitSignalActions(() => { results.push(...this._queryWorkingSet(filter, options)); }); // Dedup const map = new Map>>(); for (const result of results) { map.set(result.id, result); } return [...map.values()]; } getResults(): QueryResultEntry>[] { if (!this._query) { return []; } const trivial = isSimpleSelectionQuery(this._query); if (!trivial) { return []; } const { filter, options } = trivial; if (!this._results) { prohibitSignalActions(() => { this._results = this._queryWorkingSet(filter, options); }); } return this._results!; } update(query: QueryAST.Query): void { if (!this._isValidSourceForQuery(query)) { this._query = undefined; return; } void this._ctx.dispose().catch(() => {}); this._ctx = new Context(); this._query = query; this._database.coreDatabase._updateEvent.on(this._ctx, this._onUpdate); this._results = undefined; this.changed.emit(); } /** * Queries from already loaded objects. */ private _queryWorkingSet( filter: QueryAST.Filter, options: QueryAST.QueryOptions | undefined, ): QueryResultEntry>[] { const filteredCores = isObjectIdFilter(filter) ? (filter as QueryAST.FilterObject) .id!.map((id) => this._database.coreDatabase.getObjectCoreById(id, { load: true })) .filter(isNotUndefined) .filter((core) => this._filterCore(core, filter, options)) : this._database.coreDatabase.allObjectCores().filter((core) => this._filterCore(core, filter, options)); return filteredCores.map((core) => this._mapCoreToResult(core)); } private _isValidSourceForQuery(query: QueryAST.Query): boolean { const targetSpaces = getTargetSpacesForQuery(query); // Disabled by spaces filter. if (targetSpaces.length > 0 && !targetSpaces.includes(this.spaceId)) { return false; } return true; } private _mapCoreToResult(core: ObjectCore): QueryResultEntry> { return { id: core.id, spaceId: this.spaceId, spaceKey: this.spaceKey, object: this._database.getObjectById(core.id, { deleted: true }), resolution: { source: 'local', time: 0, }, }; } private _filterCore(core: ObjectCore, filter: QueryAST.Filter, options: QueryAST.QueryOptions | undefined): boolean { return ( filterCoreByDeletedFlag(core, options) && filterMatchObject(filter, { id: core.id, doc: core.getObjectStructure(), spaceId: this.spaceId, }) ); } } const isObjectIdFilter = (filter: QueryAST.Filter) => { return filter.type === 'object' && filter.id !== undefined && filter.id.length > 0; }; const filterCoreByDeletedFlag = (core: ObjectCore, options: QueryAST.QueryOptions | undefined): boolean => { switch (options?.deleted) { case undefined: case 'exclude': return !core.isDeleted(); case 'include': return true; case 'only': return core.isDeleted(); } };