@dxos/echo-pipeline 0.8.4-main.a4bbb77 → 0.8.4-main.abd8ff62ef
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/{browser/chunk-XGG76KKU.mjs → neutral/chunk-VIHYDCCC.mjs} +404 -963
- package/dist/lib/neutral/chunk-VIHYDCCC.mjs.map +7 -0
- package/dist/lib/{browser/chunk-BVR7OOZK.mjs → neutral/chunk-YBC6ONBZ.mjs} +23 -27
- package/dist/lib/neutral/chunk-YBC6ONBZ.mjs.map +7 -0
- package/dist/lib/{browser → neutral}/filter/index.mjs +1 -2
- package/dist/lib/{browser → neutral}/index.mjs +3143 -2206
- package/dist/lib/neutral/index.mjs.map +7 -0
- package/dist/lib/neutral/meta.json +1 -0
- package/dist/lib/{browser → neutral}/testing/index.mjs +103 -395
- package/dist/lib/neutral/testing/index.mjs.map +7 -0
- package/dist/types/src/automerge/automerge-host.d.ts +43 -23
- package/dist/types/src/automerge/automerge-host.d.ts.map +1 -1
- package/dist/types/src/automerge/automerge-repo.test.d.ts +1 -1
- package/dist/types/src/automerge/automerge-repo.test.d.ts.map +1 -1
- package/dist/types/src/automerge/collection-synchronizer.d.ts +5 -3
- package/dist/types/src/automerge/collection-synchronizer.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-data-monitor.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-network-adapter.d.ts +17 -11
- package/dist/types/src/automerge/echo-network-adapter.d.ts.map +1 -1
- package/dist/types/src/automerge/echo-replicator.d.ts +20 -16
- package/dist/types/src/automerge/echo-replicator.d.ts.map +1 -1
- package/dist/types/src/automerge/heads-store.d.ts +9 -2
- package/dist/types/src/automerge/heads-store.d.ts.map +1 -1
- package/dist/types/src/automerge/leveldb-storage-adapter.d.ts +4 -4
- package/dist/types/src/automerge/leveldb-storage-adapter.d.ts.map +1 -1
- package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts +8 -8
- package/dist/types/src/automerge/mesh-echo-replicator-connection.d.ts.map +1 -1
- package/dist/types/src/automerge/mesh-echo-replicator.d.ts +6 -5
- package/dist/types/src/automerge/mesh-echo-replicator.d.ts.map +1 -1
- package/dist/types/src/automerge/network-protocol.d.ts.map +1 -1
- package/dist/types/src/automerge/space-collection.d.ts.map +1 -1
- package/dist/types/src/common/feeds.d.ts.map +1 -1
- package/dist/types/src/common/space-id.d.ts.map +1 -1
- package/dist/types/src/db-host/automerge-data-source.d.ts +35 -0
- package/dist/types/src/db-host/automerge-data-source.d.ts.map +1 -0
- package/dist/types/src/db-host/automerge-data-source.test.d.ts +2 -0
- package/dist/types/src/db-host/automerge-data-source.test.d.ts.map +1 -0
- package/dist/types/src/db-host/automerge-metrics.d.ts.map +1 -1
- package/dist/types/src/db-host/data-service.d.ts +7 -6
- package/dist/types/src/db-host/data-service.d.ts.map +1 -1
- package/dist/types/src/db-host/database-root.d.ts.map +1 -1
- package/dist/types/src/db-host/documents-synchronizer.d.ts +8 -7
- package/dist/types/src/db-host/documents-synchronizer.d.ts.map +1 -1
- package/dist/types/src/db-host/echo-host.d.ts +58 -28
- package/dist/types/src/db-host/echo-host.d.ts.map +1 -1
- package/dist/types/src/db-host/index.d.ts +2 -0
- package/dist/types/src/db-host/index.d.ts.map +1 -1
- package/dist/types/src/db-host/invalidation-hint.d.ts +19 -0
- package/dist/types/src/db-host/invalidation-hint.d.ts.map +1 -0
- package/dist/types/src/db-host/local-queue-service.d.ts +19 -0
- package/dist/types/src/db-host/local-queue-service.d.ts.map +1 -0
- package/dist/types/src/db-host/query-invalidation.test.d.ts +2 -0
- package/dist/types/src/db-host/query-invalidation.test.d.ts.map +1 -0
- package/dist/types/src/db-host/query-service.d.ts +18 -10
- package/dist/types/src/db-host/query-service.d.ts.map +1 -1
- package/dist/types/src/db-host/queue-data-source.d.ts +38 -0
- package/dist/types/src/db-host/queue-data-source.d.ts.map +1 -0
- package/dist/types/src/db-host/queue-service.test.d.ts +2 -0
- package/dist/types/src/db-host/queue-service.test.d.ts.map +1 -0
- package/dist/types/src/db-host/space-state-manager.d.ts +1 -0
- package/dist/types/src/db-host/space-state-manager.d.ts.map +1 -1
- package/dist/types/src/db-host/stub.d.ts +11 -0
- package/dist/types/src/db-host/stub.d.ts.map +1 -0
- package/dist/types/src/edge/echo-edge-replicator.d.ts +7 -6
- package/dist/types/src/edge/echo-edge-replicator.d.ts.map +1 -1
- package/dist/types/src/edge/inflight-request-limiter.d.ts.map +1 -1
- package/dist/types/src/filter/filter-match.d.ts +2 -2
- package/dist/types/src/filter/filter-match.d.ts.map +1 -1
- package/dist/types/src/metadata/metadata-store.d.ts.map +1 -1
- package/dist/types/src/pipeline/message-selector.d.ts.map +1 -1
- package/dist/types/src/pipeline/pipeline.d.ts +2 -2
- package/dist/types/src/pipeline/pipeline.d.ts.map +1 -1
- package/dist/types/src/pipeline/timeframe-clock.d.ts.map +1 -1
- package/dist/types/src/query/errors.d.ts +16 -20
- package/dist/types/src/query/errors.d.ts.map +1 -1
- package/dist/types/src/query/plan.d.ts +59 -8
- package/dist/types/src/query/plan.d.ts.map +1 -1
- package/dist/types/src/query/query-executor.d.ts +62 -10
- package/dist/types/src/query/query-executor.d.ts.map +1 -1
- package/dist/types/src/query/query-planner.d.ts +10 -1
- package/dist/types/src/query/query-planner.d.ts.map +1 -1
- package/dist/types/src/space/admission-discovery-extension.d.ts.map +1 -1
- package/dist/types/src/space/auth.d.ts +3 -3
- package/dist/types/src/space/auth.d.ts.map +1 -1
- package/dist/types/src/space/control-pipeline.d.ts +4 -3
- package/dist/types/src/space/control-pipeline.d.ts.map +1 -1
- package/dist/types/src/space/space-manager.d.ts +7 -7
- package/dist/types/src/space/space-manager.d.ts.map +1 -1
- package/dist/types/src/space/space-protocol.d.ts +9 -8
- package/dist/types/src/space/space-protocol.d.ts.map +1 -1
- package/dist/types/src/space/space.d.ts +5 -5
- package/dist/types/src/space/space.d.ts.map +1 -1
- package/dist/types/src/testing/change-metadata.d.ts.map +1 -1
- package/dist/types/src/testing/index.d.ts +0 -2
- package/dist/types/src/testing/index.d.ts.map +1 -1
- package/dist/types/src/testing/test-agent-builder.d.ts.map +1 -1
- package/dist/types/src/testing/test-feed-builder.d.ts.map +1 -1
- package/dist/types/src/testing/test-network-adapter.d.ts +1 -1
- package/dist/types/src/testing/test-network-adapter.d.ts.map +1 -1
- package/dist/types/src/testing/test-replicator.d.ts +13 -13
- package/dist/types/src/testing/test-replicator.d.ts.map +1 -1
- package/dist/types/src/util.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +51 -54
- package/src/automerge/automerge-host.test.ts +42 -23
- package/src/automerge/automerge-host.ts +163 -88
- package/src/automerge/automerge-repo.test.ts +149 -32
- package/src/automerge/collection-synchronizer.test.ts +19 -13
- package/src/automerge/collection-synchronizer.ts +69 -28
- package/src/automerge/echo-network-adapter.test.ts +2 -1
- package/src/automerge/echo-network-adapter.ts +40 -29
- package/src/automerge/echo-replicator.ts +21 -16
- package/src/automerge/heads-store.ts +42 -3
- package/src/automerge/leveldb-storage-adapter.ts +4 -4
- package/src/automerge/mesh-echo-replicator-connection.ts +8 -8
- package/src/automerge/mesh-echo-replicator.ts +14 -11
- package/src/db-host/automerge-data-source.test.ts +299 -0
- package/src/db-host/automerge-data-source.ts +186 -0
- package/src/db-host/data-service.ts +17 -10
- package/src/db-host/documents-synchronizer.test.ts +143 -14
- package/src/db-host/documents-synchronizer.ts +54 -51
- package/src/db-host/echo-host.ts +321 -86
- package/src/db-host/index.ts +2 -0
- package/src/db-host/invalidation-hint.ts +50 -0
- package/src/db-host/local-queue-service.ts +127 -0
- package/src/db-host/query-invalidation.test.ts +270 -0
- package/src/db-host/query-service.ts +110 -112
- package/src/db-host/queue-data-source.ts +159 -0
- package/src/db-host/queue-service.test.ts +145 -0
- package/src/db-host/space-state-manager.ts +5 -1
- package/src/db-host/stub.ts +33 -0
- package/src/edge/echo-edge-replicator.test.ts +9 -9
- package/src/edge/echo-edge-replicator.ts +76 -47
- package/src/filter/filter-match.test.ts +41 -25
- package/src/filter/filter-match.ts +33 -36
- package/src/metadata/metadata-store.ts +8 -5
- package/src/pipeline/pipeline-stress.test.ts +1 -3
- package/src/pipeline/pipeline.test.ts +0 -1
- package/src/pipeline/pipeline.ts +2 -3
- package/src/query/errors.ts +2 -2
- package/src/query/plan.ts +71 -8
- package/src/query/query-executor.ts +1170 -197
- package/src/query/query-planner.test.ts +854 -86
- package/src/query/query-planner.ts +408 -38
- package/src/space/admission-discovery-extension.ts +1 -1
- package/src/space/auth.ts +6 -6
- package/src/space/control-pipeline.test.ts +2 -2
- package/src/space/control-pipeline.ts +7 -7
- package/src/space/space-manager.ts +12 -17
- package/src/space/space-protocol.browser.test.ts +13 -12
- package/src/space/space-protocol.test.ts +13 -13
- package/src/space/space-protocol.ts +16 -15
- package/src/space/space.test.ts +2 -2
- package/src/space/space.ts +9 -10
- package/src/testing/index.ts +0 -2
- package/src/testing/test-agent-builder.ts +0 -1
- package/src/testing/test-network-adapter.ts +16 -3
- package/src/testing/test-replicator.ts +19 -18
- package/src/util.ts +7 -3
- package/dist/lib/browser/chunk-BVR7OOZK.mjs.map +0 -7
- package/dist/lib/browser/chunk-CGS2ULMK.mjs +0 -11
- package/dist/lib/browser/chunk-CGS2ULMK.mjs.map +0 -7
- package/dist/lib/browser/chunk-XGG76KKU.mjs.map +0 -7
- package/dist/lib/browser/index.mjs.map +0 -7
- package/dist/lib/browser/meta.json +0 -1
- package/dist/lib/browser/testing/index.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs +0 -2230
- package/dist/lib/node-esm/chunk-CHMJJ4DG.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-HSLMI22Q.mjs +0 -11
- package/dist/lib/node-esm/chunk-HSLMI22Q.mjs.map +0 -7
- package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs +0 -251
- package/dist/lib/node-esm/chunk-L3ZEKVDR.mjs.map +0 -7
- package/dist/lib/node-esm/filter/index.mjs +0 -13
- package/dist/lib/node-esm/filter/index.mjs.map +0 -7
- package/dist/lib/node-esm/index.mjs +0 -5560
- package/dist/lib/node-esm/index.mjs.map +0 -7
- package/dist/lib/node-esm/meta.json +0 -1
- package/dist/lib/node-esm/testing/index.mjs +0 -805
- package/dist/lib/node-esm/testing/index.mjs.map +0 -7
- package/dist/types/src/db-host/documents-iterator.d.ts +0 -7
- package/dist/types/src/db-host/documents-iterator.d.ts.map +0 -1
- package/dist/types/src/testing/test-data.d.ts +0 -18
- package/dist/types/src/testing/test-data.d.ts.map +0 -1
- package/dist/types/src/testing/test-schema.d.ts +0 -37
- package/dist/types/src/testing/test-schema.d.ts.map +0 -1
- package/src/db-host/documents-iterator.ts +0 -74
- package/src/testing/test-data.ts +0 -127
- package/src/testing/test-schema.ts +0 -53
- /package/dist/lib/{browser → neutral}/filter/index.mjs.map +0 -0
|
@@ -3,30 +3,39 @@
|
|
|
3
3
|
//
|
|
4
4
|
|
|
5
5
|
import type { AutomergeUrl, DocumentId } from '@automerge/automerge-repo';
|
|
6
|
-
import
|
|
7
|
-
|
|
8
|
-
import
|
|
9
|
-
|
|
10
|
-
import {
|
|
6
|
+
import type * as SqlClient from '@effect/sql/SqlClient';
|
|
7
|
+
import type * as Effect from 'effect/Effect';
|
|
8
|
+
import * as Runtime from 'effect/Runtime';
|
|
9
|
+
|
|
10
|
+
import { ContextDisposedError, LifecycleState, Resource } from '@dxos/context';
|
|
11
|
+
import { type Obj, Query } from '@dxos/echo';
|
|
12
|
+
import {
|
|
13
|
+
DatabaseDirectory,
|
|
14
|
+
EncodedReference,
|
|
15
|
+
type ObjectPropPath,
|
|
16
|
+
ObjectStructure,
|
|
17
|
+
type QueryAST,
|
|
18
|
+
isEncodedReference,
|
|
19
|
+
} from '@dxos/echo-protocol';
|
|
20
|
+
import { ATTR_PARENT, ATTR_RELATION_SOURCE, ATTR_RELATION_TARGET } from '@dxos/echo/internal';
|
|
21
|
+
import { type RuntimeProvider, runAndForwardErrors, unwrapExit } from '@dxos/effect';
|
|
22
|
+
import { EscapedPropPath, type IndexEngine, type ObjectMeta, type ReverseRef } from '@dxos/index-core';
|
|
11
23
|
import { invariant } from '@dxos/invariant';
|
|
12
|
-
import { DXN, type ObjectId,
|
|
24
|
+
import { DXN, type ObjectId, type SpaceId } from '@dxos/keys';
|
|
13
25
|
import { log } from '@dxos/log';
|
|
14
|
-
import { objectPointerCodec } from '@dxos/protocols';
|
|
15
26
|
import { type QueryReactivity, type QueryResult } from '@dxos/protocols/proto/dxos/echo/query';
|
|
16
|
-
import { getDeep, isNonNullable } from '@dxos/util';
|
|
27
|
+
import { compositeKey, getDeep, isNonNullable } from '@dxos/util';
|
|
17
28
|
|
|
18
29
|
import type { AutomergeHost } from '../automerge';
|
|
19
|
-
import {
|
|
20
|
-
import
|
|
21
|
-
import {
|
|
22
|
-
|
|
30
|
+
import type { InvalidationHint, SpaceStateManager } from '../db-host';
|
|
31
|
+
import { filterMatchObject, filterMatchObjectJSON } from '../filter';
|
|
32
|
+
import { QueryError } from './errors';
|
|
23
33
|
import type { QueryPlan } from './plan';
|
|
24
34
|
import { QueryPlanner } from './query-planner';
|
|
25
35
|
|
|
26
|
-
const isNullable: Predicate.Refinement<unknown, null | undefined> = Predicate.isNullable;
|
|
27
|
-
|
|
28
36
|
type QueryExecutorOptions = {
|
|
29
|
-
|
|
37
|
+
indexEngine: IndexEngine;
|
|
38
|
+
runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;
|
|
30
39
|
automergeHost: AutomergeHost;
|
|
31
40
|
spaceStateManager: SpaceStateManager;
|
|
32
41
|
|
|
@@ -47,11 +56,84 @@ type QueryExecutionResult = {
|
|
|
47
56
|
*/
|
|
48
57
|
type QueryItem = {
|
|
49
58
|
objectId: ObjectId;
|
|
50
|
-
|
|
59
|
+
|
|
51
60
|
spaceId: SpaceId;
|
|
52
|
-
|
|
61
|
+
queueId: ObjectId | null;
|
|
62
|
+
queueNamespace: string | null;
|
|
63
|
+
|
|
64
|
+
// For objects from automerge documents.
|
|
65
|
+
documentId: DocumentId | null;
|
|
66
|
+
|
|
67
|
+
// For objects from automerge documents.
|
|
68
|
+
doc: ObjectStructure | null;
|
|
69
|
+
|
|
70
|
+
// For objects from queues.
|
|
71
|
+
data: Obj.JSON | null;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Relevance rank for this item.
|
|
75
|
+
* Higher values indicate better matches for FTS/vector searches.
|
|
76
|
+
* Defaults to 1 for non-ranked queries (predicate matches).
|
|
77
|
+
*/
|
|
78
|
+
rank: number;
|
|
53
79
|
};
|
|
54
80
|
|
|
81
|
+
const QueryItem = Object.freeze({
|
|
82
|
+
/**
|
|
83
|
+
* Checks if the item is deleted.
|
|
84
|
+
* Only applies to this item, not its parents.
|
|
85
|
+
*/
|
|
86
|
+
isDeleted: (item: QueryItem) => {
|
|
87
|
+
if (item.doc) {
|
|
88
|
+
return ObjectStructure.isDeleted(item.doc);
|
|
89
|
+
} else if (item.data) {
|
|
90
|
+
return item.data['@deleted'] === true;
|
|
91
|
+
} else {
|
|
92
|
+
throw new Error('Invalid query item');
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
getProperty: (item: QueryItem, property: ObjectPropPath) => {
|
|
97
|
+
if (item.doc) {
|
|
98
|
+
return getDeep(item.doc.data, property);
|
|
99
|
+
} else if (item.data) {
|
|
100
|
+
return getDeep(item.data, property);
|
|
101
|
+
} else {
|
|
102
|
+
throw new Error('Invalid query item');
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
|
|
106
|
+
getParent: (item: QueryItem): DXN.String | undefined => {
|
|
107
|
+
if (item.doc) {
|
|
108
|
+
return ObjectStructure.getParent(item.doc)?.['/'] as DXN.String | undefined;
|
|
109
|
+
} else if (item.data) {
|
|
110
|
+
return item.data[ATTR_PARENT] as DXN.String;
|
|
111
|
+
} else {
|
|
112
|
+
throw new Error('Invalid query item');
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
|
|
116
|
+
getRelationSource: (item: QueryItem): DXN.String | undefined => {
|
|
117
|
+
if (item.doc) {
|
|
118
|
+
return ObjectStructure.getRelationSource(item.doc)?.['/'] as DXN.String | undefined;
|
|
119
|
+
} else if (item.data) {
|
|
120
|
+
return item.data[ATTR_RELATION_SOURCE] as DXN.String;
|
|
121
|
+
} else {
|
|
122
|
+
throw new Error('Invalid query item');
|
|
123
|
+
}
|
|
124
|
+
},
|
|
125
|
+
|
|
126
|
+
getRelationTarget: (item: QueryItem): DXN.String | undefined => {
|
|
127
|
+
if (item.doc) {
|
|
128
|
+
return ObjectStructure.getRelationTarget(item.doc)?.['/'] as DXN.String | undefined;
|
|
129
|
+
} else if (item.data) {
|
|
130
|
+
return item.data[ATTR_RELATION_TARGET] as DXN.String;
|
|
131
|
+
} else {
|
|
132
|
+
throw new Error('Invalid query item');
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
});
|
|
136
|
+
|
|
55
137
|
/**
|
|
56
138
|
* Recursive data structure that represents the execution trace of a query.
|
|
57
139
|
*/
|
|
@@ -63,6 +145,9 @@ export type ExecutionTrace = {
|
|
|
63
145
|
documentsLoaded: number;
|
|
64
146
|
indexHits: number;
|
|
65
147
|
|
|
148
|
+
beginTs: number;
|
|
149
|
+
endTs: number;
|
|
150
|
+
|
|
66
151
|
executionTime: number;
|
|
67
152
|
indexQueryTime: number;
|
|
68
153
|
documentLoadTime: number;
|
|
@@ -77,11 +162,42 @@ export const ExecutionTrace = Object.freeze({
|
|
|
77
162
|
objectCount: 0,
|
|
78
163
|
documentsLoaded: 0,
|
|
79
164
|
indexHits: 0,
|
|
165
|
+
beginTs: 0,
|
|
166
|
+
endTs: 0,
|
|
80
167
|
indexQueryTime: 0,
|
|
81
168
|
documentLoadTime: 0,
|
|
82
169
|
executionTime: 0,
|
|
83
170
|
children: [],
|
|
84
171
|
}),
|
|
172
|
+
markEnd: (trace: ExecutionTrace) => {
|
|
173
|
+
trace.endTs = performance.now();
|
|
174
|
+
trace.executionTime = trace.endTs - trace.beginTs;
|
|
175
|
+
},
|
|
176
|
+
putOnPerformanceTimeline: (trace: ExecutionTrace) => {
|
|
177
|
+
performance.measure(trace.name, {
|
|
178
|
+
start: trace.beginTs,
|
|
179
|
+
end: trace.endTs,
|
|
180
|
+
detail: {
|
|
181
|
+
devtools: {
|
|
182
|
+
dataType: 'track-entry',
|
|
183
|
+
track: 'Query Execution',
|
|
184
|
+
trackGroup: 'ECHO', // Group related tracks together
|
|
185
|
+
color: 'tertiary-dark',
|
|
186
|
+
properties: [
|
|
187
|
+
['objectCount', trace.objectCount],
|
|
188
|
+
['documentsLoaded', trace.documentsLoaded],
|
|
189
|
+
['index hits', trace.indexHits],
|
|
190
|
+
['indexQueryTime', trace.indexQueryTime],
|
|
191
|
+
['documentLoadTime', trace.documentLoadTime],
|
|
192
|
+
],
|
|
193
|
+
tooltipText: trace.details,
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
});
|
|
197
|
+
for (const child of trace.children) {
|
|
198
|
+
ExecutionTrace.putOnPerformanceTimeline(child);
|
|
199
|
+
}
|
|
200
|
+
},
|
|
85
201
|
format: (trace: ExecutionTrace): string => {
|
|
86
202
|
const go = (trace: ExecutionTrace, indent: number): string => {
|
|
87
203
|
return [
|
|
@@ -100,10 +216,167 @@ type StepExecutionResult = {
|
|
|
100
216
|
trace: ExecutionTrace;
|
|
101
217
|
};
|
|
102
218
|
|
|
103
|
-
|
|
219
|
+
declare global {
|
|
220
|
+
interface ImportMeta {
|
|
221
|
+
env: ImportMetaEnv;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
interface ImportMetaEnv {
|
|
225
|
+
DX_TRACE_QUERY_EXECUTION: string;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const TRACE_QUERY_EXECUTION = !!import.meta.env.DX_TRACE_QUERY_EXECUTION;
|
|
230
|
+
|
|
231
|
+
const MAX_DEPTH_FOR_DELETION_TRACING = 10;
|
|
232
|
+
const MAX_DEPTH_FOR_CHILD_OF_TRACING = 10;
|
|
104
233
|
|
|
105
234
|
/**
|
|
106
|
-
*
|
|
235
|
+
* Cached scope constraints extracted from a query plan.
|
|
236
|
+
* Used to quickly determine whether an invalidation hint can affect this query.
|
|
237
|
+
*
|
|
238
|
+
* A null dimension means the query is unconstrained on that dimension (matches any value).
|
|
239
|
+
*/
|
|
240
|
+
type QueryScopes = {
|
|
241
|
+
/**
|
|
242
|
+
* False for text-search, traversal, union, set-difference, or child-of queries.
|
|
243
|
+
* When false, matchesHint always returns true (conservative: always re-execute).
|
|
244
|
+
*/
|
|
245
|
+
isSimple: boolean;
|
|
246
|
+
spaceIds: Set<SpaceId> | null;
|
|
247
|
+
queueIds: Set<ObjectId> | null;
|
|
248
|
+
typenames: Set<string> | null;
|
|
249
|
+
objectIds: Set<ObjectId> | null;
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
const extractScopes = (plan: QueryPlan.Plan): QueryScopes => {
|
|
253
|
+
const scopes: QueryScopes = {
|
|
254
|
+
isSimple: true,
|
|
255
|
+
spaceIds: null,
|
|
256
|
+
queueIds: null,
|
|
257
|
+
typenames: null,
|
|
258
|
+
objectIds: null,
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
for (const step of plan.steps) {
|
|
262
|
+
switch (step._tag) {
|
|
263
|
+
case 'SelectStep': {
|
|
264
|
+
// Extract spaceIds from scope.
|
|
265
|
+
if (step.scope.spaceIds && step.scope.spaceIds.length > 0) {
|
|
266
|
+
if (!scopes.spaceIds) {
|
|
267
|
+
scopes.spaceIds = new Set();
|
|
268
|
+
}
|
|
269
|
+
for (const spaceId of step.scope.spaceIds) {
|
|
270
|
+
scopes.spaceIds.add(spaceId as SpaceId);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Extract queueIds from explicit queue DXNs and derive spaceIds from them.
|
|
275
|
+
if (step.scope.queues && step.scope.queues.length > 0 && !step.scope.allQueuesFromSpaces) {
|
|
276
|
+
let parseFailed = false;
|
|
277
|
+
const derivedQueueIds = new Set<ObjectId>();
|
|
278
|
+
const derivedSpaceIds = new Set<SpaceId>();
|
|
279
|
+
for (const queueDxnStr of step.scope.queues as DXN.String[]) {
|
|
280
|
+
try {
|
|
281
|
+
const queueDxn = DXN.parse(queueDxnStr).asQueueDXN();
|
|
282
|
+
if (queueDxn) {
|
|
283
|
+
derivedQueueIds.add(queueDxn.queueId as ObjectId);
|
|
284
|
+
derivedSpaceIds.add(queueDxn.spaceId as SpaceId);
|
|
285
|
+
}
|
|
286
|
+
} catch {
|
|
287
|
+
parseFailed = true;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (!parseFailed) {
|
|
292
|
+
if (derivedQueueIds.size > 0) {
|
|
293
|
+
scopes.queueIds ??= new Set<ObjectId>();
|
|
294
|
+
for (const id of derivedQueueIds) {
|
|
295
|
+
scopes.queueIds.add(id);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (derivedSpaceIds.size > 0) {
|
|
299
|
+
scopes.spaceIds ??= new Set<SpaceId>();
|
|
300
|
+
for (const id of derivedSpaceIds) {
|
|
301
|
+
// Derive spaceId from the queue DXN so space-scoped hints can skip this query.
|
|
302
|
+
scopes.spaceIds.add(id);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
// On any parse error, leave queue-derived dimensions unconstrained.
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Extract typename / objectId constraints from selector.
|
|
310
|
+
switch (step.selector._tag) {
|
|
311
|
+
case 'TypeSelector': {
|
|
312
|
+
if (step.selector.inverted) {
|
|
313
|
+
// Inverted type selectors come from Filter.not — mark as non-simple.
|
|
314
|
+
scopes.isSimple = false;
|
|
315
|
+
} else {
|
|
316
|
+
if (!scopes.typenames) {
|
|
317
|
+
scopes.typenames = new Set();
|
|
318
|
+
}
|
|
319
|
+
for (const typename of step.selector.typename) {
|
|
320
|
+
scopes.typenames.add(typename as string);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
325
|
+
case 'IdSelector': {
|
|
326
|
+
if (!scopes.objectIds) {
|
|
327
|
+
scopes.objectIds = new Set();
|
|
328
|
+
}
|
|
329
|
+
for (const id of step.selector.objectIds) {
|
|
330
|
+
scopes.objectIds.add(id);
|
|
331
|
+
}
|
|
332
|
+
break;
|
|
333
|
+
}
|
|
334
|
+
case 'TextSelector': {
|
|
335
|
+
scopes.isSimple = false;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
default:
|
|
339
|
+
// WildcardSelector, TimestampSelector — no type/id constraint.
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
case 'FilterStep': {
|
|
345
|
+
// child-of filters require transitive parent traversal which can't be hinted.
|
|
346
|
+
if (step.filter.type === 'child-of') {
|
|
347
|
+
scopes.isSimple = false;
|
|
348
|
+
}
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
351
|
+
case 'TraverseStep':
|
|
352
|
+
case 'UnionStep':
|
|
353
|
+
case 'SetDifferenceStep':
|
|
354
|
+
scopes.isSimple = false;
|
|
355
|
+
break;
|
|
356
|
+
default:
|
|
357
|
+
// ClearWorkingSetStep, FilterDeletedStep, OrderStep, LimitStep are fine.
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
return scopes;
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
const setsOverlap = <T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean => {
|
|
366
|
+
const [smaller, larger]: [ReadonlySet<T>, ReadonlySet<T>] = a.size <= b.size ? [a, b] : [b, a];
|
|
367
|
+
for (const item of smaller) {
|
|
368
|
+
if (larger.has(item)) {
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return false;
|
|
373
|
+
};
|
|
374
|
+
|
|
375
|
+
const overlapsOrUnconstrained = <T>(hintSet: ReadonlySet<T> | undefined, scopeSet: Set<T> | null): boolean =>
|
|
376
|
+
hintSet === undefined || scopeSet === null || setsOverlap(hintSet, scopeSet);
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Executes query plans against the IndexEngine and AutomergeHost.
|
|
107
380
|
*
|
|
108
381
|
* The QueryExecutor is responsible for:
|
|
109
382
|
* - Executing query plans step by step
|
|
@@ -113,7 +386,8 @@ const TRACE_QUERY_EXECUTION = false;
|
|
|
113
386
|
* - Handling different types of query operations (select, filter, traverse, etc.)
|
|
114
387
|
*/
|
|
115
388
|
export class QueryExecutor extends Resource {
|
|
116
|
-
private readonly
|
|
389
|
+
private readonly _indexEngine: IndexEngine;
|
|
390
|
+
private readonly _runtime: RuntimeProvider.RuntimeProvider<SqlClient.SqlClient>;
|
|
117
391
|
private readonly _automergeHost: AutomergeHost;
|
|
118
392
|
private readonly _spaceStateManager: SpaceStateManager;
|
|
119
393
|
/**
|
|
@@ -125,13 +399,15 @@ export class QueryExecutor extends Resource {
|
|
|
125
399
|
private readonly _reactivity: QueryReactivity;
|
|
126
400
|
|
|
127
401
|
private _plan: QueryPlan.Plan;
|
|
402
|
+
#scopes: QueryScopes;
|
|
128
403
|
private _trace: ExecutionTrace = ExecutionTrace.makeEmpty();
|
|
129
404
|
private _lastResultSet: QueryItem[] = [];
|
|
130
405
|
|
|
131
406
|
constructor(options: QueryExecutorOptions) {
|
|
132
407
|
super();
|
|
133
408
|
|
|
134
|
-
this.
|
|
409
|
+
this._indexEngine = options.indexEngine;
|
|
410
|
+
this._runtime = options.runtime;
|
|
135
411
|
this._automergeHost = options.automergeHost;
|
|
136
412
|
this._spaceStateManager = options.spaceStateManager;
|
|
137
413
|
|
|
@@ -141,6 +417,11 @@ export class QueryExecutor extends Resource {
|
|
|
141
417
|
|
|
142
418
|
const queryPlanner = new QueryPlanner();
|
|
143
419
|
this._plan = queryPlanner.createPlan(this._query);
|
|
420
|
+
this.#scopes = extractScopes(this._plan);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
get queryId(): string {
|
|
424
|
+
return this._id;
|
|
144
425
|
}
|
|
145
426
|
|
|
146
427
|
get query(): QueryAST.Query {
|
|
@@ -155,31 +436,54 @@ export class QueryExecutor extends Resource {
|
|
|
155
436
|
return this._trace;
|
|
156
437
|
}
|
|
157
438
|
|
|
158
|
-
protected override async _open(ctx: Context): Promise<void> {}
|
|
159
|
-
|
|
160
|
-
protected override async _close(ctx: Context): Promise<void> {}
|
|
161
|
-
|
|
162
439
|
getResults(): QueryResult[] {
|
|
163
440
|
return this._lastResultSet.map(
|
|
164
441
|
(item): QueryResult => ({
|
|
165
442
|
id: item.objectId,
|
|
166
|
-
documentId: item.documentId,
|
|
443
|
+
documentId: item.documentId ?? undefined,
|
|
444
|
+
queueId: item.queueId ?? undefined,
|
|
445
|
+
queueNamespace: item.queueNamespace ?? undefined,
|
|
167
446
|
spaceId: item.spaceId,
|
|
168
447
|
|
|
169
|
-
|
|
170
|
-
|
|
448
|
+
rank: item.rank,
|
|
449
|
+
|
|
450
|
+
documentJson: item.doc ? JSON.stringify(item.doc) : item.data ? JSON.stringify(item.data) : undefined,
|
|
171
451
|
}),
|
|
172
452
|
);
|
|
173
453
|
}
|
|
174
454
|
|
|
455
|
+
/**
|
|
456
|
+
* Returns true if the given invalidation hint could affect this query's result set.
|
|
457
|
+
* When false, the query can safely be skipped for this invalidation cycle.
|
|
458
|
+
*
|
|
459
|
+
* Conservative: returns true for complex queries (traversals, text-search, unions) and
|
|
460
|
+
* for any dimension where either the hint or the query is unconstrained.
|
|
461
|
+
*/
|
|
462
|
+
matchesHint(hint: InvalidationHint): boolean {
|
|
463
|
+
if (!this.#scopes.isSimple) {
|
|
464
|
+
return true;
|
|
465
|
+
}
|
|
466
|
+
return (
|
|
467
|
+
overlapsOrUnconstrained(hint.spaceIds, this.#scopes.spaceIds) &&
|
|
468
|
+
overlapsOrUnconstrained(hint.queueIds, this.#scopes.queueIds) &&
|
|
469
|
+
overlapsOrUnconstrained(hint.typenames, this.#scopes.typenames) &&
|
|
470
|
+
overlapsOrUnconstrained(hint.objectIds, this.#scopes.objectIds)
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
|
|
175
474
|
async execQuery(): Promise<QueryExecutionResult> {
|
|
176
475
|
invariant(this._lifecycleState === LifecycleState.OPEN);
|
|
177
476
|
|
|
477
|
+
log('exec query', {
|
|
478
|
+
queryId: this._id,
|
|
479
|
+
query: Query.pretty(Query.fromAst(this._query)),
|
|
480
|
+
});
|
|
481
|
+
|
|
178
482
|
const prevResultSet = this._lastResultSet;
|
|
179
483
|
const { workingSet, trace } = await this._execPlan(this._plan, []);
|
|
180
484
|
this._lastResultSet = workingSet;
|
|
181
485
|
trace.name = 'Root';
|
|
182
|
-
trace.details = JSON.stringify({ id: this._id });
|
|
486
|
+
trace.details = JSON.stringify({ id: this._id, query: Query.pretty(Query.fromAst(this._query)) });
|
|
183
487
|
this._trace = trace;
|
|
184
488
|
|
|
185
489
|
const changed =
|
|
@@ -191,7 +495,11 @@ export class QueryExecutor extends Resource {
|
|
|
191
495
|
workingSet[index].documentId !== item.documentId,
|
|
192
496
|
);
|
|
193
497
|
|
|
498
|
+
// Disabled because concurrent queries don't print hierarchies correctly.
|
|
499
|
+
// ExecutionTrace.putOnPerformanceTimeline(trace);
|
|
500
|
+
|
|
194
501
|
if (TRACE_QUERY_EXECUTION) {
|
|
502
|
+
// eslint-disable-next-line no-console
|
|
195
503
|
console.log(ExecutionTrace.format(trace));
|
|
196
504
|
}
|
|
197
505
|
|
|
@@ -202,7 +510,6 @@ export class QueryExecutor extends Resource {
|
|
|
202
510
|
|
|
203
511
|
private async _execPlan(plan: QueryPlan.Plan, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
204
512
|
const trace = ExecutionTrace.makeEmpty();
|
|
205
|
-
const begin = performance.now();
|
|
206
513
|
for (const step of plan.steps) {
|
|
207
514
|
if (this._ctx.disposed) {
|
|
208
515
|
throw new ContextDisposedError();
|
|
@@ -213,7 +520,7 @@ export class QueryExecutor extends Resource {
|
|
|
213
520
|
trace.children.push(result.trace);
|
|
214
521
|
}
|
|
215
522
|
trace.objectCount = workingSet.length;
|
|
216
|
-
|
|
523
|
+
ExecutionTrace.markEnd(trace);
|
|
217
524
|
return { workingSet, trace };
|
|
218
525
|
}
|
|
219
526
|
|
|
@@ -250,10 +557,14 @@ export class QueryExecutor extends Resource {
|
|
|
250
557
|
case 'OrderStep':
|
|
251
558
|
({ workingSet: newWorkingSet, trace } = await this._execOrderStep(step, workingSet));
|
|
252
559
|
break;
|
|
560
|
+
case 'LimitStep':
|
|
561
|
+
({ workingSet: newWorkingSet, trace } = await this._execLimitStep(step, workingSet));
|
|
562
|
+
break;
|
|
253
563
|
default:
|
|
254
564
|
throw new Error(`Unknown step type: ${(step as any)._tag}`);
|
|
255
565
|
}
|
|
256
|
-
trace.
|
|
566
|
+
trace.beginTs = begin;
|
|
567
|
+
ExecutionTrace.markEnd(trace);
|
|
257
568
|
|
|
258
569
|
return { workingSet: newWorkingSet, trace };
|
|
259
570
|
}
|
|
@@ -261,20 +572,23 @@ export class QueryExecutor extends Resource {
|
|
|
261
572
|
private async _execSelectStep(step: QueryPlan.SelectStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
262
573
|
workingSet = [...workingSet];
|
|
263
574
|
|
|
575
|
+
const spaces = (step.scope.spaceIds ?? []) as SpaceId[];
|
|
576
|
+
const queues = (step.scope.queues ?? []) as DXN.String[];
|
|
577
|
+
const allQueuesFromSpaces = step.scope.allQueuesFromSpaces ?? false;
|
|
578
|
+
|
|
264
579
|
const trace: ExecutionTrace = {
|
|
265
580
|
...ExecutionTrace.makeEmpty(),
|
|
266
581
|
name: 'Select',
|
|
267
582
|
details: JSON.stringify(step.selector),
|
|
583
|
+
beginTs: performance.now(),
|
|
268
584
|
};
|
|
269
585
|
|
|
270
586
|
switch (step.selector._tag) {
|
|
271
587
|
case 'WildcardSelector': {
|
|
272
588
|
const beginIndexQuery = performance.now();
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
});
|
|
277
|
-
trace.indexHits = +indexHits.length;
|
|
589
|
+
const queueIds = extractQueueIds(queues);
|
|
590
|
+
const metas = await this._queryAllFromSqlIndex(spaces, allQueuesFromSpaces, queueIds);
|
|
591
|
+
trace.indexHits = metas.length;
|
|
278
592
|
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
279
593
|
|
|
280
594
|
if (this._ctx.disposed) {
|
|
@@ -282,11 +596,11 @@ export class QueryExecutor extends Resource {
|
|
|
282
596
|
}
|
|
283
597
|
|
|
284
598
|
const documentLoadStart = performance.now();
|
|
285
|
-
const results = await this.
|
|
599
|
+
const results = await this._loadDocumentsAfterSqlQuery(metas);
|
|
286
600
|
trace.documentsLoaded += results.length;
|
|
287
601
|
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
288
602
|
|
|
289
|
-
workingSet.push(...results.filter(isNonNullable)
|
|
603
|
+
workingSet.push(...results.filter(isNonNullable));
|
|
290
604
|
trace.objectCount = workingSet.length;
|
|
291
605
|
|
|
292
606
|
break;
|
|
@@ -294,10 +608,18 @@ export class QueryExecutor extends Resource {
|
|
|
294
608
|
|
|
295
609
|
case 'IdSelector': {
|
|
296
610
|
const beginLoad = performance.now();
|
|
611
|
+
|
|
297
612
|
const items = await Promise.all(
|
|
298
|
-
step.selector.objectIds.map((id) =>
|
|
299
|
-
|
|
300
|
-
|
|
613
|
+
step.selector.objectIds.map((id) => {
|
|
614
|
+
if (queues.length > 0) {
|
|
615
|
+
const { spaceId } = DXN.parse(queues[0]).asQueueDXN()!;
|
|
616
|
+
return this._loadFromDXN(DXN.parse(queues[0]).extend([id]), { sourceSpaceId: spaceId });
|
|
617
|
+
} else if (spaces.length > 0) {
|
|
618
|
+
return this._loadFromDXN(DXN.fromLocalObjectId(id), { sourceSpaceId: spaces[0] });
|
|
619
|
+
} else {
|
|
620
|
+
return null; // Unknown scope.
|
|
621
|
+
}
|
|
622
|
+
}),
|
|
301
623
|
);
|
|
302
624
|
trace.documentLoadTime += performance.now() - beginLoad;
|
|
303
625
|
|
|
@@ -308,11 +630,15 @@ export class QueryExecutor extends Resource {
|
|
|
308
630
|
|
|
309
631
|
case 'TypeSelector': {
|
|
310
632
|
const beginIndexQuery = performance.now();
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
633
|
+
const queueIds = extractQueueIds(queues);
|
|
634
|
+
const metas = await this._queryTypesFromSqlIndex(
|
|
635
|
+
spaces,
|
|
636
|
+
step.selector.typename,
|
|
637
|
+
step.selector.inverted,
|
|
638
|
+
allQueuesFromSpaces,
|
|
639
|
+
queueIds,
|
|
640
|
+
);
|
|
641
|
+
trace.indexHits = metas.length;
|
|
316
642
|
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
317
643
|
|
|
318
644
|
if (this._ctx.disposed) {
|
|
@@ -320,43 +646,144 @@ export class QueryExecutor extends Resource {
|
|
|
320
646
|
}
|
|
321
647
|
|
|
322
648
|
const documentLoadStart = performance.now();
|
|
323
|
-
const results = await this.
|
|
649
|
+
const results = await this._loadDocumentsAfterSqlQuery(metas);
|
|
324
650
|
trace.documentsLoaded += results.length;
|
|
325
651
|
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
326
652
|
|
|
327
|
-
workingSet.push(...results.filter(isNonNullable)
|
|
653
|
+
workingSet.push(...results.filter(isNonNullable));
|
|
654
|
+
trace.objectCount = workingSet.length;
|
|
655
|
+
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
case 'TimestampSelector': {
|
|
660
|
+
const beginIndexQuery = performance.now();
|
|
661
|
+
const queueIds = extractQueueIds(queues);
|
|
662
|
+
const metas = await this._runInRuntime(
|
|
663
|
+
this._indexEngine.queryByTimeRange({
|
|
664
|
+
spaceIds: spaces,
|
|
665
|
+
updatedAfter: step.selector.updatedAfter,
|
|
666
|
+
updatedBefore: step.selector.updatedBefore,
|
|
667
|
+
createdAfter: step.selector.createdAfter,
|
|
668
|
+
createdBefore: step.selector.createdBefore,
|
|
669
|
+
includeAllQueues: allQueuesFromSpaces,
|
|
670
|
+
queueIds,
|
|
671
|
+
}),
|
|
672
|
+
);
|
|
673
|
+
trace.indexHits = metas.length;
|
|
674
|
+
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
675
|
+
|
|
676
|
+
if (this._ctx.disposed) {
|
|
677
|
+
return { workingSet, trace };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const documentLoadStart = performance.now();
|
|
681
|
+
const results = await this._loadDocumentsAfterSqlQuery(metas);
|
|
682
|
+
trace.documentsLoaded += results.length;
|
|
683
|
+
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
684
|
+
|
|
685
|
+
workingSet.push(...results.filter(isNonNullable));
|
|
328
686
|
trace.objectCount = workingSet.length;
|
|
329
687
|
|
|
330
688
|
break;
|
|
331
689
|
}
|
|
332
690
|
|
|
333
691
|
case 'TextSelector': {
|
|
692
|
+
// TODO(dmaretskyi): type + FTS queries would be very common so we should support those, maybe chunk the fts index.
|
|
693
|
+
// TODO(dmaretskyi): nice to have matched text snippets/highlighting.
|
|
694
|
+
if (step.selector.searchKind === 'vector') {
|
|
695
|
+
// Vector search is not currently supported.
|
|
696
|
+
log.warn('Vector search is not supported');
|
|
697
|
+
break;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Full-text search using SQLite FTS5.
|
|
334
701
|
const beginIndexQuery = performance.now();
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
702
|
+
invariant(spaces.length <= 1, 'Multiple spaces are not supported for full-text search');
|
|
703
|
+
const queueIds = extractQueueIds(queues);
|
|
704
|
+
const textResults = await this._runInRuntime(
|
|
705
|
+
this._indexEngine.queryText({
|
|
338
706
|
query: step.selector.text,
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
},
|
|
346
|
-
});
|
|
347
|
-
trace.indexHits = +indexHits.length;
|
|
707
|
+
spaceId: spaces,
|
|
708
|
+
includeAllQueues: allQueuesFromSpaces,
|
|
709
|
+
queueIds,
|
|
710
|
+
}),
|
|
711
|
+
);
|
|
712
|
+
trace.indexHits = textResults.length;
|
|
348
713
|
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
349
714
|
|
|
350
715
|
if (this._ctx.disposed) {
|
|
351
716
|
return { workingSet, trace };
|
|
352
717
|
}
|
|
353
718
|
|
|
719
|
+
// Load documents from the results.
|
|
354
720
|
const documentLoadStart = performance.now();
|
|
355
|
-
|
|
356
|
-
|
|
721
|
+
|
|
722
|
+
// Separate queue items from space items.
|
|
723
|
+
const queueResults = textResults.filter((r) => r.queueId);
|
|
724
|
+
const spaceResults = textResults.filter((r) => !r.queueId);
|
|
725
|
+
|
|
726
|
+
// Build a map from recordId to rank for all FTS results.
|
|
727
|
+
const rankMap = new Map(textResults.map((r) => [r.recordId, r.rank]));
|
|
728
|
+
|
|
729
|
+
// Load queue items from indexed snapshots.
|
|
730
|
+
let queueItems: QueryItem[] = [];
|
|
731
|
+
if (queueResults.length > 0) {
|
|
732
|
+
const snapshots = await this._runInRuntime(
|
|
733
|
+
this._indexEngine.querySnapshotsJSON(queueResults.map((r) => r.recordId)),
|
|
734
|
+
);
|
|
735
|
+
const snapshotMap = new Map(snapshots.map((s) => [s.recordId, s.snapshot]));
|
|
736
|
+
queueItems = queueResults
|
|
737
|
+
.map((result): QueryItem | null => {
|
|
738
|
+
const snapshot = snapshotMap.get(result.recordId);
|
|
739
|
+
if (!snapshot || typeof snapshot !== 'object') {
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
objectId: result.objectId as ObjectId,
|
|
744
|
+
spaceId: result.spaceId as SpaceId,
|
|
745
|
+
queueId: result.queueId as ObjectId,
|
|
746
|
+
queueNamespace: 'data',
|
|
747
|
+
documentId: null,
|
|
748
|
+
doc: null,
|
|
749
|
+
data: snapshot as Obj.JSON,
|
|
750
|
+
rank: rankMap.get(result.recordId) ?? 1,
|
|
751
|
+
};
|
|
752
|
+
})
|
|
753
|
+
.filter(isNonNullable);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
// Load space items from documents.
|
|
757
|
+
const spaceItems = await Promise.all(
|
|
758
|
+
spaceResults.map(async (result): Promise<QueryItem | null> => {
|
|
759
|
+
const dxn = DXN.fromLocalObjectId(result.objectId);
|
|
760
|
+
const item = await this._loadFromDXN(dxn, { sourceSpaceId: result.spaceId as SpaceId });
|
|
761
|
+
if (item) {
|
|
762
|
+
// Override the default rank with the FTS rank.
|
|
763
|
+
item.rank = rankMap.get(result.recordId) ?? 1;
|
|
764
|
+
}
|
|
765
|
+
return item;
|
|
766
|
+
}),
|
|
767
|
+
);
|
|
768
|
+
|
|
769
|
+
const items = [...queueItems, ...spaceItems.filter(isNonNullable)];
|
|
770
|
+
trace.documentsLoaded += items.length;
|
|
357
771
|
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
358
772
|
|
|
359
|
-
workingSet.push(
|
|
773
|
+
workingSet.push(
|
|
774
|
+
...items.filter((item) => {
|
|
775
|
+
if (spaces.includes(item.spaceId)) {
|
|
776
|
+
return true;
|
|
777
|
+
}
|
|
778
|
+
if (item.queueId) {
|
|
779
|
+
return queues.some((dxn) => {
|
|
780
|
+
const { queueId, spaceId } = DXN.parse(dxn).asQueueDXN()!;
|
|
781
|
+
return queueId === item.queueId && spaceId === item.spaceId;
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
return false;
|
|
785
|
+
}),
|
|
786
|
+
);
|
|
360
787
|
trace.objectCount = workingSet.length;
|
|
361
788
|
break;
|
|
362
789
|
}
|
|
@@ -365,17 +792,46 @@ export class QueryExecutor extends Resource {
|
|
|
365
792
|
throw new Error(`Unknown selector type: ${(step.selector as any)._tag}`);
|
|
366
793
|
}
|
|
367
794
|
|
|
795
|
+
// Apply limit if specified on the select step.
|
|
796
|
+
if (step.limit !== undefined && workingSet.length > step.limit) {
|
|
797
|
+
workingSet = workingSet.slice(0, step.limit);
|
|
798
|
+
trace.objectCount = workingSet.length;
|
|
799
|
+
}
|
|
800
|
+
|
|
368
801
|
return { workingSet, trace };
|
|
369
802
|
}
|
|
370
803
|
|
|
371
804
|
private async _execFilterStep(step: QueryPlan.FilterStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
805
|
+
if (step.filter.type === 'child-of') {
|
|
806
|
+
return this._execChildOfFilterStep(step.filter, workingSet);
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
const timestampParams = extractTimestampParams(step.filter);
|
|
810
|
+
if (timestampParams !== null) {
|
|
811
|
+
return this._execTimestampFilterStep(step, workingSet, timestampParams);
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
if (filterContainsTimestamp(step.filter)) {
|
|
815
|
+
throw new QueryError({
|
|
816
|
+
message:
|
|
817
|
+
'Timestamp filter in unsupported composition (not, or). Use Filter.updated/Filter.created with explicit range instead.',
|
|
818
|
+
context: {},
|
|
819
|
+
});
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
const result = workingSet.filter((item) => {
|
|
823
|
+
if (item.doc) {
|
|
824
|
+
return filterMatchObject(step.filter, {
|
|
825
|
+
id: item.objectId,
|
|
826
|
+
spaceId: item.spaceId,
|
|
827
|
+
doc: item.doc,
|
|
828
|
+
});
|
|
829
|
+
} else if (item.data) {
|
|
830
|
+
return filterMatchObjectJSON(step.filter, item.data);
|
|
831
|
+
} else {
|
|
832
|
+
return false;
|
|
833
|
+
}
|
|
834
|
+
});
|
|
379
835
|
|
|
380
836
|
return {
|
|
381
837
|
workingSet: result,
|
|
@@ -388,12 +844,52 @@ export class QueryExecutor extends Resource {
|
|
|
388
844
|
};
|
|
389
845
|
}
|
|
390
846
|
|
|
847
|
+
private async _execTimestampFilterStep(
|
|
848
|
+
step: QueryPlan.FilterStep,
|
|
849
|
+
workingSet: QueryItem[],
|
|
850
|
+
params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number },
|
|
851
|
+
): Promise<StepExecutionResult> {
|
|
852
|
+
const spaces = [...new Set(workingSet.map((item) => item.spaceId).filter(isNonNullable))];
|
|
853
|
+
const metas = await this._runInRuntime(
|
|
854
|
+
this._indexEngine.queryByTimeRange({
|
|
855
|
+
spaceIds: spaces,
|
|
856
|
+
...params,
|
|
857
|
+
includeAllQueues: false,
|
|
858
|
+
queueIds: [],
|
|
859
|
+
}),
|
|
860
|
+
);
|
|
861
|
+
const matchingIds = new Set(metas.map((m) => m.objectId));
|
|
862
|
+
const result = workingSet.filter((item) => matchingIds.has(item.objectId));
|
|
863
|
+
return {
|
|
864
|
+
workingSet: result,
|
|
865
|
+
trace: {
|
|
866
|
+
...ExecutionTrace.makeEmpty(),
|
|
867
|
+
name: 'Filter(timestamp)',
|
|
868
|
+
details: JSON.stringify(params),
|
|
869
|
+
objectCount: result.length,
|
|
870
|
+
},
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
391
874
|
private async _execFilterDeletedStep(
|
|
392
875
|
step: QueryPlan.FilterDeletedStep,
|
|
393
876
|
workingSet: QueryItem[],
|
|
394
877
|
): Promise<StepExecutionResult> {
|
|
395
878
|
const expected = step.mode === 'only-deleted';
|
|
396
|
-
|
|
879
|
+
|
|
880
|
+
const deletedState = workingSet.map((item) => QueryItem.isDeleted(item));
|
|
881
|
+
await Promise.all(
|
|
882
|
+
workingSet.map(async (item, index) => {
|
|
883
|
+
if (deletedState[index]) {
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
deletedState[index] ||= await this._getTransitiveDeletionState(item, MAX_DEPTH_FOR_DELETION_TRACING);
|
|
887
|
+
}),
|
|
888
|
+
);
|
|
889
|
+
|
|
890
|
+
const result = workingSet.filter((item, index) => deletedState[index] === expected);
|
|
891
|
+
|
|
892
|
+
// TODO(dmaretskyi): How do we handle items with parents and cascade deletions? -- perhaps we forbid queue items from having parents -- i.e. queue is their parent.
|
|
397
893
|
return {
|
|
398
894
|
workingSet: result,
|
|
399
895
|
trace: {
|
|
@@ -405,6 +901,78 @@ export class QueryExecutor extends Resource {
|
|
|
405
901
|
};
|
|
406
902
|
}
|
|
407
903
|
|
|
904
|
+
private async _execChildOfFilterStep(
|
|
905
|
+
filter: QueryAST.FilterChildOf,
|
|
906
|
+
workingSet: QueryItem[],
|
|
907
|
+
): Promise<StepExecutionResult> {
|
|
908
|
+
const parentObjectIds = new Set<string>();
|
|
909
|
+
for (const parentDxnStr of filter.parents) {
|
|
910
|
+
const dxn = DXN.parse(parentDxnStr);
|
|
911
|
+
const echoDxn = dxn.asEchoDXN();
|
|
912
|
+
if (echoDxn) {
|
|
913
|
+
parentObjectIds.add(echoDxn.echoId);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
const maxDepth = filter.transitive ? MAX_DEPTH_FOR_CHILD_OF_TRACING : 1;
|
|
917
|
+
|
|
918
|
+
const matches = await Promise.all(
|
|
919
|
+
workingSet.map(async (item) => this._isChildOfAny(item, parentObjectIds, maxDepth)),
|
|
920
|
+
);
|
|
921
|
+
const result = workingSet.filter((_item, index) => matches[index]);
|
|
922
|
+
|
|
923
|
+
return {
|
|
924
|
+
workingSet: result,
|
|
925
|
+
trace: {
|
|
926
|
+
...ExecutionTrace.makeEmpty(),
|
|
927
|
+
name: 'Filter(child-of)',
|
|
928
|
+
details: JSON.stringify({ parents: filter.parents, transitive: filter.transitive }),
|
|
929
|
+
objectCount: result.length,
|
|
930
|
+
},
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* Checks if an item is a child of any of the given parent object IDs.
|
|
936
|
+
* Walks up the parent chain (and feed ownership for queue items) until a match is found or depth is exhausted.
|
|
937
|
+
*/
|
|
938
|
+
private async _isChildOfAny(item: QueryItem, parentObjectIds: Set<string>, remainingDepth: number): Promise<boolean> {
|
|
939
|
+
if (remainingDepth <= 0) {
|
|
940
|
+
return false;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
const parentRefs: { dxnStr: string; objectId: string }[] = [];
|
|
944
|
+
|
|
945
|
+
const directParent = QueryItem.getParent(item);
|
|
946
|
+
if (directParent) {
|
|
947
|
+
const echoDxn = DXN.parse(directParent).asEchoDXN();
|
|
948
|
+
if (echoDxn) {
|
|
949
|
+
parentRefs.push({ dxnStr: directParent, objectId: echoDxn.echoId });
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (item.queueId && !directParent) {
|
|
954
|
+
parentRefs.push({
|
|
955
|
+
dxnStr: DXN.fromSpaceAndObjectId(item.spaceId, item.queueId).toString(),
|
|
956
|
+
objectId: item.queueId,
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
for (const ref of parentRefs) {
|
|
961
|
+
if (parentObjectIds.has(ref.objectId)) {
|
|
962
|
+
return true;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
for (const ref of parentRefs) {
|
|
967
|
+
const parentItem = await this._loadFromDXN(DXN.parse(ref.dxnStr), { sourceSpaceId: item.spaceId });
|
|
968
|
+
if (parentItem && (await this._isChildOfAny(parentItem, parentObjectIds, remainingDepth - 1))) {
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
return false;
|
|
974
|
+
}
|
|
975
|
+
|
|
408
976
|
// TODO(dmaretskyi): This needs to be completed.
|
|
409
977
|
private async _execTraverseStep(step: QueryPlan.TraverseStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
410
978
|
const trace: ExecutionTrace = {
|
|
@@ -419,11 +987,12 @@ export class QueryExecutor extends Resource {
|
|
|
419
987
|
case 'ReferenceTraversal': {
|
|
420
988
|
switch (step.traversal.direction) {
|
|
421
989
|
case 'outgoing': {
|
|
990
|
+
invariant(step.traversal.property !== null, 'Outgoing reference traversal requires a property');
|
|
422
991
|
const property = EscapedPropPath.unescape(step.traversal.property);
|
|
423
992
|
|
|
424
993
|
const refs = workingSet
|
|
425
994
|
.flatMap((item) => {
|
|
426
|
-
const ref =
|
|
995
|
+
const ref = QueryItem.getProperty(item, property);
|
|
427
996
|
const refs = Array.isArray(ref) ? ref : [ref];
|
|
428
997
|
return refs.map((ref) => {
|
|
429
998
|
try {
|
|
@@ -453,19 +1022,13 @@ export class QueryExecutor extends Resource {
|
|
|
453
1022
|
break;
|
|
454
1023
|
}
|
|
455
1024
|
case 'incoming': {
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
kind: 'inbound-reference',
|
|
461
|
-
property: step.traversal.property,
|
|
462
|
-
anchors: workingSet.map((item) => item.objectId),
|
|
463
|
-
},
|
|
464
|
-
});
|
|
465
|
-
trace.indexHits += indexHits.length;
|
|
1025
|
+
const beginIndexQuery = performance.now();
|
|
1026
|
+
const metas = await this._queryIncomingReferencesFromSqlIndex(workingSet, step.traversal.property);
|
|
1027
|
+
trace.indexHits += metas.length;
|
|
1028
|
+
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
466
1029
|
|
|
467
1030
|
const documentLoadStart = performance.now();
|
|
468
|
-
const results = await this.
|
|
1031
|
+
const results = await this._loadDocumentsAfterSqlQuery(metas);
|
|
469
1032
|
trace.documentsLoaded += results.length;
|
|
470
1033
|
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
471
1034
|
|
|
@@ -483,21 +1046,20 @@ export class QueryExecutor extends Resource {
|
|
|
483
1046
|
case 'relation-to-target': {
|
|
484
1047
|
const refs = workingSet
|
|
485
1048
|
.map((item) => {
|
|
486
|
-
const
|
|
1049
|
+
const dxn =
|
|
487
1050
|
step.traversal.direction === 'relation-to-source'
|
|
488
|
-
?
|
|
489
|
-
:
|
|
490
|
-
|
|
491
|
-
if (!isEncodedReference(ref)) {
|
|
1051
|
+
? QueryItem.getRelationSource(item)
|
|
1052
|
+
: QueryItem.getRelationTarget(item);
|
|
1053
|
+
if (!dxn) {
|
|
492
1054
|
return null;
|
|
493
1055
|
}
|
|
494
1056
|
try {
|
|
495
1057
|
return {
|
|
496
|
-
ref: DXN.parse(
|
|
1058
|
+
ref: DXN.parse(dxn),
|
|
497
1059
|
spaceId: item.spaceId,
|
|
498
1060
|
};
|
|
499
1061
|
} catch {
|
|
500
|
-
log.warn('invalid reference', { ref:
|
|
1062
|
+
log.warn('invalid reference', { ref: dxn });
|
|
501
1063
|
return null;
|
|
502
1064
|
}
|
|
503
1065
|
})
|
|
@@ -517,20 +1079,16 @@ export class QueryExecutor extends Resource {
|
|
|
517
1079
|
|
|
518
1080
|
case 'source-to-relation':
|
|
519
1081
|
case 'target-to-relation': {
|
|
520
|
-
const
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
},
|
|
528
|
-
});
|
|
529
|
-
|
|
530
|
-
trace.indexHits += indexHits.length;
|
|
1082
|
+
const beginIndexQuery = performance.now();
|
|
1083
|
+
const metas = await this._queryRelationsFromSqlIndex(
|
|
1084
|
+
workingSet,
|
|
1085
|
+
step.traversal.direction === 'source-to-relation' ? 'source' : 'target',
|
|
1086
|
+
);
|
|
1087
|
+
trace.indexHits += metas.length;
|
|
1088
|
+
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
531
1089
|
|
|
532
1090
|
const documentLoadStart = performance.now();
|
|
533
|
-
const results = await this.
|
|
1091
|
+
const results = await this._loadDocumentsAfterSqlQuery(metas);
|
|
534
1092
|
trace.documentsLoaded += results.length;
|
|
535
1093
|
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
536
1094
|
|
|
@@ -542,6 +1100,80 @@ export class QueryExecutor extends Resource {
|
|
|
542
1100
|
}
|
|
543
1101
|
break;
|
|
544
1102
|
}
|
|
1103
|
+
case 'HierarchyTraversal': {
|
|
1104
|
+
switch (step.traversal.direction) {
|
|
1105
|
+
case 'to-parent': {
|
|
1106
|
+
// Traverse from child to parent using the parent reference in the document.
|
|
1107
|
+
const refs = workingSet
|
|
1108
|
+
.map((item) => {
|
|
1109
|
+
if (!item.doc) {
|
|
1110
|
+
return null; // TODO(dmaretskyi): Queue items not supported here.
|
|
1111
|
+
}
|
|
1112
|
+
const ref = ObjectStructure.getParent(item.doc);
|
|
1113
|
+
if (!EncodedReference.isEncodedReference(ref)) {
|
|
1114
|
+
return null;
|
|
1115
|
+
}
|
|
1116
|
+
try {
|
|
1117
|
+
return {
|
|
1118
|
+
ref: DXN.parse(ref['/']),
|
|
1119
|
+
spaceId: item.spaceId,
|
|
1120
|
+
};
|
|
1121
|
+
} catch {
|
|
1122
|
+
log.warn('invalid parent reference', { ref: ref['/'] });
|
|
1123
|
+
return null;
|
|
1124
|
+
}
|
|
1125
|
+
})
|
|
1126
|
+
.filter(isNonNullable);
|
|
1127
|
+
|
|
1128
|
+
const beginLoad = performance.now();
|
|
1129
|
+
const items = await Promise.all(
|
|
1130
|
+
refs.map(({ ref, spaceId }) => this._loadFromDXN(ref, { sourceSpaceId: spaceId })),
|
|
1131
|
+
);
|
|
1132
|
+
trace.documentLoadTime += performance.now() - beginLoad;
|
|
1133
|
+
|
|
1134
|
+
newWorkingSet.push(...items.filter(isNonNullable));
|
|
1135
|
+
trace.objectCount = newWorkingSet.length;
|
|
1136
|
+
break;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
case 'to-children': {
|
|
1140
|
+
// Traverse from parent to children using the SQL index.
|
|
1141
|
+
// Covers both standard parent/child hierarchy (via the `parent` field) and
|
|
1142
|
+
// feed -> queue items (via the `queueId` field — a feed's queue id matches the feed's object id).
|
|
1143
|
+
// Group working set by spaceId.
|
|
1144
|
+
const bySpace = new Map<SpaceId, ObjectId[]>();
|
|
1145
|
+
for (const item of workingSet) {
|
|
1146
|
+
const existing = bySpace.get(item.spaceId);
|
|
1147
|
+
if (existing) {
|
|
1148
|
+
existing.push(item.objectId);
|
|
1149
|
+
} else {
|
|
1150
|
+
bySpace.set(item.spaceId, [item.objectId]);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
const beginIndexQuery = performance.now();
|
|
1155
|
+
const allMetas: ObjectMeta[] = [];
|
|
1156
|
+
for (const [spaceId, parentIds] of bySpace) {
|
|
1157
|
+
const children = await this._runInRuntime(
|
|
1158
|
+
this._indexEngine.queryChildren({ spaceId: [spaceId], parentIds }),
|
|
1159
|
+
);
|
|
1160
|
+
allMetas.push(...children);
|
|
1161
|
+
}
|
|
1162
|
+
trace.indexHits += allMetas.length;
|
|
1163
|
+
trace.indexQueryTime += performance.now() - beginIndexQuery;
|
|
1164
|
+
|
|
1165
|
+
const documentLoadStart = performance.now();
|
|
1166
|
+
const results = await this._loadDocumentsAfterSqlQuery(allMetas);
|
|
1167
|
+
trace.documentsLoaded += results.filter(isNonNullable).length;
|
|
1168
|
+
trace.documentLoadTime += performance.now() - documentLoadStart;
|
|
1169
|
+
|
|
1170
|
+
newWorkingSet.push(...results.filter(isNonNullable));
|
|
1171
|
+
trace.objectCount = newWorkingSet.length;
|
|
1172
|
+
break;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
break;
|
|
1176
|
+
}
|
|
545
1177
|
default:
|
|
546
1178
|
throw new Error(`Unknown traversal type: ${(step.traversal as any)._tag}`);
|
|
547
1179
|
}
|
|
@@ -563,7 +1195,7 @@ export class QueryExecutor extends Resource {
|
|
|
563
1195
|
for (const resultSet of resultSets) {
|
|
564
1196
|
for (const item of resultSet.workingSet) {
|
|
565
1197
|
// Could be duplicate object ids in different spaces or in different epochs of the same space.
|
|
566
|
-
results.set(
|
|
1198
|
+
results.set(compositeKey(item.spaceId, String(item.documentId), item.objectId), item);
|
|
567
1199
|
}
|
|
568
1200
|
trace.children.push(resultSet.trace);
|
|
569
1201
|
}
|
|
@@ -597,145 +1229,486 @@ export class QueryExecutor extends Resource {
|
|
|
597
1229
|
}
|
|
598
1230
|
|
|
599
1231
|
private async _execOrderStep(step: QueryPlan.OrderStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
600
|
-
|
|
601
|
-
step.order.reduce((comparison, order) => {
|
|
602
|
-
// If we already have a definitive result, return it
|
|
603
|
-
if (comparison !== 0) {
|
|
604
|
-
return comparison;
|
|
605
|
-
}
|
|
1232
|
+
let sortedWorkingSet = [...workingSet].sort((a, b) => this._compareMultiOrder(a, b, step.order));
|
|
606
1233
|
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
1234
|
+
// Apply limit if specified on the order step.
|
|
1235
|
+
if (step.limit !== undefined && sortedWorkingSet.length > step.limit) {
|
|
1236
|
+
sortedWorkingSet = sortedWorkingSet.slice(0, step.limit);
|
|
1237
|
+
}
|
|
611
1238
|
|
|
612
1239
|
return {
|
|
613
1240
|
workingSet: sortedWorkingSet,
|
|
614
1241
|
trace: {
|
|
615
1242
|
...ExecutionTrace.makeEmpty(),
|
|
616
1243
|
name: 'Order',
|
|
617
|
-
details: JSON.stringify(step.order),
|
|
1244
|
+
details: JSON.stringify({ order: step.order, limit: step.limit }),
|
|
618
1245
|
objectCount: sortedWorkingSet.length,
|
|
619
1246
|
},
|
|
620
1247
|
};
|
|
621
1248
|
}
|
|
622
1249
|
|
|
1250
|
+
private async _execLimitStep(step: QueryPlan.LimitStep, workingSet: QueryItem[]): Promise<StepExecutionResult> {
|
|
1251
|
+
const limitedWorkingSet = workingSet.slice(0, step.limit);
|
|
1252
|
+
|
|
1253
|
+
return {
|
|
1254
|
+
workingSet: limitedWorkingSet,
|
|
1255
|
+
trace: {
|
|
1256
|
+
...ExecutionTrace.makeEmpty(),
|
|
1257
|
+
name: 'Limit',
|
|
1258
|
+
details: JSON.stringify({ limit: step.limit }),
|
|
1259
|
+
objectCount: limitedWorkingSet.length,
|
|
1260
|
+
},
|
|
1261
|
+
};
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
private _compareMultiOrder(a: QueryItem, b: QueryItem, orders: readonly QueryAST.Order[]): number {
|
|
1265
|
+
// Short circuit for common cases.
|
|
1266
|
+
if (orders.length === 0) {
|
|
1267
|
+
return 0;
|
|
1268
|
+
} else if (orders.length === 1) {
|
|
1269
|
+
return this._compareByOrder(a, b, orders[0]);
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
for (const order of orders) {
|
|
1273
|
+
const comparison = this._compareByOrder(a, b, order);
|
|
1274
|
+
if (comparison !== 0) {
|
|
1275
|
+
return comparison;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
return 0;
|
|
1279
|
+
}
|
|
1280
|
+
|
|
623
1281
|
private _compareByOrder(a: QueryItem, b: QueryItem, order: QueryAST.Order): number {
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
const comparison = this._compareByProperty(a, b, property);
|
|
629
|
-
return direction === 'desc' ? -comparison : comparison;
|
|
630
|
-
}
|
|
631
|
-
|
|
632
|
-
|
|
1282
|
+
switch (order.kind) {
|
|
1283
|
+
case 'natural':
|
|
1284
|
+
return a.objectId.localeCompare(b.objectId);
|
|
1285
|
+
case 'property': {
|
|
1286
|
+
const comparison = this._compareByProperty(a, b, order.property);
|
|
1287
|
+
return order.direction === 'desc' ? -comparison : comparison;
|
|
1288
|
+
}
|
|
1289
|
+
case 'rank': {
|
|
1290
|
+
// Higher rank = better match. By default, descending order (best first).
|
|
1291
|
+
const comparison = a.rank - b.rank;
|
|
1292
|
+
return order.direction === 'desc' ? -comparison : comparison;
|
|
1293
|
+
}
|
|
1294
|
+
default:
|
|
1295
|
+
// Should never reach here with proper TypeScript types.
|
|
1296
|
+
return 0;
|
|
1297
|
+
}
|
|
633
1298
|
}
|
|
634
1299
|
|
|
635
1300
|
private _compareByProperty(a: QueryItem, b: QueryItem, property: string): number {
|
|
636
|
-
const aValue = a
|
|
637
|
-
const bValue = b
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
1301
|
+
const aValue = QueryItem.getProperty(a, [property]);
|
|
1302
|
+
const bValue = QueryItem.getProperty(b, [property]);
|
|
1303
|
+
|
|
1304
|
+
// Both null or undefined
|
|
1305
|
+
if (aValue == null && bValue == null) {
|
|
1306
|
+
return 0;
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
// Only a is null/undefined
|
|
1310
|
+
if (aValue == null) {
|
|
1311
|
+
return 1;
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// Only b is null/undefined
|
|
1315
|
+
if (bValue == null) {
|
|
1316
|
+
return -1;
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
// Both strings
|
|
1320
|
+
if (typeof aValue === 'string' && typeof bValue === 'string') {
|
|
1321
|
+
return aValue.localeCompare(bValue);
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// Both numbers
|
|
1325
|
+
if (typeof aValue === 'number' && typeof bValue === 'number') {
|
|
1326
|
+
return aValue - bValue;
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
// Both booleans
|
|
1330
|
+
if (typeof aValue === 'boolean' && typeof bValue === 'boolean') {
|
|
1331
|
+
return aValue === bValue ? 0 : aValue ? 1 : -1;
|
|
1332
|
+
}
|
|
1333
|
+
|
|
1334
|
+
// Fallback: convert to strings and compare
|
|
1335
|
+
return String(aValue).localeCompare(String(bValue));
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
private async _runInRuntime<T>(effect: Effect.Effect<T, unknown, SqlClient.SqlClient>): Promise<T> {
|
|
1339
|
+
const runtimeProvider = this._runtime;
|
|
1340
|
+
invariant(runtimeProvider, 'SQL runtime is required.');
|
|
1341
|
+
const runtime = await runAndForwardErrors(runtimeProvider);
|
|
1342
|
+
return await unwrapExit(await effect.pipe(Runtime.runPromiseExit(runtime)));
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
private async _queryAllFromSqlIndex(
|
|
1346
|
+
spaceIds: readonly SpaceId[],
|
|
1347
|
+
includeAllQueues: boolean,
|
|
1348
|
+
queueIds: readonly ObjectId[] | null,
|
|
1349
|
+
): Promise<readonly ObjectMeta[]> {
|
|
1350
|
+
return await this._runInRuntime(this._indexEngine.queryAll({ spaceIds, includeAllQueues, queueIds }));
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
private async _queryTypesFromSqlIndex(
|
|
1354
|
+
spaceIds: readonly SpaceId[],
|
|
1355
|
+
typeDxns: readonly string[],
|
|
1356
|
+
inverted: boolean,
|
|
1357
|
+
includeAllQueues: boolean,
|
|
1358
|
+
queueIds: readonly ObjectId[] | null,
|
|
1359
|
+
): Promise<readonly ObjectMeta[]> {
|
|
1360
|
+
return await this._runInRuntime(
|
|
1361
|
+
this._indexEngine.queryTypes({ spaceIds, typeDxns, inverted, includeAllQueues, queueIds }),
|
|
658
1362
|
);
|
|
659
1363
|
}
|
|
660
1364
|
|
|
661
|
-
private async
|
|
662
|
-
|
|
1365
|
+
private async _queryIncomingReferencesFromSqlIndex(
|
|
1366
|
+
workingSet: QueryItem[],
|
|
1367
|
+
property: EscapedPropPath | null,
|
|
1368
|
+
): Promise<readonly ObjectMeta[]> {
|
|
1369
|
+
const anchorDxns = workingSet.map((item) => DXN.fromLocalObjectId(item.objectId).toString());
|
|
1370
|
+
const rows: readonly ReverseRef[] = (
|
|
1371
|
+
await Promise.all(
|
|
1372
|
+
anchorDxns.map((targetDxn) => this._runInRuntime(this._indexEngine.queryReverseRef({ targetDxn }))),
|
|
1373
|
+
)
|
|
1374
|
+
).flat();
|
|
1375
|
+
|
|
1376
|
+
const recordIds = rows
|
|
1377
|
+
.filter((row) => {
|
|
1378
|
+
if (property === null) {
|
|
1379
|
+
return true;
|
|
1380
|
+
}
|
|
663
1381
|
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
1382
|
+
const queryPath = EscapedPropPath.unescape(property);
|
|
1383
|
+
const rowPath = EscapedPropPath.unescape(row.propPath);
|
|
1384
|
+
return QueryExecutor._matchesReferencePropertyPath(rowPath, queryPath);
|
|
1385
|
+
})
|
|
1386
|
+
.map((row) => row.recordId);
|
|
1387
|
+
|
|
1388
|
+
const uniqueRecordIds = Array.from(new Set<number>(recordIds));
|
|
1389
|
+
return await this._runInRuntime(this._indexEngine.lookupByRecordIds(uniqueRecordIds));
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
/**
|
|
1393
|
+
* Matches a reverse-reference row path against a query property path.
|
|
1394
|
+
* Allows numeric segments in the row path (array indices) that are not present in the query.
|
|
1395
|
+
*
|
|
1396
|
+
* Examples:
|
|
1397
|
+
* - query: ['assignee'] matches row: ['assignee'] and ['assignee', '0'].
|
|
1398
|
+
* - query: ['items', 'assignee'] matches row: ['items', '0', 'assignee'].
|
|
1399
|
+
* - query: ['a', 'b'] does NOT match row: ['a'].
|
|
1400
|
+
* - query: ['a'] does NOT match row: ['a', 'b'].
|
|
1401
|
+
*/
|
|
1402
|
+
private static _matchesReferencePropertyPath(rowPath: readonly string[], queryPath: readonly string[]): boolean {
|
|
1403
|
+
const isNumericSegment = (segment: string) => /^[0-9]+$/.test(segment);
|
|
1404
|
+
|
|
1405
|
+
let i = 0; // queryPath index.
|
|
1406
|
+
let j = 0; // rowPath index.
|
|
1407
|
+
|
|
1408
|
+
while (i < queryPath.length && j < rowPath.length) {
|
|
1409
|
+
if (rowPath[j] === queryPath[i]) {
|
|
1410
|
+
i++;
|
|
1411
|
+
j++;
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
// Row may contain array indices that aren't present in the query path.
|
|
1416
|
+
if (isNumericSegment(rowPath[j])) {
|
|
1417
|
+
j++;
|
|
1418
|
+
continue;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
return false;
|
|
668
1422
|
}
|
|
669
1423
|
|
|
670
|
-
|
|
671
|
-
if (
|
|
672
|
-
return
|
|
1424
|
+
// Must consume full query path.
|
|
1425
|
+
if (i !== queryPath.length) {
|
|
1426
|
+
return false;
|
|
673
1427
|
}
|
|
674
1428
|
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
1429
|
+
// Any remaining row segments must be numeric (array indices).
|
|
1430
|
+
for (; j < rowPath.length; j++) {
|
|
1431
|
+
if (!isNumericSegment(rowPath[j])) {
|
|
1432
|
+
return false;
|
|
1433
|
+
}
|
|
678
1434
|
}
|
|
679
1435
|
|
|
680
|
-
return
|
|
681
|
-
objectId,
|
|
682
|
-
documentId: documentId as DocumentId,
|
|
683
|
-
spaceId: await createIdFromSpaceKey(PublicKey.from(spaceKey)),
|
|
684
|
-
doc: object,
|
|
685
|
-
};
|
|
1436
|
+
return true;
|
|
686
1437
|
}
|
|
687
1438
|
|
|
688
|
-
private async
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
}
|
|
1439
|
+
private async _queryRelationsFromSqlIndex(
|
|
1440
|
+
workingSet: QueryItem[],
|
|
1441
|
+
endpoint: 'source' | 'target',
|
|
1442
|
+
): Promise<readonly ObjectMeta[]> {
|
|
1443
|
+
const anchorDxns = workingSet.map((item) => DXN.fromLocalObjectId(item.objectId).toString());
|
|
1444
|
+
return await this._runInRuntime(this._indexEngine.queryRelations({ endpoint, anchorDxns }));
|
|
1445
|
+
}
|
|
694
1446
|
|
|
695
|
-
|
|
1447
|
+
private async _loadDocumentsAfterSqlQuery(metas: readonly ObjectMeta[]): Promise<(QueryItem | null)[]> {
|
|
1448
|
+
const snapshotMap = await this._loadQueueSnapshotMap(metas);
|
|
1449
|
+
return await Promise.all(
|
|
1450
|
+
metas.map(async (meta) => {
|
|
1451
|
+
// Branch 1: Document-backed object.
|
|
1452
|
+
if (meta.documentId) {
|
|
1453
|
+
return this._loadFromAutomerge(meta);
|
|
1454
|
+
}
|
|
696
1455
|
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
1456
|
+
// Branch 2: Queue-backed object.
|
|
1457
|
+
if (meta.queueId) {
|
|
1458
|
+
return this._loadFromQueue(meta, snapshotMap);
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
return null;
|
|
1462
|
+
}),
|
|
1463
|
+
);
|
|
1464
|
+
}
|
|
1465
|
+
|
|
1466
|
+
private async _loadQueueSnapshotMap(metas: readonly ObjectMeta[]): Promise<Map<number, unknown>> {
|
|
1467
|
+
const queueMetas = metas.filter((meta) => !meta.documentId && !!meta.queueId);
|
|
1468
|
+
if (queueMetas.length === 0) {
|
|
1469
|
+
return new Map();
|
|
701
1470
|
}
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
1471
|
+
|
|
1472
|
+
const snapshots = await this._runInRuntime(
|
|
1473
|
+
this._indexEngine.querySnapshotsJSON(queueMetas.map((meta) => meta.recordId)),
|
|
1474
|
+
);
|
|
1475
|
+
return new Map(snapshots.map((s) => [s.recordId, s.snapshot]));
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
/**
|
|
1479
|
+
* Loads a queue-backed object from an indexed snapshot (by `recordId`).
|
|
1480
|
+
* Returns `null` when the snapshot is missing or is not a JSON object.
|
|
1481
|
+
*/
|
|
1482
|
+
private _loadFromQueue(meta: ObjectMeta, snapshotMap: Map<number, unknown>): QueryItem | null {
|
|
1483
|
+
const snapshot = snapshotMap.get(meta.recordId);
|
|
1484
|
+
if (!snapshot || typeof snapshot !== 'object') {
|
|
705
1485
|
return null;
|
|
706
1486
|
}
|
|
707
1487
|
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
1488
|
+
return {
|
|
1489
|
+
objectId: meta.objectId as ObjectId,
|
|
1490
|
+
spaceId: meta.spaceId as SpaceId,
|
|
1491
|
+
queueId: meta.queueId as ObjectId,
|
|
1492
|
+
queueNamespace: 'data',
|
|
1493
|
+
documentId: null,
|
|
1494
|
+
doc: null,
|
|
1495
|
+
data: snapshot as Obj.JSON,
|
|
1496
|
+
rank: 1,
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
717
1499
|
|
|
718
|
-
|
|
719
|
-
|
|
1500
|
+
/**
|
|
1501
|
+
* Loads a document-backed object from an Automerge `DatabaseDirectory`.
|
|
1502
|
+
* Returns `null` if the document can't be loaded, the inline object isn't present, or if the meta does not have a
|
|
1503
|
+
* document id (e.g. queue-backed objects).
|
|
1504
|
+
*/
|
|
1505
|
+
private async _loadFromAutomerge(meta: ObjectMeta): Promise<QueryItem | null> {
|
|
1506
|
+
if (!meta.documentId) {
|
|
720
1507
|
return null;
|
|
721
1508
|
}
|
|
722
|
-
|
|
723
|
-
|
|
1509
|
+
const handle = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, meta.documentId as DocumentId, {
|
|
1510
|
+
fetchFromNetwork: true,
|
|
1511
|
+
});
|
|
724
1512
|
const doc = handle.doc();
|
|
725
1513
|
if (!doc) {
|
|
726
1514
|
return null;
|
|
727
1515
|
}
|
|
728
|
-
|
|
729
|
-
const object = DatabaseDirectory.getInlineObject(doc, echoDxn.echoId);
|
|
1516
|
+
const object = DatabaseDirectory.getInlineObject(doc, meta.objectId);
|
|
730
1517
|
if (!object) {
|
|
731
1518
|
return null;
|
|
732
1519
|
}
|
|
733
|
-
|
|
734
1520
|
return {
|
|
735
|
-
objectId:
|
|
736
|
-
documentId:
|
|
737
|
-
spaceId,
|
|
1521
|
+
objectId: meta.objectId,
|
|
1522
|
+
documentId: meta.documentId as DocumentId,
|
|
1523
|
+
spaceId: meta.spaceId as SpaceId,
|
|
1524
|
+
queueId: null,
|
|
1525
|
+
queueNamespace: null,
|
|
738
1526
|
doc: object,
|
|
1527
|
+
data: null,
|
|
1528
|
+
rank: 1,
|
|
739
1529
|
};
|
|
740
1530
|
}
|
|
1531
|
+
|
|
1532
|
+
private async _loadFromDXN(dxn: DXN, { sourceSpaceId }: { sourceSpaceId: SpaceId }): Promise<QueryItem | null> {
|
|
1533
|
+
switch (dxn.kind) {
|
|
1534
|
+
case DXN.kind.ECHO: {
|
|
1535
|
+
const echoDxn = dxn.asEchoDXN();
|
|
1536
|
+
if (!echoDxn) {
|
|
1537
|
+
log.warn('unable to resolve DXN', { dxn });
|
|
1538
|
+
return null;
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
const spaceId = echoDxn.spaceId ?? sourceSpaceId;
|
|
1542
|
+
|
|
1543
|
+
const spaceRoot = this._spaceStateManager.getRootBySpaceId(spaceId);
|
|
1544
|
+
if (!spaceRoot) {
|
|
1545
|
+
log.warn('no space state found for', { spaceId });
|
|
1546
|
+
return null;
|
|
1547
|
+
}
|
|
1548
|
+
const dbDirectory = spaceRoot.doc();
|
|
1549
|
+
if (!dbDirectory) {
|
|
1550
|
+
log.warn('no space state found for', { spaceId });
|
|
1551
|
+
return null;
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
const inlineObject = DatabaseDirectory.getInlineObject(dbDirectory, echoDxn.echoId);
|
|
1555
|
+
if (inlineObject) {
|
|
1556
|
+
return {
|
|
1557
|
+
objectId: echoDxn.echoId,
|
|
1558
|
+
documentId: spaceRoot.documentId,
|
|
1559
|
+
spaceId,
|
|
1560
|
+
queueId: null,
|
|
1561
|
+
queueNamespace: null,
|
|
1562
|
+
data: null,
|
|
1563
|
+
doc: inlineObject,
|
|
1564
|
+
rank: 1,
|
|
1565
|
+
};
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
const link = DatabaseDirectory.getLink(dbDirectory, echoDxn.echoId);
|
|
1569
|
+
if (!link) {
|
|
1570
|
+
return null;
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
const handle = await this._automergeHost.loadDoc<DatabaseDirectory>(this._ctx, link as AutomergeUrl, {
|
|
1574
|
+
fetchFromNetwork: true,
|
|
1575
|
+
});
|
|
1576
|
+
const doc = handle.doc();
|
|
1577
|
+
if (!doc) {
|
|
1578
|
+
return null;
|
|
1579
|
+
}
|
|
1580
|
+
|
|
1581
|
+
const object = DatabaseDirectory.getInlineObject(doc, echoDxn.echoId);
|
|
1582
|
+
if (!object) {
|
|
1583
|
+
return null;
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
return {
|
|
1587
|
+
objectId: echoDxn.echoId,
|
|
1588
|
+
documentId: handle.documentId,
|
|
1589
|
+
spaceId,
|
|
1590
|
+
queueId: null,
|
|
1591
|
+
queueNamespace: null,
|
|
1592
|
+
data: null,
|
|
1593
|
+
doc: object,
|
|
1594
|
+
rank: 1,
|
|
1595
|
+
};
|
|
1596
|
+
break;
|
|
1597
|
+
}
|
|
1598
|
+
case DXN.kind.QUEUE: {
|
|
1599
|
+
const queueDxn = dxn.asQueueDXN();
|
|
1600
|
+
if (!queueDxn || !queueDxn.objectId) {
|
|
1601
|
+
log.warn('unable to resolve queue DXN', { dxn });
|
|
1602
|
+
return null;
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
const { spaceId, queueId, objectId } = queueDxn;
|
|
1606
|
+
const meta = await this._runInRuntime(
|
|
1607
|
+
this._indexEngine.lookupByObjectId({
|
|
1608
|
+
objectId,
|
|
1609
|
+
spaceId,
|
|
1610
|
+
queueId,
|
|
1611
|
+
}),
|
|
1612
|
+
);
|
|
1613
|
+
if (!meta) {
|
|
1614
|
+
return null;
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
const snapshotMap = await this._loadQueueSnapshotMap([meta]);
|
|
1618
|
+
return this._loadFromQueue(meta, snapshotMap);
|
|
1619
|
+
}
|
|
1620
|
+
default: {
|
|
1621
|
+
log.warn('unable to resolve DXN', { dxn });
|
|
1622
|
+
return null;
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
}
|
|
1626
|
+
|
|
1627
|
+
private async _getTransitiveDeletionState(item: QueryItem, remainingDepth: number): Promise<boolean> {
|
|
1628
|
+
const strongDeps = [
|
|
1629
|
+
QueryItem.getParent(item),
|
|
1630
|
+
QueryItem.getRelationSource(item),
|
|
1631
|
+
QueryItem.getRelationTarget(item),
|
|
1632
|
+
].filter((x) => x !== undefined);
|
|
1633
|
+
|
|
1634
|
+
if (strongDeps.length === 0) {
|
|
1635
|
+
return false;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
// TODO(dmaretskyi): This could be optimized to bail early if any of the dependencies are deleted.
|
|
1639
|
+
const strongDepStates = await Promise.all(
|
|
1640
|
+
strongDeps.map(async (dxn) => {
|
|
1641
|
+
const dep = await this._loadFromDXN(DXN.parse(dxn), { sourceSpaceId: item.spaceId });
|
|
1642
|
+
if (!dep) {
|
|
1643
|
+
return false;
|
|
1644
|
+
}
|
|
1645
|
+
if (QueryItem.isDeleted(dep)) {
|
|
1646
|
+
return true;
|
|
1647
|
+
}
|
|
1648
|
+
if (remainingDepth > 0) {
|
|
1649
|
+
return this._getTransitiveDeletionState(dep, remainingDepth - 1);
|
|
1650
|
+
}
|
|
1651
|
+
return false;
|
|
1652
|
+
}),
|
|
1653
|
+
);
|
|
1654
|
+
|
|
1655
|
+
return strongDepStates.some((x) => x);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
|
|
1659
|
+
const extractQueueIds = (queues: readonly DXN.String[]): ObjectId[] | null => {
|
|
1660
|
+
if (queues.length === 0) {
|
|
1661
|
+
return null;
|
|
1662
|
+
}
|
|
1663
|
+
return queues.map((dxnStr) => DXN.parse(dxnStr).asQueueDXN()?.queueId).filter(Boolean) as ObjectId[];
|
|
1664
|
+
};
|
|
1665
|
+
|
|
1666
|
+
/**
|
|
1667
|
+
* Extract timestamp parameters from a filter AST node.
|
|
1668
|
+
* Returns null if the filter doesn't contain timestamp nodes.
|
|
1669
|
+
*/
|
|
1670
|
+
const extractTimestampParams = (
|
|
1671
|
+
filter: QueryAST.Filter,
|
|
1672
|
+
): { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } | null => {
|
|
1673
|
+
const collect = (f: QueryAST.Filter): QueryAST.FilterTimestamp[] => {
|
|
1674
|
+
if (f.type === 'timestamp') {
|
|
1675
|
+
return [f];
|
|
1676
|
+
}
|
|
1677
|
+
if (f.type === 'and') {
|
|
1678
|
+
return f.filters.flatMap(collect);
|
|
1679
|
+
}
|
|
1680
|
+
return [];
|
|
1681
|
+
};
|
|
1682
|
+
|
|
1683
|
+
const timestamps = collect(filter);
|
|
1684
|
+
if (timestamps.length === 0) {
|
|
1685
|
+
return null;
|
|
1686
|
+
}
|
|
1687
|
+
|
|
1688
|
+
const params: { updatedAfter?: number; updatedBefore?: number; createdAfter?: number; createdBefore?: number } = {};
|
|
1689
|
+
for (const ts of timestamps) {
|
|
1690
|
+
if (ts.field === 'updatedAt' && (ts.operator === 'gt' || ts.operator === 'gte')) {
|
|
1691
|
+
params.updatedAfter = ts.value;
|
|
1692
|
+
} else if (ts.field === 'updatedAt' && (ts.operator === 'lt' || ts.operator === 'lte')) {
|
|
1693
|
+
params.updatedBefore = ts.value;
|
|
1694
|
+
} else if (ts.field === 'createdAt' && (ts.operator === 'gt' || ts.operator === 'gte')) {
|
|
1695
|
+
params.createdAfter = ts.value;
|
|
1696
|
+
} else if (ts.field === 'createdAt' && (ts.operator === 'lt' || ts.operator === 'lte')) {
|
|
1697
|
+
params.createdBefore = ts.value;
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
return params;
|
|
1701
|
+
};
|
|
1702
|
+
|
|
1703
|
+
function filterContainsTimestamp(filter: QueryAST.Filter): boolean {
|
|
1704
|
+
if (filter.type === 'timestamp') {
|
|
1705
|
+
return true;
|
|
1706
|
+
}
|
|
1707
|
+
if (filter.type === 'and' || filter.type === 'or') {
|
|
1708
|
+
return filter.filters.some(filterContainsTimestamp);
|
|
1709
|
+
}
|
|
1710
|
+
if (filter.type === 'not') {
|
|
1711
|
+
return filterContainsTimestamp(filter.filter);
|
|
1712
|
+
}
|
|
1713
|
+
return false;
|
|
741
1714
|
}
|