@hot-updater/plugin-core 1.2.0-rc.49 → 1.2.0-rc.50
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/coreApi.d.cts +20 -1
- package/dist/coreApi.d.mts +20 -1
- package/dist/database/adapter.d.cts +12 -0
- package/dist/database/adapter.d.mts +12 -0
- package/dist/engine/core/schema.cjs +21 -2
- package/dist/engine/core/schema.d.cts +4 -0
- package/dist/engine/core/schema.d.mts +4 -0
- package/dist/engine/core/schema.mjs +21 -3
- package/dist/engine/database/engineTransaction.cjs +21 -1
- package/dist/engine/database/engineTransaction.d.cts +5 -1
- package/dist/engine/database/engineTransaction.d.mts +5 -1
- package/dist/engine/database/engineTransaction.mjs +21 -1
- package/dist/engine/database/kv/kvAdapter.cjs +80 -4
- package/dist/engine/database/kv/kvAdapter.mjs +80 -4
- package/dist/engine/database/sql/sqlSchema.cjs +6 -2
- package/dist/engine/database/sql/sqlSchema.d.cts +1 -1
- package/dist/engine/database/sql/sqlSchema.d.mts +1 -1
- package/dist/engine/database/sql/sqlSchema.mjs +6 -2
- package/dist/engine/db/coreDatabase.cjs +10 -5
- package/dist/engine/db/coreDatabase.d.cts +2 -1
- package/dist/engine/db/coreDatabase.d.mts +2 -1
- package/dist/engine/db/coreDatabase.mjs +10 -5
- package/dist/engine/db/engineMigrator.cjs +21 -16
- package/dist/engine/db/engineMigrator.mjs +22 -17
- package/dist/engine/db/engineSqlMigrator.cjs +23 -22
- package/dist/engine/db/engineSqlMigrator.d.cts +2 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +2 -0
- package/dist/engine/db/engineSqlMigrator.mjs +25 -24
- package/dist/engine/db/schemaSettings.cjs +36 -5
- package/dist/engine/db/schemaSettings.d.cts +5 -2
- package/dist/engine/db/schemaSettings.d.mts +5 -2
- package/dist/engine/db/schemaSettings.mjs +36 -6
- package/dist/engine/db/settingsMigrator.cjs +92 -14
- package/dist/engine/db/settingsMigrator.d.cts +18 -8
- package/dist/engine/db/settingsMigrator.d.mts +18 -8
- package/dist/engine/db/settingsMigrator.mjs +89 -15
- package/dist/engine/db/sqlSchemaState.cjs +108 -0
- package/dist/engine/db/sqlSchemaState.mjs +104 -0
- package/dist/engine/db/types.d.cts +6 -0
- package/dist/engine/db/types.d.mts +6 -0
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/serverPlugin/coreReads.d.cts +10 -1
- package/dist/serverPlugin/coreReads.d.mts +10 -1
- package/dist/types/databaseConfig.d.cts +2 -1
- package/dist/types/databaseConfig.d.mts +2 -1
- package/package.json +2 -2
package/dist/coreApi.d.cts
CHANGED
|
@@ -239,7 +239,26 @@ interface HotUpdaterCoreApi {
|
|
|
239
239
|
}): Promise<ReleaseRow[]>;
|
|
240
240
|
getReleaseCatalogRow(scopeKey: string): Promise<ReleaseCatalogRow | null>;
|
|
241
241
|
listReleaseCatalogs(input: KeysetInput): Promise<ReleaseCatalogRow[]>;
|
|
242
|
-
|
|
242
|
+
/**
|
|
243
|
+
* Up to `limit` scope keys that have releases, ascending after `after`,
|
|
244
|
+
* with or without a catalog row: one limit-1 seek per scope, so the reads
|
|
245
|
+
* grow with scopes, not with releases. Doctor walks them to find a scope
|
|
246
|
+
* whose catalog row was lost.
|
|
247
|
+
*/
|
|
248
|
+
listReleaseScopeKeys(input: {
|
|
249
|
+
readonly after?: string;
|
|
250
|
+
readonly limit: number;
|
|
251
|
+
}): Promise<string[]>;
|
|
252
|
+
/**
|
|
253
|
+
* Every channel, by name. With `input`, one keyset page of them, whose
|
|
254
|
+
* cursor is the last channel's name.
|
|
255
|
+
*/
|
|
256
|
+
listChannels(input?: KeysetInput): Promise<ChannelRow[]>;
|
|
257
|
+
/**
|
|
258
|
+
* The channels of these IDs, in their order, without the IDs no channel
|
|
259
|
+
* has: one batch read of their keys.
|
|
260
|
+
*/
|
|
261
|
+
getChannels(ids: readonly string[]): Promise<ChannelRow[]>;
|
|
243
262
|
findChannelByName(name: string): Promise<ChannelRow | null>;
|
|
244
263
|
/** A native build by ID: one read of its key. */
|
|
245
264
|
getNativeBuild(id: string): Promise<NativeBuildRow | null>;
|
package/dist/coreApi.d.mts
CHANGED
|
@@ -239,7 +239,26 @@ interface HotUpdaterCoreApi {
|
|
|
239
239
|
}): Promise<ReleaseRow[]>;
|
|
240
240
|
getReleaseCatalogRow(scopeKey: string): Promise<ReleaseCatalogRow | null>;
|
|
241
241
|
listReleaseCatalogs(input: KeysetInput): Promise<ReleaseCatalogRow[]>;
|
|
242
|
-
|
|
242
|
+
/**
|
|
243
|
+
* Up to `limit` scope keys that have releases, ascending after `after`,
|
|
244
|
+
* with or without a catalog row: one limit-1 seek per scope, so the reads
|
|
245
|
+
* grow with scopes, not with releases. Doctor walks them to find a scope
|
|
246
|
+
* whose catalog row was lost.
|
|
247
|
+
*/
|
|
248
|
+
listReleaseScopeKeys(input: {
|
|
249
|
+
readonly after?: string;
|
|
250
|
+
readonly limit: number;
|
|
251
|
+
}): Promise<string[]>;
|
|
252
|
+
/**
|
|
253
|
+
* Every channel, by name. With `input`, one keyset page of them, whose
|
|
254
|
+
* cursor is the last channel's name.
|
|
255
|
+
*/
|
|
256
|
+
listChannels(input?: KeysetInput): Promise<ChannelRow[]>;
|
|
257
|
+
/**
|
|
258
|
+
* The channels of these IDs, in their order, without the IDs no channel
|
|
259
|
+
* has: one batch read of their keys.
|
|
260
|
+
*/
|
|
261
|
+
getChannels(ids: readonly string[]): Promise<ChannelRow[]>;
|
|
243
262
|
findChannelByName(name: string): Promise<ChannelRow | null>;
|
|
244
263
|
/** A native build by ID: one read of its key. */
|
|
245
264
|
getNativeBuild(id: string): Promise<NativeBuildRow | null>;
|
|
@@ -156,6 +156,18 @@ interface DatabaseAdapter {
|
|
|
156
156
|
/** Called only by migration tooling, such as `hot-updater db migrate`. */
|
|
157
157
|
readonly migrations?: {
|
|
158
158
|
apply(tables: readonly PhysicalTable[]): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* For a store that keeps index items of its own: writes the items of
|
|
161
|
+
* `index` that rows of `table` lack, or with `dryRun` only counts them,
|
|
162
|
+
* and returns how many rows lacked one. Migrations call it for an index
|
|
163
|
+
* declared on a table rows of a released schema were written to, such
|
|
164
|
+
* as core's `releases.scopes`, whose server may still write rows
|
|
165
|
+
* without the index's items. A store whose indexes cover every row
|
|
166
|
+
* itself, such as SQL or MongoDB, leaves it out.
|
|
167
|
+
*/
|
|
168
|
+
fillIndex?(table: PhysicalTable, index: string, options?: {
|
|
169
|
+
readonly dryRun?: boolean;
|
|
170
|
+
}): Promise<number>;
|
|
159
171
|
};
|
|
160
172
|
dispose?(): Promise<void>;
|
|
161
173
|
}
|
|
@@ -156,6 +156,18 @@ interface DatabaseAdapter {
|
|
|
156
156
|
/** Called only by migration tooling, such as `hot-updater db migrate`. */
|
|
157
157
|
readonly migrations?: {
|
|
158
158
|
apply(tables: readonly PhysicalTable[]): Promise<void>;
|
|
159
|
+
/**
|
|
160
|
+
* For a store that keeps index items of its own: writes the items of
|
|
161
|
+
* `index` that rows of `table` lack, or with `dryRun` only counts them,
|
|
162
|
+
* and returns how many rows lacked one. Migrations call it for an index
|
|
163
|
+
* declared on a table rows of a released schema were written to, such
|
|
164
|
+
* as core's `releases.scopes`, whose server may still write rows
|
|
165
|
+
* without the index's items. A store whose indexes cover every row
|
|
166
|
+
* itself, such as SQL or MongoDB, leaves it out.
|
|
167
|
+
*/
|
|
168
|
+
fillIndex?(table: PhysicalTable, index: string, options?: {
|
|
169
|
+
readonly dryRun?: boolean;
|
|
170
|
+
}): Promise<number>;
|
|
159
171
|
};
|
|
160
172
|
dispose?(): Promise<void>;
|
|
161
173
|
}
|
|
@@ -14,8 +14,9 @@ const CHANNEL_ID = {
|
|
|
14
14
|
* applies it to managed databases an earlier release created. The official
|
|
15
15
|
* plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
|
|
16
16
|
* every database's migrator creates missing tables and then records the
|
|
17
|
-
* version, and none of them changes an existing table, so changing
|
|
18
|
-
* needs a migration step of its own first.
|
|
17
|
+
* version, and none of them changes an existing table's columns, so changing
|
|
18
|
+
* one needs a migration step of its own first. An index added to an existing
|
|
19
|
+
* table is listed in `LATE_INDEXES`. The schema fence answers 503 on
|
|
19
20
|
* a database whose row differs, until it runs. Before a version is released,
|
|
20
21
|
* its tables change in place in its own migration, and a database one of its
|
|
21
22
|
* prereleases migrated takes the same change by hand: the fence compares this
|
|
@@ -201,9 +202,26 @@ const releases = require_schema.defineTable({
|
|
|
201
202
|
all: {
|
|
202
203
|
eq: [],
|
|
203
204
|
sort: ["id"]
|
|
205
|
+
},
|
|
206
|
+
scopes: {
|
|
207
|
+
eq: [],
|
|
208
|
+
sort: ["scope_key"]
|
|
204
209
|
}
|
|
205
210
|
}
|
|
206
211
|
});
|
|
212
|
+
/**
|
|
213
|
+
* Indexes declared on a table that a released schema's servers write: a
|
|
214
|
+
* store that keeps index items of its own (`migrations.fillIndex`) lacks
|
|
215
|
+
* them for rows written before, and for rows such a server still writes
|
|
216
|
+
* after the migration, since its schema fence keeps a check that passed.
|
|
217
|
+
* Each migration writes the missing items, and `db migrate` on a database
|
|
218
|
+
* whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
|
|
219
|
+
* 1.1.x servers write releases without it.
|
|
220
|
+
*/
|
|
221
|
+
const LATE_INDEXES = [{
|
|
222
|
+
table: "releases",
|
|
223
|
+
index: "scopes"
|
|
224
|
+
}];
|
|
207
225
|
/** One compiled catalog per scope; the update check reads exactly this row. */
|
|
208
226
|
const releaseCatalogs = require_schema.defineTable({
|
|
209
227
|
scope_key: {
|
|
@@ -581,5 +599,6 @@ const coreModule = {
|
|
|
581
599
|
};
|
|
582
600
|
//#endregion
|
|
583
601
|
exports.HOT_UPDATER_SCHEMA_VERSION = HOT_UPDATER_SCHEMA_VERSION;
|
|
602
|
+
exports.LATE_INDEXES = LATE_INDEXES;
|
|
584
603
|
exports.coreModule = coreModule;
|
|
585
604
|
exports.coreSchema = coreSchema;
|
|
@@ -210,6 +210,10 @@ declare const coreSchema: {
|
|
|
210
210
|
readonly eq: readonly [];
|
|
211
211
|
readonly sort: readonly ["id"];
|
|
212
212
|
};
|
|
213
|
+
readonly scopes: {
|
|
214
|
+
readonly eq: readonly [];
|
|
215
|
+
readonly sort: readonly ["scope_key"];
|
|
216
|
+
};
|
|
213
217
|
}, readonly ["id"]>;
|
|
214
218
|
readonly release_catalogs: TableDefinition<{
|
|
215
219
|
readonly scope_key: {
|
|
@@ -210,6 +210,10 @@ declare const coreSchema: {
|
|
|
210
210
|
readonly eq: readonly [];
|
|
211
211
|
readonly sort: readonly ["id"];
|
|
212
212
|
};
|
|
213
|
+
readonly scopes: {
|
|
214
|
+
readonly eq: readonly [];
|
|
215
|
+
readonly sort: readonly ["scope_key"];
|
|
216
|
+
};
|
|
213
217
|
}, readonly ["id"]>;
|
|
214
218
|
readonly release_catalogs: TableDefinition<{
|
|
215
219
|
readonly scope_key: {
|
|
@@ -14,8 +14,9 @@ const CHANNEL_ID = {
|
|
|
14
14
|
* applies it to managed databases an earlier release created. The official
|
|
15
15
|
* plugins' `schemaVersion`s follow the same rule. A bump only adds tables:
|
|
16
16
|
* every database's migrator creates missing tables and then records the
|
|
17
|
-
* version, and none of them changes an existing table, so changing
|
|
18
|
-
* needs a migration step of its own first.
|
|
17
|
+
* version, and none of them changes an existing table's columns, so changing
|
|
18
|
+
* one needs a migration step of its own first. An index added to an existing
|
|
19
|
+
* table is listed in `LATE_INDEXES`. The schema fence answers 503 on
|
|
19
20
|
* a database whose row differs, until it runs. Before a version is released,
|
|
20
21
|
* its tables change in place in its own migration, and a database one of its
|
|
21
22
|
* prereleases migrated takes the same change by hand: the fence compares this
|
|
@@ -201,9 +202,26 @@ const releases = defineTable({
|
|
|
201
202
|
all: {
|
|
202
203
|
eq: [],
|
|
203
204
|
sort: ["id"]
|
|
205
|
+
},
|
|
206
|
+
scopes: {
|
|
207
|
+
eq: [],
|
|
208
|
+
sort: ["scope_key"]
|
|
204
209
|
}
|
|
205
210
|
}
|
|
206
211
|
});
|
|
212
|
+
/**
|
|
213
|
+
* Indexes declared on a table that a released schema's servers write: a
|
|
214
|
+
* store that keeps index items of its own (`migrations.fillIndex`) lacks
|
|
215
|
+
* them for rows written before, and for rows such a server still writes
|
|
216
|
+
* after the migration, since its schema fence keeps a check that passed.
|
|
217
|
+
* Each migration writes the missing items, and `db migrate` on a database
|
|
218
|
+
* whose settings match looks for them. `releases.scopes` arrived in 1.2.0;
|
|
219
|
+
* 1.1.x servers write releases without it.
|
|
220
|
+
*/
|
|
221
|
+
const LATE_INDEXES = [{
|
|
222
|
+
table: "releases",
|
|
223
|
+
index: "scopes"
|
|
224
|
+
}];
|
|
207
225
|
/** One compiled catalog per scope; the update check reads exactly this row. */
|
|
208
226
|
const releaseCatalogs = defineTable({
|
|
209
227
|
scope_key: {
|
|
@@ -580,4 +598,4 @@ const coreModule = {
|
|
|
580
598
|
schema: coreSchema
|
|
581
599
|
};
|
|
582
600
|
//#endregion
|
|
583
|
-
export { HOT_UPDATER_SCHEMA_VERSION, coreModule, coreSchema };
|
|
601
|
+
export { HOT_UPDATER_SCHEMA_VERSION, LATE_INDEXES, coreModule, coreSchema };
|
|
@@ -6,6 +6,12 @@ const require_engineAggregates = require("./engineAggregates.cjs");
|
|
|
6
6
|
/** A row this attempt read changed while it ran; the attempt reruns. */
|
|
7
7
|
var StaleReadError = class extends Error {};
|
|
8
8
|
const idOf = (table, key) => JSON.stringify([table, key]);
|
|
9
|
+
/** The aggregate rows a write changes, at the versions it read them. */
|
|
10
|
+
const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, require_adapter.rowKey(op.table, op.row)] : [
|
|
11
|
+
op.table.name,
|
|
12
|
+
op.key,
|
|
13
|
+
"guard" in op ? op.guard?.v : void 0
|
|
14
|
+
]));
|
|
9
15
|
const versionOf = (row) => Number(row["_v"]);
|
|
10
16
|
const isKeyed = (value) => value !== null && value !== void 0;
|
|
11
17
|
const misuse = (table, message) => new require_errors.DatabaseTransactionError(`${table}: ${message}`);
|
|
@@ -350,7 +356,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
350
356
|
assertOutsideTransaction();
|
|
351
357
|
let run;
|
|
352
358
|
let negative;
|
|
353
|
-
|
|
359
|
+
let failures = 0;
|
|
360
|
+
let lost;
|
|
361
|
+
for (let round = 0;; round += 1) {
|
|
354
362
|
const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
|
|
355
363
|
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
|
|
356
364
|
run ??= await attempt(fn).catch((error) => {
|
|
@@ -359,6 +367,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
359
367
|
});
|
|
360
368
|
if (run === void 0) {
|
|
361
369
|
onRetry?.("rerun", round + 1);
|
|
370
|
+
lost = void 0;
|
|
371
|
+
if ((failures += 1) >= attempts) break;
|
|
362
372
|
continue;
|
|
363
373
|
}
|
|
364
374
|
let aggregates;
|
|
@@ -369,8 +379,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
369
379
|
negative = error;
|
|
370
380
|
onRetry?.("rerun", round + 1);
|
|
371
381
|
run = void 0;
|
|
382
|
+
lost = void 0;
|
|
383
|
+
if ((failures += 1) >= attempts) break;
|
|
372
384
|
continue;
|
|
373
385
|
}
|
|
386
|
+
const versions = versionsOf(aggregates);
|
|
387
|
+
if (lost !== void 0 && versions !== lost) failures -= 1;
|
|
388
|
+
lost = void 0;
|
|
389
|
+
if (failures >= attempts) break;
|
|
374
390
|
const ops = [...run.ops, ...aggregates];
|
|
375
391
|
if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
|
|
376
392
|
if (!adapter.fits(ops)) throw new require_errors.DatabaseConstraintError("too_large", ops[0].table.name);
|
|
@@ -384,12 +400,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
384
400
|
const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
|
|
385
401
|
if (failed === void 0 || failed >= run.ops.length) {
|
|
386
402
|
onRetry?.("resend", round + 1);
|
|
403
|
+
failures += 1;
|
|
404
|
+
if (failed !== void 0) lost = versions;
|
|
405
|
+
else if (failures >= attempts) break;
|
|
387
406
|
continue;
|
|
388
407
|
}
|
|
389
408
|
const reason = await classify(ops[failed], run.read);
|
|
390
409
|
if (reason) throw new require_errors.DatabaseConstraintError(reason, ops[failed].table.name);
|
|
391
410
|
onRetry?.("rerun", round + 1);
|
|
392
411
|
run = void 0;
|
|
412
|
+
if ((failures += 1) >= attempts) break;
|
|
393
413
|
}
|
|
394
414
|
throw negative ?? new require_errors.DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
|
|
395
415
|
} };
|
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
* observe each rerun.
|
|
6
6
|
*/
|
|
7
7
|
interface RetryOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* How many failed rounds a transaction takes before it fails; 8 by default.
|
|
10
|
+
* A resend that lost its aggregate rows to another writer's commit does not
|
|
11
|
+
* count: it reads them again until it applies.
|
|
12
|
+
*/
|
|
9
13
|
readonly attempts?: number;
|
|
10
14
|
/** The wait before the second attempt, doubling after each; 5 ms by default. */
|
|
11
15
|
readonly baseDelayMs?: number;
|
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
* observe each rerun.
|
|
6
6
|
*/
|
|
7
7
|
interface RetryOptions {
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* How many failed rounds a transaction takes before it fails; 8 by default.
|
|
10
|
+
* A resend that lost its aggregate rows to another writer's commit does not
|
|
11
|
+
* count: it reads them again until it applies.
|
|
12
|
+
*/
|
|
9
13
|
readonly attempts?: number;
|
|
10
14
|
/** The wait before the second attempt, doubling after each; 5 ms by default. */
|
|
11
15
|
readonly baseDelayMs?: number;
|
|
@@ -6,6 +6,12 @@ import { NegativeGaugeError, compileAggregates, recordAggregate } from "./engine
|
|
|
6
6
|
/** A row this attempt read changed while it ran; the attempt reruns. */
|
|
7
7
|
var StaleReadError = class extends Error {};
|
|
8
8
|
const idOf = (table, key) => JSON.stringify([table, key]);
|
|
9
|
+
/** The aggregate rows a write changes, at the versions it read them. */
|
|
10
|
+
const versionsOf = (ops) => JSON.stringify(ops.map((op) => op.type === "insert" ? [op.table.name, rowKey(op.table, op.row)] : [
|
|
11
|
+
op.table.name,
|
|
12
|
+
op.key,
|
|
13
|
+
"guard" in op ? op.guard?.v : void 0
|
|
14
|
+
]));
|
|
9
15
|
const versionOf = (row) => Number(row["_v"]);
|
|
10
16
|
const isKeyed = (value) => value !== null && value !== void 0;
|
|
11
17
|
const misuse = (table, message) => new DatabaseTransactionError(`${table}: ${message}`);
|
|
@@ -350,7 +356,9 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
350
356
|
assertOutsideTransaction();
|
|
351
357
|
let run;
|
|
352
358
|
let negative;
|
|
353
|
-
|
|
359
|
+
let failures = 0;
|
|
360
|
+
let lost;
|
|
361
|
+
for (let round = 0;; round += 1) {
|
|
354
362
|
const delay = round && Math.min(maxDelayMs, baseDelayMs * 2 ** (round - 1));
|
|
355
363
|
if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay / 2 + Math.random() * (delay / 2)));
|
|
356
364
|
run ??= await attempt(fn).catch((error) => {
|
|
@@ -359,6 +367,8 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
359
367
|
});
|
|
360
368
|
if (run === void 0) {
|
|
361
369
|
onRetry?.("rerun", round + 1);
|
|
370
|
+
lost = void 0;
|
|
371
|
+
if ((failures += 1) >= attempts) break;
|
|
362
372
|
continue;
|
|
363
373
|
}
|
|
364
374
|
let aggregates;
|
|
@@ -369,8 +379,14 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
369
379
|
negative = error;
|
|
370
380
|
onRetry?.("rerun", round + 1);
|
|
371
381
|
run = void 0;
|
|
382
|
+
lost = void 0;
|
|
383
|
+
if ((failures += 1) >= attempts) break;
|
|
372
384
|
continue;
|
|
373
385
|
}
|
|
386
|
+
const versions = versionsOf(aggregates);
|
|
387
|
+
if (lost !== void 0 && versions !== lost) failures -= 1;
|
|
388
|
+
lost = void 0;
|
|
389
|
+
if (failures >= attempts) break;
|
|
374
390
|
const ops = [...run.ops, ...aggregates];
|
|
375
391
|
if (ops.length <= 1 && ops.every(({ type }) => type === "check")) return run.result;
|
|
376
392
|
if (!adapter.fits(ops)) throw new DatabaseConstraintError("too_large", ops[0].table.name);
|
|
@@ -384,12 +400,16 @@ const createTransactions = ({ adapter, schema, reads, retry = {} }) => {
|
|
|
384
400
|
const failed = "failedOp" in outcome ? outcome.failedOp : void 0;
|
|
385
401
|
if (failed === void 0 || failed >= run.ops.length) {
|
|
386
402
|
onRetry?.("resend", round + 1);
|
|
403
|
+
failures += 1;
|
|
404
|
+
if (failed !== void 0) lost = versions;
|
|
405
|
+
else if (failures >= attempts) break;
|
|
387
406
|
continue;
|
|
388
407
|
}
|
|
389
408
|
const reason = await classify(ops[failed], run.read);
|
|
390
409
|
if (reason) throw new DatabaseConstraintError(reason, ops[failed].table.name);
|
|
391
410
|
onRetry?.("rerun", round + 1);
|
|
392
411
|
run = void 0;
|
|
412
|
+
if ((failures += 1) >= attempts) break;
|
|
393
413
|
}
|
|
394
414
|
throw negative ?? new DatabaseConflictError(`The transaction conflicted ${attempts} times.`);
|
|
395
415
|
} };
|
|
@@ -67,10 +67,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
67
67
|
const at = row && require_adapter.expiresAt(table, row);
|
|
68
68
|
return at === void 0 ? {} : { expiresAt: at };
|
|
69
69
|
};
|
|
70
|
-
/** Every index and unique item a row has, by address. */
|
|
71
|
-
const itemsOf = (layout, row) => {
|
|
70
|
+
/** Every index and unique item a row has, by address: in `indexes`, if given. */
|
|
71
|
+
const itemsOf = (layout, row, indexes = layout.indexed) => {
|
|
72
72
|
const items = /* @__PURE__ */ new Map();
|
|
73
|
-
for (const index of row === null ? [] :
|
|
73
|
+
for (const index of row === null ? [] : indexes) for (const eq of require_values.indexEntries(layout.table, index, row)) {
|
|
74
74
|
const pk = partition(layout, index, eq);
|
|
75
75
|
const sk = index.unique ? ONLY : encodeKvKey(require_values.indexOrderTuple(layout.table, index, row)) || ONLY;
|
|
76
76
|
items.set(JSON.stringify([pk, sk]), {
|
|
@@ -225,6 +225,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
225
225
|
lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
|
|
226
226
|
};
|
|
227
227
|
};
|
|
228
|
+
/** One row's check and its item puts in `index`, copies of the row as it is. */
|
|
229
|
+
const fillOps = (layout, index, row) => [{
|
|
230
|
+
type: "check",
|
|
231
|
+
key: rowItem(layout, require_adapter.rowKey(layout.table, row)),
|
|
232
|
+
condition: { v: Number(row["_v"]) }
|
|
233
|
+
}, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
|
|
234
|
+
type: "put",
|
|
235
|
+
key,
|
|
236
|
+
value: copyOf(layout, row),
|
|
237
|
+
...stamp(layout.table, row)
|
|
238
|
+
}))];
|
|
239
|
+
/**
|
|
240
|
+
* Writes one row's items in `index`, checking the row's `_v` in the same
|
|
241
|
+
* write: a row that changed is read again, and a deleted one needs none.
|
|
242
|
+
*/
|
|
243
|
+
const fillRow = async (layout, index, first) => {
|
|
244
|
+
const key = rowItem(layout, require_adapter.rowKey(layout.table, first));
|
|
245
|
+
let row = first;
|
|
246
|
+
for (let attempt = 0; row !== null; attempt += 1) {
|
|
247
|
+
if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
|
|
248
|
+
if ((await store.write(fillOps(layout, index, row))).ok) return;
|
|
249
|
+
[row] = await store.get([key]);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Finds the rows that lack an item in `index` and, unless `dryRun`, writes
|
|
254
|
+
* them, as many rows per atomic write as the store takes. It reads every
|
|
255
|
+
* row and its items, page by page.
|
|
256
|
+
*/
|
|
257
|
+
const fillIndex = async (table, name, { dryRun = false } = {}) => {
|
|
258
|
+
const layout = layoutOf(table);
|
|
259
|
+
const index = layout.indexed.find((candidate) => candidate.name === name);
|
|
260
|
+
if (index === void 0) return 0;
|
|
261
|
+
if (index.unique) throw new require_verifyAdapter.DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
|
|
262
|
+
const { items: most, bytes } = store.limits;
|
|
263
|
+
let lacking = 0;
|
|
264
|
+
for (let after;;) {
|
|
265
|
+
const page = await store.query({
|
|
266
|
+
pk: layout.rows,
|
|
267
|
+
order: "asc",
|
|
268
|
+
limit: 100,
|
|
269
|
+
after
|
|
270
|
+
});
|
|
271
|
+
const rows = page.items.map(({ value }) => value);
|
|
272
|
+
const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
|
|
273
|
+
const wanted = keys.flat();
|
|
274
|
+
const found = wanted.length === 0 ? [] : await store.get(wanted);
|
|
275
|
+
let at = 0;
|
|
276
|
+
const missing = rows.filter((_, position) => {
|
|
277
|
+
return found.slice(at, at += keys[position].length).some((item) => item === null);
|
|
278
|
+
});
|
|
279
|
+
lacking += missing.length;
|
|
280
|
+
if (!dryRun) {
|
|
281
|
+
let chunk = [];
|
|
282
|
+
let ops = [];
|
|
283
|
+
const flush = async () => {
|
|
284
|
+
if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
|
|
285
|
+
chunk = [];
|
|
286
|
+
ops = [];
|
|
287
|
+
};
|
|
288
|
+
for (const row of missing) {
|
|
289
|
+
const next = fillOps(layout, index, row);
|
|
290
|
+
const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
|
|
291
|
+
if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
|
|
292
|
+
chunk.push(row);
|
|
293
|
+
ops.push(...next);
|
|
294
|
+
}
|
|
295
|
+
await flush();
|
|
296
|
+
}
|
|
297
|
+
if (!page.more || page.items.length === 0) return lacking;
|
|
298
|
+
after = page.items.at(-1).sk;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
228
301
|
return {
|
|
229
302
|
id: store.id,
|
|
230
303
|
fits(ops) {
|
|
@@ -284,7 +357,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
284
357
|
const layout = layoutOf(table);
|
|
285
358
|
return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, require_adapter.rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
|
|
286
359
|
} },
|
|
287
|
-
migrations: {
|
|
360
|
+
migrations: {
|
|
361
|
+
apply: async () => store.migrations?.apply(),
|
|
362
|
+
fillIndex
|
|
363
|
+
},
|
|
288
364
|
...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
|
|
289
365
|
};
|
|
290
366
|
};
|
|
@@ -67,10 +67,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
67
67
|
const at = row && expiresAt(table, row);
|
|
68
68
|
return at === void 0 ? {} : { expiresAt: at };
|
|
69
69
|
};
|
|
70
|
-
/** Every index and unique item a row has, by address. */
|
|
71
|
-
const itemsOf = (layout, row) => {
|
|
70
|
+
/** Every index and unique item a row has, by address: in `indexes`, if given. */
|
|
71
|
+
const itemsOf = (layout, row, indexes = layout.indexed) => {
|
|
72
72
|
const items = /* @__PURE__ */ new Map();
|
|
73
|
-
for (const index of row === null ? [] :
|
|
73
|
+
for (const index of row === null ? [] : indexes) for (const eq of indexEntries(layout.table, index, row)) {
|
|
74
74
|
const pk = partition(layout, index, eq);
|
|
75
75
|
const sk = index.unique ? ONLY : encodeKvKey(indexOrderTuple(layout.table, index, row)) || ONLY;
|
|
76
76
|
items.set(JSON.stringify([pk, sk]), {
|
|
@@ -225,6 +225,79 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
225
225
|
lte: lt.endsWith(SEPARATOR) ? lt.slice(0, -1) : lt
|
|
226
226
|
};
|
|
227
227
|
};
|
|
228
|
+
/** One row's check and its item puts in `index`, copies of the row as it is. */
|
|
229
|
+
const fillOps = (layout, index, row) => [{
|
|
230
|
+
type: "check",
|
|
231
|
+
key: rowItem(layout, rowKey(layout.table, row)),
|
|
232
|
+
condition: { v: Number(row["_v"]) }
|
|
233
|
+
}, ...[...itemsOf(layout, row, [index]).values()].map(({ key }) => ({
|
|
234
|
+
type: "put",
|
|
235
|
+
key,
|
|
236
|
+
value: copyOf(layout, row),
|
|
237
|
+
...stamp(layout.table, row)
|
|
238
|
+
}))];
|
|
239
|
+
/**
|
|
240
|
+
* Writes one row's items in `index`, checking the row's `_v` in the same
|
|
241
|
+
* write: a row that changed is read again, and a deleted one needs none.
|
|
242
|
+
*/
|
|
243
|
+
const fillRow = async (layout, index, first) => {
|
|
244
|
+
const key = rowItem(layout, rowKey(layout.table, first));
|
|
245
|
+
let row = first;
|
|
246
|
+
for (let attempt = 0; row !== null; attempt += 1) {
|
|
247
|
+
if (attempt === 8) throw new Error(`${layout.table.name}.${index.name}: a row kept changing while its index items were written; run the migration again.`);
|
|
248
|
+
if ((await store.write(fillOps(layout, index, row))).ok) return;
|
|
249
|
+
[row] = await store.get([key]);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
/**
|
|
253
|
+
* Finds the rows that lack an item in `index` and, unless `dryRun`, writes
|
|
254
|
+
* them, as many rows per atomic write as the store takes. It reads every
|
|
255
|
+
* row and its items, page by page.
|
|
256
|
+
*/
|
|
257
|
+
const fillIndex = async (table, name, { dryRun = false } = {}) => {
|
|
258
|
+
const layout = layoutOf(table);
|
|
259
|
+
const index = layout.indexed.find((candidate) => candidate.name === name);
|
|
260
|
+
if (index === void 0) return 0;
|
|
261
|
+
if (index.unique) throw new DatabaseAdapterContractError(`${table.name}.${name} is unique: its items can't be written for rows stored before it, since two of them may hold one value.`);
|
|
262
|
+
const { items: most, bytes } = store.limits;
|
|
263
|
+
let lacking = 0;
|
|
264
|
+
for (let after;;) {
|
|
265
|
+
const page = await store.query({
|
|
266
|
+
pk: layout.rows,
|
|
267
|
+
order: "asc",
|
|
268
|
+
limit: 100,
|
|
269
|
+
after
|
|
270
|
+
});
|
|
271
|
+
const rows = page.items.map(({ value }) => value);
|
|
272
|
+
const keys = rows.map((row) => [...itemsOf(layout, row, [index]).values()].map(({ key }) => key));
|
|
273
|
+
const wanted = keys.flat();
|
|
274
|
+
const found = wanted.length === 0 ? [] : await store.get(wanted);
|
|
275
|
+
let at = 0;
|
|
276
|
+
const missing = rows.filter((_, position) => {
|
|
277
|
+
return found.slice(at, at += keys[position].length).some((item) => item === null);
|
|
278
|
+
});
|
|
279
|
+
lacking += missing.length;
|
|
280
|
+
if (!dryRun) {
|
|
281
|
+
let chunk = [];
|
|
282
|
+
let ops = [];
|
|
283
|
+
const flush = async () => {
|
|
284
|
+
if (ops.length > 0 && !(await store.write(ops)).ok) for (const row of chunk) await fillRow(layout, index, row);
|
|
285
|
+
chunk = [];
|
|
286
|
+
ops = [];
|
|
287
|
+
};
|
|
288
|
+
for (const row of missing) {
|
|
289
|
+
const next = fillOps(layout, index, row);
|
|
290
|
+
const size = (list) => list.reduce((sum, op) => sum + encoder.encode(op.key.pk + op.key.sk + JSON.stringify(op.type === "put" ? op.value : null)).length, 0);
|
|
291
|
+
if (chunk.length > 0 && (ops.length + next.length > most || size(ops) + size(next) > bytes)) await flush();
|
|
292
|
+
chunk.push(row);
|
|
293
|
+
ops.push(...next);
|
|
294
|
+
}
|
|
295
|
+
await flush();
|
|
296
|
+
}
|
|
297
|
+
if (!page.more || page.items.length === 0) return lacking;
|
|
298
|
+
after = page.items.at(-1).sk;
|
|
299
|
+
}
|
|
300
|
+
};
|
|
228
301
|
return {
|
|
229
302
|
id: store.id,
|
|
230
303
|
fits(ops) {
|
|
@@ -284,7 +357,10 @@ const createKvAdapter = ({ store, tablePrefix = "" }) => {
|
|
|
284
357
|
const layout = layoutOf(table);
|
|
285
358
|
return store.deleteConsumed(rows.flatMap((row) => [rowItem(layout, rowKey(table, row)), ...[...itemsOf(layout, row).values()].map(({ key }) => key)]));
|
|
286
359
|
} },
|
|
287
|
-
migrations: {
|
|
360
|
+
migrations: {
|
|
361
|
+
apply: async () => store.migrations?.apply(),
|
|
362
|
+
fillIndex
|
|
363
|
+
},
|
|
288
364
|
...store.dispose === void 0 ? {} : { dispose: () => store.dispose() }
|
|
289
365
|
};
|
|
290
366
|
};
|
|
@@ -49,7 +49,7 @@ const checkMysqlKey = (table, name, columns) => {
|
|
|
49
49
|
};
|
|
50
50
|
/**
|
|
51
51
|
* Each table as the DDL creates it, for the DDL below and for ORM schema
|
|
52
|
-
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
|
|
52
|
+
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
|
|
53
53
|
* table `<table>__<index>` for each index over a multi-valued field, keyed by
|
|
54
54
|
* every column it holds.
|
|
55
55
|
*/
|
|
@@ -57,6 +57,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
|
|
|
57
57
|
const name = tablePrefix + table.name;
|
|
58
58
|
const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
|
|
59
59
|
if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
|
|
60
|
+
const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
|
|
60
61
|
const indexes = table.indexes.flatMap((index) => {
|
|
61
62
|
const columns = [...index.eq, ...require_adapter.indexOrderColumns(table, index)];
|
|
62
63
|
if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
|
|
@@ -81,7 +82,10 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
|
|
|
81
82
|
}
|
|
82
83
|
}];
|
|
83
84
|
}
|
|
84
|
-
if (!index.unique
|
|
85
|
+
if (!index.unique) {
|
|
86
|
+
if (covered.has(JSON.stringify(columns))) return [];
|
|
87
|
+
covered.add(JSON.stringify(columns));
|
|
88
|
+
}
|
|
85
89
|
return [{
|
|
86
90
|
kind: "index",
|
|
87
91
|
name: shortSqlName(`${name}_${index.name}`),
|
|
@@ -34,7 +34,7 @@ interface SqlTableShape {
|
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
36
|
* Each table as the DDL creates it, for the DDL below and for ORM schema
|
|
37
|
-
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
|
|
37
|
+
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
|
|
38
38
|
* table `<table>__<index>` for each index over a multi-valued field, keyed by
|
|
39
39
|
* every column it holds.
|
|
40
40
|
*/
|
|
@@ -34,7 +34,7 @@ interface SqlTableShape {
|
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
36
|
* Each table as the DDL creates it, for the DDL below and for ORM schema
|
|
37
|
-
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
|
|
37
|
+
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
|
|
38
38
|
* table `<table>__<index>` for each index over a multi-valued field, keyed by
|
|
39
39
|
* every column it holds.
|
|
40
40
|
*/
|
|
@@ -49,7 +49,7 @@ const checkMysqlKey = (table, name, columns) => {
|
|
|
49
49
|
};
|
|
50
50
|
/**
|
|
51
51
|
* Each table as the DDL creates it, for the DDL below and for ORM schema
|
|
52
|
-
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index, and an index
|
|
52
|
+
* generators, such as the Drizzle and Prisma adapters': binary collation, one index per declared index (an index whose columns the key or an earlier index already orders by needs none), and an index
|
|
53
53
|
* table `<table>__<index>` for each index over a multi-valued field, keyed by
|
|
54
54
|
* every column it holds.
|
|
55
55
|
*/
|
|
@@ -57,6 +57,7 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
|
|
|
57
57
|
const name = tablePrefix + table.name;
|
|
58
58
|
const indexed = /* @__PURE__ */ new Set([...table.key, ...table.indexes.flatMap(({ eq, sort }) => [...eq, ...sort])]);
|
|
59
59
|
if (dialect === "mysql") checkMysqlKey(table, "key", table.key);
|
|
60
|
+
const covered = /* @__PURE__ */ new Set([JSON.stringify(table.key)]);
|
|
60
61
|
const indexes = table.indexes.flatMap((index) => {
|
|
61
62
|
const columns = [...index.eq, ...indexOrderColumns(table, index)];
|
|
62
63
|
if (dialect === "mysql") checkMysqlKey(table, `index ${index.name}`, columns);
|
|
@@ -81,7 +82,10 @@ const sqlTableShapes = (dialect, tables, tablePrefix = "") => tables.map((table)
|
|
|
81
82
|
}
|
|
82
83
|
}];
|
|
83
84
|
}
|
|
84
|
-
if (!index.unique
|
|
85
|
+
if (!index.unique) {
|
|
86
|
+
if (covered.has(JSON.stringify(columns))) return [];
|
|
87
|
+
covered.add(JSON.stringify(columns));
|
|
88
|
+
}
|
|
85
89
|
return [{
|
|
86
90
|
kind: "index",
|
|
87
91
|
name: shortSqlName(`${name}_${index.name}`),
|