@peerbit/document 6.0.7 → 7.0.0-3a75d6e

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.
Files changed (66) hide show
  1. package/README.md +2 -2
  2. package/dist/benchmark/index.d.ts +2 -0
  3. package/dist/benchmark/index.d.ts.map +1 -0
  4. package/dist/benchmark/index.js +125 -0
  5. package/dist/benchmark/index.js.map +1 -0
  6. package/dist/benchmark/memory/index.d.ts +2 -0
  7. package/dist/benchmark/memory/index.d.ts.map +1 -0
  8. package/dist/benchmark/memory/index.js +122 -0
  9. package/dist/benchmark/memory/index.js.map +1 -0
  10. package/dist/benchmark/memory/insert.d.ts +2 -0
  11. package/dist/benchmark/memory/insert.d.ts.map +1 -0
  12. package/dist/benchmark/memory/insert.js +133 -0
  13. package/dist/benchmark/memory/insert.js.map +1 -0
  14. package/dist/benchmark/memory/utils.d.ts +13 -0
  15. package/dist/benchmark/memory/utils.d.ts.map +1 -0
  16. package/dist/benchmark/memory/utils.js +2 -0
  17. package/dist/benchmark/memory/utils.js.map +1 -0
  18. package/dist/benchmark/replication.d.ts +2 -0
  19. package/dist/benchmark/replication.d.ts.map +1 -0
  20. package/dist/benchmark/replication.js +172 -0
  21. package/dist/benchmark/replication.js.map +1 -0
  22. package/dist/src/borsh.d.ts +2 -0
  23. package/dist/src/borsh.d.ts.map +1 -0
  24. package/dist/src/borsh.js +16 -0
  25. package/dist/src/borsh.js.map +1 -0
  26. package/dist/src/constants.d.ts +2 -0
  27. package/dist/src/constants.d.ts.map +1 -0
  28. package/dist/src/constants.js +2 -0
  29. package/dist/src/constants.js.map +1 -0
  30. package/dist/src/index.d.ts +4 -0
  31. package/dist/src/index.d.ts.map +1 -0
  32. package/dist/src/index.js +4 -0
  33. package/dist/src/index.js.map +1 -0
  34. package/dist/src/program.d.ts +87 -0
  35. package/dist/src/program.d.ts.map +1 -0
  36. package/{lib/esm/document-store.js → dist/src/program.js} +159 -138
  37. package/dist/src/program.js.map +1 -0
  38. package/dist/src/search.d.ts +132 -0
  39. package/dist/src/search.d.ts.map +1 -0
  40. package/dist/src/search.js +845 -0
  41. package/dist/src/search.js.map +1 -0
  42. package/package.json +74 -43
  43. package/src/borsh.ts +19 -0
  44. package/src/constants.ts +1 -0
  45. package/src/index.ts +3 -3
  46. package/src/program.ts +580 -0
  47. package/src/search.ts +1217 -0
  48. package/LICENSE +0 -202
  49. package/lib/esm/document-index.d.ts +0 -147
  50. package/lib/esm/document-index.js +0 -942
  51. package/lib/esm/document-index.js.map +0 -1
  52. package/lib/esm/document-store.d.ts +0 -72
  53. package/lib/esm/document-store.js.map +0 -1
  54. package/lib/esm/index.d.ts +0 -3
  55. package/lib/esm/index.js +0 -4
  56. package/lib/esm/index.js.map +0 -1
  57. package/lib/esm/query.d.ts +0 -191
  58. package/lib/esm/query.js +0 -615
  59. package/lib/esm/query.js.map +0 -1
  60. package/lib/esm/utils.d.ts +0 -3
  61. package/lib/esm/utils.js +0 -12
  62. package/lib/esm/utils.js.map +0 -1
  63. package/src/document-index.ts +0 -1268
  64. package/src/document-store.ts +0 -547
  65. package/src/query.ts +0 -525
  66. package/src/utils.ts +0 -17
@@ -1,942 +0,0 @@
1
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
6
- };
7
- var __metadata = (this && this.__metadata) || function (k, v) {
8
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
- };
10
- import { field, variant } from "@dao-xyz/borsh";
11
- import { asString } from "./utils.js";
12
- import { BORSH_ENCODING } from "@peerbit/log";
13
- import { equals } from "@peerbit/uint8arrays";
14
- import { Program } from "@peerbit/program";
15
- import { IntegerCompare, ByteMatchQuery, StringMatch, ResultWithSource, StateFieldQuery, compare, MissingField, StringMatchMethod, LogicalQuery, And, Or, BoolQuery, CollectNextRequest, AbstractSearchRequest, SearchRequest, SortDirection, CloseIteratorRequest, NoAccess, AbstractSearchResult } from "./query.js";
16
- import { RPC, queryAll, MissingResponsesError } from "@peerbit/rpc";
17
- import { Results } from "./query.js";
18
- import { logger as loggerFn } from "@peerbit/logger";
19
- import { Cache } from "@peerbit/cache";
20
- import { sha256Base64Sync } from "@peerbit/crypto";
21
- import { concat, fromString } from "uint8arrays";
22
- import { SilentDelivery } from "@peerbit/stream-interface";
23
- import { AbortError } from "@peerbit/time";
24
- const logger = loggerFn({ module: "document-index" });
25
- const stringArraysEquals = (a, b) => {
26
- if (a.length !== b.length) {
27
- return false;
28
- }
29
- for (let i = 0; i < a.length; i++) {
30
- if (a[i] !== b[i]) {
31
- return false;
32
- }
33
- }
34
- return true;
35
- };
36
- let Operation = class Operation {
37
- };
38
- Operation = __decorate([
39
- variant(0)
40
- ], Operation);
41
- export { Operation };
42
- export const BORSH_ENCODING_OPERATION = BORSH_ENCODING(Operation);
43
- let PutOperation = class PutOperation extends Operation {
44
- key;
45
- data;
46
- _value;
47
- constructor(props) {
48
- super();
49
- if (props) {
50
- this.key = props.key;
51
- this.data = props.data;
52
- this._value = props.value;
53
- }
54
- }
55
- get value() {
56
- if (!this._value) {
57
- throw new Error("Value not decoded, invoke getValue(...) once");
58
- }
59
- return this._value;
60
- }
61
- getValue(encoding) {
62
- if (this._value) {
63
- return this._value;
64
- }
65
- this._value = encoding.decoder(this.data);
66
- return this._value;
67
- }
68
- };
69
- __decorate([
70
- field({ type: "string" }),
71
- __metadata("design:type", String)
72
- ], PutOperation.prototype, "key", void 0);
73
- __decorate([
74
- field({ type: Uint8Array }),
75
- __metadata("design:type", Uint8Array)
76
- ], PutOperation.prototype, "data", void 0);
77
- PutOperation = __decorate([
78
- variant(0),
79
- __metadata("design:paramtypes", [Object])
80
- ], PutOperation);
81
- export { PutOperation };
82
- /* @variant(1)
83
- export class PutAllOperation<T> extends Operation<T> {
84
- @field({ type: vec(PutOperation) })
85
- docs: PutOperation<T>[];
86
-
87
- constructor(props?: { docs: PutOperation<T>[] }) {
88
- super();
89
- if (props) {
90
- this.docs = props.docs;
91
- }
92
- }
93
- }
94
- */
95
- let DeleteOperation = class DeleteOperation extends Operation {
96
- key;
97
- constructor(props) {
98
- super();
99
- if (props) {
100
- this.key = props.key;
101
- }
102
- }
103
- };
104
- __decorate([
105
- field({ type: "string" }),
106
- __metadata("design:type", String)
107
- ], DeleteOperation.prototype, "key", void 0);
108
- DeleteOperation = __decorate([
109
- variant(2),
110
- __metadata("design:paramtypes", [Object])
111
- ], DeleteOperation);
112
- export { DeleteOperation };
113
- const sortCompare = (av, bv) => {
114
- if (typeof av === "string" && typeof bv === "string") {
115
- return av.localeCompare(bv);
116
- }
117
- if (av < bv) {
118
- return -1;
119
- }
120
- else if (av > bv) {
121
- return 1;
122
- }
123
- return 0;
124
- };
125
- const extractFieldValue = (doc, path) => {
126
- for (let i = 0; i < path.length; i++) {
127
- doc = doc[path[i]];
128
- }
129
- return doc;
130
- };
131
- const extractSortCompare = (a, b, sorts) => {
132
- for (const sort of sorts) {
133
- const av = extractFieldValue(a, sort.key);
134
- const bv = extractFieldValue(b, sort.key);
135
- const cmp = sortCompare(av, bv);
136
- if (cmp != 0) {
137
- if (sort.direction === SortDirection.ASC) {
138
- return cmp;
139
- }
140
- else {
141
- return -cmp;
142
- }
143
- }
144
- }
145
- return 0;
146
- };
147
- const resolvedSort = async (arr, index, sorts) => {
148
- await Promise.all(arr.map(async (result) => (result[SORT_TMP_KEY] = await index(result.value.value, result.context))));
149
- arr.sort((a, b) => extractSortCompare(a[SORT_TMP_KEY], b[SORT_TMP_KEY], sorts));
150
- return arr;
151
- };
152
- const SORT_TMP_KEY = "__sort_ref";
153
- const introduceEntries = async (responses, type, sync, options) => {
154
- const results = [];
155
- for (const response of responses) {
156
- if (!response.from) {
157
- logger.error("Missing from for response");
158
- }
159
- if (response.response instanceof Results) {
160
- response.response.results.forEach((r) => r.init(type));
161
- if (typeof options?.remote !== "boolean" && options?.remote?.sync) {
162
- await sync(response.response);
163
- }
164
- options?.onResponse &&
165
- options.onResponse(response.response, response.from); // TODO fix types
166
- results.push(response);
167
- }
168
- else if (response.response instanceof NoAccess) {
169
- logger.error("Search resulted in access error");
170
- }
171
- else {
172
- throw new Error("Unsupported");
173
- }
174
- }
175
- return results;
176
- };
177
- const dedup = (allResult, dedupBy) => {
178
- const unique = new Set();
179
- const dedup = [];
180
- for (const result of allResult) {
181
- const key = asString(dedupBy(result));
182
- if (unique.has(key)) {
183
- continue;
184
- }
185
- unique.add(key);
186
- dedup.push(result);
187
- }
188
- return dedup;
189
- };
190
- const DEFAULT_INDEX_BY = "id";
191
- /*
192
- if (!(await this.canRead(message.sender))) {
193
- throw new AccessError();
194
- } */
195
- export const MAX_DOCUMENT_SIZE = 5e6;
196
- const getBatchFromResults = (results, wantedSize, maxSize = MAX_DOCUMENT_SIZE) => {
197
- const batch = [];
198
- let size = 0;
199
- for (const result of results) {
200
- batch.push(result);
201
- size += result.value.last.data.length;
202
- if (size > maxSize) {
203
- break;
204
- }
205
- if (wantedSize <= batch.length) {
206
- break;
207
- }
208
- }
209
- results.splice(0, batch.length);
210
- return batch;
211
- };
212
- let DocumentIndex = class DocumentIndex extends Program {
213
- _query;
214
- type;
215
- dbType;
216
- // Index key
217
- _indexBy;
218
- _indexByArr;
219
- // Resolve doc value by index key
220
- indexByResolver;
221
- // Indexed (transforms an docuemnt into an obj with fields that ought to be indexed)
222
- _toIndex;
223
- _valueEncoding;
224
- _sync;
225
- _index;
226
- _resultsCollectQueue;
227
- _log;
228
- constructor(properties) {
229
- super();
230
- this._query = properties?.query || new RPC();
231
- }
232
- get index() {
233
- return this._index;
234
- }
235
- get valueEncoding() {
236
- return this._valueEncoding;
237
- }
238
- get toIndex() {
239
- return this._toIndex;
240
- }
241
- async open(properties) {
242
- this._index = new Map();
243
- this._log = properties.log;
244
- this.type = properties.type;
245
- this.dbType = properties.dbType;
246
- this._sync = properties.sync;
247
- this._toIndex = properties.fields;
248
- this._indexBy = properties.indexBy || DEFAULT_INDEX_BY;
249
- this._indexByArr = Array.isArray(this._indexBy)
250
- ? this._indexBy
251
- : [this._indexBy];
252
- this.indexByResolver =
253
- typeof this._indexBy === "string"
254
- ? (obj) => obj[this._indexBy]
255
- : (obj) => extractFieldValue(obj, this._indexBy);
256
- this._valueEncoding = BORSH_ENCODING(this.type);
257
- this._resultsCollectQueue = new Cache({ max: 10000 }); // TODO choose limit better
258
- await this._query.open({
259
- topic: sha256Base64Sync(concat([this._log.log.id, fromString("/document")])),
260
- responseHandler: async (query, ctx) => {
261
- if (!ctx.from) {
262
- logger.info("Receieved query without from");
263
- return;
264
- }
265
- if (properties.canSearch &&
266
- (query instanceof SearchRequest ||
267
- query instanceof CollectNextRequest) &&
268
- !(await properties.canSearch(query, ctx.from))) {
269
- return new NoAccess();
270
- }
271
- if (query instanceof CloseIteratorRequest) {
272
- this.processCloseIteratorRequest(query, ctx.from);
273
- }
274
- else {
275
- const results = await this.processFetchRequest(query, ctx.from, {
276
- canRead: properties.canRead
277
- });
278
- return new Results({
279
- // Even if results might have length 0, respond, because then we now at least there are no matching results
280
- results: results.results.map((r) => {
281
- if (r.value.last instanceof PutOperation === false) {
282
- throw new Error("Unexpected value type on local results: " +
283
- r.value.last?.constructor.name ||
284
- typeof r.value.last);
285
- }
286
- return new ResultWithSource({
287
- source: r.value.last.data,
288
- context: r.context
289
- });
290
- }),
291
- kept: BigInt(results.kept)
292
- });
293
- }
294
- },
295
- responseType: AbstractSearchResult,
296
- queryType: AbstractSearchRequest
297
- });
298
- }
299
- async get(key, options) {
300
- return (await this.getDetailed(key, options))?.[0]?.results[0]?.value;
301
- }
302
- async getDetailed(key, options) {
303
- let results;
304
- if (key instanceof Uint8Array) {
305
- results = await this.queryDetailed(new SearchRequest({
306
- query: [new ByteMatchQuery({ key: this._indexByArr, value: key })]
307
- }), options);
308
- }
309
- else {
310
- const stringValue = asString(key);
311
- results = await this.queryDetailed(new SearchRequest({
312
- query: [
313
- new StringMatch({
314
- key: this._indexByArr,
315
- value: stringValue
316
- })
317
- ]
318
- }), options);
319
- }
320
- return results;
321
- }
322
- get size() {
323
- return this._index.size;
324
- }
325
- async getDocumentWithLastOperation(value) {
326
- if (value.reference) {
327
- return value.reference;
328
- }
329
- const head = await await this._log.log.get(value.context.head);
330
- if (!head) {
331
- return undefined; // we could end up here if we recently pruned the document and other peers never persisted the entry
332
- // TODO update changes in index before removing entries from log entry storage
333
- }
334
- const payloadValue = await head.getPayloadValue();
335
- if (payloadValue instanceof PutOperation) {
336
- return {
337
- value: payloadValue.getValue(this.valueEncoding),
338
- last: payloadValue
339
- };
340
- }
341
- throw new Error("Unexpected value type when getting document: " +
342
- payloadValue?.constructor?.name || typeof payloadValue);
343
- }
344
- getDocument(value) {
345
- return this.getDocumentWithLastOperation(value).then((r) => r?.value);
346
- }
347
- async _queryDocuments(filter) {
348
- // Whether we return the full operation data or just the db value
349
- const results = [];
350
- for (const value of this._index.values()) {
351
- if (await filter(value)) {
352
- const topDoc = await this.getDocumentWithLastOperation(value);
353
- topDoc &&
354
- results.push({
355
- context: value.context,
356
- value: topDoc
357
- });
358
- }
359
- }
360
- return results;
361
- }
362
- async processFetchRequest(query, from, options) {
363
- // We do special case for querying the id as we can do it faster than iterating
364
- if (query instanceof SearchRequest) {
365
- // Special case querying ids
366
- if (query.query.length === 1 &&
367
- (query.query[0] instanceof ByteMatchQuery ||
368
- query.query[0] instanceof StringMatch) &&
369
- stringArraysEquals(query.query[0].key, this._indexByArr)) {
370
- const firstQuery = query.query[0];
371
- if (firstQuery instanceof ByteMatchQuery) {
372
- const doc = this._index.get(asString(firstQuery.value));
373
- const topDoc = doc && (await this.getDocumentWithLastOperation(doc));
374
- return topDoc
375
- ? {
376
- results: [
377
- {
378
- value: topDoc,
379
- context: doc.context
380
- }
381
- ],
382
- kept: 0
383
- }
384
- : { results: [], kept: 0 };
385
- }
386
- else if (firstQuery instanceof StringMatch &&
387
- firstQuery.method === StringMatchMethod.exact &&
388
- firstQuery.caseInsensitive === false) {
389
- const doc = this._index.get(firstQuery.value);
390
- const topDoc = doc && (await this.getDocumentWithLastOperation(doc));
391
- return topDoc
392
- ? {
393
- results: [
394
- {
395
- value: topDoc,
396
- context: doc.context
397
- }
398
- ],
399
- kept: 0
400
- }
401
- : { results: [], kept: 0 };
402
- }
403
- }
404
- // Handle query normally
405
- let results = await this._queryDocuments(async (doc) => {
406
- for (const f of query.query) {
407
- if (!(await this.handleQueryObject(f, doc))) {
408
- return false;
409
- }
410
- }
411
- return true;
412
- });
413
- if (options?.canRead) {
414
- const keepFilter = await Promise.all(results.map((x) => options?.canRead(x.value.value, from)));
415
- results = results.filter((x, i) => keepFilter[i]);
416
- }
417
- // Sort
418
- await resolvedSort(results, this._toIndex, query.sort);
419
- const batch = getBatchFromResults(results, query.fetch);
420
- if (results.length > 0) {
421
- this._resultsCollectQueue.add(query.idString, {
422
- arr: results,
423
- from
424
- }); // cache resulst not returned
425
- }
426
- return { results: batch, kept: results.length }; // Only return 1 result since we are doing distributed sort, TODO buffer more initially
427
- }
428
- else if (query instanceof CollectNextRequest) {
429
- const results = this._resultsCollectQueue.get(query.idString);
430
- if (!results) {
431
- return {
432
- results: [],
433
- kept: 0
434
- };
435
- }
436
- const batch = getBatchFromResults(results.arr, query.amount);
437
- if (results.arr.length === 0) {
438
- this._resultsCollectQueue.del(query.idString); // TODO add tests for proper cleanup/timeouts
439
- }
440
- return { results: batch, kept: results.arr.length };
441
- }
442
- throw new Error("Unsupported");
443
- }
444
- async processCloseIteratorRequest(query, publicKey) {
445
- const entry = this._resultsCollectQueue.get(query.idString);
446
- if (entry?.from.equals(publicKey)) {
447
- this._resultsCollectQueue.del(query.idString);
448
- }
449
- else if (entry) {
450
- logger.warn("Received a close iterator request for a iterator that does not belong to the requesting peer");
451
- }
452
- }
453
- async handleFieldQuery(f, obj, startIndex) {
454
- // this clause is needed if we have a field that is of type [][] (we will recursively go through each subarray)
455
- if (Array.isArray(obj)) {
456
- for (const element of obj) {
457
- if (await this.handleFieldQuery(f, element, startIndex)) {
458
- return true;
459
- }
460
- }
461
- return false;
462
- }
463
- // Resolve the field from the key path. If we reach an array or nested Document store,
464
- // then do a recursive call or a search to look into them
465
- for (let i = startIndex; i < f.key.length; i++) {
466
- obj = obj[f.key[i]];
467
- if (Array.isArray(obj)) {
468
- for (const element of obj) {
469
- if (await this.handleFieldQuery(f, element, i + 1)) {
470
- return true;
471
- }
472
- }
473
- return false;
474
- }
475
- if (obj instanceof this.dbType) {
476
- const queryCloned = f.clone();
477
- queryCloned.key.splice(0, i + 1); // remove key path until the document store
478
- const results = await obj.index.search(new SearchRequest({ query: [queryCloned] }));
479
- return results.length > 0 ? true : false; // TODO return INNER HITS?
480
- }
481
- }
482
- // When we reach here, the field value (obj) is comparable
483
- if (f instanceof StringMatch) {
484
- let compare = f.value;
485
- if (f.caseInsensitive) {
486
- compare = compare.toLowerCase();
487
- }
488
- if (this.handleStringMatch(f, compare, obj)) {
489
- return true;
490
- }
491
- return false;
492
- }
493
- else if (f instanceof ByteMatchQuery) {
494
- if (obj instanceof Uint8Array === false) {
495
- if (stringArraysEquals(f.key, this._indexByArr)) {
496
- return f.valueString === obj;
497
- }
498
- return false;
499
- }
500
- return equals(obj, f.value);
501
- }
502
- else if (f instanceof IntegerCompare) {
503
- const value = obj;
504
- if (typeof value !== "bigint" && typeof value !== "number") {
505
- return false;
506
- }
507
- return compare(value, f.compare, f.value.value);
508
- }
509
- else if (f instanceof MissingField) {
510
- return obj == null; // null or undefined
511
- }
512
- else if (f instanceof BoolQuery) {
513
- return obj === f.value; // true/false
514
- }
515
- logger.warn("Unsupported query type: " + f.constructor.name);
516
- return false;
517
- }
518
- async handleQueryObject(f, doc) {
519
- if (f instanceof StateFieldQuery) {
520
- return this.handleFieldQuery(f, doc.value, 0);
521
- }
522
- else if (f instanceof LogicalQuery) {
523
- if (f instanceof And) {
524
- for (const and of f.and) {
525
- if (!(await this.handleQueryObject(and, doc))) {
526
- return false;
527
- }
528
- }
529
- return true;
530
- }
531
- if (f instanceof Or) {
532
- for (const or of f.or) {
533
- if (await this.handleQueryObject(or, doc)) {
534
- return true;
535
- }
536
- }
537
- return false;
538
- }
539
- return false;
540
- }
541
- logger.info("Unsupported query type: " + f.constructor.name);
542
- return false;
543
- }
544
- handleStringMatch(f, compare, fv) {
545
- if (typeof fv !== "string") {
546
- return false;
547
- }
548
- if (f.caseInsensitive) {
549
- fv = fv.toLowerCase();
550
- }
551
- if (f.method === StringMatchMethod.exact) {
552
- return fv === compare;
553
- }
554
- if (f.method === StringMatchMethod.prefix) {
555
- return fv.startsWith(compare);
556
- }
557
- if (f.method === StringMatchMethod.contains) {
558
- return fv.includes(compare);
559
- }
560
- throw new Error("Unsupported");
561
- }
562
- /**
563
- * Query and retrieve results with most details
564
- * @param queryRequest
565
- * @param options
566
- * @returns
567
- */
568
- async queryDetailed(queryRequest, options) {
569
- const local = typeof options?.local == "boolean" ? options?.local : true;
570
- let remote = undefined;
571
- if (typeof options?.remote === "boolean") {
572
- if (options?.remote) {
573
- remote = {};
574
- }
575
- else {
576
- remote = undefined;
577
- }
578
- }
579
- else {
580
- remote = options?.remote || {};
581
- }
582
- if (remote && remote.priority == null) {
583
- // give queries higher priority than other "normal" data activities
584
- // without this, we might have a scenario that a peer joina network with large amount of data to be synced, but can not query anything before that is done
585
- // this will lead to bad UX as you usually want to list/expore whats going on before doing any replication work
586
- remote.priority = 1;
587
- }
588
- const promises = [];
589
- if (!local && !remote) {
590
- throw new Error("Expecting either 'options.remote' or 'options.local' to be true");
591
- }
592
- const allResults = [];
593
- if (local) {
594
- const results = await this.processFetchRequest(queryRequest, this.node.identity.publicKey);
595
- if (results.results.length > 0) {
596
- const resultsObject = new Results({
597
- results: results.results.map((r) => {
598
- if (r.value.last instanceof PutOperation === false) {
599
- throw new Error("Unexpected value type on local results: " +
600
- r.value.last?.constructor.name || typeof r.value.last);
601
- }
602
- return new ResultWithSource({
603
- context: r.context,
604
- value: r.value.value,
605
- source: r.value.last.data
606
- });
607
- }),
608
- kept: BigInt(results.kept)
609
- });
610
- options?.onResponse &&
611
- options.onResponse(resultsObject, this.node.identity.publicKey);
612
- allResults.push(resultsObject);
613
- }
614
- }
615
- if (remote) {
616
- const replicatorGroups = await this._log.getReplicatorUnion(remote.minAge);
617
- if (replicatorGroups) {
618
- const groupHashes = replicatorGroups.map((x) => [x]);
619
- const fn = async () => {
620
- const rs = [];
621
- const responseHandler = async (results) => {
622
- for (const r of await introduceEntries(results, this.type, this._sync, options)) {
623
- rs.push(r.response);
624
- }
625
- };
626
- try {
627
- if (queryRequest instanceof CloseIteratorRequest) {
628
- // don't wait for responses
629
- await this._query.request(queryRequest, { mode: remote.mode });
630
- }
631
- else {
632
- await queryAll(this._query, groupHashes, queryRequest, responseHandler, remote);
633
- }
634
- }
635
- catch (error) {
636
- if (error instanceof MissingResponsesError) {
637
- logger.warn("Did not reciveve responses from all shard");
638
- if (remote?.throwOnMissing) {
639
- throw error;
640
- }
641
- }
642
- else {
643
- throw error;
644
- }
645
- }
646
- return rs;
647
- };
648
- promises.push(fn());
649
- }
650
- else {
651
- // TODO send without direction out to the world? or just assume we can insert?
652
- /* promises.push(
653
- this._query
654
- .request(queryRequest, remote)
655
- .then((results) => introduceEntries(results, this.type, this._sync, options).then(x => x.map(y => y.response)))
656
- ); */
657
- /* throw new Error(
658
- "Missing remote replicator info for performing distributed document query"
659
- ); */
660
- }
661
- }
662
- const resolved = await Promise.all(promises);
663
- for (const r of resolved) {
664
- if (r) {
665
- if (r instanceof Array) {
666
- allResults.push(...r);
667
- }
668
- else {
669
- allResults.push(r);
670
- }
671
- }
672
- }
673
- return allResults;
674
- }
675
- /**
676
- * Query and retrieve results
677
- * @param queryRequest
678
- * @param options
679
- * @returns
680
- */
681
- async search(queryRequest, options) {
682
- // Set fetch to search size, or max value (default to max u32 (4294967295))
683
- queryRequest.fetch = options?.size ?? 0xffffffff;
684
- // So that the iterator is pre-fetching the right amount of entries
685
- const iterator = this.iterate(queryRequest, options);
686
- // So that this call will not do any remote requests
687
- const allResults = [];
688
- while (iterator.done() === false &&
689
- queryRequest.fetch > allResults.length) {
690
- // We might need to pull .next multiple time due to data message size limitations
691
- for (const result of await iterator.next(queryRequest.fetch - allResults.length)) {
692
- allResults.push(result);
693
- }
694
- }
695
- await iterator.close();
696
- //s Deduplicate and return values directly
697
- return dedup(allResults, this.indexByResolver);
698
- }
699
- /**
700
- * Query and retrieve documents in a iterator
701
- * @param queryRequest
702
- * @param options
703
- * @returns
704
- */
705
- iterate(queryRequest, options) {
706
- let fetchPromise = undefined;
707
- const peerBufferMap = new Map();
708
- const visited = new Set();
709
- let done = false;
710
- let first = false;
711
- // TODO handle join/leave while iterating
712
- const controller = new AbortController();
713
- const peerBuffers = () => {
714
- return [...peerBufferMap.values()].map((x) => x.buffer).flat();
715
- };
716
- const fetchFirst = async (n) => {
717
- done = true; // Assume we are donne
718
- queryRequest.fetch = n;
719
- await this.queryDetailed(queryRequest, {
720
- ...options,
721
- onResponse: (response, from) => {
722
- if (!from) {
723
- logger.error("Missing response from");
724
- return;
725
- }
726
- if (response instanceof NoAccess) {
727
- logger.error("Dont have access");
728
- return;
729
- }
730
- else if (response instanceof Results) {
731
- const results = response;
732
- if (results.kept === 0n && results.results.length === 0) {
733
- return;
734
- }
735
- if (results.kept > 0n) {
736
- done = false; // we have more to do later!
737
- }
738
- peerBufferMap.set(from.hashcode(), {
739
- buffer: results.results
740
- .filter((x) => !visited.has(asString(this.indexByResolver(x.value))))
741
- .map((x) => {
742
- visited.add(asString(this.indexByResolver(x.value)));
743
- return {
744
- from,
745
- value: { value: x.value },
746
- context: x.context
747
- };
748
- }),
749
- kept: Number(response.kept)
750
- });
751
- }
752
- else {
753
- throw new Error("Unsupported result type: " + response?.constructor?.name);
754
- }
755
- }
756
- });
757
- return done;
758
- };
759
- const fetchAtLeast = async (n) => {
760
- if (done && first) {
761
- return;
762
- }
763
- await fetchPromise;
764
- if (!first) {
765
- first = true;
766
- fetchPromise = fetchFirst(n);
767
- return fetchPromise;
768
- }
769
- const promises = [];
770
- let resultsLeft = 0;
771
- for (const [peer, buffer] of peerBufferMap) {
772
- if (buffer.buffer.length < n) {
773
- if (buffer.kept === 0) {
774
- if (peerBufferMap.get(peer)?.buffer.length === 0) {
775
- peerBufferMap.delete(peer); // No more results
776
- }
777
- continue;
778
- }
779
- // TODO buffer more than deleted?
780
- // TODO batch to multiple 'to's
781
- const collectRequest = new CollectNextRequest({
782
- id: queryRequest.id,
783
- amount: n - buffer.buffer.length
784
- });
785
- // Fetch locally?
786
- if (peer === this.node.identity.publicKey.hashcode()) {
787
- promises.push(this.processFetchRequest(collectRequest, this.node.identity.publicKey)
788
- .then((results) => {
789
- resultsLeft += results.kept;
790
- if (results.results.length === 0) {
791
- if (peerBufferMap.get(peer)?.buffer.length === 0) {
792
- peerBufferMap.delete(peer); // No more results
793
- }
794
- }
795
- else {
796
- const peerBuffer = peerBufferMap.get(peer);
797
- if (!peerBuffer) {
798
- return;
799
- }
800
- peerBuffer.kept = results.kept;
801
- peerBuffer.buffer.push(...results.results
802
- .filter((x) => !visited.has(asString(this.indexByResolver(x.value.value))))
803
- .map((x) => {
804
- visited.add(asString(this.indexByResolver(x.value.value)));
805
- return {
806
- value: x.value,
807
- context: x.context,
808
- from: this.node.identity.publicKey
809
- };
810
- }));
811
- }
812
- })
813
- .catch((e) => {
814
- logger.error("Failed to collect sorted results from self. " + e?.message);
815
- peerBufferMap.delete(peer);
816
- }));
817
- }
818
- else {
819
- // Fetch remotely
820
- promises.push(this._query
821
- .request(collectRequest, {
822
- ...options,
823
- signal: controller.signal,
824
- priority: 1,
825
- mode: new SilentDelivery({ to: [peer], redundancy: 1 })
826
- })
827
- .then((response) => introduceEntries(response, this.type, this._sync, options)
828
- .then((responses) => {
829
- responses.map((response) => {
830
- resultsLeft += Number(response.response.kept);
831
- if (!response.from) {
832
- logger.error("Missing from for sorted query");
833
- return;
834
- }
835
- if (response.response.results.length === 0) {
836
- if (peerBufferMap.get(peer)?.buffer.length === 0) {
837
- peerBufferMap.delete(peer); // No more results
838
- }
839
- }
840
- else {
841
- const peerBuffer = peerBufferMap.get(peer);
842
- if (!peerBuffer) {
843
- return;
844
- }
845
- peerBuffer.kept = Number(response.response.kept);
846
- peerBuffer.buffer.push(...response.response.results
847
- .filter((x) => !visited.has(asString(this.indexByResolver(x.value))))
848
- .map((x) => {
849
- visited.add(asString(this.indexByResolver(x.value)));
850
- return {
851
- value: { value: x.value },
852
- context: x.context,
853
- from: response.from
854
- };
855
- }));
856
- }
857
- });
858
- })
859
- .catch((e) => {
860
- logger.error("Failed to collect sorted results from: " +
861
- peer +
862
- ". " +
863
- e?.message);
864
- peerBufferMap.delete(peer);
865
- })));
866
- }
867
- }
868
- else {
869
- resultsLeft += peerBufferMap.get(peer)?.kept || 0;
870
- }
871
- }
872
- return (fetchPromise = Promise.all(promises).then(() => {
873
- return resultsLeft === 0; // 0 results left to fetch and 0 pending results
874
- }));
875
- };
876
- const next = async (n) => {
877
- if (n < 0) {
878
- throw new Error("Expecting to fetch a positive amount of element");
879
- }
880
- if (n === 0) {
881
- return [];
882
- }
883
- // TODO everything below is not very optimized
884
- const fetchedAll = await fetchAtLeast(n);
885
- // get n next top entries, shift and pull more results
886
- const results = await resolvedSort(peerBuffers(), this._toIndex, queryRequest.sort);
887
- const pendingMoreResults = n < results.length;
888
- const batch = results.splice(0, n);
889
- for (const result of batch) {
890
- const arr = peerBufferMap.get(result.from.hashcode());
891
- if (!arr) {
892
- logger.error("Unexpected empty result buffer");
893
- continue;
894
- }
895
- const idx = arr.buffer.findIndex((x) => x == result);
896
- if (idx >= 0) {
897
- arr.buffer.splice(idx, 1);
898
- }
899
- }
900
- done = fetchedAll && !pendingMoreResults;
901
- return dedup(batch.map((x) => x.value.value), this.indexByResolver);
902
- };
903
- const close = async () => {
904
- controller.abort(new AbortError("Iterator closed"));
905
- const closeRequest = new CloseIteratorRequest({ id: queryRequest.id });
906
- const promises = [];
907
- for (const [peer, buffer] of peerBufferMap) {
908
- if (buffer.kept === 0) {
909
- peerBufferMap.delete(peer);
910
- continue;
911
- }
912
- // Fetch locally?
913
- if (peer === this.node.identity.publicKey.hashcode()) {
914
- promises.push(this.processCloseIteratorRequest(closeRequest, this.node.identity.publicKey));
915
- }
916
- else {
917
- // Close remote
918
- promises.push(this._query.send(closeRequest, {
919
- ...options,
920
- mode: new SilentDelivery({ to: [peer], redundancy: 1 })
921
- }));
922
- }
923
- }
924
- await Promise.all(promises);
925
- };
926
- return {
927
- close,
928
- next,
929
- done: () => done
930
- };
931
- }
932
- };
933
- __decorate([
934
- field({ type: RPC }),
935
- __metadata("design:type", RPC)
936
- ], DocumentIndex.prototype, "_query", void 0);
937
- DocumentIndex = __decorate([
938
- variant("documents_index"),
939
- __metadata("design:paramtypes", [Object])
940
- ], DocumentIndex);
941
- export { DocumentIndex };
942
- //# sourceMappingURL=document-index.js.map