js-bao 0.12.0-alpha.6 → 0.12.0-alpha.8
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/browser.cjs +1235 -170
- package/dist/browser.d.cts +479 -34
- package/dist/browser.d.ts +479 -34
- package/dist/browser.js +1233 -168
- package/dist/client.cjs +242 -1
- package/dist/client.d.cts +136 -4
- package/dist/client.d.ts +136 -4
- package/dist/client.js +242 -1
- package/dist/cloudflare-do.cjs +365 -36
- package/dist/cloudflare-do.d.cts +217 -16
- package/dist/cloudflare-do.d.ts +217 -16
- package/dist/cloudflare-do.js +365 -36
- package/dist/cloudflare.cjs +245 -2
- package/dist/cloudflare.d.cts +139 -5
- package/dist/cloudflare.d.ts +139 -5
- package/dist/cloudflare.js +245 -2
- package/dist/codegen-v2.cjs +245 -2
- package/dist/format2-worker.js +2004 -1820
- package/dist/index.cjs +1285 -200
- package/dist/index.d.cts +526 -38
- package/dist/index.d.ts +526 -38
- package/dist/index.js +1276 -196
- package/dist/node.cjs +1240 -171
- package/dist/node.d.cts +479 -34
- package/dist/node.d.ts +479 -34
- package/dist/node.js +1233 -167
- package/dist/record-log.cjs +34 -1
- package/dist/record-log.d.cts +48 -5
- package/dist/record-log.d.ts +48 -5
- package/dist/record-log.js +34 -1
- package/package.json +1 -1
package/dist/browser.cjs
CHANGED
|
@@ -257,6 +257,8 @@ var init_queryTypes = __esm({
|
|
|
257
257
|
}
|
|
258
258
|
};
|
|
259
259
|
InvalidCursorError = class _InvalidCursorError extends DocumentQueryError {
|
|
260
|
+
code = "INVALID_CURSOR";
|
|
261
|
+
status = 400;
|
|
260
262
|
cursor;
|
|
261
263
|
constructor(message, cursor) {
|
|
262
264
|
super(message);
|
|
@@ -292,7 +294,7 @@ function stripCursorSortValues(row, aliasedFields) {
|
|
|
292
294
|
}
|
|
293
295
|
return stripped ?? row;
|
|
294
296
|
}
|
|
295
|
-
var base64Encode, base64Decode, CURSOR_SORT_ALIAS_PREFIX, CursorManager;
|
|
297
|
+
var base64Encode, asciiJson, base64Decode, CURSOR_SORT_ALIAS_PREFIX, CursorManager;
|
|
296
298
|
var init_CursorManager = __esm({
|
|
297
299
|
"src/query/CursorManager.ts"() {
|
|
298
300
|
"use strict";
|
|
@@ -306,6 +308,10 @@ var init_CursorManager = __esm({
|
|
|
306
308
|
throw new Error("No base64 encoding available");
|
|
307
309
|
}
|
|
308
310
|
};
|
|
311
|
+
asciiJson = (json) => json.replace(
|
|
312
|
+
/[\u0080-\uffff]/g,
|
|
313
|
+
(c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0")
|
|
314
|
+
);
|
|
309
315
|
base64Decode = (str) => {
|
|
310
316
|
if (typeof atob !== "undefined") {
|
|
311
317
|
return atob(str);
|
|
@@ -323,7 +329,7 @@ var init_CursorManager = __esm({
|
|
|
323
329
|
static encodeCursor(cursorData) {
|
|
324
330
|
try {
|
|
325
331
|
const jsonString = JSON.stringify(cursorData);
|
|
326
|
-
return base64Encode(jsonString);
|
|
332
|
+
return base64Encode(asciiJson(jsonString));
|
|
327
333
|
} catch (error) {
|
|
328
334
|
throw new InvalidCursorError(
|
|
329
335
|
`Failed to encode cursor: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
@@ -350,6 +356,11 @@ var init_CursorManager = __esm({
|
|
|
350
356
|
if (parsed.direction !== 1 && parsed.direction !== -1) {
|
|
351
357
|
throw new Error("Cursor direction must be 1 or -1");
|
|
352
358
|
}
|
|
359
|
+
if (parsed.sortDirections !== void 0 && (!Array.isArray(parsed.sortDirections) || parsed.sortDirections.length !== parsed.sortFields.length || !parsed.sortDirections.every((d) => d === 1 || d === -1))) {
|
|
360
|
+
throw new Error(
|
|
361
|
+
"Cursor sortDirections must be 1 or -1 for each sort field"
|
|
362
|
+
);
|
|
363
|
+
}
|
|
353
364
|
return parsed;
|
|
354
365
|
} catch (error) {
|
|
355
366
|
throw new InvalidCursorError(
|
|
@@ -369,8 +380,13 @@ var init_CursorManager = __esm({
|
|
|
369
380
|
* engine. `null` rather than `undefined` because `JSON.stringify` drops a key
|
|
370
381
|
* whose value is `undefined`, and the payload's shape is the wire contract
|
|
371
382
|
* the Swift port reads.
|
|
383
|
+
*
|
|
384
|
+
* `sortDirections` are the query's declared per-field directions (as
|
|
385
|
+
* {@link CursorManager.buildOrderClause} returns them). They are written into
|
|
386
|
+
* the cursor so {@link CursorManager.buildPaginationConditions} can refuse it
|
|
387
|
+
* under any other sort.
|
|
372
388
|
*/
|
|
373
|
-
static generateCursor(record, sortFields, direction) {
|
|
389
|
+
static generateCursor(record, sortFields, direction, sortDirections) {
|
|
374
390
|
const values = {};
|
|
375
391
|
for (const field of sortFields) {
|
|
376
392
|
const value = Object.prototype.hasOwnProperty.call(record, field) ? record[field] : void 0;
|
|
@@ -379,7 +395,8 @@ var init_CursorManager = __esm({
|
|
|
379
395
|
const cursorData = {
|
|
380
396
|
values,
|
|
381
397
|
sortFields,
|
|
382
|
-
direction
|
|
398
|
+
direction,
|
|
399
|
+
...sortDirections ? { sortDirections } : {}
|
|
383
400
|
};
|
|
384
401
|
return this.encodeCursor(cursorData);
|
|
385
402
|
}
|
|
@@ -408,16 +425,36 @@ var init_CursorManager = __esm({
|
|
|
408
425
|
* receives `IS NULL` handling and the default `sort: {id}` pagination SQL
|
|
409
426
|
* stays byte-identical to what it was. So does every non-null `>` level, so
|
|
410
427
|
* an ascending page over an old-format cursor compiles exactly as before.
|
|
428
|
+
*
|
|
429
|
+
* A cursor is valid only under the sort that minted it. One whose
|
|
430
|
+
* `sortFields` differ from the query's, or whose `sortDirections` differ
|
|
431
|
+
* from the query's declared directions, is refused with
|
|
432
|
+
* {@link InvalidCursorError}: paging from it would skip and repeat rows. A
|
|
433
|
+
* cursor without `sortDirections` predates them and is checked on its
|
|
434
|
+
* fields only.
|
|
411
435
|
*/
|
|
412
436
|
static buildPaginationConditions(cursor, currentSortFields, sortDirections, requestedDirection, fieldFormatter = (field) => field) {
|
|
413
437
|
if (!this.arraysEqual(cursor.sortFields, currentSortFields)) {
|
|
414
438
|
throw new InvalidCursorError(
|
|
415
|
-
`
|
|
439
|
+
`Invalid cursor: its sort fields [${cursor.sortFields.join(
|
|
416
440
|
", "
|
|
417
441
|
)}] don't match query sort fields [${currentSortFields.join(", ")}]`,
|
|
418
442
|
JSON.stringify(cursor)
|
|
419
443
|
);
|
|
420
444
|
}
|
|
445
|
+
if (cursor.sortDirections) {
|
|
446
|
+
const declared = currentSortFields.map(
|
|
447
|
+
(_, i) => sortDirections[i] ?? 1
|
|
448
|
+
);
|
|
449
|
+
if (!this.arraysEqual(cursor.sortDirections, declared)) {
|
|
450
|
+
throw new InvalidCursorError(
|
|
451
|
+
`Invalid cursor: its sort directions [${cursor.sortDirections.join(
|
|
452
|
+
", "
|
|
453
|
+
)}] don't match query sort directions [${declared.join(", ")}]`,
|
|
454
|
+
JSON.stringify(cursor)
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
421
458
|
const conditions = [];
|
|
422
459
|
const params = [];
|
|
423
460
|
const sortFields = cursor.sortFields;
|
|
@@ -506,11 +543,9 @@ var init_CursorManager = __esm({
|
|
|
506
543
|
directions.push(dir);
|
|
507
544
|
}
|
|
508
545
|
}
|
|
509
|
-
if (!sort || !
|
|
546
|
+
if (!sort || !Object.prototype.hasOwnProperty.call(sort, "id")) {
|
|
510
547
|
clauses.push(`${fieldFormatter("id")} ${sqlDir(1)}`);
|
|
511
548
|
directions.push(1);
|
|
512
|
-
} else if (sort && sort.hasOwnProperty("id")) {
|
|
513
|
-
directions.push(sort["id"]);
|
|
514
549
|
}
|
|
515
550
|
return {
|
|
516
551
|
sql: clauses.join(", "),
|
|
@@ -528,9 +563,11 @@ var init_CursorManager = __esm({
|
|
|
528
563
|
return actualResultCount >= requestedLimit;
|
|
529
564
|
}
|
|
530
565
|
/**
|
|
531
|
-
* Generate next and previous cursors from result set
|
|
566
|
+
* Generate next and previous cursors from result set. `sortDirections` are
|
|
567
|
+
* the query's declared per-field directions, written into each cursor (see
|
|
568
|
+
* {@link CursorManager.generateCursor}).
|
|
532
569
|
*/
|
|
533
|
-
static generateResultCursors(results, sortFields, requestedDirection, hasMore, isFirstPage = false) {
|
|
570
|
+
static generateResultCursors(results, sortFields, requestedDirection, hasMore, isFirstPage = false, sortDirections) {
|
|
534
571
|
if (results.length === 0) {
|
|
535
572
|
return {};
|
|
536
573
|
}
|
|
@@ -540,7 +577,8 @@ var init_CursorManager = __esm({
|
|
|
540
577
|
cursors.nextCursor = this.generateCursor(
|
|
541
578
|
lastResult,
|
|
542
579
|
sortFields,
|
|
543
|
-
requestedDirection
|
|
580
|
+
requestedDirection,
|
|
581
|
+
sortDirections
|
|
544
582
|
);
|
|
545
583
|
}
|
|
546
584
|
if (results.length > 0 && !isFirstPage) {
|
|
@@ -549,7 +587,8 @@ var init_CursorManager = __esm({
|
|
|
549
587
|
cursors.prevCursor = this.generateCursor(
|
|
550
588
|
firstResult,
|
|
551
589
|
sortFields,
|
|
552
|
-
opposite
|
|
590
|
+
opposite,
|
|
591
|
+
sortDirections
|
|
553
592
|
);
|
|
554
593
|
}
|
|
555
594
|
return cursors;
|
|
@@ -922,7 +961,7 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
922
961
|
/**
|
|
923
962
|
* Translate document filter and options to SQL for find operations
|
|
924
963
|
*/
|
|
925
|
-
translateFind(filter, options) {
|
|
964
|
+
translateFind(filter, options, internal) {
|
|
926
965
|
if (options?.projection) {
|
|
927
966
|
this.validateProjection(options.projection);
|
|
928
967
|
}
|
|
@@ -948,7 +987,8 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
948
987
|
);
|
|
949
988
|
const selectClause = this.buildSelectClause(
|
|
950
989
|
options?.projection,
|
|
951
|
-
cursorSortValueFields
|
|
990
|
+
cursorSortValueFields,
|
|
991
|
+
internal?.selectDocument === true
|
|
952
992
|
);
|
|
953
993
|
let sql = `SELECT ${selectClause} FROM ${this.quotedTableName}`;
|
|
954
994
|
const params = [];
|
|
@@ -1423,8 +1463,12 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
1423
1463
|
* ({@link cursorSortValueFields}, #3228) so the cursor carries the row's real
|
|
1424
1464
|
* value rather than a false null; `BaseModel.query` strips those columns
|
|
1425
1465
|
* before the rows leave it, so response shapes are unchanged.
|
|
1466
|
+
*
|
|
1467
|
+
* `selectDocument` adds the row's document column to an inclusion
|
|
1468
|
+
* projection for a consumer that reads per-document data after the query
|
|
1469
|
+
* ({@link FindInternals}); it is never added unasked.
|
|
1426
1470
|
*/
|
|
1427
|
-
buildSelectClause(projection, aliasedSortFields) {
|
|
1471
|
+
buildSelectClause(projection, aliasedSortFields, selectDocument = false) {
|
|
1428
1472
|
if (!projection || Object.keys(projection).length === 0) {
|
|
1429
1473
|
return "*";
|
|
1430
1474
|
}
|
|
@@ -1453,6 +1497,9 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
1453
1497
|
includeFields.unshift("id");
|
|
1454
1498
|
}
|
|
1455
1499
|
const quoted = includeFields.map((field) => this.getQuotedField(field));
|
|
1500
|
+
if (selectDocument) {
|
|
1501
|
+
quoted.push(quoteIdentifier(DOCUMENT_TIEBREAKER));
|
|
1502
|
+
}
|
|
1456
1503
|
for (const field of aliasedSortFields ?? []) {
|
|
1457
1504
|
quoted.push(
|
|
1458
1505
|
`${this.quotedSortField(field)} AS ${quoteIdentifier(
|
|
@@ -1494,26 +1541,26 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
1494
1541
|
if (!options?.uniqueStartKey || !sortFields || !sortDirections) {
|
|
1495
1542
|
return { sql: "", params: [] };
|
|
1496
1543
|
}
|
|
1544
|
+
let cursor;
|
|
1497
1545
|
try {
|
|
1498
|
-
|
|
1499
|
-
const direction = options.direction || 1;
|
|
1500
|
-
const fields = sortFields.slice();
|
|
1501
|
-
const directions = sortDirections.slice();
|
|
1502
|
-
if (fields[fields.length - 1] === DOCUMENT_TIEBREAKER && cursor.sortFields.length === fields.length - 1) {
|
|
1503
|
-
fields.pop();
|
|
1504
|
-
directions.pop();
|
|
1505
|
-
}
|
|
1506
|
-
return CursorManager.buildPaginationConditions(
|
|
1507
|
-
cursor,
|
|
1508
|
-
fields,
|
|
1509
|
-
directions,
|
|
1510
|
-
direction,
|
|
1511
|
-
(field) => this.quotedSortField(field)
|
|
1512
|
-
);
|
|
1546
|
+
cursor = CursorManager.decodeCursor(options.uniqueStartKey);
|
|
1513
1547
|
} catch (error) {
|
|
1514
1548
|
console.warn("Invalid cursor provided, ignoring pagination:", error);
|
|
1515
1549
|
return { sql: "", params: [] };
|
|
1516
1550
|
}
|
|
1551
|
+
const fields = sortFields.slice();
|
|
1552
|
+
const directions = sortDirections.slice();
|
|
1553
|
+
if (fields[fields.length - 1] === DOCUMENT_TIEBREAKER && cursor.sortFields.length === fields.length - 1) {
|
|
1554
|
+
fields.pop();
|
|
1555
|
+
directions.pop();
|
|
1556
|
+
}
|
|
1557
|
+
return CursorManager.buildPaginationConditions(
|
|
1558
|
+
cursor,
|
|
1559
|
+
fields,
|
|
1560
|
+
directions,
|
|
1561
|
+
options.direction || 1,
|
|
1562
|
+
(field) => this.quotedSortField(field)
|
|
1563
|
+
);
|
|
1517
1564
|
}
|
|
1518
1565
|
/**
|
|
1519
1566
|
* Validate that field exists in schema
|
|
@@ -1673,6 +1720,51 @@ var init_DocumentQueryTranslator = __esm({
|
|
|
1673
1720
|
}
|
|
1674
1721
|
});
|
|
1675
1722
|
|
|
1723
|
+
// src/query/projectedRows.ts
|
|
1724
|
+
function projectedStringSetFields(projection, schema) {
|
|
1725
|
+
if (!projection) return [];
|
|
1726
|
+
return Object.entries(projection).filter(
|
|
1727
|
+
([field, include]) => include === 1 && schema.get(field)?.type === "stringset"
|
|
1728
|
+
).map(([field]) => field);
|
|
1729
|
+
}
|
|
1730
|
+
function projectedFieldValue(fieldOptions, value) {
|
|
1731
|
+
if (fieldOptions?.type === "boolean" && typeof value === "number") {
|
|
1732
|
+
return value !== 0;
|
|
1733
|
+
}
|
|
1734
|
+
return value;
|
|
1735
|
+
}
|
|
1736
|
+
async function attachStringSetMembers(engine, junctions, rows) {
|
|
1737
|
+
if (junctions.length === 0 || rows.length === 0) return;
|
|
1738
|
+
const key = (id, doc) => JSON.stringify([String(id), doc ?? null]);
|
|
1739
|
+
const ids = [...new Set(rows.map((row) => String(row.id)))];
|
|
1740
|
+
for (const { field, table, foreignKey } of junctions) {
|
|
1741
|
+
const members = /* @__PURE__ */ new Map();
|
|
1742
|
+
const quotedForeignKey = quoteIdentifier(foreignKey);
|
|
1743
|
+
for (let i = 0; i < ids.length; i += CHUNK_SIZE) {
|
|
1744
|
+
const chunk = ids.slice(i, i + CHUNK_SIZE);
|
|
1745
|
+
const sql = `SELECT ${quotedForeignKey} AS "record_id", "value", ${quoteIdentifier(DOC2)} AS "doc" FROM ${quoteIdentifier(table)} WHERE ${quotedForeignKey} IN (${chunk.map(() => "?").join(", ")}) ORDER BY "value"`;
|
|
1746
|
+
for (const member of await engine.query(sql, chunk)) {
|
|
1747
|
+
const at = key(member.record_id, member.doc);
|
|
1748
|
+
const list = members.get(at);
|
|
1749
|
+
if (list) list.push(String(member.value));
|
|
1750
|
+
else members.set(at, [String(member.value)]);
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
for (const row of rows) {
|
|
1754
|
+
row[field] = members.get(key(row.id, row[DOC2])) ?? [];
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
var DOC2, CHUNK_SIZE;
|
|
1759
|
+
var init_projectedRows = __esm({
|
|
1760
|
+
"src/query/projectedRows.ts"() {
|
|
1761
|
+
"use strict";
|
|
1762
|
+
init_sql();
|
|
1763
|
+
DOC2 = "_meta_doc_id";
|
|
1764
|
+
CHUNK_SIZE = 99;
|
|
1765
|
+
}
|
|
1766
|
+
});
|
|
1767
|
+
|
|
1676
1768
|
// src/utils/yjsValues.ts
|
|
1677
1769
|
function isYjsComposite(value) {
|
|
1678
1770
|
return value instanceof Y.Map || value instanceof Y.Array || value instanceof Y.Text;
|
|
@@ -2459,6 +2551,225 @@ var init_OrmContext = __esm({
|
|
|
2459
2551
|
}
|
|
2460
2552
|
});
|
|
2461
2553
|
|
|
2554
|
+
// src/utils/reservedFieldNames.json
|
|
2555
|
+
var reservedFieldNames_default;
|
|
2556
|
+
var init_reservedFieldNames = __esm({
|
|
2557
|
+
"src/utils/reservedFieldNames.json"() {
|
|
2558
|
+
reservedFieldNames_default = {
|
|
2559
|
+
reserved: {
|
|
2560
|
+
CodingKeys: {
|
|
2561
|
+
breaks: ["swift"],
|
|
2562
|
+
reason: "the generated struct's coding keys on the Swift client"
|
|
2563
|
+
},
|
|
2564
|
+
applyAutoStampsForSave: {
|
|
2565
|
+
breaks: ["js"],
|
|
2566
|
+
reason: "a record method on the JavaScript client",
|
|
2567
|
+
jsEvidence: "compile"
|
|
2568
|
+
},
|
|
2569
|
+
applyStringSetChangeToYMap: {
|
|
2570
|
+
breaks: ["js"],
|
|
2571
|
+
reason: "a record method on the JavaScript client",
|
|
2572
|
+
jsEvidence: "compile"
|
|
2573
|
+
},
|
|
2574
|
+
clearLocalChanges: {
|
|
2575
|
+
breaks: ["js"],
|
|
2576
|
+
reason: "a record method on the JavaScript client",
|
|
2577
|
+
jsEvidence: "compile"
|
|
2578
|
+
},
|
|
2579
|
+
constructor: {
|
|
2580
|
+
breaks: ["js"],
|
|
2581
|
+
reason: "the JavaScript client reads a record's class through it",
|
|
2582
|
+
jsEvidence: "runtime"
|
|
2583
|
+
},
|
|
2584
|
+
delete: {
|
|
2585
|
+
breaks: ["js"],
|
|
2586
|
+
reason: "a record method on the JavaScript client",
|
|
2587
|
+
jsEvidence: "compile"
|
|
2588
|
+
},
|
|
2589
|
+
deleteRecordLog: {
|
|
2590
|
+
breaks: ["js"],
|
|
2591
|
+
reason: "a record method on the JavaScript client",
|
|
2592
|
+
jsEvidence: "compile"
|
|
2593
|
+
},
|
|
2594
|
+
discardChanges: {
|
|
2595
|
+
breaks: ["js", "swift"],
|
|
2596
|
+
reason: "a record method on the JavaScript and Swift clients",
|
|
2597
|
+
jsEvidence: "compile"
|
|
2598
|
+
},
|
|
2599
|
+
ensureLocalChanges: {
|
|
2600
|
+
breaks: ["js"],
|
|
2601
|
+
reason: "a record method on the JavaScript client",
|
|
2602
|
+
jsEvidence: "compile"
|
|
2603
|
+
},
|
|
2604
|
+
getChangedFields: {
|
|
2605
|
+
breaks: ["js"],
|
|
2606
|
+
reason: "a record method on the JavaScript client",
|
|
2607
|
+
jsEvidence: "compile"
|
|
2608
|
+
},
|
|
2609
|
+
getCurrentJSState: {
|
|
2610
|
+
breaks: ["js"],
|
|
2611
|
+
reason: "a record method on the JavaScript client",
|
|
2612
|
+
jsEvidence: "compile"
|
|
2613
|
+
},
|
|
2614
|
+
getCurrentValue: {
|
|
2615
|
+
breaks: ["js"],
|
|
2616
|
+
reason: "a record method on the JavaScript client",
|
|
2617
|
+
jsEvidence: "compile"
|
|
2618
|
+
},
|
|
2619
|
+
getDocumentId: {
|
|
2620
|
+
breaks: ["js"],
|
|
2621
|
+
reason: "a record method on the JavaScript client",
|
|
2622
|
+
jsEvidence: "compile"
|
|
2623
|
+
},
|
|
2624
|
+
getFromYjs: {
|
|
2625
|
+
breaks: ["js"],
|
|
2626
|
+
reason: "a record method on the JavaScript client",
|
|
2627
|
+
jsEvidence: "compile"
|
|
2628
|
+
},
|
|
2629
|
+
getOrCreateStringSet: {
|
|
2630
|
+
breaks: ["js"],
|
|
2631
|
+
reason: "a record method on the JavaScript client",
|
|
2632
|
+
jsEvidence: "compile"
|
|
2633
|
+
},
|
|
2634
|
+
getOriginalValue: {
|
|
2635
|
+
breaks: ["js"],
|
|
2636
|
+
reason: "a record method on the JavaScript client",
|
|
2637
|
+
jsEvidence: "compile"
|
|
2638
|
+
},
|
|
2639
|
+
getStringSetCurrentValues: {
|
|
2640
|
+
breaks: ["js"],
|
|
2641
|
+
reason: "a record method on the JavaScript client",
|
|
2642
|
+
jsEvidence: "compile"
|
|
2643
|
+
},
|
|
2644
|
+
getStringSetFromYjs: {
|
|
2645
|
+
breaks: ["js"],
|
|
2646
|
+
reason: "a record method on the JavaScript client",
|
|
2647
|
+
jsEvidence: "compile"
|
|
2648
|
+
},
|
|
2649
|
+
getValue: {
|
|
2650
|
+
breaks: ["js"],
|
|
2651
|
+
reason: "a record method on the JavaScript client",
|
|
2652
|
+
jsEvidence: "compile"
|
|
2653
|
+
},
|
|
2654
|
+
hasFieldChanged: {
|
|
2655
|
+
breaks: ["js"],
|
|
2656
|
+
reason: "a record method on the JavaScript client",
|
|
2657
|
+
jsEvidence: "compile"
|
|
2658
|
+
},
|
|
2659
|
+
hasLocalChange: {
|
|
2660
|
+
breaks: ["js"],
|
|
2661
|
+
reason: "a record method on the JavaScript client",
|
|
2662
|
+
jsEvidence: "compile"
|
|
2663
|
+
},
|
|
2664
|
+
hasUnsavedChanges: {
|
|
2665
|
+
breaks: ["js"],
|
|
2666
|
+
reason: "a record property on the JavaScript client",
|
|
2667
|
+
jsEvidence: "compile"
|
|
2668
|
+
},
|
|
2669
|
+
hashValue: {
|
|
2670
|
+
breaks: ["swift"],
|
|
2671
|
+
reason: "a Hashable requirement on the Swift client"
|
|
2672
|
+
},
|
|
2673
|
+
isDirty: {
|
|
2674
|
+
breaks: ["js"],
|
|
2675
|
+
reason: "a record property on the JavaScript client",
|
|
2676
|
+
jsEvidence: "compile"
|
|
2677
|
+
},
|
|
2678
|
+
markAllChanged: {
|
|
2679
|
+
breaks: ["swift"],
|
|
2680
|
+
reason: "a record method on the Swift client"
|
|
2681
|
+
},
|
|
2682
|
+
markStringSetChange: {
|
|
2683
|
+
breaks: ["js"],
|
|
2684
|
+
reason: "a record method on the JavaScript client",
|
|
2685
|
+
jsEvidence: "compile"
|
|
2686
|
+
},
|
|
2687
|
+
normalizeNonStringSetValue: {
|
|
2688
|
+
breaks: ["js"],
|
|
2689
|
+
reason: "a record method on the JavaScript client",
|
|
2690
|
+
jsEvidence: "compile"
|
|
2691
|
+
},
|
|
2692
|
+
primitiveValues: {
|
|
2693
|
+
breaks: ["swift"],
|
|
2694
|
+
reason: "a record method on the Swift client"
|
|
2695
|
+
},
|
|
2696
|
+
related: {
|
|
2697
|
+
breaks: ["swift"],
|
|
2698
|
+
reason: "the generated struct's query-time includes on the Swift client"
|
|
2699
|
+
},
|
|
2700
|
+
resolveUnresolvedFormat2Document: {
|
|
2701
|
+
breaks: ["js"],
|
|
2702
|
+
reason: "a record method on the JavaScript client",
|
|
2703
|
+
jsEvidence: "compile"
|
|
2704
|
+
},
|
|
2705
|
+
save: {
|
|
2706
|
+
breaks: ["js"],
|
|
2707
|
+
reason: "a record method on the JavaScript client",
|
|
2708
|
+
jsEvidence: "compile"
|
|
2709
|
+
},
|
|
2710
|
+
saveRecordLog: {
|
|
2711
|
+
breaks: ["js"],
|
|
2712
|
+
reason: "a record method on the JavaScript client",
|
|
2713
|
+
jsEvidence: "compile"
|
|
2714
|
+
},
|
|
2715
|
+
schemaDefaultFor: {
|
|
2716
|
+
breaks: ["js"],
|
|
2717
|
+
reason: "a record method on the JavaScript client",
|
|
2718
|
+
jsEvidence: "compile"
|
|
2719
|
+
},
|
|
2720
|
+
setValue: {
|
|
2721
|
+
breaks: ["js"],
|
|
2722
|
+
reason: "a record method on the JavaScript client",
|
|
2723
|
+
jsEvidence: "compile"
|
|
2724
|
+
},
|
|
2725
|
+
syncState: {
|
|
2726
|
+
breaks: ["js"],
|
|
2727
|
+
reason: "a record property on the JavaScript client",
|
|
2728
|
+
jsEvidence: "compile"
|
|
2729
|
+
},
|
|
2730
|
+
toJSON: {
|
|
2731
|
+
breaks: ["js"],
|
|
2732
|
+
reason: "a record method on the JavaScript client",
|
|
2733
|
+
jsEvidence: "compile"
|
|
2734
|
+
},
|
|
2735
|
+
validateBeforeSave: {
|
|
2736
|
+
breaks: ["js"],
|
|
2737
|
+
reason: "a record method on the JavaScript client",
|
|
2738
|
+
jsEvidence: "compile"
|
|
2739
|
+
},
|
|
2740
|
+
validateFieldValue: {
|
|
2741
|
+
breaks: ["js"],
|
|
2742
|
+
reason: "a record method on the JavaScript client",
|
|
2743
|
+
jsEvidence: "compile"
|
|
2744
|
+
}
|
|
2745
|
+
},
|
|
2746
|
+
exempt: {
|
|
2747
|
+
aggregate: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2748
|
+
autoStampFields: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2749
|
+
count: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2750
|
+
encode: "the Swift model's labelled encode(to:), which a field of the same name coexists with; not a JavaScript record member",
|
|
2751
|
+
find: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2752
|
+
findAll: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2753
|
+
findByUnique: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2754
|
+
hasOwnProperty: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
|
|
2755
|
+
hash: "the Swift model's labelled hash(into:), which a field of the same name coexists with; not a JavaScript record member",
|
|
2756
|
+
isPrototypeOf: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
|
|
2757
|
+
modelName: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2758
|
+
primitiveSchema: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2759
|
+
propertyIsEnumerable: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
|
|
2760
|
+
query: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2761
|
+
queryOne: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2762
|
+
queryPaged: "a static read on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2763
|
+
subscribe: "a static on the Swift model, which a field of the same name coexists with; not a JavaScript record member",
|
|
2764
|
+
toLocaleString: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
|
|
2765
|
+
toString: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients",
|
|
2766
|
+
upsertByUnique: "the Swift model's labelled upsertByUnique(_:mode:in:) methods, which a field of the same name coexists with; not a JavaScript record member",
|
|
2767
|
+
valueOf: "an Object.prototype method the JavaScript client never calls on a record; the generated model compiles on both clients"
|
|
2768
|
+
}
|
|
2769
|
+
};
|
|
2770
|
+
}
|
|
2771
|
+
});
|
|
2772
|
+
|
|
2462
2773
|
// src/utils/reservedFields.ts
|
|
2463
2774
|
function checkReservedFieldName(fieldName) {
|
|
2464
2775
|
if (fieldName === "id") return null;
|
|
@@ -2468,12 +2779,18 @@ function checkReservedFieldName(fieldName) {
|
|
|
2468
2779
|
if (fieldName.startsWith("_")) {
|
|
2469
2780
|
return `Field '${fieldName}' is reserved (fields starting with '_' are internal)`;
|
|
2470
2781
|
}
|
|
2782
|
+
if (Object.prototype.hasOwnProperty.call(RESERVED_FIELD_NAMES, fieldName)) {
|
|
2783
|
+
return `Field '${fieldName}' is reserved (${RESERVED_FIELD_NAMES[fieldName].reason})`;
|
|
2784
|
+
}
|
|
2471
2785
|
return null;
|
|
2472
2786
|
}
|
|
2473
|
-
var ReservedFieldNameError;
|
|
2787
|
+
var RESERVED_FIELD_NAMES, EXEMPT_FIELD_NAMES, ReservedFieldNameError;
|
|
2474
2788
|
var init_reservedFields = __esm({
|
|
2475
2789
|
"src/utils/reservedFields.ts"() {
|
|
2476
2790
|
"use strict";
|
|
2791
|
+
init_reservedFieldNames();
|
|
2792
|
+
RESERVED_FIELD_NAMES = reservedFieldNames_default.reserved;
|
|
2793
|
+
EXEMPT_FIELD_NAMES = reservedFieldNames_default.exempt;
|
|
2477
2794
|
ReservedFieldNameError = class extends Error {
|
|
2478
2795
|
constructor(message) {
|
|
2479
2796
|
super(message);
|
|
@@ -2484,6 +2801,9 @@ var init_reservedFields = __esm({
|
|
|
2484
2801
|
});
|
|
2485
2802
|
|
|
2486
2803
|
// src/record-log-client/types.ts
|
|
2804
|
+
function recordLogSegmentChunkObject(segmentId, chunk) {
|
|
2805
|
+
return `${chunk.source?.segmentId ?? segmentId}/${chunk.model}/${chunk.index}`;
|
|
2806
|
+
}
|
|
2487
2807
|
function refusedWritesOf(entry) {
|
|
2488
2808
|
return [entry.m, ...entry.also ?? []].map((m) => ({
|
|
2489
2809
|
model: m.model,
|
|
@@ -2494,16 +2814,18 @@ function refusedWritesOf(entry) {
|
|
|
2494
2814
|
seq: entry.seq
|
|
2495
2815
|
}));
|
|
2496
2816
|
}
|
|
2497
|
-
var RECORD_LOG_DEFAULT_EPOCH_ENTRIES, RECORD_LOG_ENTRY_MAX_BYTES, RECORD_LOG_FRAME_TARGET_BYTES,
|
|
2817
|
+
var RECORD_LOG_DEFAULT_EPOCH_ENTRIES, RECORD_LOG_ENTRY_MAX_BYTES, RECORD_LOG_FRAME_TARGET_BYTES, RECORD_LOG_FRAMES_IN_FLIGHT, RECORD_LOG_FRAME_WAIT_MS, RECORD_LOG_TICK_MS, RECORD_LOG_UP_BATCH_MAX, RECORD_LOG_FRAME_ENTRIES_MAX, RECORD_LOG_FIRST_EPOCH, RecordLogStaleReceiptError, RecordLogStaleReplacementError, RecordLogWriteRefusedError;
|
|
2498
2818
|
var init_types = __esm({
|
|
2499
2819
|
"src/record-log-client/types.ts"() {
|
|
2500
2820
|
"use strict";
|
|
2501
2821
|
RECORD_LOG_DEFAULT_EPOCH_ENTRIES = 1e4;
|
|
2502
2822
|
RECORD_LOG_ENTRY_MAX_BYTES = 1024 * 1024;
|
|
2503
2823
|
RECORD_LOG_FRAME_TARGET_BYTES = 64 * 1024;
|
|
2504
|
-
|
|
2824
|
+
RECORD_LOG_FRAMES_IN_FLIGHT = 1;
|
|
2825
|
+
RECORD_LOG_FRAME_WAIT_MS = 2e3;
|
|
2505
2826
|
RECORD_LOG_TICK_MS = 5;
|
|
2506
2827
|
RECORD_LOG_UP_BATCH_MAX = 200;
|
|
2828
|
+
RECORD_LOG_FRAME_ENTRIES_MAX = 64;
|
|
2507
2829
|
RECORD_LOG_FIRST_EPOCH = 1;
|
|
2508
2830
|
RecordLogStaleReceiptError = class _RecordLogStaleReceiptError extends Error {
|
|
2509
2831
|
/**
|
|
@@ -2766,6 +3088,34 @@ var init_resolve = __esm({
|
|
|
2766
3088
|
}
|
|
2767
3089
|
});
|
|
2768
3090
|
|
|
3091
|
+
// src/record-log/results.ts
|
|
3092
|
+
function plainRowAfter(row, m) {
|
|
3093
|
+
if (m.kind === "delete") return null;
|
|
3094
|
+
const prior = m.kind === "create" ? { id: m.id } : row;
|
|
3095
|
+
if (!prior) return null;
|
|
3096
|
+
const next = { ...prior };
|
|
3097
|
+
for (const [field, v] of Object.entries(m.fields ?? {})) {
|
|
3098
|
+
if (v === void 0) delete next[field];
|
|
3099
|
+
else next[field] = v;
|
|
3100
|
+
}
|
|
3101
|
+
for (const [field, deltas] of Object.entries(m.stringSetDeltas ?? {})) {
|
|
3102
|
+
const members = new Set(Array.isArray(next[field]) ? next[field] : []);
|
|
3103
|
+
for (const [member, present] of Object.entries(deltas)) {
|
|
3104
|
+
if (present) members.add(member);
|
|
3105
|
+
else members.delete(member);
|
|
3106
|
+
}
|
|
3107
|
+
next[field] = canonicalStringSet(members);
|
|
3108
|
+
}
|
|
3109
|
+
return next;
|
|
3110
|
+
}
|
|
3111
|
+
var init_results = __esm({
|
|
3112
|
+
"src/record-log/results.ts"() {
|
|
3113
|
+
"use strict";
|
|
3114
|
+
init_stringSetOrder();
|
|
3115
|
+
init_types2();
|
|
3116
|
+
}
|
|
3117
|
+
});
|
|
3118
|
+
|
|
2769
3119
|
// src/record-log-client/guess.ts
|
|
2770
3120
|
function upsertConstraints(entry) {
|
|
2771
3121
|
if (entry.upsertOn === void 0) return [];
|
|
@@ -2776,26 +3126,9 @@ function applyGuess(table, entry) {
|
|
|
2776
3126
|
for (const m of resolveEntry(table, entry, upsertConstraints(entry)).mutations) {
|
|
2777
3127
|
const key = { model: m.model, id: m.id };
|
|
2778
3128
|
touched.push(key);
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
}
|
|
2783
|
-
const prior = m.kind === "create" ? { id: m.id } : table.row(key);
|
|
2784
|
-
if (!prior) continue;
|
|
2785
|
-
const row = { ...prior };
|
|
2786
|
-
for (const [field, v] of Object.entries(m.fields ?? {})) {
|
|
2787
|
-
if (v === void 0) delete row[field];
|
|
2788
|
-
else row[field] = v;
|
|
2789
|
-
}
|
|
2790
|
-
for (const [field, deltas] of Object.entries(m.stringSetDeltas ?? {})) {
|
|
2791
|
-
const members = new Set(Array.isArray(row[field]) ? row[field] : []);
|
|
2792
|
-
for (const [member, present] of Object.entries(deltas)) {
|
|
2793
|
-
if (present) members.add(member);
|
|
2794
|
-
else members.delete(member);
|
|
2795
|
-
}
|
|
2796
|
-
row[field] = canonicalStringSet(members);
|
|
2797
|
-
}
|
|
2798
|
-
table.set(key, row);
|
|
3129
|
+
const row = plainRowAfter(table.row(key), m);
|
|
3130
|
+
if (row) table.set(key, row);
|
|
3131
|
+
else if (m.kind === "delete") table.delete(key);
|
|
2799
3132
|
}
|
|
2800
3133
|
return touched;
|
|
2801
3134
|
}
|
|
@@ -2812,8 +3145,8 @@ var MapRowTable;
|
|
|
2812
3145
|
var init_guess = __esm({
|
|
2813
3146
|
"src/record-log-client/guess.ts"() {
|
|
2814
3147
|
"use strict";
|
|
2815
|
-
init_stringSetOrder();
|
|
2816
3148
|
init_resolve();
|
|
3149
|
+
init_results();
|
|
2817
3150
|
MapRowTable = class _MapRowTable {
|
|
2818
3151
|
/**
|
|
2819
3152
|
* @param rows - The rows by `model` NUL `id`; the table keeps this map.
|
|
@@ -3803,6 +4136,7 @@ var init_IncludeResolver = __esm({
|
|
|
3803
4136
|
"use strict";
|
|
3804
4137
|
init_ModelRegistry();
|
|
3805
4138
|
init_DocumentQueryTranslator();
|
|
4139
|
+
init_projectedRows();
|
|
3806
4140
|
init_sql();
|
|
3807
4141
|
IncludeResolver = class {
|
|
3808
4142
|
db;
|
|
@@ -4001,6 +4335,7 @@ var init_IncludeResolver = __esm({
|
|
|
4001
4335
|
grouped.get(fk).push(r);
|
|
4002
4336
|
}
|
|
4003
4337
|
if (spec.projection) {
|
|
4338
|
+
await this._fillProjectedValues(spec.model, related, spec.projection);
|
|
4004
4339
|
for (const [key, list] of grouped) {
|
|
4005
4340
|
grouped.set(
|
|
4006
4341
|
key,
|
|
@@ -4099,6 +4434,7 @@ var init_IncludeResolver = __esm({
|
|
|
4099
4434
|
return [];
|
|
4100
4435
|
}
|
|
4101
4436
|
const translator = new DocumentQueryTranslator(model, modelInfo.fields);
|
|
4437
|
+
const selectDocument = projectedStringSetFields(extraOptions?.projection, modelInfo.fields).length > 0;
|
|
4102
4438
|
let filterParamCount = 0;
|
|
4103
4439
|
if (extraFilter) {
|
|
4104
4440
|
const translated = translator.translateFilter(extraFilter);
|
|
@@ -4118,12 +4454,53 @@ var init_IncludeResolver = __esm({
|
|
|
4118
4454
|
if (extraOptions?.sort) options.sort = extraOptions.sort;
|
|
4119
4455
|
if (extraOptions?.projection) options.projection = extraOptions.projection;
|
|
4120
4456
|
if (this.documents !== null) options.documents = [...this.documents];
|
|
4121
|
-
const { sql, params } = translator.translateFind(filter, options
|
|
4457
|
+
const { sql, params } = translator.translateFind(filter, options, {
|
|
4458
|
+
selectDocument
|
|
4459
|
+
});
|
|
4122
4460
|
const rows = await db.query(sql, params);
|
|
4123
4461
|
allResults.push(...rows);
|
|
4124
4462
|
}
|
|
4463
|
+
if (extraOptions?.projection) {
|
|
4464
|
+
await this._fillProjectedValues(
|
|
4465
|
+
model,
|
|
4466
|
+
allResults,
|
|
4467
|
+
extraOptions.projection,
|
|
4468
|
+
modelInfo.fields
|
|
4469
|
+
);
|
|
4470
|
+
}
|
|
4471
|
+
if (selectDocument) {
|
|
4472
|
+
for (const row of allResults) delete row._meta_doc_id;
|
|
4473
|
+
}
|
|
4125
4474
|
return allResults;
|
|
4126
4475
|
}
|
|
4476
|
+
/**
|
|
4477
|
+
* Give rows read under an inclusion `projection` the values the records
|
|
4478
|
+
* hold (#4501): each projected string set's members from its junction table,
|
|
4479
|
+
* matched on the row's id and `_meta_doc_id`, and each projected boolean as
|
|
4480
|
+
* `true`/`false` rather than the stored 0/1.
|
|
4481
|
+
*/
|
|
4482
|
+
async _fillProjectedValues(model, rows, projection, fields) {
|
|
4483
|
+
const schema = fields ?? this.registry.getModelInfo(model)?.fields;
|
|
4484
|
+
if (!schema || rows.length === 0) return;
|
|
4485
|
+
const tableName = `model_${model.toLowerCase()}`;
|
|
4486
|
+
await attachStringSetMembers(
|
|
4487
|
+
await this.engineFor(model),
|
|
4488
|
+
projectedStringSetFields(projection, schema).map((field) => ({
|
|
4489
|
+
field,
|
|
4490
|
+
table: `${tableName}_${field}`,
|
|
4491
|
+
foreignKey: `${model.toLowerCase()}_id`
|
|
4492
|
+
})),
|
|
4493
|
+
rows
|
|
4494
|
+
);
|
|
4495
|
+
for (const [field, include] of Object.entries(projection)) {
|
|
4496
|
+
if (include !== 1) continue;
|
|
4497
|
+
for (const row of rows) {
|
|
4498
|
+
if (Object.prototype.hasOwnProperty.call(row, field)) {
|
|
4499
|
+
row[field] = projectedFieldValue(schema.get(field), row[field]);
|
|
4500
|
+
}
|
|
4501
|
+
}
|
|
4502
|
+
}
|
|
4503
|
+
}
|
|
4127
4504
|
/** Validate an include spec, returning an error string or null if valid. */
|
|
4128
4505
|
_validateIncludeSpec(spec) {
|
|
4129
4506
|
if (!spec.model || typeof spec.model !== "string") {
|
|
@@ -4256,6 +4633,7 @@ var init_BaseModel = __esm({
|
|
|
4256
4633
|
init_documentTypes();
|
|
4257
4634
|
init_DocumentQueryTranslator();
|
|
4258
4635
|
init_CursorManager();
|
|
4636
|
+
init_projectedRows();
|
|
4259
4637
|
init_sql();
|
|
4260
4638
|
init_metaSync();
|
|
4261
4639
|
init_writeLifecycle();
|
|
@@ -7220,7 +7598,9 @@ var init_BaseModel = __esm({
|
|
|
7220
7598
|
translatorOptions = { ...translatorOptions || {}, documents: scope };
|
|
7221
7599
|
}
|
|
7222
7600
|
const translator = new DocumentQueryTranslator(modelName, schema.fields);
|
|
7223
|
-
const translatedQuery = translator.translateFind(filter, translatorOptions
|
|
7601
|
+
const translatedQuery = translator.translateFind(filter, translatorOptions, {
|
|
7602
|
+
selectDocument: projectedStringSetFields(translatorOptions?.projection, schema.fields).length > 0
|
|
7603
|
+
});
|
|
7224
7604
|
Logger.verbose(`[${modelName}] Translated SQL:`, translatedQuery.sql);
|
|
7225
7605
|
Logger.verbose(`[${modelName}] SQL params:`, translatedQuery.params);
|
|
7226
7606
|
const queryEngine = await this.queryEngineFor(
|
|
@@ -7255,7 +7635,8 @@ var init_BaseModel = __esm({
|
|
|
7255
7635
|
translatedQuery.sortFields,
|
|
7256
7636
|
direction,
|
|
7257
7637
|
hasMore,
|
|
7258
|
-
isFirstPage
|
|
7638
|
+
isFirstPage,
|
|
7639
|
+
translatedQuery.sortDirections
|
|
7259
7640
|
);
|
|
7260
7641
|
results = results.map(
|
|
7261
7642
|
(row) => stripCursorSortValues(row, aliasedSortFields)
|
|
@@ -7265,6 +7646,21 @@ var init_BaseModel = __esm({
|
|
|
7265
7646
|
}
|
|
7266
7647
|
let transformedData;
|
|
7267
7648
|
if (options?.projection && Object.keys(options.projection).length > 0) {
|
|
7649
|
+
const modelConstructor = this;
|
|
7650
|
+
await attachStringSetMembers(
|
|
7651
|
+
queryEngine,
|
|
7652
|
+
projectedStringSetFields(options.projection, schema.fields).map(
|
|
7653
|
+
(field) => ({
|
|
7654
|
+
field,
|
|
7655
|
+
table: modelConstructor.getDatabaseJunctionTableName(
|
|
7656
|
+
modelName,
|
|
7657
|
+
field
|
|
7658
|
+
),
|
|
7659
|
+
foreignKey: `${modelName.toLowerCase()}_id`
|
|
7660
|
+
})
|
|
7661
|
+
),
|
|
7662
|
+
results
|
|
7663
|
+
);
|
|
7268
7664
|
transformedData = results.map((row) => {
|
|
7269
7665
|
const projected = {};
|
|
7270
7666
|
if (row.hasOwnProperty("id")) {
|
|
@@ -7272,7 +7668,10 @@ var init_BaseModel = __esm({
|
|
|
7272
7668
|
}
|
|
7273
7669
|
for (const [field, include] of Object.entries(options.projection)) {
|
|
7274
7670
|
if (include === 1 && row.hasOwnProperty(field)) {
|
|
7275
|
-
projected[field] =
|
|
7671
|
+
projected[field] = projectedFieldValue(
|
|
7672
|
+
schema.fields.get(field),
|
|
7673
|
+
row[field]
|
|
7674
|
+
);
|
|
7276
7675
|
}
|
|
7277
7676
|
}
|
|
7278
7677
|
if (row._related) projected._related = row._related;
|
|
@@ -8737,9 +9136,11 @@ __export(browser_exports, {
|
|
|
8737
9136
|
RECORD_LOG_DRAIN_WAIT_MS: () => RECORD_LOG_DRAIN_WAIT_MS,
|
|
8738
9137
|
RECORD_LOG_ENTRY_MAX_BYTES: () => RECORD_LOG_ENTRY_MAX_BYTES,
|
|
8739
9138
|
RECORD_LOG_FIRST_EPOCH: () => RECORD_LOG_FIRST_EPOCH,
|
|
9139
|
+
RECORD_LOG_FRAMES_IN_FLIGHT: () => RECORD_LOG_FRAMES_IN_FLIGHT,
|
|
9140
|
+
RECORD_LOG_FRAME_ENTRIES_MAX: () => RECORD_LOG_FRAME_ENTRIES_MAX,
|
|
8740
9141
|
RECORD_LOG_FRAME_TARGET_BYTES: () => RECORD_LOG_FRAME_TARGET_BYTES,
|
|
9142
|
+
RECORD_LOG_FRAME_WAIT_MS: () => RECORD_LOG_FRAME_WAIT_MS,
|
|
8741
9143
|
RECORD_LOG_RESULT_GAP_MS: () => RECORD_LOG_RESULT_GAP_MS,
|
|
8742
|
-
RECORD_LOG_SEND_WINDOW: () => RECORD_LOG_SEND_WINDOW,
|
|
8743
9144
|
RECORD_LOG_STORE_CHANNEL: () => RECORD_LOG_STORE_CHANNEL,
|
|
8744
9145
|
RECORD_LOG_TEARDOWN_DRAIN_BOUND_MS: () => RECORD_LOG_TEARDOWN_DRAIN_BOUND_MS,
|
|
8745
9146
|
RECORD_LOG_TICK_MS: () => RECORD_LOG_TICK_MS,
|
|
@@ -8816,6 +9217,7 @@ __export(browser_exports, {
|
|
|
8816
9217
|
recordLogFieldIndexName: () => recordLogFieldIndexName,
|
|
8817
9218
|
recordLogJsonBytes: () => recordLogJsonBytes,
|
|
8818
9219
|
recordLogRowRevision: () => recordLogRowRevision,
|
|
9220
|
+
recordLogSegmentChunkObject: () => recordLogSegmentChunkObject,
|
|
8819
9221
|
refusedWritesOf: () => refusedWritesOf,
|
|
8820
9222
|
registerFunctionDefault: () => registerFunctionDefault,
|
|
8821
9223
|
requestStoragePersistence: () => requestStoragePersistence,
|
|
@@ -8966,7 +9368,7 @@ var DatabaseEngine = class {
|
|
|
8966
9368
|
};
|
|
8967
9369
|
|
|
8968
9370
|
// src/engines/SqljsEngine.ts
|
|
8969
|
-
var
|
|
9371
|
+
var import_sql7 = __toESM(require("sql.js"), 1);
|
|
8970
9372
|
|
|
8971
9373
|
// src/engines/sqliteQueryEngine.ts
|
|
8972
9374
|
init_logger();
|
|
@@ -9353,7 +9755,7 @@ async function loadSqlJsModule(locateFile) {
|
|
|
9353
9755
|
abortGuard.catch(() => {
|
|
9354
9756
|
});
|
|
9355
9757
|
try {
|
|
9356
|
-
const initPromise = (0,
|
|
9758
|
+
const initPromise = (0, import_sql7.default)({
|
|
9357
9759
|
locateFile,
|
|
9358
9760
|
// Layer 1: emscripten onAbort.
|
|
9359
9761
|
onAbort: (reason) => abortReject?.(toError(reason))
|
|
@@ -10358,6 +10760,9 @@ function dispatchRecordLogStoreCommand(store, command) {
|
|
|
10358
10760
|
case "applySegmentChunk":
|
|
10359
10761
|
value = store.applySegmentChunk({ ...c, rows: c.rows ?? undecoded(c.kind) });
|
|
10360
10762
|
break;
|
|
10763
|
+
case "keepSegmentChunk":
|
|
10764
|
+
value = store.keepSegmentChunk(c);
|
|
10765
|
+
break;
|
|
10361
10766
|
case "applySegmentCorrections":
|
|
10362
10767
|
value = store.applySegmentCorrections({ ...c, lines: c.lines ?? undecoded(c.kind) });
|
|
10363
10768
|
break;
|
|
@@ -10568,6 +10973,7 @@ init_sql();
|
|
|
10568
10973
|
init_logger();
|
|
10569
10974
|
|
|
10570
10975
|
// src/record-log-client/client.ts
|
|
10976
|
+
init_results();
|
|
10571
10977
|
init_types2();
|
|
10572
10978
|
init_guess();
|
|
10573
10979
|
init_types();
|
|
@@ -10593,6 +10999,16 @@ var RecordLogClient = class {
|
|
|
10593
10999
|
get pending() {
|
|
10594
11000
|
return this.tables.pending(this.writer);
|
|
10595
11001
|
}
|
|
11002
|
+
/** One of a writer's unjudged entries, or `undefined`. */
|
|
11003
|
+
entryOf(writer, seq) {
|
|
11004
|
+
if (this.tables.pendingEntry) return this.tables.pendingEntry(writer, seq);
|
|
11005
|
+
return this.tables.pending(writer).find((p) => p.seq === seq);
|
|
11006
|
+
}
|
|
11007
|
+
/** A writer's unjudged entries at or below `seq`, in `seq` order. */
|
|
11008
|
+
entriesThrough(writer, seq) {
|
|
11009
|
+
if (this.tables.pendingThrough) return this.tables.pendingThrough(writer, seq);
|
|
11010
|
+
return this.tables.pending(writer).filter((p) => p.seq <= seq);
|
|
11011
|
+
}
|
|
10596
11012
|
/**
|
|
10597
11013
|
* Write an entry: the next `seq`, the open epoch, the cursor. It joins the
|
|
10598
11014
|
* pending log; the store applies it to the view as a guess.
|
|
@@ -10662,7 +11078,7 @@ var RecordLogClient = class {
|
|
|
10662
11078
|
}
|
|
10663
11079
|
/** The room has moved past a withdrawn entry's sequence number. */
|
|
10664
11080
|
settled(seq) {
|
|
10665
|
-
const entry = this.
|
|
11081
|
+
const entry = this.entryOf(this.writer, seq);
|
|
10666
11082
|
if (entry?.void) this.tables.deletePending(this.writer, seq);
|
|
10667
11083
|
return { touched: [] };
|
|
10668
11084
|
}
|
|
@@ -10673,11 +11089,17 @@ var RecordLogClient = class {
|
|
|
10673
11089
|
* this store acknowledges that writer's entry at once; the entry leaves
|
|
10674
11090
|
* the pending log, and its guess the view, once its result's row is
|
|
10675
11091
|
* applied. `void` and `duplicate` items settle the entry they name.
|
|
11092
|
+
*
|
|
11093
|
+
* A compact acknowledgement (no `changes`) is applied, in its turn, by its
|
|
11094
|
+
* pending entry's mutations as plain row operations, the rule by which the
|
|
11095
|
+
* room vouched for it. With no unwithdrawn pending entry for its `seq` it
|
|
11096
|
+
* stays buffered, the cursor stops below it, and the outcome names it
|
|
11097
|
+
* (`underivable`).
|
|
10676
11098
|
*/
|
|
10677
11099
|
receive(item) {
|
|
10678
11100
|
const out = { touched: [], acknowledged: [], settled: [] };
|
|
10679
11101
|
if ("void" in item) {
|
|
10680
|
-
const entry = this.
|
|
11102
|
+
const entry = this.entryOf(this.writer, item.seq);
|
|
10681
11103
|
if (entry) {
|
|
10682
11104
|
this.tables.deletePending(this.writer, item.seq);
|
|
10683
11105
|
out.settled.push({ writer: this.writer, seq: item.seq });
|
|
@@ -10686,7 +11108,7 @@ var RecordLogClient = class {
|
|
|
10686
11108
|
return out;
|
|
10687
11109
|
}
|
|
10688
11110
|
if ("duplicate" in item) {
|
|
10689
|
-
const entry = this.
|
|
11111
|
+
const entry = this.entryOf(this.writer, item.seq);
|
|
10690
11112
|
out.acknowledged.push({ writer: this.writer, seq: item.seq });
|
|
10691
11113
|
if (entry) {
|
|
10692
11114
|
this.tables.deletePending(this.writer, item.seq);
|
|
@@ -10696,7 +11118,7 @@ var RecordLogClient = class {
|
|
|
10696
11118
|
return out;
|
|
10697
11119
|
}
|
|
10698
11120
|
if (item.w !== void 0 && item.seq !== void 0 && this.tables.isWriter(item.w)) {
|
|
10699
|
-
const entry = this.
|
|
11121
|
+
const entry = this.entryOf(item.w, item.seq);
|
|
10700
11122
|
out.acknowledged.push({ writer: item.w, seq: item.seq });
|
|
10701
11123
|
if (entry && !entry.void && entry.acked === void 0) {
|
|
10702
11124
|
this.tables.putPending(item.w, { ...entry, acked: item.l, ...item.alias ? { alias: item.alias } : {} });
|
|
@@ -10706,9 +11128,14 @@ var RecordLogClient = class {
|
|
|
10706
11128
|
if (item.l > this.tables.cursor()) {
|
|
10707
11129
|
this.tables.buffer(item);
|
|
10708
11130
|
for (let next = this.tables.buffered(this.tables.cursor() + 1); next; next = this.tables.buffered(this.tables.cursor() + 1)) {
|
|
10709
|
-
|
|
10710
|
-
|
|
10711
|
-
|
|
11131
|
+
if (next.changes) {
|
|
11132
|
+
for (const change of next.changes) {
|
|
11133
|
+
applyChange(confirmed, change);
|
|
11134
|
+
out.touched.push({ model: change.model, id: change.id });
|
|
11135
|
+
}
|
|
11136
|
+
} else if (!this.applyOwnEntry(confirmed, next, out)) {
|
|
11137
|
+
out.underivable = { l: next.l, writer: next.w ?? "", seq: next.seq ?? 0 };
|
|
11138
|
+
break;
|
|
10712
11139
|
}
|
|
10713
11140
|
this.tables.setCursor(next.l);
|
|
10714
11141
|
this.tables.dropBufferedThrough(next.l);
|
|
@@ -10722,6 +11149,25 @@ var RecordLogClient = class {
|
|
|
10722
11149
|
this.settleAcknowledged(out);
|
|
10723
11150
|
return out;
|
|
10724
11151
|
}
|
|
11152
|
+
/**
|
|
11153
|
+
* A compact acknowledgement's changes, derived: the mutations of the
|
|
11154
|
+
* pending entry it names applied in order to the confirmed rows as plain
|
|
11155
|
+
* row operations. Answers `false`, changing nothing, when no unwithdrawn
|
|
11156
|
+
* pending entry of a writer of this store has its `seq`.
|
|
11157
|
+
*/
|
|
11158
|
+
applyOwnEntry(confirmed, item, out) {
|
|
11159
|
+
if (item.w === void 0 || item.seq === void 0 || !this.tables.isWriter(item.w)) return false;
|
|
11160
|
+
const entry = this.entryOf(item.w, item.seq);
|
|
11161
|
+
if (!entry || entry.void) return false;
|
|
11162
|
+
for (const m of mutationsOf(entry)) {
|
|
11163
|
+
const key = { model: m.model, id: m.id };
|
|
11164
|
+
const row = plainRowAfter(confirmed.row(key), m);
|
|
11165
|
+
if (row) confirmed.set(key, row);
|
|
11166
|
+
else if (m.kind === "delete") confirmed.delete(key);
|
|
11167
|
+
out.touched.push(key);
|
|
11168
|
+
}
|
|
11169
|
+
return true;
|
|
11170
|
+
}
|
|
10725
11171
|
/**
|
|
10726
11172
|
* Acknowledged entries whose result's row the cursor has passed leave the
|
|
10727
11173
|
* pending log: their row was applied, here or by another writer of this
|
|
@@ -10729,7 +11175,7 @@ var RecordLogClient = class {
|
|
|
10729
11175
|
*/
|
|
10730
11176
|
settleAcknowledged(out) {
|
|
10731
11177
|
for (const { writer, seq } of this.tables.acknowledgedThrough(this.tables.cursor())) {
|
|
10732
|
-
const entry = this.
|
|
11178
|
+
const entry = this.entryOf(writer, seq);
|
|
10733
11179
|
if (!entry) continue;
|
|
10734
11180
|
this.tables.deletePending(writer, seq);
|
|
10735
11181
|
out.settled.push({ writer, seq });
|
|
@@ -10744,8 +11190,7 @@ var RecordLogClient = class {
|
|
|
10744
11190
|
* wrote since.
|
|
10745
11191
|
*/
|
|
10746
11192
|
confirmEntry(writer, seq, alias, out) {
|
|
10747
|
-
for (const p of this.
|
|
10748
|
-
if (p.seq > seq) continue;
|
|
11193
|
+
for (const p of this.entriesThrough(writer, seq)) {
|
|
10749
11194
|
this.tables.deletePending(writer, p.seq);
|
|
10750
11195
|
out.settled.push({ writer, seq: p.seq });
|
|
10751
11196
|
if (!p.void) out.touched.push(...keysOf(p));
|
|
@@ -10875,7 +11320,10 @@ var RecordLogClient = class {
|
|
|
10875
11320
|
completeCatchUp(done) {
|
|
10876
11321
|
this.assertGeneration(done.generation);
|
|
10877
11322
|
const out = { touched: [], acknowledged: [], settled: [] };
|
|
10878
|
-
if (done.full)
|
|
11323
|
+
if (done.full) {
|
|
11324
|
+
out.touched.push(...this.tables.completeReplace());
|
|
11325
|
+
this.tables.setHeldSegment?.(done.segment ?? null);
|
|
11326
|
+
}
|
|
10879
11327
|
this.settleReceipts(done.full === true, done.receipt);
|
|
10880
11328
|
this.tables.setCursor(done.lsn);
|
|
10881
11329
|
this.tables.dropBufferedThrough(done.lsn);
|
|
@@ -10886,6 +11334,7 @@ var RecordLogClient = class {
|
|
|
10886
11334
|
out.touched.push(...replay.touched);
|
|
10887
11335
|
out.acknowledged.push(...replay.acknowledged);
|
|
10888
11336
|
out.settled.push(...replay.settled);
|
|
11337
|
+
if (replay.underivable) out.underivable = replay.underivable;
|
|
10889
11338
|
}
|
|
10890
11339
|
this.settleAcknowledged(out);
|
|
10891
11340
|
return out;
|
|
@@ -11028,6 +11477,31 @@ var RecordLogClient = class {
|
|
|
11028
11477
|
}
|
|
11029
11478
|
return { touched };
|
|
11030
11479
|
}
|
|
11480
|
+
/**
|
|
11481
|
+
* Keep one chunk of a segment from the rows the store holds instead of
|
|
11482
|
+
* reading it, under the replacement `generation` as receipt `attempt`. The
|
|
11483
|
+
* rows are kept only when the held segment's marker lists the same object
|
|
11484
|
+
* with the same digest, row count and range, no other receipt attempt is in
|
|
11485
|
+
* progress, and the confirmed rows of that range number exactly `rows`;
|
|
11486
|
+
* otherwise nothing changes and it answers `mismatch`, and the chunk is
|
|
11487
|
+
* read. A kept row the room changed after the new segment began is
|
|
11488
|
+
* corrected by its corrections or the pages after them.
|
|
11489
|
+
*
|
|
11490
|
+
* @throws RecordLogStaleReplacementError under a superseded generation.
|
|
11491
|
+
* @throws RecordLogStaleReceiptError for an attempt no longer in progress.
|
|
11492
|
+
*/
|
|
11493
|
+
keepSegmentChunk(chunk) {
|
|
11494
|
+
this.assertGeneration(chunk.generation);
|
|
11495
|
+
const state = this.receiptTables().receipts();
|
|
11496
|
+
if (!state || !state.attempts.some((a) => a.attempt === chunk.attempt)) throw new RecordLogStaleReceiptError(chunk.attempt);
|
|
11497
|
+
const entry = this.tables.heldSegment?.()?.chunks.find((c) => c.object === chunk.object);
|
|
11498
|
+
const same = entry !== void 0 && entry.model === chunk.model && entry.sha256 === chunk.sha256 && entry.rows === chunk.rows && entry.firstId === chunk.firstId && entry.lastId === chunk.lastId;
|
|
11499
|
+
const alone = state.attempts.every((a) => a.attempt === chunk.attempt);
|
|
11500
|
+
const range = { model: chunk.model, firstId: chunk.firstId, lastId: chunk.lastId };
|
|
11501
|
+
if (!same || !alone || !this.tables.keepConfirmedRange?.({ ...range, rows: chunk.rows })) return { mismatch: true };
|
|
11502
|
+
this.touchReceipt(chunk.attempt);
|
|
11503
|
+
return { kept: chunk.rows, ranges: [range] };
|
|
11504
|
+
}
|
|
11031
11505
|
/**
|
|
11032
11506
|
* Apply a segment's corrections under the replacement `generation`: a row
|
|
11033
11507
|
* replaces the record's, a `null` deletes it (one the chunks did not carry
|
|
@@ -11067,8 +11541,11 @@ var MemoryRecordLogTables = class {
|
|
|
11067
11541
|
constraintList = [];
|
|
11068
11542
|
rows;
|
|
11069
11543
|
replacingKeys = null;
|
|
11544
|
+
/** The records interrupted replacements put since the last completion: not of the confirmed generation. */
|
|
11545
|
+
interruptedKeys = /* @__PURE__ */ new Set();
|
|
11070
11546
|
generationValue = 0;
|
|
11071
11547
|
receiptValue = null;
|
|
11548
|
+
heldValue = null;
|
|
11072
11549
|
loadKeys = /* @__PURE__ */ new Map();
|
|
11073
11550
|
held = /* @__PURE__ */ new Map();
|
|
11074
11551
|
writers = /* @__PURE__ */ new Map();
|
|
@@ -11125,6 +11602,7 @@ var MemoryRecordLogTables = class {
|
|
|
11125
11602
|
};
|
|
11126
11603
|
}
|
|
11127
11604
|
beginReplace() {
|
|
11605
|
+
for (const text of this.replacingKeys ?? []) this.interruptedKeys.add(text);
|
|
11128
11606
|
this.replacingKeys = /* @__PURE__ */ new Set();
|
|
11129
11607
|
this.generationValue++;
|
|
11130
11608
|
}
|
|
@@ -11134,6 +11612,7 @@ var MemoryRecordLogTables = class {
|
|
|
11134
11612
|
completeReplace() {
|
|
11135
11613
|
const kept = this.replacingKeys ?? /* @__PURE__ */ new Set();
|
|
11136
11614
|
this.replacingKeys = null;
|
|
11615
|
+
this.interruptedKeys = /* @__PURE__ */ new Set();
|
|
11137
11616
|
const removed = [];
|
|
11138
11617
|
const next = /* @__PURE__ */ new Map();
|
|
11139
11618
|
for (const text of kept) {
|
|
@@ -11180,6 +11659,27 @@ var MemoryRecordLogTables = class {
|
|
|
11180
11659
|
const kept = new Set(attempts);
|
|
11181
11660
|
for (const attempt of [...this.loadKeys.keys()]) if (!kept.has(attempt)) this.loadKeys.delete(attempt);
|
|
11182
11661
|
}
|
|
11662
|
+
heldSegment() {
|
|
11663
|
+
return this.heldValue ? JSON.parse(JSON.stringify(this.heldValue)) : null;
|
|
11664
|
+
}
|
|
11665
|
+
setHeldSegment(segment) {
|
|
11666
|
+
this.heldValue = segment ? JSON.parse(JSON.stringify(segment)) : null;
|
|
11667
|
+
}
|
|
11668
|
+
keepConfirmedRange(range) {
|
|
11669
|
+
const replacing = this.replacingKeys;
|
|
11670
|
+
if (!replacing) return false;
|
|
11671
|
+
const within = [];
|
|
11672
|
+
for (const text of this.rows.rows.keys()) {
|
|
11673
|
+
const at = text.indexOf("\0");
|
|
11674
|
+
const id = text.slice(at + 1);
|
|
11675
|
+
if (text.slice(0, at) !== range.model || replacing.has(text) || this.interruptedKeys.has(text)) continue;
|
|
11676
|
+
if (compareRecordIds(id, range.firstId) >= 0 && compareRecordIds(id, range.lastId) <= 0) within.push({ text, id });
|
|
11677
|
+
}
|
|
11678
|
+
if (within.length !== range.rows) return false;
|
|
11679
|
+
within.sort((a, b) => compareRecordIds(a.id, b.id));
|
|
11680
|
+
for (const { text } of within) replacing.add(text);
|
|
11681
|
+
return true;
|
|
11682
|
+
}
|
|
11183
11683
|
/** The receipt attempts whose load keys are kept: a check that none outlives its receipt. */
|
|
11184
11684
|
loadKeyAttempts() {
|
|
11185
11685
|
return [...this.loadKeys.keys()];
|
|
@@ -11208,6 +11708,12 @@ var MemoryRecordLogTables = class {
|
|
|
11208
11708
|
pending(writer) {
|
|
11209
11709
|
return [...this.writers.get(writer)?.pending ?? []];
|
|
11210
11710
|
}
|
|
11711
|
+
pendingEntry(writer, seq) {
|
|
11712
|
+
return this.writers.get(writer)?.pending.find((p) => p.seq === seq);
|
|
11713
|
+
}
|
|
11714
|
+
pendingThrough(writer, seq) {
|
|
11715
|
+
return (this.writers.get(writer)?.pending ?? []).filter((p) => p.seq <= seq);
|
|
11716
|
+
}
|
|
11211
11717
|
putPending(writer, entry) {
|
|
11212
11718
|
const w = this.writerOf(writer);
|
|
11213
11719
|
const at = w.pending.findIndex((p) => p.seq === entry.seq);
|
|
@@ -11308,7 +11814,8 @@ function recordLogClientDDL() {
|
|
|
11308
11814
|
permission TEXT,
|
|
11309
11815
|
rows_gen INTEGER NOT NULL DEFAULT 0,
|
|
11310
11816
|
replacing INTEGER,
|
|
11311
|
-
receipt TEXT
|
|
11817
|
+
receipt TEXT,
|
|
11818
|
+
segment TEXT
|
|
11312
11819
|
)`,
|
|
11313
11820
|
`CREATE TABLE IF NOT EXISTS record_log_writers (
|
|
11314
11821
|
doc_id TEXT NOT NULL,
|
|
@@ -11332,6 +11839,10 @@ function recordLogClientDDL() {
|
|
|
11332
11839
|
PRIMARY KEY (doc_id, writer, seq)
|
|
11333
11840
|
)`,
|
|
11334
11841
|
`CREATE INDEX IF NOT EXISTS record_log_pending_acked ON record_log_pending(doc_id, acked) WHERE acked IS NOT NULL`,
|
|
11842
|
+
// A write numbers its entry after the highest `ord` and counts its
|
|
11843
|
+
// epoch's unwithdrawn entries; neither reads the entries.
|
|
11844
|
+
`CREATE INDEX IF NOT EXISTS record_log_pending_by_ord ON record_log_pending(doc_id, ord)`,
|
|
11845
|
+
`CREATE INDEX IF NOT EXISTS record_log_pending_by_epoch ON record_log_pending(doc_id, e) WHERE void = 0`,
|
|
11335
11846
|
`CREATE TABLE IF NOT EXISTS record_log_pending_keys (
|
|
11336
11847
|
doc_id TEXT NOT NULL,
|
|
11337
11848
|
writer TEXT NOT NULL,
|
|
@@ -11341,7 +11852,10 @@ function recordLogClientDDL() {
|
|
|
11341
11852
|
resolved INTEGER NOT NULL DEFAULT 0,
|
|
11342
11853
|
PRIMARY KEY (doc_id, writer, seq, _type, _id)
|
|
11343
11854
|
)`,
|
|
11344
|
-
|
|
11855
|
+
// The entries touching a record, answered from the index alone: without
|
|
11856
|
+
// `writer, seq` in it SQLite reads the keys' primary key by document.
|
|
11857
|
+
`DROP INDEX IF EXISTS record_log_pending_keys_by_record`,
|
|
11858
|
+
`CREATE INDEX IF NOT EXISTS record_log_pending_keys_by_record_entry ON record_log_pending_keys(doc_id, _type, _id, writer, seq)`,
|
|
11345
11859
|
`CREATE TABLE IF NOT EXISTS record_log_pending_values (
|
|
11346
11860
|
doc_id TEXT NOT NULL,
|
|
11347
11861
|
writer TEXT NOT NULL,
|
|
@@ -11383,7 +11897,8 @@ function recordLogClientDDL() {
|
|
|
11383
11897
|
];
|
|
11384
11898
|
}
|
|
11385
11899
|
var RECORD_LOG_CLIENT_ADDED_COLUMNS = Object.freeze([
|
|
11386
|
-
{ table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` }
|
|
11900
|
+
{ table: "record_log_state", column: "receipt", add: `ALTER TABLE record_log_state ADD COLUMN receipt TEXT` },
|
|
11901
|
+
{ table: "record_log_state", column: "segment", add: `ALTER TABLE record_log_state ADD COLUMN segment TEXT` }
|
|
11387
11902
|
]);
|
|
11388
11903
|
function recordLogFieldIndexName(kind, model, name, table = "view") {
|
|
11389
11904
|
const tag = kind === "field" ? "f" : "u";
|
|
@@ -11445,6 +11960,11 @@ function queryRow(row, spec) {
|
|
|
11445
11960
|
function rowsOf(sql, query, ...bindings) {
|
|
11446
11961
|
return Array.from(sql.exec(query, ...bindings));
|
|
11447
11962
|
}
|
|
11963
|
+
function pendingRow(row) {
|
|
11964
|
+
const entry = JSON.parse(String(row.entry));
|
|
11965
|
+
if (row.acked !== null && row.acked !== void 0) entry.acked = Number(row.acked);
|
|
11966
|
+
return entry;
|
|
11967
|
+
}
|
|
11448
11968
|
var SqlRecordLogTables = class {
|
|
11449
11969
|
constructor(sql, docId) {
|
|
11450
11970
|
this.sql = sql;
|
|
@@ -11456,6 +11976,11 @@ var SqlRecordLogTables = class {
|
|
|
11456
11976
|
heldWarned = false;
|
|
11457
11977
|
/** Records of entries changed or removed since the last {@link takeDirty}, resolutions included. */
|
|
11458
11978
|
dirty = [];
|
|
11979
|
+
/**
|
|
11980
|
+
* Inside {@link countingEpochs}, each epoch's unwithdrawn pending entries
|
|
11981
|
+
* once counted, kept as entries are added; `null` outside it.
|
|
11982
|
+
*/
|
|
11983
|
+
epochPending = null;
|
|
11459
11984
|
state() {
|
|
11460
11985
|
return rowsOf(this.sql, `SELECT * FROM record_log_state WHERE doc_id = ?`, this.docId)[0] ?? null;
|
|
11461
11986
|
}
|
|
@@ -11523,6 +12048,24 @@ var SqlRecordLogTables = class {
|
|
|
11523
12048
|
this.ensureState();
|
|
11524
12049
|
this.sql.exec(`UPDATE record_log_state SET receipt = ? WHERE doc_id = ?`, state ? JSON.stringify(state) : null, this.docId);
|
|
11525
12050
|
}
|
|
12051
|
+
heldSegment() {
|
|
12052
|
+
const text = this.state()?.segment;
|
|
12053
|
+
return text ? JSON.parse(String(text)) : null;
|
|
12054
|
+
}
|
|
12055
|
+
setHeldSegment(segment) {
|
|
12056
|
+
this.ensureState();
|
|
12057
|
+
this.sql.exec(`UPDATE record_log_state SET segment = ? WHERE doc_id = ?`, segment ? JSON.stringify(segment) : null, this.docId);
|
|
12058
|
+
}
|
|
12059
|
+
keepConfirmedRange(range) {
|
|
12060
|
+
const state = this.state();
|
|
12061
|
+
if (state?.replacing === null || state?.replacing === void 0) return false;
|
|
12062
|
+
const where = `WHERE doc_id = ? AND _type = ? AND _id >= ? AND _id <= ? AND _gen = ?`;
|
|
12063
|
+
const bindings = [this.docId, range.model, range.firstId, range.lastId, Number(state.rows_gen ?? 0)];
|
|
12064
|
+
const [count] = rowsOf(this.sql, `SELECT COUNT(*) AS n FROM record_log_rows ${where}`, ...bindings);
|
|
12065
|
+
if (Number(count?.n ?? 0) !== range.rows) return false;
|
|
12066
|
+
this.sql.exec(`UPDATE record_log_rows SET _gen = ? ${where}`, Number(state.replacing), ...bindings);
|
|
12067
|
+
return true;
|
|
12068
|
+
}
|
|
11526
12069
|
noteLoadKeys(attempt, keys) {
|
|
11527
12070
|
for (const key of keys) {
|
|
11528
12071
|
this.sql.exec(
|
|
@@ -11680,16 +12223,32 @@ var SqlRecordLogTables = class {
|
|
|
11680
12223
|
`SELECT entry, acked FROM record_log_pending WHERE doc_id = ? AND writer = ? ORDER BY seq`,
|
|
11681
12224
|
this.docId,
|
|
11682
12225
|
writer
|
|
11683
|
-
).map(
|
|
11684
|
-
|
|
11685
|
-
|
|
11686
|
-
|
|
11687
|
-
|
|
12226
|
+
).map(pendingRow);
|
|
12227
|
+
}
|
|
12228
|
+
pendingEntry(writer, seq) {
|
|
12229
|
+
const [row] = rowsOf(
|
|
12230
|
+
this.sql,
|
|
12231
|
+
`SELECT entry, acked FROM record_log_pending WHERE doc_id = ? AND writer = ? AND seq = ?`,
|
|
12232
|
+
this.docId,
|
|
12233
|
+
writer,
|
|
12234
|
+
seq
|
|
12235
|
+
);
|
|
12236
|
+
return row ? pendingRow(row) : void 0;
|
|
12237
|
+
}
|
|
12238
|
+
pendingThrough(writer, seq) {
|
|
12239
|
+
return rowsOf(
|
|
12240
|
+
this.sql,
|
|
12241
|
+
`SELECT entry, acked FROM record_log_pending WHERE doc_id = ? AND writer = ? AND seq <= ? ORDER BY seq`,
|
|
12242
|
+
this.docId,
|
|
12243
|
+
writer,
|
|
12244
|
+
seq
|
|
12245
|
+
).map(pendingRow);
|
|
11688
12246
|
}
|
|
11689
12247
|
putPending(writer, entry) {
|
|
11690
12248
|
const { acked, ...stored } = entry;
|
|
11691
12249
|
const exists = rowsOf(this.sql, `SELECT 1 FROM record_log_pending WHERE doc_id = ? AND writer = ? AND seq = ?`, this.docId, writer, entry.seq).length > 0;
|
|
11692
12250
|
if (exists) {
|
|
12251
|
+
this.epochPending?.clear();
|
|
11693
12252
|
this.markDirty(writer, entry.seq);
|
|
11694
12253
|
this.sql.exec(
|
|
11695
12254
|
`UPDATE record_log_pending SET entry = ?, void = ?, acked = ?, e = ? WHERE doc_id = ? AND writer = ? AND seq = ?`,
|
|
@@ -11721,6 +12280,8 @@ var SqlRecordLogTables = class {
|
|
|
11721
12280
|
entry.void ? 1 : 0,
|
|
11722
12281
|
acked ?? null
|
|
11723
12282
|
);
|
|
12283
|
+
const counted = this.epochPending?.get(entry.e);
|
|
12284
|
+
if (!entry.void && counted !== void 0) this.epochPending.set(entry.e, counted + 1);
|
|
11724
12285
|
}
|
|
11725
12286
|
this.putValues(writer, entry);
|
|
11726
12287
|
for (const key of keysOf(entry)) {
|
|
@@ -11761,6 +12322,7 @@ var SqlRecordLogTables = class {
|
|
|
11761
12322
|
}
|
|
11762
12323
|
}
|
|
11763
12324
|
deletePending(writer, seq) {
|
|
12325
|
+
this.epochPending?.clear();
|
|
11764
12326
|
this.markDirty(writer, seq);
|
|
11765
12327
|
this.sql.exec(`DELETE FROM record_log_pending WHERE doc_id = ? AND writer = ? AND seq = ?`, this.docId, writer, seq);
|
|
11766
12328
|
this.sql.exec(`DELETE FROM record_log_pending_keys WHERE doc_id = ? AND writer = ? AND seq = ?`, this.docId, writer, seq);
|
|
@@ -11810,13 +12372,30 @@ var SqlRecordLogTables = class {
|
|
|
11810
12372
|
);
|
|
11811
12373
|
}
|
|
11812
12374
|
pendingInEpoch(e) {
|
|
12375
|
+
const counted = this.epochPending?.get(e);
|
|
12376
|
+
if (counted !== void 0) return counted;
|
|
11813
12377
|
const [row] = rowsOf(
|
|
11814
12378
|
this.sql,
|
|
11815
12379
|
`SELECT COUNT(*) AS n FROM record_log_pending WHERE doc_id = ? AND void = 0 AND e = ?`,
|
|
11816
12380
|
this.docId,
|
|
11817
12381
|
e
|
|
11818
12382
|
);
|
|
11819
|
-
|
|
12383
|
+
const n = Number(row?.n ?? 0);
|
|
12384
|
+
this.epochPending?.set(e, n);
|
|
12385
|
+
return n;
|
|
12386
|
+
}
|
|
12387
|
+
/**
|
|
12388
|
+
* Run `fn` counting each epoch's pending entries once: a commit's writes
|
|
12389
|
+
* each check the budget, and inside one transaction only they change the
|
|
12390
|
+
* count. Any other change to the pending log counts again.
|
|
12391
|
+
*/
|
|
12392
|
+
countingEpochs(fn) {
|
|
12393
|
+
this.epochPending = /* @__PURE__ */ new Map();
|
|
12394
|
+
try {
|
|
12395
|
+
return fn();
|
|
12396
|
+
} finally {
|
|
12397
|
+
this.epochPending = null;
|
|
12398
|
+
}
|
|
11820
12399
|
}
|
|
11821
12400
|
};
|
|
11822
12401
|
function modelsOf(keys) {
|
|
@@ -12032,6 +12611,7 @@ var RecordLogStore = class {
|
|
|
12032
12611
|
const epochs = this.tables.epochs();
|
|
12033
12612
|
const [state] = rowsOf(this.sql, `SELECT * FROM record_log_state WHERE doc_id = ?`, this.docId);
|
|
12034
12613
|
const writer = this.writer();
|
|
12614
|
+
const writerState = writer ? this.tables.writerState(writer) : null;
|
|
12035
12615
|
const [pending] = writer ? rowsOf(
|
|
12036
12616
|
this.sql,
|
|
12037
12617
|
`SELECT MIN(seq) AS lowest, COUNT(*) AS n FROM record_log_pending WHERE doc_id = ? AND writer = ?`,
|
|
@@ -12047,11 +12627,13 @@ var RecordLogStore = class {
|
|
|
12047
12627
|
replacement: this.tables.replacing(),
|
|
12048
12628
|
lastCatchUpAt: state?.last_catch_up_at ?? null,
|
|
12049
12629
|
writer,
|
|
12050
|
-
nextSeq:
|
|
12630
|
+
nextSeq: writerState?.nextSeq ?? 1,
|
|
12631
|
+
resumedAt: writerState?.resumedAt ?? 0,
|
|
12051
12632
|
lowestPending: pending && pending.lowest !== null && pending.lowest !== void 0 ? Number(pending.lowest) : null,
|
|
12052
12633
|
pending: Number(pending?.n ?? 0),
|
|
12053
12634
|
unacked: writer ? this.unackedOf(writer) : [],
|
|
12054
|
-
receipt: latestReceipt(this.tables.receipts())
|
|
12635
|
+
receipt: latestReceipt(this.tables.receipts()),
|
|
12636
|
+
segment: this.tables.heldSegment()
|
|
12055
12637
|
};
|
|
12056
12638
|
}
|
|
12057
12639
|
/** A writer's unacknowledged, unwithdrawn entries and the records each touches. */
|
|
@@ -12441,31 +13023,33 @@ var RecordLogStore = class {
|
|
|
12441
13023
|
* epochs this client may write into are full; nothing of the command lands.
|
|
12442
13024
|
*/
|
|
12443
13025
|
commitEntries(command) {
|
|
12444
|
-
return this.sql.transaction(
|
|
12445
|
-
|
|
12446
|
-
|
|
12447
|
-
|
|
12448
|
-
|
|
12449
|
-
const
|
|
12450
|
-
|
|
12451
|
-
|
|
12452
|
-
|
|
12453
|
-
|
|
12454
|
-
|
|
12455
|
-
|
|
12456
|
-
|
|
12457
|
-
|
|
12458
|
-
|
|
12459
|
-
|
|
12460
|
-
|
|
12461
|
-
|
|
12462
|
-
|
|
12463
|
-
|
|
12464
|
-
|
|
12465
|
-
|
|
12466
|
-
|
|
12467
|
-
|
|
12468
|
-
|
|
13026
|
+
return this.sql.transaction(
|
|
13027
|
+
() => this.tables.countingEpochs(() => {
|
|
13028
|
+
const client = this.client(command.writer);
|
|
13029
|
+
const results = [];
|
|
13030
|
+
const refreshed = [];
|
|
13031
|
+
for (const write of command.writes) {
|
|
13032
|
+
const stale = (write.expect ?? []).some(
|
|
13033
|
+
({ model, id, revision }) => recordLogRowRevision(this.read(model, id)) !== revision
|
|
13034
|
+
);
|
|
13035
|
+
if (stale) {
|
|
13036
|
+
results.push({ stale: true });
|
|
13037
|
+
continue;
|
|
13038
|
+
}
|
|
13039
|
+
client.budgetCheck(this.docId);
|
|
13040
|
+
const [m, ...also] = write.mutations;
|
|
13041
|
+
const entry = client.write(m, {
|
|
13042
|
+
also,
|
|
13043
|
+
...write.upsertOn !== void 0 ? { upsertOn: write.upsertOn } : {},
|
|
13044
|
+
ts: command.ts ?? Date.now()
|
|
13045
|
+
});
|
|
13046
|
+
refreshed.push(...this.refreshView([...keysOf(entry), ...this.tables.takeDirty()]));
|
|
13047
|
+
results.push({ entry });
|
|
13048
|
+
}
|
|
13049
|
+
const changed = this.settleView([], command.project ?? [], refreshed);
|
|
13050
|
+
return { results, changed, cursor: this.tables.cursor() };
|
|
13051
|
+
})
|
|
13052
|
+
);
|
|
12469
13053
|
}
|
|
12470
13054
|
/** Apply what the room relayed, item by item. */
|
|
12471
13055
|
receive(command) {
|
|
@@ -12474,14 +13058,16 @@ var RecordLogStore = class {
|
|
|
12474
13058
|
const touched = [];
|
|
12475
13059
|
const acknowledged = [];
|
|
12476
13060
|
const settled = [];
|
|
13061
|
+
let underivable;
|
|
12477
13062
|
for (const item of command.items) {
|
|
12478
13063
|
const out = client.receive(item);
|
|
12479
13064
|
touched.push(...out.touched);
|
|
12480
13065
|
acknowledged.push(...out.acknowledged);
|
|
12481
13066
|
settled.push(...out.settled);
|
|
13067
|
+
underivable ??= out.underivable;
|
|
12482
13068
|
}
|
|
12483
13069
|
const changed = this.settleView(touched, command.project ?? []);
|
|
12484
|
-
return { acknowledged, settled, changed, cursor: this.tables.cursor() };
|
|
13070
|
+
return { acknowledged, settled, changed, cursor: this.tables.cursor(), ...underivable ? { underivable } : {} };
|
|
12485
13071
|
});
|
|
12486
13072
|
}
|
|
12487
13073
|
/** Act on a refusal: hand back what it reaches and answer the frames that move the room past it. */
|
|
@@ -12506,7 +13092,10 @@ var RecordLogStore = class {
|
|
|
12506
13092
|
* the store beginning a replacement makes it stale.
|
|
12507
13093
|
*/
|
|
12508
13094
|
beginFencedCatchUp(command) {
|
|
12509
|
-
return this.sql.transaction(() =>
|
|
13095
|
+
return this.sql.transaction(() => {
|
|
13096
|
+
const generation = this.client(command.writer).beginFencedCatchUp(command.full);
|
|
13097
|
+
return command.full ? { generation, held: this.tables.heldSegment() } : { generation };
|
|
13098
|
+
});
|
|
12510
13099
|
}
|
|
12511
13100
|
/** Whether `generation` is not the replacement the store is in. */
|
|
12512
13101
|
staleGeneration(generation) {
|
|
@@ -12547,11 +13136,18 @@ var RecordLogStore = class {
|
|
|
12547
13136
|
high: command.high,
|
|
12548
13137
|
full: command.full,
|
|
12549
13138
|
...command.generation !== void 0 ? { generation: command.generation } : {},
|
|
12550
|
-
...command.receipt !== void 0 ? { receipt: command.receipt } : {}
|
|
13139
|
+
...command.receipt !== void 0 ? { receipt: command.receipt } : {},
|
|
13140
|
+
...command.segment !== void 0 ? { segment: command.segment } : {}
|
|
12551
13141
|
});
|
|
12552
13142
|
this.tables.setLastCatchUpAt(command.at ?? Date.now());
|
|
12553
13143
|
const changed = this.settleView(out.touched, command.project ?? []);
|
|
12554
|
-
return {
|
|
13144
|
+
return {
|
|
13145
|
+
acknowledged: out.acknowledged,
|
|
13146
|
+
settled: out.settled,
|
|
13147
|
+
changed,
|
|
13148
|
+
cursor: this.tables.cursor(),
|
|
13149
|
+
...out.underivable ? { underivable: out.underivable } : {}
|
|
13150
|
+
};
|
|
12555
13151
|
});
|
|
12556
13152
|
}
|
|
12557
13153
|
// ── Receipts of chunks ────────────────────────────────────────────
|
|
@@ -12661,6 +13257,25 @@ var RecordLogStore = class {
|
|
|
12661
13257
|
};
|
|
12662
13258
|
});
|
|
12663
13259
|
}
|
|
13260
|
+
/**
|
|
13261
|
+
* Keep one chunk of segment `segmentId` from the confirmed rows instead of
|
|
13262
|
+
* reading it, in one transaction, as {@link RecordLogClient.keepSegmentChunk}
|
|
13263
|
+
* decides: the reply's `applied` is the rows kept, or it answers
|
|
13264
|
+
* `mismatch` and nothing changed. `stale` as {@link applySegmentChunk}, and
|
|
13265
|
+
* for an attempt no longer in progress. The view and query rows are
|
|
13266
|
+
* already the kept rows'.
|
|
13267
|
+
*/
|
|
13268
|
+
keepSegmentChunk(command) {
|
|
13269
|
+
return this.sql.transaction(() => {
|
|
13270
|
+
const cursor = this.tables.cursor();
|
|
13271
|
+
if (this.staleGeneration(command.generation)) return { applied: 0, removed: 0, changed: [], models: [], cursor, stale: true };
|
|
13272
|
+
const stale = this.staleReceipt(command.writer, command.attempt);
|
|
13273
|
+
if (stale) return stale;
|
|
13274
|
+
const out = this.client(command.writer).keepSegmentChunk(command);
|
|
13275
|
+
if ("mismatch" in out) return { applied: 0, removed: 0, changed: [], models: [], cursor, mismatch: true };
|
|
13276
|
+
return { applied: out.kept, removed: 0, changed: [], models: [], ranges: out.ranges, cursor };
|
|
13277
|
+
});
|
|
13278
|
+
}
|
|
12664
13279
|
/** Apply a segment's corrections under the replacement `generation`; `stale` as {@link applySegmentChunk}. */
|
|
12665
13280
|
applySegmentCorrections(command) {
|
|
12666
13281
|
return this.sql.transaction(() => {
|
|
@@ -16148,6 +16763,17 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
16148
16763
|
return typeof generation === "number" ? generation : null;
|
|
16149
16764
|
});
|
|
16150
16765
|
}
|
|
16766
|
+
/**
|
|
16767
|
+
* Begin a segment's full replacement: its generation, and the segment the
|
|
16768
|
+
* store's rows were last replaced from, read in the same transaction (the
|
|
16769
|
+
* mirror's may be older). The receipt tries to keep only those chunks.
|
|
16770
|
+
*/
|
|
16771
|
+
beginSegmentReplacement(writer = this.writer()) {
|
|
16772
|
+
return this.run("beginCatchUp", async () => {
|
|
16773
|
+
const reply = await this.host.dispatch({ kind: "beginCatchUp", writer, full: true });
|
|
16774
|
+
return { generation: typeof reply?.generation === "number" ? reply.generation : null, held: reply?.held ?? null };
|
|
16775
|
+
});
|
|
16776
|
+
}
|
|
16151
16777
|
/** Apply one catch-up page, read by the room at log number `lsn`; answered `stale` when the store is past it. */
|
|
16152
16778
|
applyCatchUpPage(page, project = [], writer = this.writer()) {
|
|
16153
16779
|
return this.run("applyCatchUpPage", async () => {
|
|
@@ -16189,6 +16815,14 @@ var RecordLogStoreAsync = class _RecordLogStoreAsync {
|
|
|
16189
16815
|
applySegmentChunk(chunk, project = [], writer = this.writer()) {
|
|
16190
16816
|
return this.bulk("applySegmentChunk", { kind: "applySegmentChunk", writer, ...chunk, ...project.length ? { project } : {} });
|
|
16191
16817
|
}
|
|
16818
|
+
/**
|
|
16819
|
+
* Keep one chunk of a segment from the rows the store holds instead of
|
|
16820
|
+
* reading it: `applied` is the rows kept, or the reply is `mismatch` (the
|
|
16821
|
+
* chunk is read instead) or `stale`. Nothing the views show changes.
|
|
16822
|
+
*/
|
|
16823
|
+
keepSegmentChunk(chunk, writer = this.writer()) {
|
|
16824
|
+
return this.run("keepSegmentChunk", () => this.host.dispatch({ kind: "keepSegmentChunk", writer, ...chunk }));
|
|
16825
|
+
}
|
|
16192
16826
|
/** Apply a segment's corrections under the replacement `generation`; answered `stale` when it was superseded. */
|
|
16193
16827
|
applySegmentCorrections(corrections, project = [], writer = this.writer()) {
|
|
16194
16828
|
return this.bulk("applySegmentCorrections", {
|
|
@@ -16294,20 +16928,23 @@ var RecordLogSender = class {
|
|
|
16294
16928
|
constructor(transport, options = {}) {
|
|
16295
16929
|
this.transport = transport;
|
|
16296
16930
|
this.tickMs = options.tickMs ?? RECORD_LOG_TICK_MS;
|
|
16297
|
-
this.window = options.window ?? RECORD_LOG_SEND_WINDOW;
|
|
16298
16931
|
this.frameTargetBytes = options.frameTargetBytes ?? RECORD_LOG_FRAME_TARGET_BYTES;
|
|
16299
|
-
this.batchMax = options.batchMax ??
|
|
16932
|
+
this.batchMax = options.batchMax ?? RECORD_LOG_FRAME_ENTRIES_MAX;
|
|
16933
|
+
this.frameWaitMs = options.frameWaitMs ?? RECORD_LOG_FRAME_WAIT_MS;
|
|
16300
16934
|
this.clock = options.clock ?? platformClock;
|
|
16301
16935
|
}
|
|
16302
16936
|
queue = [];
|
|
16303
16937
|
inFlight = /* @__PURE__ */ new Set();
|
|
16938
|
+
/** The frames sent and not yet answered in full, oldest first: the numbers each still owes. */
|
|
16939
|
+
frames = [];
|
|
16304
16940
|
timer = null;
|
|
16941
|
+
/** Runs out when the oldest frame has waited {@link frameWaitMs}. */
|
|
16942
|
+
frameTimer = null;
|
|
16305
16943
|
tickMs;
|
|
16306
16944
|
frameTargetBytes;
|
|
16307
16945
|
batchMax;
|
|
16946
|
+
frameWaitMs;
|
|
16308
16947
|
clock;
|
|
16309
|
-
/** How many unacknowledged entries may be in flight; a bulk-saving app may widen it. */
|
|
16310
|
-
window;
|
|
16311
16948
|
/** Entries queued and not yet sent. */
|
|
16312
16949
|
queued() {
|
|
16313
16950
|
return this.queue.filter((q) => q.kind === "entry").length;
|
|
@@ -16316,6 +16953,14 @@ var RecordLogSender = class {
|
|
|
16316
16953
|
inFlightCount() {
|
|
16317
16954
|
return this.inFlight.size;
|
|
16318
16955
|
}
|
|
16956
|
+
/** The numbers of the entries sent and not yet acknowledged. */
|
|
16957
|
+
inFlightSeqs() {
|
|
16958
|
+
return [...this.inFlight];
|
|
16959
|
+
}
|
|
16960
|
+
/** `record.entries` frames that hold the next back: sent, not answered in full, and within their wait. */
|
|
16961
|
+
framesInFlight() {
|
|
16962
|
+
return this.frames.length;
|
|
16963
|
+
}
|
|
16319
16964
|
/** Queue an entry to send; one already queued or in flight is not queued twice. */
|
|
16320
16965
|
enqueue(entry) {
|
|
16321
16966
|
if (this.inFlight.has(entry.seq)) return;
|
|
@@ -16336,10 +16981,12 @@ var RecordLogSender = class {
|
|
|
16336
16981
|
}
|
|
16337
16982
|
/**
|
|
16338
16983
|
* The room is missing entries from `expected` on: every entry in flight
|
|
16339
|
-
* from there is sent again, in `seq` order, ahead of what is queued.
|
|
16984
|
+
* from there is sent again, in `seq` order, ahead of what is queued. A
|
|
16985
|
+
* frame no longer owes them; one that owed nothing else is done.
|
|
16340
16986
|
*/
|
|
16341
16987
|
resendFrom(expected, entries) {
|
|
16342
16988
|
for (const seq of [...this.inFlight]) if (seq >= expected) this.inFlight.delete(seq);
|
|
16989
|
+
this.forget((seq) => seq >= expected);
|
|
16343
16990
|
const again = entries.filter((entry) => entry.seq >= expected).filter((entry) => !this.queue.some((q) => q.kind === "entry" && q.entry.seq === entry.seq)).sort((a, b) => a.seq - b.seq).map((entry) => ({ kind: "entry", entry, bytes: recordLogJsonBytes(entry) }));
|
|
16344
16991
|
this.queue.unshift(...again);
|
|
16345
16992
|
if (this.queue.length) this.schedule();
|
|
@@ -16349,7 +16996,7 @@ var RecordLogSender = class {
|
|
|
16349
16996
|
* entry it already judged only when it arrives again. Every entry in
|
|
16350
16997
|
* flight goes back to the head of the queue in `seq` order, ahead of what
|
|
16351
16998
|
* was queued after it, in its form among `unjudged`; one no longer there
|
|
16352
|
-
* is dropped.
|
|
16999
|
+
* is dropped. No frame is in flight any more.
|
|
16353
17000
|
*/
|
|
16354
17001
|
requeueInFlight(unjudged) {
|
|
16355
17002
|
const bySeq = new Map(unjudged.map((entry) => [entry.seq, entry]));
|
|
@@ -16360,6 +17007,7 @@ var RecordLogSender = class {
|
|
|
16360
17007
|
again.push({ kind: "entry", entry, bytes: recordLogJsonBytes(entry) });
|
|
16361
17008
|
}
|
|
16362
17009
|
this.inFlight.clear();
|
|
17010
|
+
this.clearFrames();
|
|
16363
17011
|
this.queue.unshift(...again);
|
|
16364
17012
|
if (this.queue.length) this.schedule();
|
|
16365
17013
|
}
|
|
@@ -16368,14 +17016,21 @@ var RecordLogSender = class {
|
|
|
16368
17016
|
this.queue.push({ kind: "control", frame });
|
|
16369
17017
|
this.schedule();
|
|
16370
17018
|
}
|
|
16371
|
-
/**
|
|
17019
|
+
/**
|
|
17020
|
+
* The room has judged `seq` (a result, `void`, `duplicate` or a refusal):
|
|
17021
|
+
* its frame no longer owes it, and a frame answered in full lets the next
|
|
17022
|
+
* leave at the next tick.
|
|
17023
|
+
*/
|
|
16372
17024
|
acknowledged(seq) {
|
|
16373
|
-
|
|
17025
|
+
const answered = this.inFlight.delete(seq);
|
|
17026
|
+
this.forget((owed) => owed === seq);
|
|
17027
|
+
if (answered && this.queue.length) this.schedule();
|
|
16374
17028
|
}
|
|
16375
17029
|
/** Forget everything queued and in flight: the connection that would carry it is gone. */
|
|
16376
17030
|
reset() {
|
|
16377
17031
|
this.queue.length = 0;
|
|
16378
17032
|
this.inFlight.clear();
|
|
17033
|
+
this.clearFrames();
|
|
16379
17034
|
if (this.timer !== null) this.clock.clearTimeout(this.timer);
|
|
16380
17035
|
this.timer = null;
|
|
16381
17036
|
}
|
|
@@ -16390,7 +17045,39 @@ var RecordLogSender = class {
|
|
|
16390
17045
|
this.flush();
|
|
16391
17046
|
}, this.tickMs);
|
|
16392
17047
|
}
|
|
16393
|
-
/**
|
|
17048
|
+
/** The frames no longer owe the numbers `owed` picks; one that owes nothing is done. */
|
|
17049
|
+
forget(owed) {
|
|
17050
|
+
const oldest = this.frames[0];
|
|
17051
|
+
for (const frame of this.frames) for (const seq of [...frame]) if (owed(seq)) frame.delete(seq);
|
|
17052
|
+
this.frames = this.frames.filter((frame) => frame.size > 0);
|
|
17053
|
+
if (this.frames[0] !== oldest) {
|
|
17054
|
+
this.clearFrameTimer();
|
|
17055
|
+
this.armFrameTimer();
|
|
17056
|
+
}
|
|
17057
|
+
}
|
|
17058
|
+
clearFrames() {
|
|
17059
|
+
this.frames = [];
|
|
17060
|
+
this.clearFrameTimer();
|
|
17061
|
+
}
|
|
17062
|
+
clearFrameTimer() {
|
|
17063
|
+
if (this.frameTimer !== null) this.clock.clearTimeout(this.frameTimer);
|
|
17064
|
+
this.frameTimer = null;
|
|
17065
|
+
}
|
|
17066
|
+
/**
|
|
17067
|
+
* Time the oldest frame. Unanswered at the end of its wait, it stops
|
|
17068
|
+
* holding the next back; its numbers stay in flight, so a `record.gap`
|
|
17069
|
+
* still sends them again and their answers are still taken.
|
|
17070
|
+
*/
|
|
17071
|
+
armFrameTimer() {
|
|
17072
|
+
if (this.frameTimer !== null || !this.frames.length) return;
|
|
17073
|
+
this.frameTimer = this.clock.setTimeout(() => {
|
|
17074
|
+
this.frameTimer = null;
|
|
17075
|
+
this.frames.shift();
|
|
17076
|
+
this.armFrameTimer();
|
|
17077
|
+
if (this.queue.length) this.schedule();
|
|
17078
|
+
}, this.frameWaitMs);
|
|
17079
|
+
}
|
|
17080
|
+
/** Send what the frame in flight and the transport allow now. */
|
|
16394
17081
|
flush() {
|
|
16395
17082
|
if (!this.transport.connected()) return;
|
|
16396
17083
|
let batch = [];
|
|
@@ -16398,6 +17085,8 @@ var RecordLogSender = class {
|
|
|
16398
17085
|
const send = () => {
|
|
16399
17086
|
if (!batch.length) return;
|
|
16400
17087
|
this.transport.send({ type: "record.entries", entries: batch });
|
|
17088
|
+
this.frames.push(new Set(batch.map((entry) => entry.seq)));
|
|
17089
|
+
this.armFrameTimer();
|
|
16401
17090
|
batch = [];
|
|
16402
17091
|
bytes = 0;
|
|
16403
17092
|
};
|
|
@@ -16409,7 +17098,7 @@ var RecordLogSender = class {
|
|
|
16409
17098
|
this.transport.send(head.frame);
|
|
16410
17099
|
continue;
|
|
16411
17100
|
}
|
|
16412
|
-
if (this.
|
|
17101
|
+
if (!batch.length && this.frames.length >= RECORD_LOG_FRAMES_IN_FLIGHT) break;
|
|
16413
17102
|
const fits = batch.length < this.batchMax && (batch.length === 0 || bytes + head.bytes <= this.frameTargetBytes);
|
|
16414
17103
|
if (!fits) {
|
|
16415
17104
|
send();
|
|
@@ -16442,7 +17131,11 @@ var RECORD_LOG_DRAIN_WAIT_MS = 15e3;
|
|
|
16442
17131
|
var RECORD_LOG_RESULT_GAP_MS = 2e3;
|
|
16443
17132
|
var WRITER_TAKEN_RETRY_MS = 500;
|
|
16444
17133
|
var CATCH_UP_RETRY_MS = 250;
|
|
16445
|
-
var RECORD_LOG_ACCEPTS = ["load", "segment"];
|
|
17134
|
+
var RECORD_LOG_ACCEPTS = ["load", "segment", "building"];
|
|
17135
|
+
var RECORD_LOG_STREAM_CREDIT_PAGES = 4;
|
|
17136
|
+
var RECORD_LOG_BUILDING_MAX_WAIT_MS = 6e4;
|
|
17137
|
+
var BUILDING_RETRY_MS = 1e3;
|
|
17138
|
+
var streamIds = 0;
|
|
16446
17139
|
var RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS = 2;
|
|
16447
17140
|
var RECORD_LOG_REPLACEMENT_WAIT_MS = 3e4;
|
|
16448
17141
|
var REPLACEMENT_POLL_MS = 100;
|
|
@@ -16457,6 +17150,14 @@ function isChunkIntegrityError(error) {
|
|
|
16457
17150
|
return name === "IngestChunkError" || name === "SnapshotChunkIntegrityError";
|
|
16458
17151
|
}
|
|
16459
17152
|
var errorText = (error) => error instanceof Error ? error.message : String(error);
|
|
17153
|
+
function answeredSeqs(items, writer) {
|
|
17154
|
+
const seqs = [];
|
|
17155
|
+
for (const item of items) {
|
|
17156
|
+
if ("void" in item || "duplicate" in item) seqs.push(item.seq);
|
|
17157
|
+
else if (item.w === writer && item.seq !== void 0) seqs.push(item.seq);
|
|
17158
|
+
}
|
|
17159
|
+
return seqs;
|
|
17160
|
+
}
|
|
16460
17161
|
var shownPath = (path) => path.replace(/\/doc-artifact\/[^/]+/, "/doc-artifact/\u2026");
|
|
16461
17162
|
function loadManifestOf(bytes, pointer) {
|
|
16462
17163
|
let manifest;
|
|
@@ -16493,15 +17194,17 @@ var RecordLogDocumentSession = class {
|
|
|
16493
17194
|
* @param store - Its store.
|
|
16494
17195
|
* @param host - The instance's side.
|
|
16495
17196
|
* @param senderOptions - How entries are batched.
|
|
17197
|
+
* @param history - What the document's earlier sessions on this connection id left.
|
|
16496
17198
|
*/
|
|
16497
|
-
constructor(docId, store, host, senderOptions = {}) {
|
|
17199
|
+
constructor(docId, store, host, senderOptions = {}, history = { opened: /* @__PURE__ */ new Set(), stale: null }) {
|
|
16498
17200
|
this.docId = docId;
|
|
16499
17201
|
this.store = store;
|
|
16500
17202
|
this.host = host;
|
|
17203
|
+
this.history = history;
|
|
16501
17204
|
this.sender = new RecordLogSender(
|
|
16502
17205
|
{
|
|
16503
17206
|
send: (frame) => this.sendFrame(frame),
|
|
16504
|
-
connected: () => this.phase === "open" && this.connected()
|
|
17207
|
+
connected: () => (this.phase === "open" || this.sendingAhead) && this.connected()
|
|
16505
17208
|
},
|
|
16506
17209
|
senderOptions
|
|
16507
17210
|
);
|
|
@@ -16518,14 +17221,38 @@ var RecordLogDocumentSession = class {
|
|
|
16518
17221
|
/** The orphan writer's entries the room has not answered yet. */
|
|
16519
17222
|
outstanding = /* @__PURE__ */ new Set();
|
|
16520
17223
|
drainDone = null;
|
|
16521
|
-
/** Result frames that arrived while a catch-up was being read. */
|
|
16522
|
-
heldResults = [];
|
|
16523
17224
|
/**
|
|
16524
|
-
*
|
|
16525
|
-
*
|
|
16526
|
-
*
|
|
17225
|
+
* Result frames that arrived while a catch-up was being read; for an open
|
|
17226
|
+
* that sent frames ahead, also their answers (results and refusals) that
|
|
17227
|
+
* arrived while it was opening.
|
|
17228
|
+
*/
|
|
17229
|
+
held = [];
|
|
17230
|
+
/** The open in progress sent its declaration and entries ahead of `record.opened`, or `null`. */
|
|
17231
|
+
ahead = null;
|
|
17232
|
+
/** `record.open` frames sent on this connection; only its first may send frames ahead. */
|
|
17233
|
+
openedOnConnection = 0;
|
|
17234
|
+
/** Set while the frames sent ahead are flushed: the sender may send before the open completes. */
|
|
17235
|
+
sendingAhead = false;
|
|
17236
|
+
/** The wait past which a re-minted writer's open asks the old id's stream for a barrier. */
|
|
17237
|
+
staleTimer = null;
|
|
17238
|
+
/**
|
|
17239
|
+
* A `record.open` of the re-minted writer's old id is out on this
|
|
17240
|
+
* connection: its `record.opened`, queued on the old id's stream behind
|
|
17241
|
+
* every answer queued there before it, ends the wait.
|
|
16527
17242
|
*/
|
|
17243
|
+
barrier = false;
|
|
17244
|
+
/** The paged catch-up in progress. */
|
|
16528
17245
|
paging = null;
|
|
17246
|
+
/**
|
|
17247
|
+
* The room streams: its last `record.opened` said so (`streams: true`), or
|
|
17248
|
+
* a page marked with a stream id arrived on this connection. A stream start
|
|
17249
|
+
* then has no answer out; an older room answers it with an unmarked page.
|
|
17250
|
+
*/
|
|
17251
|
+
roomStreams = false;
|
|
17252
|
+
/** When the first of the `building` answers in a row arrived; `null` when the last answer was another form. */
|
|
17253
|
+
buildingSince = null;
|
|
17254
|
+
/** Streamed catch-ups: pages applied, pages ignored as another stream's, credits sent. */
|
|
17255
|
+
streamCounters = { pages: 0, stalePages: 0, credits: 0 };
|
|
16529
17256
|
/** The load the room said is applying (`record.load started`): results stall behind its numbers on purpose. */
|
|
16530
17257
|
loadInProgress = null;
|
|
16531
17258
|
/** Completed loads announced while the session was not open, received once it is. */
|
|
@@ -16590,6 +17317,13 @@ var RecordLogDocumentSession = class {
|
|
|
16590
17317
|
this.host.synced(this.docId);
|
|
16591
17318
|
return;
|
|
16592
17319
|
}
|
|
17320
|
+
if ((this.phase === "catchingUp" || this.phase === "loading") && this.paging?.stream !== void 0 && (this.paging.streamed || this.roomStreams)) {
|
|
17321
|
+
Logger.info(`[record-log] ${this.docId}: the streamed catch-up ${this.paging.stream} stopped; opening again from the cursor`);
|
|
17322
|
+
this.paging = null;
|
|
17323
|
+
this.receipt = null;
|
|
17324
|
+
await this.sendOpen();
|
|
17325
|
+
return;
|
|
17326
|
+
}
|
|
16593
17327
|
if (this.phase !== "idle") return;
|
|
16594
17328
|
if (!this.connected()) {
|
|
16595
17329
|
this.host.syncFailed(this.docId, "not connected");
|
|
@@ -16604,6 +17338,7 @@ var RecordLogDocumentSession = class {
|
|
|
16604
17338
|
if (this.orphans.length) {
|
|
16605
17339
|
Logger.info(`[record-log] ${this.docId}: draining ${this.orphans.length} earlier session writer(s) before opening`);
|
|
16606
17340
|
}
|
|
17341
|
+
if (this.history.stale) return this.sendBarrier();
|
|
16607
17342
|
await this.openNext();
|
|
16608
17343
|
});
|
|
16609
17344
|
}
|
|
@@ -16616,6 +17351,10 @@ var RecordLogDocumentSession = class {
|
|
|
16616
17351
|
const current = this.current;
|
|
16617
17352
|
const generation = this.generation;
|
|
16618
17353
|
this.opens++;
|
|
17354
|
+
if (this.ahead) {
|
|
17355
|
+
this.ahead = null;
|
|
17356
|
+
this.held = [];
|
|
17357
|
+
}
|
|
16619
17358
|
const marks = await this.store.refreshMarks();
|
|
16620
17359
|
const pending = await this.store.pendingOf(current.writer);
|
|
16621
17360
|
if (generation !== this.generation) return;
|
|
@@ -16623,7 +17362,17 @@ var RecordLogDocumentSession = class {
|
|
|
16623
17362
|
const nextSeq = unacked.length ? unacked[0].seq : current.orphan ? Math.max(1, ...pending.map((p) => p.seq + 1)) : marks.nextSeq;
|
|
16624
17363
|
this.phase = "opening";
|
|
16625
17364
|
this.loadInProgress = null;
|
|
17365
|
+
const sendAhead = !current.orphan && this.openedOnConnection === 0 && [...this.history.opened].every((writer) => writer === current.writer) && nextSeq > marks.resumedAt;
|
|
17366
|
+
this.openedOnConnection++;
|
|
17367
|
+
this.history.opened.add(current.writer);
|
|
16626
17368
|
const fetches = typeof this.host.connection()?.fetchArtifact === "function";
|
|
17369
|
+
const waited = this.buildingSince !== null && Date.now() - this.buildingSince >= RECORD_LOG_BUILDING_MAX_WAIT_MS;
|
|
17370
|
+
if (fetches && waited) {
|
|
17371
|
+
Logger.info(
|
|
17372
|
+
`[record-log] ${this.docId}: waited ${RECORD_LOG_BUILDING_MAX_WAIT_MS} ms for a segment being built; opening for pages instead`
|
|
17373
|
+
);
|
|
17374
|
+
}
|
|
17375
|
+
const accepts = RECORD_LOG_ACCEPTS.filter((token) => token !== "building" || !waited);
|
|
16627
17376
|
this.sendFrame({
|
|
16628
17377
|
type: "record.open",
|
|
16629
17378
|
writer: current.writer,
|
|
@@ -16632,9 +17381,107 @@ var RecordLogDocumentSession = class {
|
|
|
16632
17381
|
open: marks.open,
|
|
16633
17382
|
formats: [3],
|
|
16634
17383
|
documentFormat: 3,
|
|
16635
|
-
|
|
17384
|
+
// Own entries the room applied as written come back as {l, e, w, seq}:
|
|
17385
|
+
// the store derives their rows from its pending entries.
|
|
17386
|
+
acks: "compact",
|
|
17387
|
+
...fetches ? { accepts: this.failedReceipts >= RECORD_LOG_RECEIPT_FAILURES_BEFORE_ROWS ? [] : accepts } : {}
|
|
17388
|
+
});
|
|
17389
|
+
if (!sendAhead) return;
|
|
17390
|
+
const models = this.host.declarations();
|
|
17391
|
+
const ahead = { declarations: JSON.stringify(models), refused: false, seqs: [] };
|
|
17392
|
+
this.ahead = ahead;
|
|
17393
|
+
this.sender.enqueueControl({ type: "record.declare", models });
|
|
17394
|
+
for (const entry of unacked) this.sender.enqueue(wireEntryOf(entry));
|
|
17395
|
+
this.sendingAhead = true;
|
|
17396
|
+
try {
|
|
17397
|
+
this.sender.flush();
|
|
17398
|
+
} finally {
|
|
17399
|
+
this.sendingAhead = false;
|
|
17400
|
+
}
|
|
17401
|
+
ahead.seqs = this.sender.inFlightSeqs();
|
|
17402
|
+
}
|
|
17403
|
+
/**
|
|
17404
|
+
* The numbers sent ahead under the writer being opened that the room has
|
|
17405
|
+
* not answered: none once it refused them, and none an answer held so far
|
|
17406
|
+
* names.
|
|
17407
|
+
*/
|
|
17408
|
+
owedAhead(writer) {
|
|
17409
|
+
const owed = new Set(this.ahead && !this.ahead.refused ? this.ahead.seqs : []);
|
|
17410
|
+
for (const answer of this.held) {
|
|
17411
|
+
if (answer.kind === "refused") owed.delete(answer.refusal.seq);
|
|
17412
|
+
else for (const seq of answeredSeqs(answer.items, writer)) owed.delete(seq);
|
|
17413
|
+
}
|
|
17414
|
+
return owed;
|
|
17415
|
+
}
|
|
17416
|
+
/**
|
|
17417
|
+
* A restored store's writer was re-minted while the room owed answers to
|
|
17418
|
+
* entries sent ahead under its old id. The room queues those answers on
|
|
17419
|
+
* the old subscription's stream, which the new open's does not wait for,
|
|
17420
|
+
* and a `void` or `duplicate` names no writer: one arriving once the new
|
|
17421
|
+
* id's renumbered entries went would be read as theirs. So the new id
|
|
17422
|
+
* opens once every owed number is answered (the answers are dropped), the
|
|
17423
|
+
* entries frame is refused, or the subscription is released. Past
|
|
17424
|
+
* {@link RECORD_LOG_DRAIN_WAIT_MS} the old id is opened again
|
|
17425
|
+
* ({@link sendBarrier}): its `record.opened` follows what is queued for it.
|
|
17426
|
+
*/
|
|
17427
|
+
waitForStale(writer, nextSeq, owed) {
|
|
17428
|
+
this.ahead = null;
|
|
17429
|
+
this.held = [];
|
|
17430
|
+
this.history.stale = { writer, nextSeq, seqs: owed };
|
|
17431
|
+
const timer = setTimeout(() => {
|
|
17432
|
+
void this.serially(async () => {
|
|
17433
|
+
if (this.staleTimer !== timer || !this.history.stale) return;
|
|
17434
|
+
this.staleTimer = null;
|
|
17435
|
+
Logger.warn(
|
|
17436
|
+
`[record-log] ${this.docId}: the room has not answered ${this.history.stale.seqs.size} entr(ies) sent under the re-minted writer's old id; opening the old id again so its answer follows them`
|
|
17437
|
+
);
|
|
17438
|
+
this.sendBarrier();
|
|
17439
|
+
});
|
|
17440
|
+
}, RECORD_LOG_DRAIN_WAIT_MS);
|
|
17441
|
+
timer.unref?.();
|
|
17442
|
+
this.staleTimer = timer;
|
|
17443
|
+
}
|
|
17444
|
+
/**
|
|
17445
|
+
* Open the re-minted writer's old id again. The room queues the answer on
|
|
17446
|
+
* that id's stream, behind every answer queued there before it; a room
|
|
17447
|
+
* that lost them (stopped, or its delivery failed) answers on a stream
|
|
17448
|
+
* that never carries them. A wait past which answers are taken to be lost
|
|
17449
|
+
* would let a late one settle the new id's numbers. Answers that arrive
|
|
17450
|
+
* meanwhile are dropped; only this open's answer ends the wait.
|
|
17451
|
+
*/
|
|
17452
|
+
sendBarrier() {
|
|
17453
|
+
const stale = this.history.stale;
|
|
17454
|
+
const marks = this.store.marks();
|
|
17455
|
+
this.barrier = true;
|
|
17456
|
+
this.openedOnConnection++;
|
|
17457
|
+
this.history.opened.add(stale.writer);
|
|
17458
|
+
this.sendFrame({
|
|
17459
|
+
type: "record.open",
|
|
17460
|
+
writer: stale.writer,
|
|
17461
|
+
cursor: marks.cursor,
|
|
17462
|
+
nextSeq: stale.nextSeq,
|
|
17463
|
+
open: marks.open,
|
|
17464
|
+
formats: [3],
|
|
17465
|
+
documentFormat: 3,
|
|
17466
|
+
acks: "compact"
|
|
16636
17467
|
});
|
|
16637
17468
|
}
|
|
17469
|
+
/** Answers to the old id's entries arrived: dropped, and the new id opens once none is owed. */
|
|
17470
|
+
async staleAnswered(seqs) {
|
|
17471
|
+
const stale = this.history.stale;
|
|
17472
|
+
if (!stale || this.barrier) return;
|
|
17473
|
+
for (const seq of seqs) stale.seqs.delete(seq);
|
|
17474
|
+
if (stale.seqs.size === 0) await this.endStale();
|
|
17475
|
+
}
|
|
17476
|
+
/** Nothing more of the old id can come: the document opens (orphans first, on a new connection). */
|
|
17477
|
+
async endStale() {
|
|
17478
|
+
if (!this.history.stale) return;
|
|
17479
|
+
if (this.staleTimer) clearTimeout(this.staleTimer);
|
|
17480
|
+
this.staleTimer = null;
|
|
17481
|
+
this.barrier = false;
|
|
17482
|
+
this.history.stale = null;
|
|
17483
|
+
await this.openNext();
|
|
17484
|
+
}
|
|
16638
17485
|
/** The socket closed: everything in flight is gone, and the next open starts over. */
|
|
16639
17486
|
disconnected() {
|
|
16640
17487
|
if (this.phase === "closed") return;
|
|
@@ -16643,7 +17490,14 @@ var RecordLogDocumentSession = class {
|
|
|
16643
17490
|
this.current = null;
|
|
16644
17491
|
this.orphans = [];
|
|
16645
17492
|
this.paging = null;
|
|
16646
|
-
this.
|
|
17493
|
+
this.roomStreams = false;
|
|
17494
|
+
this.buildingSince = null;
|
|
17495
|
+
this.held = [];
|
|
17496
|
+
this.ahead = null;
|
|
17497
|
+
this.openedOnConnection = 0;
|
|
17498
|
+
if (this.staleTimer) clearTimeout(this.staleTimer);
|
|
17499
|
+
this.staleTimer = null;
|
|
17500
|
+
this.barrier = false;
|
|
16647
17501
|
this.receipt = null;
|
|
16648
17502
|
this.queuedLoads = [];
|
|
16649
17503
|
this.loadInProgress = null;
|
|
@@ -16749,11 +17603,17 @@ var RecordLogDocumentSession = class {
|
|
|
16749
17603
|
});
|
|
16750
17604
|
}
|
|
16751
17605
|
async opened(frame) {
|
|
17606
|
+
if (this.history.stale) {
|
|
17607
|
+
if (this.barrier && this.phase === "opening") return this.endStale();
|
|
17608
|
+
Logger.debug(`[record-log] ${this.docId}: record.opened while a re-minted writer waits for its old id; ignored`);
|
|
17609
|
+
return;
|
|
17610
|
+
}
|
|
16752
17611
|
if (this.phase !== "opening" || !this.current) {
|
|
16753
17612
|
Logger.debug(`[record-log] ${this.docId}: record.opened outside an open; ignored`);
|
|
16754
17613
|
return;
|
|
16755
17614
|
}
|
|
16756
17615
|
this.takenRetryMs = WRITER_TAKEN_RETRY_MS;
|
|
17616
|
+
this.roomStreams = frame.streams === true;
|
|
16757
17617
|
const generation = this.generation;
|
|
16758
17618
|
const epochs = frame.epochs ?? {};
|
|
16759
17619
|
const current = Number(epochs.current ?? 1);
|
|
@@ -16772,15 +17632,22 @@ var RecordLogDocumentSession = class {
|
|
|
16772
17632
|
Logger.warn(
|
|
16773
17633
|
`[record-log] ${this.docId}: the room has judged writer ${this.current.writer} up to ${this.lastSeq}, past the ${this.store.marks().nextSeq - 1} it minted (a restored store); re-minting`
|
|
16774
17634
|
);
|
|
17635
|
+
const old = this.current.writer;
|
|
17636
|
+
const owed = this.owedAhead(old);
|
|
16775
17637
|
const { writer, renumbered } = await this.store.dispatch({ kind: "remintWriter", writer: this.current.writer });
|
|
16776
17638
|
this.store.renumbered(renumbered);
|
|
16777
17639
|
await this.store.refreshMarks();
|
|
16778
17640
|
if (generation !== this.generation) return;
|
|
16779
17641
|
this.current = { writer, orphan: false };
|
|
17642
|
+
this.sender.reset();
|
|
17643
|
+
if (owed.size) return this.waitForStale(old, this.lastSeq + 1, owed);
|
|
16780
17644
|
await this.sendOpen();
|
|
16781
17645
|
return;
|
|
16782
17646
|
}
|
|
17647
|
+
if (!this.current.orphan) this.history.opened = /* @__PURE__ */ new Set([this.current.writer]);
|
|
16783
17648
|
const catchUp = frame.catchUp ?? { mode: "inline", rows: [], gone: [], lsn: frame.lsn };
|
|
17649
|
+
if (catchUp.mode === "building") return this.waitForSegment(catchUp);
|
|
17650
|
+
this.buildingSince = null;
|
|
16784
17651
|
this.phase = "catchingUp";
|
|
16785
17652
|
const specs = this.host.projectionSpecs();
|
|
16786
17653
|
if (catchUp.mode === "load") {
|
|
@@ -16802,22 +17669,20 @@ var RecordLogDocumentSession = class {
|
|
|
16802
17669
|
);
|
|
16803
17670
|
const replacing2 = await this.store.beginFencedCatchUp(true, this.current.writer);
|
|
16804
17671
|
if (generation !== this.generation) return;
|
|
16805
|
-
this.
|
|
16806
|
-
this.sendFrame({ type: "record.catchUp", cursor: 0, upTo, full: true });
|
|
17672
|
+
this.beginPaging({ cursor: 0, upTo, full: true, high, ...replacing2 !== null ? { generation: replacing2 } : {} });
|
|
16807
17673
|
return;
|
|
16808
17674
|
}
|
|
16809
17675
|
if (catchUp.mode === "paged") {
|
|
16810
17676
|
const full2 = catchUp.full === true;
|
|
16811
17677
|
const replacing2 = await this.store.beginFencedCatchUp(full2, this.current.writer);
|
|
16812
17678
|
if (generation !== this.generation) return;
|
|
16813
|
-
this.
|
|
17679
|
+
this.beginPaging({
|
|
16814
17680
|
cursor: Number(catchUp.cursor),
|
|
16815
17681
|
upTo: Number(catchUp.upTo),
|
|
16816
17682
|
full: full2,
|
|
16817
17683
|
high,
|
|
16818
17684
|
...replacing2 !== null ? { generation: replacing2 } : {}
|
|
16819
|
-
};
|
|
16820
|
-
this.sendFrame({ type: "record.catchUp", cursor: this.paging.cursor, upTo: this.paging.upTo, ...full2 ? { full: true } : {} });
|
|
17685
|
+
});
|
|
16821
17686
|
return;
|
|
16822
17687
|
}
|
|
16823
17688
|
const full = catchUp.mode === "full";
|
|
@@ -16838,7 +17703,7 @@ var RecordLogDocumentSession = class {
|
|
|
16838
17703
|
return;
|
|
16839
17704
|
}
|
|
16840
17705
|
if (done.stale) return this.overtaken(lsn, done.cursor, replacing);
|
|
16841
|
-
await this.caughtUp(done.acknowledged);
|
|
17706
|
+
await this.caughtUp(done.acknowledged, done.underivable);
|
|
16842
17707
|
}
|
|
16843
17708
|
/**
|
|
16844
17709
|
* Another client of this store applied results past the log number the
|
|
@@ -16889,8 +17754,71 @@ var RecordLogDocumentSession = class {
|
|
|
16889
17754
|
}
|
|
16890
17755
|
/** The room's `lastSeq` for the writer being opened, from its `record.opened`. */
|
|
16891
17756
|
lastSeq = 0;
|
|
17757
|
+
/**
|
|
17758
|
+
* Begin a paged catch-up as a stream: the start carries a fresh id, and the
|
|
17759
|
+
* room pushes every page marked with it. An older room answers the start
|
|
17760
|
+
* with an unmarked page, and the rest are asked for one at a time.
|
|
17761
|
+
*/
|
|
17762
|
+
beginPaging(paging, extra = {}) {
|
|
17763
|
+
const stream = String(++streamIds);
|
|
17764
|
+
this.paging = { ...paging, stream, pages: 0 };
|
|
17765
|
+
this.sendFrame({
|
|
17766
|
+
type: "record.catchUp",
|
|
17767
|
+
stream,
|
|
17768
|
+
cursor: paging.cursor,
|
|
17769
|
+
upTo: paging.upTo,
|
|
17770
|
+
...paging.full ? { full: true } : {},
|
|
17771
|
+
...extra
|
|
17772
|
+
});
|
|
17773
|
+
}
|
|
17774
|
+
/** A page of a stream this session is not running (ended, replaced or released): it applies to nothing. */
|
|
17775
|
+
stalePage(frame, why) {
|
|
17776
|
+
this.streamCounters.stalePages++;
|
|
17777
|
+
Logger.debug(`[record-log] ${this.docId}: catch-up page of stream ${String(frame.stream ?? "(none)")} ignored: ${why}`);
|
|
17778
|
+
}
|
|
17779
|
+
/**
|
|
17780
|
+
* The room is building a segment for this open (`mode: "building"`): the
|
|
17781
|
+
* subscription is registered, but nothing is caught up. Results that
|
|
17782
|
+
* arrive meanwhile are dropped (the next open's catch-up carries them),
|
|
17783
|
+
* progress is reported so the open's watchdog waits, and the document is
|
|
17784
|
+
* opened again after `retryMs`. Past {@link RECORD_LOG_BUILDING_MAX_WAIT_MS}
|
|
17785
|
+
* of such answers, the open no longer declares `building`.
|
|
17786
|
+
*/
|
|
17787
|
+
waitForSegment(catchUp) {
|
|
17788
|
+
this.buildingSince ??= Date.now();
|
|
17789
|
+
const retryMs = Number.isFinite(Number(catchUp.retryMs)) ? Math.max(0, Number(catchUp.retryMs)) : BUILDING_RETRY_MS;
|
|
17790
|
+
Logger.info(
|
|
17791
|
+
`[record-log] ${this.docId}: the room is building segment ${String(catchUp.segmentId ?? "")} for this open; opening again in ${retryMs} ms`
|
|
17792
|
+
);
|
|
17793
|
+
this.phase = "opening";
|
|
17794
|
+
this.host.progress?.(this.docId);
|
|
17795
|
+
const connection = this.generation;
|
|
17796
|
+
const opens = this.opens;
|
|
17797
|
+
const timer = setTimeout(() => {
|
|
17798
|
+
void this.serially(async () => {
|
|
17799
|
+
if (connection !== this.generation || opens !== this.opens || this.phase !== "opening" || !this.current) return;
|
|
17800
|
+
await this.sendOpen();
|
|
17801
|
+
});
|
|
17802
|
+
}, retryMs);
|
|
17803
|
+
timer.unref?.();
|
|
17804
|
+
}
|
|
16892
17805
|
async catchUpPage(frame) {
|
|
16893
|
-
|
|
17806
|
+
const marked = typeof frame.stream === "string";
|
|
17807
|
+
if (this.phase !== "catchingUp" && this.phase !== "loading" || !this.paging || !this.current) {
|
|
17808
|
+
if (marked) this.stalePage(frame, "no catch-up is in progress");
|
|
17809
|
+
return;
|
|
17810
|
+
}
|
|
17811
|
+
if (marked) {
|
|
17812
|
+
if (frame.stream !== this.paging.stream) return this.stalePage(frame, `the catch-up in progress is ${this.paging.stream ?? "paged per request"}`);
|
|
17813
|
+
this.paging.streamed = true;
|
|
17814
|
+
this.roomStreams = true;
|
|
17815
|
+
this.streamCounters.pages++;
|
|
17816
|
+
} else if (this.paging.stream !== void 0 && (this.paging.streamed || this.roomStreams)) {
|
|
17817
|
+
return this.stalePage(frame, "an unmarked page during a stream");
|
|
17818
|
+
} else if (this.paging.stream !== void 0) {
|
|
17819
|
+
Logger.debug(`[record-log] ${this.docId}: the room answered a stream start with a page per request; asking for each page`);
|
|
17820
|
+
delete this.paging.stream;
|
|
17821
|
+
}
|
|
16894
17822
|
const receipt = this.paging.receipt;
|
|
16895
17823
|
if (this.paging.released) {
|
|
16896
17824
|
Logger.info(`[record-log] ${this.docId}: a catch-up page requested before the room released the subscription; discarded`);
|
|
@@ -16917,6 +17845,14 @@ var RecordLogDocumentSession = class {
|
|
|
16917
17845
|
if (page.stale) return this.overtaken(lsn, page.cursor, this.paging.generation ?? null);
|
|
16918
17846
|
if (receipt) receipt.remainderRows += rows.length + gone.length;
|
|
16919
17847
|
this.host.progress?.(this.docId);
|
|
17848
|
+
if (frame.next && this.paging.stream !== void 0) {
|
|
17849
|
+
this.paging.pages = (this.paging.pages ?? 0) + 1;
|
|
17850
|
+
if (this.paging.pages % RECORD_LOG_STREAM_CREDIT_PAGES === 0) {
|
|
17851
|
+
this.streamCounters.credits++;
|
|
17852
|
+
this.sendFrame({ type: "record.catchUp", stream: this.paging.stream, credit: frame.next });
|
|
17853
|
+
}
|
|
17854
|
+
return;
|
|
17855
|
+
}
|
|
16920
17856
|
if (frame.next) {
|
|
16921
17857
|
this.sendFrame({
|
|
16922
17858
|
type: "record.catchUp",
|
|
@@ -16933,7 +17869,14 @@ var RecordLogDocumentSession = class {
|
|
|
16933
17869
|
const replacing = this.paging.generation ?? null;
|
|
16934
17870
|
this.paging = null;
|
|
16935
17871
|
const done = await this.store.completeCatchUp(
|
|
16936
|
-
{
|
|
17872
|
+
{
|
|
17873
|
+
lsn,
|
|
17874
|
+
high,
|
|
17875
|
+
full,
|
|
17876
|
+
...fence,
|
|
17877
|
+
...receipt?.attempt !== void 0 ? { receipt: receipt.attempt } : {},
|
|
17878
|
+
...receipt?.segment ? { segment: receipt.segment } : {}
|
|
17879
|
+
},
|
|
16937
17880
|
specs,
|
|
16938
17881
|
this.current.writer
|
|
16939
17882
|
);
|
|
@@ -16944,7 +17887,7 @@ var RecordLogDocumentSession = class {
|
|
|
16944
17887
|
if (done.stale) return this.overtaken(lsn, done.cursor, replacing);
|
|
16945
17888
|
if (full) this.failedReceipts = 0;
|
|
16946
17889
|
if (receipt) this.receiptDone(receipt);
|
|
16947
|
-
await this.caughtUp(done.acknowledged);
|
|
17890
|
+
await this.caughtUp(done.acknowledged, done.underivable);
|
|
16948
17891
|
}
|
|
16949
17892
|
// ── Receipts of chunks ────────────────────────────────────────────
|
|
16950
17893
|
/** The connection's artifact fetch; a receipt fails without one. */
|
|
@@ -17082,8 +18025,7 @@ var RecordLogDocumentSession = class {
|
|
|
17082
18025
|
await this.serially(async () => {
|
|
17083
18026
|
if (!this.receiving(receipt)) return;
|
|
17084
18027
|
if (receipt.released) return this.abandonReceipt(receipt, "the room released the subscription");
|
|
17085
|
-
this.
|
|
17086
|
-
this.sendFrame({ type: "record.catchUp", cursor: remainder.cursor, upTo: remainder.upTo, load: pointer.sessionId });
|
|
18028
|
+
this.beginPaging({ cursor: remainder.cursor, upTo: remainder.upTo, full: false, high: remainder.high, receipt }, { load: pointer.sessionId });
|
|
17087
18029
|
});
|
|
17088
18030
|
} catch (error) {
|
|
17089
18031
|
await this.serially(() => this.receiptFailed(receipt, errorText(error)));
|
|
@@ -17122,11 +18064,44 @@ var RecordLogDocumentSession = class {
|
|
|
17122
18064
|
this.fetcher();
|
|
17123
18065
|
const attempt = await this.store.beginReceipt({ kind: "segment", id: segment.segmentId }, receipt.writer);
|
|
17124
18066
|
receipt.attempt = attempt;
|
|
17125
|
-
const generation = await this.store.
|
|
18067
|
+
const { generation, held } = await this.store.beginSegmentReplacement(receipt.writer);
|
|
17126
18068
|
if (generation === null) throw new ReceiptFailure("the store handed out no replacement generation");
|
|
17127
18069
|
const overtaken = () => this.serially(() => this.abandonReceipt(receipt, "another client of the store began replacing it", generation));
|
|
17128
|
-
|
|
18070
|
+
const holds = new Map((held?.chunks ?? []).map((c) => [c.object, c]));
|
|
18071
|
+
receipt.kept = 0;
|
|
18072
|
+
receipt.segment = {
|
|
18073
|
+
segmentId: segment.segmentId,
|
|
18074
|
+
chunks: segment.chunks.map((chunk) => ({
|
|
18075
|
+
object: recordLogSegmentChunkObject(segment.segmentId, chunk),
|
|
18076
|
+
model: chunk.model,
|
|
18077
|
+
index: chunk.index,
|
|
18078
|
+
firstId: chunk.firstId,
|
|
18079
|
+
lastId: chunk.lastId,
|
|
18080
|
+
rows: chunk.rows,
|
|
18081
|
+
sha256: chunk.sha256
|
|
18082
|
+
}))
|
|
18083
|
+
};
|
|
18084
|
+
for (const [at, chunk] of segment.chunks.entries()) {
|
|
17129
18085
|
if (!this.receiving(receipt)) return;
|
|
18086
|
+
const mine = receipt.segment.chunks[at];
|
|
18087
|
+
const had = holds.get(mine.object);
|
|
18088
|
+
if (had && had.sha256 === mine.sha256 && had.rows === mine.rows && had.firstId === mine.firstId && had.lastId === mine.lastId) {
|
|
18089
|
+
const { index: _index, ...range } = mine;
|
|
18090
|
+
void _index;
|
|
18091
|
+
const kept = await this.store.keepSegmentChunk(
|
|
18092
|
+
{ generation, attempt, segmentId: segment.segmentId, ...range },
|
|
18093
|
+
receipt.writer
|
|
18094
|
+
);
|
|
18095
|
+
if (!this.receiving(receipt)) return;
|
|
18096
|
+
if (kept.stale) return overtaken();
|
|
18097
|
+
if (!kept.mismatch) {
|
|
18098
|
+
receipt.kept++;
|
|
18099
|
+
this.host.progress?.(this.docId);
|
|
18100
|
+
if (receipt.released) return this.serially(() => this.abandonReceipt(receipt, "the room released the subscription"));
|
|
18101
|
+
continue;
|
|
18102
|
+
}
|
|
18103
|
+
Logger.debug(`[record-log] ${this.docId}: the held chunk ${mine.object} could not be kept; fetching it`);
|
|
18104
|
+
}
|
|
17130
18105
|
const reply = await this.applyChunk(
|
|
17131
18106
|
receipt,
|
|
17132
18107
|
`${base}/${chunk.path}`,
|
|
@@ -17152,8 +18127,7 @@ var RecordLogDocumentSession = class {
|
|
|
17152
18127
|
await this.serially(async () => {
|
|
17153
18128
|
if (!this.receiving(receipt) || !this.current) return;
|
|
17154
18129
|
if (receipt.released) return this.abandonReceipt(receipt, "the room released the subscription");
|
|
17155
|
-
this.
|
|
17156
|
-
this.sendFrame({ type: "record.catchUp", cursor: segment.completedLsn, upTo });
|
|
18130
|
+
this.beginPaging({ cursor: segment.completedLsn, upTo, full: false, high, generation, receipt });
|
|
17157
18131
|
});
|
|
17158
18132
|
} catch (error) {
|
|
17159
18133
|
await this.serially(() => this.receiptFailed(receipt, errorText(error)));
|
|
@@ -17164,8 +18138,9 @@ var RecordLogDocumentSession = class {
|
|
|
17164
18138
|
if (this.receipt === receipt) this.receipt = null;
|
|
17165
18139
|
this.failedReceipts = 0;
|
|
17166
18140
|
if (this.loadInProgress === receipt.id) this.loadInProgress = null;
|
|
18141
|
+
const kept = receipt.kept !== void 0 ? `; ${receipt.kept} kept, ${receipt.chunks - receipt.kept} fetched` : "";
|
|
17167
18142
|
Logger.info(
|
|
17168
|
-
`[record-log] ${receipt.kind} received ${this.docId}: ${receipt.id} ${receipt.rows} rows in ${receipt.chunks} chunks, remainder ${receipt.remainderRows} rows, ${Date.now() - receipt.startedAt} ms`
|
|
18143
|
+
`[record-log] ${receipt.kind} received ${this.docId}: ${receipt.id} ${receipt.rows} rows in ${receipt.chunks} chunks, remainder ${receipt.remainderRows} rows, ${Date.now() - receipt.startedAt} ms${kept}`
|
|
17169
18144
|
);
|
|
17170
18145
|
}
|
|
17171
18146
|
/**
|
|
@@ -17179,7 +18154,7 @@ var RecordLogDocumentSession = class {
|
|
|
17179
18154
|
Logger.warn(`[record-log] ${receipt.kind} receipt failed ${this.docId}: ${receipt.id} ${reason}; opening again from the cursor`);
|
|
17180
18155
|
this.receipt = null;
|
|
17181
18156
|
this.paging = null;
|
|
17182
|
-
this.
|
|
18157
|
+
this.held = [];
|
|
17183
18158
|
if (this.loadInProgress === receipt.id) this.loadInProgress = null;
|
|
17184
18159
|
if (this.current) await this.sendOpen();
|
|
17185
18160
|
}
|
|
@@ -17194,7 +18169,7 @@ var RecordLogDocumentSession = class {
|
|
|
17194
18169
|
Logger.info(`[record-log] ${this.docId}: ${receipt.kind} receipt ${receipt.id} abandoned (${why}); opening again from the cursor`);
|
|
17195
18170
|
this.receipt = null;
|
|
17196
18171
|
this.paging = null;
|
|
17197
|
-
this.
|
|
18172
|
+
this.held = [];
|
|
17198
18173
|
if (!this.current) return;
|
|
17199
18174
|
if (replacing !== void 0) await this.openAfterReplacement(replacing);
|
|
17200
18175
|
else await this.sendOpen();
|
|
@@ -17269,7 +18244,8 @@ var RecordLogDocumentSession = class {
|
|
|
17269
18244
|
`[record-log] catch-up failed ${this.docId}: record.catchUp answered ${frame.code ?? frame.detail ?? "an error"}; opening again from the cursor in ${wait} ms`
|
|
17270
18245
|
);
|
|
17271
18246
|
this.paging = null;
|
|
17272
|
-
this.
|
|
18247
|
+
this.held = [];
|
|
18248
|
+
this.ahead = null;
|
|
17273
18249
|
this.phase = "idle";
|
|
17274
18250
|
this.current = null;
|
|
17275
18251
|
if (this.retryTimer) clearTimeout(this.retryTimer);
|
|
@@ -17278,19 +18254,41 @@ var RecordLogDocumentSession = class {
|
|
|
17278
18254
|
void this.start();
|
|
17279
18255
|
}, wait);
|
|
17280
18256
|
}
|
|
17281
|
-
/**
|
|
17282
|
-
|
|
18257
|
+
/**
|
|
18258
|
+
* The catch-up is complete: answers held meanwhile apply, then the writer's
|
|
18259
|
+
* entries go. A compact acknowledgement left underivable (by the
|
|
18260
|
+
* completion or a held result) opens the document again once they have.
|
|
18261
|
+
*/
|
|
18262
|
+
async caughtUp(acknowledged, underivable) {
|
|
17283
18263
|
const current = this.current;
|
|
17284
18264
|
const generation = this.generation;
|
|
18265
|
+
const ahead = this.ahead;
|
|
18266
|
+
this.ahead = null;
|
|
18267
|
+
if (ahead?.refused) this.sender.reset();
|
|
17285
18268
|
this.catchUpRetryMs = CATCH_UP_RETRY_MS;
|
|
17286
18269
|
this.clearGap();
|
|
17287
18270
|
this.settleAcknowledged(acknowledged);
|
|
17288
|
-
const held = this.
|
|
17289
|
-
this.
|
|
18271
|
+
const held = this.held;
|
|
18272
|
+
this.held = [];
|
|
17290
18273
|
this.phase = current.orphan ? "draining" : "open";
|
|
17291
|
-
for (const
|
|
18274
|
+
for (const answer of held) {
|
|
18275
|
+
if (answer.kind === "results") underivable = await this.applyResults(answer.items) ?? underivable;
|
|
18276
|
+
else await this.applyRefusal(answer.refusal);
|
|
18277
|
+
}
|
|
18278
|
+
if (underivable) {
|
|
18279
|
+
this.logUnderivable(underivable);
|
|
18280
|
+
this.reopenAfterCatchUp = true;
|
|
18281
|
+
}
|
|
17292
18282
|
const pending = await this.store.pendingOf(current.writer);
|
|
17293
18283
|
const unsent = pending.filter((p) => p.acked === void 0);
|
|
18284
|
+
if (ahead && !ahead.refused) {
|
|
18285
|
+
if (!unsent.length) await this.store.refreshMarks();
|
|
18286
|
+
if (generation !== this.generation) return;
|
|
18287
|
+
const models = this.host.declarations();
|
|
18288
|
+
if (JSON.stringify(models) !== ahead.declarations) this.sender.enqueueControl({ type: "record.declare", models });
|
|
18289
|
+
for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
|
|
18290
|
+
return this.synced();
|
|
18291
|
+
}
|
|
17294
18292
|
const first = unsent.length ? unsent[0].seq : (await this.store.refreshMarks()).nextSeq;
|
|
17295
18293
|
if (generation !== this.generation) return;
|
|
17296
18294
|
const resumeAt = current.orphan ? unsent.length ? first : 0 : first;
|
|
@@ -17304,6 +18302,10 @@ var RecordLogDocumentSession = class {
|
|
|
17304
18302
|
this.sender.requeueInFlight(unsent.map(wireEntryOf));
|
|
17305
18303
|
this.sender.enqueueControl({ type: "record.declare", models: this.host.declarations() });
|
|
17306
18304
|
for (const entry of unsent) this.sender.enqueue(wireEntryOf(entry));
|
|
18305
|
+
return this.synced();
|
|
18306
|
+
}
|
|
18307
|
+
/** The own writer is open: what waits leaves, the open is reported, and loads announced meanwhile are received. */
|
|
18308
|
+
async synced() {
|
|
17307
18309
|
this.sender.kick();
|
|
17308
18310
|
this.host.synced(this.docId);
|
|
17309
18311
|
if (this.reopenAfterCatchUp) {
|
|
@@ -17356,28 +18358,48 @@ var RecordLogDocumentSession = class {
|
|
|
17356
18358
|
if (this.current?.writer !== writer) return null;
|
|
17357
18359
|
return this.current.orphan ? this.orphanSender : this.sender;
|
|
17358
18360
|
}
|
|
18361
|
+
/**
|
|
18362
|
+
* Whether answers are held until the catch-up completes: during it, and
|
|
18363
|
+
* while an open that sent frames ahead waits for `record.opened` (a server
|
|
18364
|
+
* can answer those frames before it).
|
|
18365
|
+
*/
|
|
18366
|
+
holding() {
|
|
18367
|
+
return this.phase === "catchingUp" || this.phase === "loading" || this.ahead !== null && this.phase === "opening";
|
|
18368
|
+
}
|
|
17359
18369
|
async results(items) {
|
|
17360
18370
|
if (!Array.isArray(items) || !items.length) return;
|
|
17361
|
-
if (this.
|
|
17362
|
-
this.
|
|
18371
|
+
if (this.history.stale) {
|
|
18372
|
+
return this.staleAnswered(answeredSeqs(items, this.history.stale.writer));
|
|
18373
|
+
}
|
|
18374
|
+
if (this.holding()) {
|
|
18375
|
+
this.held.push({ kind: "results", items });
|
|
17363
18376
|
return;
|
|
17364
18377
|
}
|
|
17365
18378
|
if (this.phase !== "open" && this.phase !== "draining") return;
|
|
17366
|
-
await this.applyResults(items);
|
|
18379
|
+
const underivable = await this.applyResults(items);
|
|
18380
|
+
if (underivable) {
|
|
18381
|
+
this.logUnderivable(underivable);
|
|
18382
|
+
this.clearGap();
|
|
18383
|
+
await this.sendOpen();
|
|
18384
|
+
}
|
|
18385
|
+
}
|
|
18386
|
+
/** A compact acknowledgement the store could not derive: the open that follows brings its row. */
|
|
18387
|
+
logUnderivable({ l, writer, seq }) {
|
|
18388
|
+
Logger.warn(
|
|
18389
|
+
`[record-log] ${this.docId}: the compact acknowledgement of writer ${writer} seq ${seq} (log number ${l}) names no pending entry to derive its rows from; opening again from the cursor`
|
|
18390
|
+
);
|
|
17367
18391
|
}
|
|
18392
|
+
/** Apply relayed items; answers a compact acknowledgement the store could not derive, if one holds the cursor back. */
|
|
17368
18393
|
async applyResults(items) {
|
|
17369
18394
|
const writer = this.current?.writer ?? this.store.writer();
|
|
17370
18395
|
const reply = await this.store.receive(items, this.host.projectionSpecs(), writer);
|
|
17371
|
-
const answered =
|
|
17372
|
-
for (const item of items) {
|
|
17373
|
-
if ("void" in item || "duplicate" in item) answered.push(item.seq);
|
|
17374
|
-
else if (item.w === writer && item.seq !== void 0) answered.push(item.seq);
|
|
17375
|
-
}
|
|
18396
|
+
const answered = answeredSeqs(items, writer);
|
|
17376
18397
|
const sender = this.senderOf(writer);
|
|
17377
18398
|
for (const seq of answered) sender?.acknowledged(seq);
|
|
17378
18399
|
this.answered(answered);
|
|
17379
18400
|
this.settleAcknowledged(reply.acknowledged);
|
|
17380
18401
|
this.watchGap(reply.cursor, items);
|
|
18402
|
+
return reply.underivable;
|
|
17381
18403
|
}
|
|
17382
18404
|
/** This client's writer's entries the room acknowledged: confirmed, and their waiters resolve. */
|
|
17383
18405
|
settleAcknowledged(acknowledged) {
|
|
@@ -17388,17 +18410,28 @@ var RecordLogDocumentSession = class {
|
|
|
17388
18410
|
if (touched.length) this.host.notify(touched);
|
|
17389
18411
|
}
|
|
17390
18412
|
async refused(refusal) {
|
|
18413
|
+
if (this.history.stale) return this.staleAnswered([refusal.seq]);
|
|
17391
18414
|
if (!this.current) return;
|
|
18415
|
+
if (this.ahead && this.holding()) {
|
|
18416
|
+
this.held.push({ kind: "refused", refusal });
|
|
18417
|
+
return;
|
|
18418
|
+
}
|
|
17392
18419
|
if (this.phase === "opening" || this.phase === "idle") {
|
|
17393
18420
|
Logger.debug(`[record-log] ${this.docId}: dropped a refusal of ${refusal.seq} that arrived before record.opened`);
|
|
17394
18421
|
return;
|
|
17395
18422
|
}
|
|
18423
|
+
await this.applyRefusal(refusal);
|
|
18424
|
+
}
|
|
18425
|
+
async applyRefusal(refusal) {
|
|
18426
|
+
if (!this.current) return;
|
|
17396
18427
|
const writer = this.current.writer;
|
|
17397
|
-
const before = await this.store.pendingOf(writer);
|
|
17398
|
-
const named = before.find((p) => p.seq === refusal.seq);
|
|
17399
18428
|
const reply = await this.store.refused(refusal, this.host.projectionSpecs(), writer);
|
|
17400
18429
|
const sender = this.senderOf(writer);
|
|
17401
18430
|
const after = new Map((await this.store.pendingOf(writer)).map((p) => [p.seq, p]));
|
|
18431
|
+
if (after.get(refusal.seq)?.void) {
|
|
18432
|
+
await this.store.dispatch({ kind: "settled", writer, seq: refusal.seq });
|
|
18433
|
+
after.delete(refusal.seq);
|
|
18434
|
+
}
|
|
17402
18435
|
for (const frame of reply.frames) sender?.enqueueControl(frame);
|
|
17403
18436
|
const handed = reply.handedBack.filter((p) => !p.void);
|
|
17404
18437
|
for (const p of reply.handedBack) {
|
|
@@ -17407,7 +18440,6 @@ var RecordLogDocumentSession = class {
|
|
|
17407
18440
|
}
|
|
17408
18441
|
sender?.acknowledged(refusal.seq);
|
|
17409
18442
|
this.answered([refusal.seq, ...reply.handedBack.map((p) => p.seq)]);
|
|
17410
|
-
if (named?.void) await this.store.dispatch({ kind: "settled", writer, seq: refusal.seq });
|
|
17411
18443
|
if (!handed.length) {
|
|
17412
18444
|
Logger.debug(`[record-log] ${this.docId}: refusal of ${refusal.seq} (${refusal.code}) withdrew nothing new`);
|
|
17413
18445
|
return;
|
|
@@ -17454,6 +18486,7 @@ var RecordLogDocumentSession = class {
|
|
|
17454
18486
|
return refusal.scope === "record" ? "DOCUMENT_CONSTRAINT_VIOLATED" : "DOCUMENT_OFFLINE_WINDOW_EXPIRED";
|
|
17455
18487
|
}
|
|
17456
18488
|
async gap(expected) {
|
|
18489
|
+
if (this.history.stale) return this.barrier ? void 0 : this.endStale();
|
|
17457
18490
|
if (!this.current || !Number.isInteger(expected)) return;
|
|
17458
18491
|
Logger.info(`[record-log] ${this.docId}: the room is missing entries from ${expected}; resending`);
|
|
17459
18492
|
const pending = await this.store.pendingOf(this.current.writer);
|
|
@@ -17474,16 +18507,27 @@ var RecordLogDocumentSession = class {
|
|
|
17474
18507
|
* naming the attempt it was for: arriving after the replacement's
|
|
17475
18508
|
* `record.opened`, it would be read as that catch-up's, and a full one would
|
|
17476
18509
|
* then drop every row the replacement had not yet sent. The open goes again
|
|
17477
|
-
* once that answer is in (a page is discarded, an error starts over).
|
|
18510
|
+
* once that answer is in (a page is discarded, an error starts over). A
|
|
18511
|
+
* streamed catch-up has no request out once the room is known to stream
|
|
18512
|
+
* (its `record.opened` said so, or a marked page arrived): it dropped the
|
|
18513
|
+
* stream with the subscription, and the open goes at once (a page of that
|
|
18514
|
+
* stream arriving later is ignored by its id).
|
|
17478
18515
|
*/
|
|
17479
18516
|
async released(frame) {
|
|
18517
|
+
if (this.history.stale) return this.phase === "opening" ? this.endStale() : void 0;
|
|
17480
18518
|
if (!this.current || this.phase === "idle" || this.phase === "closed") return;
|
|
17481
18519
|
Logger.warn(
|
|
17482
18520
|
`[record-log] ${this.docId}: the room released this connection's subscription (${frame.reason ?? "no reason given"}); opening again from the cursor`
|
|
17483
18521
|
);
|
|
17484
18522
|
this.clearGap();
|
|
17485
18523
|
if ((this.phase === "catchingUp" || this.phase === "loading") && this.paging) {
|
|
17486
|
-
this.paging.
|
|
18524
|
+
if (this.paging.stream === void 0 || !(this.paging.streamed || this.roomStreams)) {
|
|
18525
|
+
this.paging.released = true;
|
|
18526
|
+
return;
|
|
18527
|
+
}
|
|
18528
|
+
this.paging = null;
|
|
18529
|
+
this.receipt = null;
|
|
18530
|
+
await this.sendOpen();
|
|
17487
18531
|
return;
|
|
17488
18532
|
}
|
|
17489
18533
|
if (this.receipt && !this.paging) {
|
|
@@ -17497,6 +18541,14 @@ var RecordLogDocumentSession = class {
|
|
|
17497
18541
|
const code = String(frame.code ?? "");
|
|
17498
18542
|
const current = this.current;
|
|
17499
18543
|
Logger.warn(`[record-log] ${this.docId}: ${frame.messageType ?? "record frame"} answered ${code}: ${frame.message ?? ""}`);
|
|
18544
|
+
if (this.history.stale && this.barrier) {
|
|
18545
|
+
if (frame.messageType === "record.open" && this.phase === "opening") await this.endStale();
|
|
18546
|
+
return;
|
|
18547
|
+
}
|
|
18548
|
+
if (this.history.stale && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) {
|
|
18549
|
+
if (frame.messageType === "record.entries") await this.endStale();
|
|
18550
|
+
return;
|
|
18551
|
+
}
|
|
17500
18552
|
if (!current) return;
|
|
17501
18553
|
if (frame.messageType === "record.catchUp" && this.paging?.receipt) {
|
|
17502
18554
|
return this.receiptFailed(this.paging.receipt, `the remainder was answered ${code || "an error"}`);
|
|
@@ -17513,6 +18565,7 @@ var RecordLogDocumentSession = class {
|
|
|
17513
18565
|
if (!current.orphan) {
|
|
17514
18566
|
this.store.renumbered(renumbered);
|
|
17515
18567
|
await this.store.refreshMarks();
|
|
18568
|
+
this.sender.reset();
|
|
17516
18569
|
}
|
|
17517
18570
|
this.current = { writer, orphan: current.orphan };
|
|
17518
18571
|
await this.sendOpen();
|
|
@@ -17529,6 +18582,8 @@ var RecordLogDocumentSession = class {
|
|
|
17529
18582
|
this.takenRetryMs = Math.min(this.takenRetryMs * 2, 3e4);
|
|
17530
18583
|
this.phase = "idle";
|
|
17531
18584
|
this.current = null;
|
|
18585
|
+
this.held = [];
|
|
18586
|
+
this.ahead = null;
|
|
17532
18587
|
this.retryTimer = setTimeout(() => {
|
|
17533
18588
|
this.retryTimer = null;
|
|
17534
18589
|
void this.start();
|
|
@@ -17538,6 +18593,8 @@ var RecordLogDocumentSession = class {
|
|
|
17538
18593
|
case "DOCUMENT_NOT_OPEN": {
|
|
17539
18594
|
if (this.phase === "open" || this.phase === "draining") {
|
|
17540
18595
|
await this.sendOpen();
|
|
18596
|
+
} else if (this.ahead && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) {
|
|
18597
|
+
this.ahead.refused = true;
|
|
17541
18598
|
}
|
|
17542
18599
|
return;
|
|
17543
18600
|
}
|
|
@@ -17569,9 +18626,12 @@ var RecordLogDocumentSession = class {
|
|
|
17569
18626
|
return;
|
|
17570
18627
|
}
|
|
17571
18628
|
default:
|
|
18629
|
+
if (this.ahead && (frame.messageType === "record.entries" || frame.messageType === "record.declare")) return;
|
|
17572
18630
|
if (this.phase === "opening") {
|
|
17573
18631
|
this.phase = "idle";
|
|
17574
18632
|
this.current = null;
|
|
18633
|
+
this.held = [];
|
|
18634
|
+
this.ahead = null;
|
|
17575
18635
|
this.host.syncFailed(this.docId, code || "error");
|
|
17576
18636
|
}
|
|
17577
18637
|
}
|
|
@@ -17599,6 +18659,8 @@ var RecordLogSessions = class {
|
|
|
17599
18659
|
this.senderOptions = senderOptions;
|
|
17600
18660
|
}
|
|
17601
18661
|
sessions = /* @__PURE__ */ new Map();
|
|
18662
|
+
/** Each document's {@link RecordLogWriterHistory}, kept while the client keeps its connection id. */
|
|
18663
|
+
histories = /* @__PURE__ */ new Map();
|
|
17602
18664
|
connection = null;
|
|
17603
18665
|
syncedListeners = /* @__PURE__ */ new Set();
|
|
17604
18666
|
failedListeners = /* @__PURE__ */ new Set();
|
|
@@ -17629,6 +18691,8 @@ var RecordLogSessions = class {
|
|
|
17629
18691
|
/** Begin a session for an opened store. */
|
|
17630
18692
|
attach(docId, store) {
|
|
17631
18693
|
this.sessions.get(docId)?.close();
|
|
18694
|
+
let history = this.histories.get(docId);
|
|
18695
|
+
if (!history) this.histories.set(docId, history = { opened: /* @__PURE__ */ new Set(), stale: null });
|
|
17632
18696
|
const session = new RecordLogDocumentSession(
|
|
17633
18697
|
docId,
|
|
17634
18698
|
store,
|
|
@@ -17648,7 +18712,8 @@ var RecordLogSessions = class {
|
|
|
17648
18712
|
for (const listener of [...this.progressListeners]) listener(id);
|
|
17649
18713
|
}
|
|
17650
18714
|
},
|
|
17651
|
-
this.senderOptions
|
|
18715
|
+
this.senderOptions,
|
|
18716
|
+
history
|
|
17652
18717
|
);
|
|
17653
18718
|
this.sessions.set(docId, session);
|
|
17654
18719
|
return session;
|