@hot-updater/plugin-core 1.0.0-rc.3 → 1.0.0-rc.35
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/README.md +33 -0
- package/dist/baseCandidateKey.cjs +50 -0
- package/dist/baseCandidateKey.d.cts +27 -0
- package/dist/baseCandidateKey.d.mts +27 -0
- package/dist/baseCandidateKey.mjs +49 -0
- package/dist/bundleStorageLayout.cjs +7 -0
- package/dist/bundleStorageLayout.d.cts +5 -1
- package/dist/bundleStorageLayout.d.mts +5 -1
- package/dist/bundleStorageLayout.mjs +7 -1
- package/dist/contentType.cjs +9 -0
- package/dist/contentType.d.cts +4 -0
- package/dist/contentType.d.mts +4 -0
- package/dist/contentType.mjs +7 -0
- package/dist/coreApi.d.cts +131 -0
- package/dist/coreApi.d.mts +131 -0
- package/dist/createStorageAdapter.cjs +8 -0
- package/dist/createStorageAdapter.d.cts +9 -0
- package/dist/createStorageAdapter.d.mts +9 -0
- package/dist/createStorageAdapter.mjs +7 -0
- package/dist/database/adapter.cjs +61 -0
- package/dist/database/adapter.d.cts +200 -0
- package/dist/database/adapter.d.mts +200 -0
- package/dist/database/adapter.mjs +55 -0
- package/dist/database/distinct.cjs +88 -0
- package/dist/database/distinct.d.cts +18 -0
- package/dist/database/distinct.d.mts +18 -0
- package/dist/database/distinct.mjs +85 -0
- package/dist/database/memoryAdapter.cjs +107 -0
- package/dist/database/memoryAdapter.d.cts +14 -0
- package/dist/database/memoryAdapter.d.mts +14 -0
- package/dist/database/memoryAdapter.mjs +107 -0
- package/dist/database/values.cjs +114 -0
- package/dist/database/values.d.cts +17 -0
- package/dist/database/values.d.mts +17 -0
- package/dist/database/values.mjs +104 -0
- package/dist/database/verifyAdapter.cjs +137 -0
- package/dist/database/verifyAdapter.d.cts +37 -0
- package/dist/database/verifyAdapter.d.mts +37 -0
- package/dist/database/verifyAdapter.mjs +136 -0
- package/dist/databaseErrors.cjs +30 -0
- package/dist/databaseErrors.d.cts +21 -0
- package/dist/databaseErrors.d.mts +21 -0
- package/dist/databaseErrors.mjs +28 -0
- package/dist/databaseJsonValue.cjs +6 -0
- package/dist/databaseJsonValue.d.cts +9 -2
- package/dist/databaseJsonValue.d.mts +9 -2
- package/dist/databaseJsonValue.mjs +6 -0
- package/dist/databaseMetadata.cjs +4 -4
- package/dist/databaseMetadata.mjs +3 -3
- package/dist/databaseRows.cjs +6 -12
- package/dist/databaseRows.d.cts +1 -1
- package/dist/databaseRows.d.mts +1 -1
- package/dist/databaseRows.mjs +1 -7
- package/dist/engine/core/schema.cjs +279 -0
- package/dist/engine/core/schema.d.cts +312 -0
- package/dist/engine/core/schema.d.mts +312 -0
- package/dist/engine/core/schema.mjs +277 -0
- package/dist/engine/createEngine.cjs +72 -0
- package/dist/engine/createEngine.d.cts +45 -0
- package/dist/engine/createEngine.d.mts +45 -0
- package/dist/engine/createEngine.mjs +72 -0
- package/dist/engine/database/aggregateBatching.cjs +627 -0
- package/dist/engine/database/aggregateBatching.mjs +626 -0
- package/dist/engine/database/cursor.cjs +42 -0
- package/dist/engine/database/cursor.mjs +38 -0
- package/dist/engine/database/database.cjs +68 -0
- package/dist/engine/database/database.mjs +68 -0
- package/dist/engine/database/engine.cjs +37 -0
- package/dist/engine/database/engine.mjs +37 -0
- package/dist/engine/database/engineAggregates.cjs +120 -0
- package/dist/engine/database/engineAggregates.mjs +117 -0
- package/dist/engine/database/engineReads.cjs +182 -0
- package/dist/engine/database/engineReads.d.cts +10 -0
- package/dist/engine/database/engineReads.d.mts +10 -0
- package/dist/engine/database/engineReads.mjs +181 -0
- package/dist/engine/database/engineTransaction.cjs +399 -0
- package/dist/engine/database/engineTransaction.d.cts +18 -0
- package/dist/engine/database/engineTransaction.d.mts +18 -0
- package/dist/engine/database/engineTransaction.mjs +398 -0
- package/dist/engine/database/fence.cjs +156 -0
- package/dist/engine/database/fence.d.cts +41 -0
- package/dist/engine/database/fence.d.mts +41 -0
- package/dist/engine/database/fence.mjs +149 -0
- package/dist/engine/database/kv/kvAdapter.cjs +293 -0
- package/dist/engine/database/kv/kvAdapter.d.cts +116 -0
- package/dist/engine/database/kv/kvAdapter.d.mts +116 -0
- package/dist/engine/database/kv/kvAdapter.mjs +292 -0
- package/dist/engine/database/readMeter.cjs +80 -0
- package/dist/engine/database/readMeter.d.cts +34 -0
- package/dist/engine/database/readMeter.d.mts +34 -0
- package/dist/engine/database/readMeter.mjs +79 -0
- package/dist/engine/database/resolveSchema.cjs +197 -0
- package/dist/engine/database/resolveSchema.d.cts +35 -0
- package/dist/engine/database/resolveSchema.d.mts +35 -0
- package/dist/engine/database/resolveSchema.mjs +195 -0
- package/dist/engine/database/retention.cjs +100 -0
- package/dist/engine/database/retention.mjs +98 -0
- package/dist/engine/database/sql/sqlAdapter.cjs +290 -0
- package/dist/engine/database/sql/sqlAdapter.d.cts +45 -0
- package/dist/engine/database/sql/sqlAdapter.d.mts +45 -0
- package/dist/engine/database/sql/sqlAdapter.mjs +288 -0
- package/dist/engine/database/sql/sqlSchema.cjs +175 -0
- package/dist/engine/database/sql/sqlSchema.d.cts +45 -0
- package/dist/engine/database/sql/sqlSchema.d.mts +45 -0
- package/dist/engine/database/sql/sqlSchema.mjs +169 -0
- package/dist/engine/db/coreDatabase.cjs +94 -0
- package/dist/engine/db/coreDatabase.d.cts +78 -0
- package/dist/engine/db/coreDatabase.d.mts +78 -0
- package/dist/engine/db/coreDatabase.mjs +86 -0
- package/dist/engine/db/engineMigrator.cjs +53 -0
- package/dist/engine/db/engineMigrator.mjs +53 -0
- package/dist/engine/db/engineSql.cjs +26 -0
- package/dist/engine/db/engineSql.d.cts +16 -0
- package/dist/engine/db/engineSql.d.mts +16 -0
- package/dist/engine/db/engineSql.mjs +25 -0
- package/dist/engine/db/engineSqlMigrator.cjs +67 -0
- package/dist/engine/db/engineSqlMigrator.d.cts +21 -0
- package/dist/engine/db/engineSqlMigrator.d.mts +21 -0
- package/dist/engine/db/engineSqlMigrator.mjs +67 -0
- package/dist/engine/db/fixedMigratorShared.cjs +12 -0
- package/dist/engine/db/fixedMigratorShared.mjs +11 -0
- package/dist/engine/db/schemaSettings.cjs +63 -0
- package/dist/engine/db/schemaSettings.d.cts +7 -0
- package/dist/engine/db/schemaSettings.d.mts +7 -0
- package/dist/engine/db/schemaSettings.mjs +62 -0
- package/dist/engine/db/settingsMigrator.cjs +94 -0
- package/dist/engine/db/settingsMigrator.d.cts +25 -0
- package/dist/engine/db/settingsMigrator.d.mts +25 -0
- package/dist/engine/db/settingsMigrator.mjs +91 -0
- package/dist/engine/db/types.d.cts +78 -0
- package/dist/engine/db/types.d.mts +78 -0
- package/dist/index.cjs +97 -49
- package/dist/index.d.cts +46 -22
- package/dist/index.d.mts +46 -22
- package/dist/index.mjs +32 -17
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.cjs +0 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/comparison-DenM3wCn.mjs +1 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.cjs +8 -0
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/range-DvX-Y6iv.mjs +9 -2
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.cjs +4 -0
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/set-CC5YeoYX.mjs +4 -1
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.cjs +0 -5
- package/dist/node_modules/.pnpm/verkit@0.4.0/node_modules/verkit/dist/version-CQ98ZBpL.mjs +2 -6
- package/dist/releaseCatalogCompiler.cjs +27 -26
- package/dist/releaseCatalogCompiler.d.cts +1 -2
- package/dist/releaseCatalogCompiler.d.mts +2 -3
- package/dist/releaseCatalogCompiler.mjs +5 -9
- package/dist/releaseCatalogMutation.cjs +0 -292
- package/dist/releaseCatalogMutation.d.cts +4 -45
- package/dist/releaseCatalogMutation.d.mts +4 -45
- package/dist/releaseCatalogMutation.mjs +1 -288
- package/dist/releaseManagement.cjs +0 -221
- package/dist/releaseManagement.d.cts +4 -28
- package/dist/releaseManagement.d.mts +4 -28
- package/dist/releaseManagement.mjs +1 -216
- package/dist/remoteBundleSigning.d.cts +2 -2
- package/dist/remoteBundleSigning.d.mts +2 -2
- package/dist/serverPlugin/busy.cjs +36 -0
- package/dist/serverPlugin/busy.d.cts +12 -0
- package/dist/serverPlugin/busy.d.mts +12 -0
- package/dist/serverPlugin/busy.mjs +36 -0
- package/dist/serverPlugin/configError.cjs +7 -0
- package/dist/serverPlugin/configError.d.cts +7 -0
- package/dist/serverPlugin/configError.d.mts +7 -0
- package/dist/serverPlugin/configError.mjs +7 -0
- package/dist/serverPlugin/coreReads.d.cts +48 -0
- package/dist/serverPlugin/coreReads.d.mts +48 -0
- package/dist/serverPlugin/databaseHandle.d.cts +105 -0
- package/dist/serverPlugin/databaseHandle.d.mts +105 -0
- package/dist/serverPlugin/definePlugin.cjs +5 -0
- package/dist/serverPlugin/definePlugin.d.cts +130 -0
- package/dist/serverPlugin/definePlugin.d.mts +130 -0
- package/dist/serverPlugin/definePlugin.mjs +5 -0
- package/dist/serverPlugin/definitions.d.cts +76 -0
- package/dist/serverPlugin/definitions.d.mts +76 -0
- package/dist/serverPlugin/errors.cjs +37 -0
- package/dist/serverPlugin/errors.d.cts +29 -0
- package/dist/serverPlugin/errors.d.mts +29 -0
- package/dist/serverPlugin/errors.mjs +32 -0
- package/dist/serverPlugin/schema.cjs +24 -0
- package/dist/serverPlugin/schema.d.cts +90 -0
- package/dist/serverPlugin/schema.d.mts +90 -0
- package/dist/serverPlugin/schema.mjs +23 -0
- package/dist/types/databaseConfig.cjs +5 -0
- package/dist/types/databaseConfig.d.cts +68 -0
- package/dist/types/databaseConfig.d.mts +68 -0
- package/dist/types/databaseConfig.mjs +5 -0
- package/dist/types/databaseOperations.d.cts +5 -180
- package/dist/types/databaseOperations.d.mts +5 -180
- package/dist/types/databaseRows.d.cts +5 -56
- package/dist/types/databaseRows.d.mts +5 -56
- package/dist/types/index.cjs +2 -0
- package/dist/types/index.d.cts +31 -97
- package/dist/types/index.d.mts +31 -97
- package/dist/types/index.mjs +2 -1
- package/dist/types/models.d.cts +14 -0
- package/dist/types/models.d.mts +14 -0
- package/dist/types/public.d.cts +4 -3
- package/dist/types/public.d.mts +4 -3
- package/dist/uuidv7.cjs +3 -3
- package/dist/uuidv7.d.cts +1 -1
- package/dist/uuidv7.d.mts +1 -1
- package/dist/uuidv7.mjs +1 -1
- package/package.json +10 -7
- package/dist/calculatePagination.cjs +0 -25
- package/dist/calculatePagination.d.cts +0 -12
- package/dist/calculatePagination.d.mts +0 -12
- package/dist/calculatePagination.mjs +0 -25
- package/dist/compressionFormat.cjs +0 -62
- package/dist/compressionFormat.d.cts +0 -33
- package/dist/compressionFormat.d.mts +0 -33
- package/dist/compressionFormat.mjs +0 -58
- package/dist/createDatabasePlugin.cjs +0 -920
- package/dist/createDatabasePlugin.d.cts +0 -28
- package/dist/createDatabasePlugin.d.mts +0 -28
- package/dist/createDatabasePlugin.mjs +0 -916
- package/dist/createStoragePlugin.cjs +0 -8
- package/dist/createStoragePlugin.d.cts +0 -9
- package/dist/createStoragePlugin.d.mts +0 -9
- package/dist/createStoragePlugin.mjs +0 -7
- package/dist/databaseClient.cjs +0 -117
- package/dist/databaseClient.d.cts +0 -32
- package/dist/databaseClient.d.mts +0 -32
- package/dist/databaseClient.mjs +0 -114
- package/dist/databaseClientReads.cjs +0 -115
- package/dist/databaseClientReads.mjs +0 -113
- package/dist/databaseClientUpdates.cjs +0 -40
- package/dist/databaseClientUpdates.d.cts +0 -11
- package/dist/databaseClientUpdates.d.mts +0 -11
- package/dist/databaseClientUpdates.mjs +0 -38
- package/dist/databasePluginCrud.cjs +0 -88
- package/dist/databasePluginCrud.d.cts +0 -4
- package/dist/databasePluginCrud.d.mts +0 -4
- package/dist/databasePluginCrud.mjs +0 -87
- package/dist/databasePluginCrudValidation.d.cts +0 -6
- package/dist/databasePluginCrudValidation.d.mts +0 -6
- package/dist/databasePluginCrudValidationErrors.cjs +0 -11
- package/dist/databasePluginCrudValidationErrors.d.cts +0 -9
- package/dist/databasePluginCrudValidationErrors.d.mts +0 -9
- package/dist/databasePluginCrudValidationErrors.mjs +0 -11
- package/dist/databasePluginCrudValidationFields.cjs +0 -321
- package/dist/databasePluginCrudValidationFields.d.cts +0 -1
- package/dist/databasePluginCrudValidationFields.d.mts +0 -1
- package/dist/databasePluginCrudValidationFields.mjs +0 -309
- package/dist/databasePluginCrudValidationMutations.cjs +0 -107
- package/dist/databasePluginCrudValidationMutations.d.cts +0 -1
- package/dist/databasePluginCrudValidationMutations.d.mts +0 -1
- package/dist/databasePluginCrudValidationMutations.mjs +0 -100
- package/dist/databasePluginCrudValidationQueries.cjs +0 -103
- package/dist/databasePluginCrudValidationQueries.d.cts +0 -2
- package/dist/databasePluginCrudValidationQueries.d.mts +0 -2
- package/dist/databasePluginCrudValidationQueries.mjs +0 -97
- package/dist/databasePluginCrudValidationRows.cjs +0 -55
- package/dist/databasePluginCrudValidationRows.d.cts +0 -1
- package/dist/databasePluginCrudValidationRows.d.mts +0 -1
- package/dist/databasePluginCrudValidationRows.mjs +0 -53
- package/dist/databasePluginTransaction.cjs +0 -7
- package/dist/databasePluginTransaction.mjs +0 -7
- package/dist/insightsContract.cjs +0 -157
- package/dist/insightsContract.d.cts +0 -11
- package/dist/insightsContract.d.mts +0 -11
- package/dist/insightsContract.mjs +0 -153
- package/dist/internal.cjs +0 -6
- package/dist/internal.d.cts +0 -10
- package/dist/internal.d.mts +0 -10
- package/dist/internal.mjs +0 -3
- package/dist/paginateBundles.cjs +0 -53
- package/dist/paginateBundles.d.cts +0 -13
- package/dist/paginateBundles.d.mts +0 -13
- package/dist/paginateBundles.mjs +0 -53
- package/dist/queryBundles.cjs +0 -34
- package/dist/queryBundles.d.cts +0 -9
- package/dist/queryBundles.d.mts +0 -9
- package/dist/queryBundles.mjs +0 -32
- package/dist/requestBundleCache.cjs +0 -22
- package/dist/requestBundleCache.d.cts +0 -8
- package/dist/requestBundleCache.d.mts +0 -8
- package/dist/requestBundleCache.mjs +0 -22
- package/dist/types/database.d.cts +0 -5
- package/dist/types/database.d.mts +0 -5
- package/dist/types/databaseFields.cjs +0 -105
- package/dist/types/databaseFields.d.cts +0 -13
- package/dist/types/databaseFields.d.mts +0 -13
- package/dist/types/databaseFields.mjs +0 -105
- package/dist/types/databasePlugin.d.cts +0 -298
- package/dist/types/databasePlugin.d.mts +0 -298
- package/dist/types/databaseQuery.d.cts +0 -46
- package/dist/types/databaseQuery.d.mts +0 -46
- package/dist/types/internal.d.cts +0 -8
- package/dist/types/internal.d.mts +0 -8
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
const require_adapter = require("../../database/adapter.cjs");
|
|
2
|
+
const require_retention = require("./retention.cjs");
|
|
3
|
+
//#region src/engine/database/resolveSchema.ts
|
|
4
|
+
const SHARD_COLUMN = "_shard";
|
|
5
|
+
const NAME = /^[a-z][a-z0-9_]*$/u;
|
|
6
|
+
const INDEX_NAME = /^[A-Za-z][A-Za-z0-9_]*$/u;
|
|
7
|
+
const tableName = (module, model) => module.namespace ? `${module.namespace}_${model}` : model;
|
|
8
|
+
const integer = (name, defaulted = false) => ({
|
|
9
|
+
name,
|
|
10
|
+
type: "integer",
|
|
11
|
+
nullable: false,
|
|
12
|
+
...defaulted ? { default: 0 } : {}
|
|
13
|
+
});
|
|
14
|
+
/** A declared or derived field's type, and whether it holds several values. */
|
|
15
|
+
const fieldType = (model, name) => {
|
|
16
|
+
const field = model.fields[name] ?? (model.kind === "table" ? model.derived[name] : void 0);
|
|
17
|
+
return field && {
|
|
18
|
+
type: field.type,
|
|
19
|
+
multi: "multi" in field && !!field.multi
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const metricsOf = (model) => [
|
|
23
|
+
...model.counters,
|
|
24
|
+
...model.gauges,
|
|
25
|
+
...model.distinct
|
|
26
|
+
];
|
|
27
|
+
/** Field names, the key, and each field's options. */
|
|
28
|
+
const fieldProblems = (definition, add) => {
|
|
29
|
+
const names = [...Object.keys(definition.fields), ...definition.kind === "table" ? Object.keys(definition.derived) : metricsOf(definition)];
|
|
30
|
+
for (const name of new Set(names)) {
|
|
31
|
+
if (!NAME.test(name)) add(`field "${name}" must match ${NAME.source}`);
|
|
32
|
+
if (names.indexOf(name) !== names.lastIndexOf(name)) add(`field "${name}" is declared twice`);
|
|
33
|
+
}
|
|
34
|
+
const { key } = definition;
|
|
35
|
+
if (key.length === 0) add("key is empty");
|
|
36
|
+
if (new Set(key).size !== key.length) add("key repeats a field");
|
|
37
|
+
for (const name of key) {
|
|
38
|
+
const field = definition.fields[name];
|
|
39
|
+
if (field === void 0) add(`key field "${name}" is not a declared field`);
|
|
40
|
+
else if (field.required === false) add(`key field "${name}" is nullable`);
|
|
41
|
+
else if (field.type === "json") add(`key field "${name}" is json`);
|
|
42
|
+
}
|
|
43
|
+
for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
|
|
44
|
+
if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
|
|
45
|
+
if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** A table's derived fields and references. */
|
|
49
|
+
const tableProblems = (definition, add, table) => {
|
|
50
|
+
for (const [name, derived] of Object.entries(definition.derived)) {
|
|
51
|
+
if (typeof derived.compute !== "function") add(`derived field "${name}" has no compute function`);
|
|
52
|
+
if (derived.multi && derived.type === "json") add(`derived field "${name}" cannot be multi-valued json`);
|
|
53
|
+
}
|
|
54
|
+
for (const [name, { type, references }] of Object.entries(definition.fields)) {
|
|
55
|
+
if (references === void 0) continue;
|
|
56
|
+
const target = table(references.model);
|
|
57
|
+
const targetKey = target?.key.length === 1 ? target.fields[target.key[0]] : void 0;
|
|
58
|
+
if (targetKey === void 0) add(`field "${name}" references "${references.model}", which is not a single-key table of this module`);
|
|
59
|
+
else if (targetKey.type !== type) add(`field "${name}" and the key of "${references.model}" differ in type`);
|
|
60
|
+
if (references.onDelete === "cascade" && !Object.values(definition.indexes).some(({ eq }) => eq.length === 1 && eq[0] === name)) add(`cascade on "${name}" needs an index whose eq is exactly [${name}]`);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/** An aggregate's identity, metrics, and shards. */
|
|
64
|
+
const aggregateProblems = (definition, add) => {
|
|
65
|
+
const identity = Object.keys(definition.fields);
|
|
66
|
+
if (definition.key.join("\0") !== identity.join("\0")) add(`key must list the identity fields in declaration order: ${identity.join(", ")}`);
|
|
67
|
+
if (metricsOf(definition).length === 0) add("aggregate has no metrics");
|
|
68
|
+
if (definition.distinct.length > 0 && definition.counters.length + definition.gauges.length > 0) add("distinct sketches need an aggregate of their own");
|
|
69
|
+
const { shards } = definition;
|
|
70
|
+
if (!Number.isSafeInteger(shards) || shards < 1 || shards > 64) add(`shards must be 1–64`);
|
|
71
|
+
};
|
|
72
|
+
/** Every problem in one model's declaration, its roots and references included. */
|
|
73
|
+
const problemsOf = (module, model, definition) => {
|
|
74
|
+
const problems = [];
|
|
75
|
+
const add = (message) => problems.push(`${module.id}.${model}: ${message}`);
|
|
76
|
+
const table = (name) => {
|
|
77
|
+
const target = module.schema[name];
|
|
78
|
+
return target?.kind === "table" ? target : void 0;
|
|
79
|
+
};
|
|
80
|
+
if (!NAME.test(model)) add("model names use lowercase letters, digits, and _");
|
|
81
|
+
fieldProblems(definition, add);
|
|
82
|
+
for (const [name, index] of Object.entries(definition.indexes)) {
|
|
83
|
+
const columns = [...index.eq, ...index.sort];
|
|
84
|
+
if (!INDEX_NAME.test(name)) add(`index "${name}" must match ${INDEX_NAME.source}`);
|
|
85
|
+
if (columns.length === 0) add(`index "${name}" has no fields`);
|
|
86
|
+
if (index.unique && index.sort.length > 0) add(`unique index "${name}" cannot sort`);
|
|
87
|
+
if (columns.filter((column) => {
|
|
88
|
+
const type = fieldType(definition, column);
|
|
89
|
+
if (type === void 0) add(`index "${name}" names undeclared field "${column}"`);
|
|
90
|
+
else if (type.type === "json") add(`index "${name}" names json field "${column}"`);
|
|
91
|
+
else if (type.multi && index.sort.includes(column)) add(`index "${name}" sorts by multi-valued field "${column}"`);
|
|
92
|
+
return type?.type !== "json" && type?.multi;
|
|
93
|
+
}).length > 1) add(`index "${name}" has more than one multi-valued field`);
|
|
94
|
+
if (index.root === void 0) continue;
|
|
95
|
+
const root = table(index.root.model);
|
|
96
|
+
if (root === void 0) add(`index "${name}" is rooted at unknown table "${index.root.model}"`);
|
|
97
|
+
else if (root.key.length > index.eq.length || root.key.some((field, position) => fieldType(definition, index.eq[position])?.type !== root.fields[field].type)) add(`index "${name}" eq must start with the key of "${index.root.model}"`);
|
|
98
|
+
}
|
|
99
|
+
if (definition.kind === "table") tableProblems(definition, add, table);
|
|
100
|
+
else aggregateProblems(definition, add);
|
|
101
|
+
for (const problem of require_retention.retentionProblems(module.schema, model)) add(problem);
|
|
102
|
+
return problems;
|
|
103
|
+
};
|
|
104
|
+
/** Rejects invalid module schemas at startup, listing every problem. */
|
|
105
|
+
const validateSchema = (modules) => {
|
|
106
|
+
const problems = [];
|
|
107
|
+
const owners = /* @__PURE__ */ new Map();
|
|
108
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
109
|
+
const name = tableName(module, model);
|
|
110
|
+
const owner = owners.get(name);
|
|
111
|
+
if (owner !== void 0) problems.push(`${module.id}.${model}: table "${name}" is also declared by ${owner}`);
|
|
112
|
+
owners.set(name, `${module.id}.${model}`);
|
|
113
|
+
problems.push(...problemsOf(module, model, definition));
|
|
114
|
+
}
|
|
115
|
+
if (problems.length > 0) throw new require_adapter.DatabaseSchemaError(`Invalid database schema:\n- ${problems.join("\n- ")}`);
|
|
116
|
+
};
|
|
117
|
+
const indexesOf = (definition) => [...Object.entries(definition.indexes).map(([name, index]) => ({
|
|
118
|
+
name,
|
|
119
|
+
eq: [...index.eq],
|
|
120
|
+
sort: [...index.sort],
|
|
121
|
+
...index.unique ? { unique: true } : {}
|
|
122
|
+
})), ...Object.entries(definition.fields).flatMap(([name, field]) => field.unique ? [{
|
|
123
|
+
name,
|
|
124
|
+
eq: [name],
|
|
125
|
+
sort: [],
|
|
126
|
+
unique: true
|
|
127
|
+
}] : [])];
|
|
128
|
+
/** Validates the modules, then resolves them into physical tables with engine columns. */
|
|
129
|
+
const resolveSchema = (modules) => {
|
|
130
|
+
validateSchema(modules);
|
|
131
|
+
const references = [];
|
|
132
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
133
|
+
if (definition.kind !== "table") continue;
|
|
134
|
+
const table = tableName(module, model);
|
|
135
|
+
for (const [field, { references: to }] of Object.entries(definition.fields)) {
|
|
136
|
+
if (to === void 0) continue;
|
|
137
|
+
const { onDelete } = to;
|
|
138
|
+
const target = tableName(module, to.model);
|
|
139
|
+
const counter = onDelete === "none" ? {} : { counter: `_refs_${table}_${field}` };
|
|
140
|
+
references.push({
|
|
141
|
+
table,
|
|
142
|
+
field,
|
|
143
|
+
target,
|
|
144
|
+
onDelete,
|
|
145
|
+
...counter
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const models = /* @__PURE__ */ new Map();
|
|
150
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
151
|
+
const name = tableName(module, model);
|
|
152
|
+
const referencedBy = references.filter(({ target }) => target === name);
|
|
153
|
+
const columns = Object.entries(definition.fields).map(([field, { type, required, maxLength, ascii }]) => ({
|
|
154
|
+
name: field,
|
|
155
|
+
type,
|
|
156
|
+
nullable: required === false,
|
|
157
|
+
...maxLength === void 0 ? {} : { maxLength },
|
|
158
|
+
...ascii ? { ascii } : {}
|
|
159
|
+
}));
|
|
160
|
+
if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
|
|
161
|
+
name: field,
|
|
162
|
+
type,
|
|
163
|
+
nullable: true,
|
|
164
|
+
...multi ? { multi } : {}
|
|
165
|
+
});
|
|
166
|
+
else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
|
|
167
|
+
name: metric,
|
|
168
|
+
type: "string",
|
|
169
|
+
nullable: true
|
|
170
|
+
})));
|
|
171
|
+
for (const { counter } of referencedBy) if (counter !== void 0) columns.push(integer(counter, true));
|
|
172
|
+
columns.push(integer("_v", true));
|
|
173
|
+
models.set(name, {
|
|
174
|
+
module: module.id,
|
|
175
|
+
model,
|
|
176
|
+
definition,
|
|
177
|
+
table: {
|
|
178
|
+
name,
|
|
179
|
+
columns,
|
|
180
|
+
key: definition.kind === "aggregate" ? [...definition.key, SHARD_COLUMN] : [...definition.key],
|
|
181
|
+
indexes: indexesOf(definition),
|
|
182
|
+
...require_retention.physicalRetention(definition)
|
|
183
|
+
},
|
|
184
|
+
references: references.filter(({ table }) => table === name),
|
|
185
|
+
referencedBy,
|
|
186
|
+
roots: new Map(Object.entries(definition.indexes).flatMap(([index, { root }]) => root === void 0 ? [] : [[index, tableName(module, root.model)]]))
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
models,
|
|
191
|
+
tables: [...models.values()].map(({ table }) => table)
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
//#endregion
|
|
195
|
+
exports.SHARD_COLUMN = SHARD_COLUMN;
|
|
196
|
+
exports.resolveSchema = resolveSchema;
|
|
197
|
+
exports.validateSchema = validateSchema;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { PhysicalTable } from "../../database/adapter.cjs";
|
|
2
|
+
import { ModelShape, ReferenceAction } from "../../serverPlugin/definitions.cjs";
|
|
3
|
+
//#region src/engine/database/resolveSchema.d.ts
|
|
4
|
+
interface ResolvedReference {
|
|
5
|
+
/** The child table and the field that holds the parent key. */
|
|
6
|
+
readonly table: string;
|
|
7
|
+
readonly field: string;
|
|
8
|
+
readonly target: string;
|
|
9
|
+
readonly onDelete: ReferenceAction;
|
|
10
|
+
/** The counter column on the parent; absent for `none`. */
|
|
11
|
+
readonly counter?: string;
|
|
12
|
+
}
|
|
13
|
+
/** A model of a `ResolvedSchema`, with its physical table. */
|
|
14
|
+
interface ResolvedModel {
|
|
15
|
+
readonly module: string;
|
|
16
|
+
/** The model name as its module declares it. */
|
|
17
|
+
readonly model: string;
|
|
18
|
+
readonly table: PhysicalTable;
|
|
19
|
+
readonly definition: ModelShape;
|
|
20
|
+
readonly references: readonly ResolvedReference[];
|
|
21
|
+
readonly referencedBy: readonly ResolvedReference[];
|
|
22
|
+
/** Index name to the physical name of its root table. */
|
|
23
|
+
readonly roots: ReadonlyMap<string, string>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Modules resolved into physical tables with the engine's columns: a
|
|
27
|
+
* `ToolingTarget`'s schema, which a schema generator renders.
|
|
28
|
+
*/
|
|
29
|
+
interface ResolvedSchema {
|
|
30
|
+
/** By physical table name. */
|
|
31
|
+
readonly models: ReadonlyMap<string, ResolvedModel>;
|
|
32
|
+
readonly tables: readonly PhysicalTable[];
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
export { ResolvedModel, ResolvedReference, ResolvedSchema };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { PhysicalTable } from "../../database/adapter.mjs";
|
|
2
|
+
import { ModelShape, ReferenceAction } from "../../serverPlugin/definitions.mjs";
|
|
3
|
+
//#region src/engine/database/resolveSchema.d.ts
|
|
4
|
+
interface ResolvedReference {
|
|
5
|
+
/** The child table and the field that holds the parent key. */
|
|
6
|
+
readonly table: string;
|
|
7
|
+
readonly field: string;
|
|
8
|
+
readonly target: string;
|
|
9
|
+
readonly onDelete: ReferenceAction;
|
|
10
|
+
/** The counter column on the parent; absent for `none`. */
|
|
11
|
+
readonly counter?: string;
|
|
12
|
+
}
|
|
13
|
+
/** A model of a `ResolvedSchema`, with its physical table. */
|
|
14
|
+
interface ResolvedModel {
|
|
15
|
+
readonly module: string;
|
|
16
|
+
/** The model name as its module declares it. */
|
|
17
|
+
readonly model: string;
|
|
18
|
+
readonly table: PhysicalTable;
|
|
19
|
+
readonly definition: ModelShape;
|
|
20
|
+
readonly references: readonly ResolvedReference[];
|
|
21
|
+
readonly referencedBy: readonly ResolvedReference[];
|
|
22
|
+
/** Index name to the physical name of its root table. */
|
|
23
|
+
readonly roots: ReadonlyMap<string, string>;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Modules resolved into physical tables with the engine's columns: a
|
|
27
|
+
* `ToolingTarget`'s schema, which a schema generator renders.
|
|
28
|
+
*/
|
|
29
|
+
interface ResolvedSchema {
|
|
30
|
+
/** By physical table name. */
|
|
31
|
+
readonly models: ReadonlyMap<string, ResolvedModel>;
|
|
32
|
+
readonly tables: readonly PhysicalTable[];
|
|
33
|
+
}
|
|
34
|
+
//#endregion
|
|
35
|
+
export { ResolvedModel, ResolvedReference, ResolvedSchema };
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { DatabaseSchemaError } from "../../database/adapter.mjs";
|
|
2
|
+
import { physicalRetention, retentionProblems } from "./retention.mjs";
|
|
3
|
+
//#region src/engine/database/resolveSchema.ts
|
|
4
|
+
const SHARD_COLUMN = "_shard";
|
|
5
|
+
const NAME = /^[a-z][a-z0-9_]*$/u;
|
|
6
|
+
const INDEX_NAME = /^[A-Za-z][A-Za-z0-9_]*$/u;
|
|
7
|
+
const tableName = (module, model) => module.namespace ? `${module.namespace}_${model}` : model;
|
|
8
|
+
const integer = (name, defaulted = false) => ({
|
|
9
|
+
name,
|
|
10
|
+
type: "integer",
|
|
11
|
+
nullable: false,
|
|
12
|
+
...defaulted ? { default: 0 } : {}
|
|
13
|
+
});
|
|
14
|
+
/** A declared or derived field's type, and whether it holds several values. */
|
|
15
|
+
const fieldType = (model, name) => {
|
|
16
|
+
const field = model.fields[name] ?? (model.kind === "table" ? model.derived[name] : void 0);
|
|
17
|
+
return field && {
|
|
18
|
+
type: field.type,
|
|
19
|
+
multi: "multi" in field && !!field.multi
|
|
20
|
+
};
|
|
21
|
+
};
|
|
22
|
+
const metricsOf = (model) => [
|
|
23
|
+
...model.counters,
|
|
24
|
+
...model.gauges,
|
|
25
|
+
...model.distinct
|
|
26
|
+
];
|
|
27
|
+
/** Field names, the key, and each field's options. */
|
|
28
|
+
const fieldProblems = (definition, add) => {
|
|
29
|
+
const names = [...Object.keys(definition.fields), ...definition.kind === "table" ? Object.keys(definition.derived) : metricsOf(definition)];
|
|
30
|
+
for (const name of new Set(names)) {
|
|
31
|
+
if (!NAME.test(name)) add(`field "${name}" must match ${NAME.source}`);
|
|
32
|
+
if (names.indexOf(name) !== names.lastIndexOf(name)) add(`field "${name}" is declared twice`);
|
|
33
|
+
}
|
|
34
|
+
const { key } = definition;
|
|
35
|
+
if (key.length === 0) add("key is empty");
|
|
36
|
+
if (new Set(key).size !== key.length) add("key repeats a field");
|
|
37
|
+
for (const name of key) {
|
|
38
|
+
const field = definition.fields[name];
|
|
39
|
+
if (field === void 0) add(`key field "${name}" is not a declared field`);
|
|
40
|
+
else if (field.required === false) add(`key field "${name}" is nullable`);
|
|
41
|
+
else if (field.type === "json") add(`key field "${name}" is json`);
|
|
42
|
+
}
|
|
43
|
+
for (const [name, { type, maxLength, ascii }] of Object.entries(definition.fields)) {
|
|
44
|
+
if (maxLength !== void 0 && (type !== "string" || !Number.isSafeInteger(maxLength) || maxLength < 1)) add(`field "${name}" has an invalid maxLength`);
|
|
45
|
+
if (ascii && type !== "string") add(`field "${name}" is ascii but not a string`);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
/** A table's derived fields and references. */
|
|
49
|
+
const tableProblems = (definition, add, table) => {
|
|
50
|
+
for (const [name, derived] of Object.entries(definition.derived)) {
|
|
51
|
+
if (typeof derived.compute !== "function") add(`derived field "${name}" has no compute function`);
|
|
52
|
+
if (derived.multi && derived.type === "json") add(`derived field "${name}" cannot be multi-valued json`);
|
|
53
|
+
}
|
|
54
|
+
for (const [name, { type, references }] of Object.entries(definition.fields)) {
|
|
55
|
+
if (references === void 0) continue;
|
|
56
|
+
const target = table(references.model);
|
|
57
|
+
const targetKey = target?.key.length === 1 ? target.fields[target.key[0]] : void 0;
|
|
58
|
+
if (targetKey === void 0) add(`field "${name}" references "${references.model}", which is not a single-key table of this module`);
|
|
59
|
+
else if (targetKey.type !== type) add(`field "${name}" and the key of "${references.model}" differ in type`);
|
|
60
|
+
if (references.onDelete === "cascade" && !Object.values(definition.indexes).some(({ eq }) => eq.length === 1 && eq[0] === name)) add(`cascade on "${name}" needs an index whose eq is exactly [${name}]`);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
/** An aggregate's identity, metrics, and shards. */
|
|
64
|
+
const aggregateProblems = (definition, add) => {
|
|
65
|
+
const identity = Object.keys(definition.fields);
|
|
66
|
+
if (definition.key.join("\0") !== identity.join("\0")) add(`key must list the identity fields in declaration order: ${identity.join(", ")}`);
|
|
67
|
+
if (metricsOf(definition).length === 0) add("aggregate has no metrics");
|
|
68
|
+
if (definition.distinct.length > 0 && definition.counters.length + definition.gauges.length > 0) add("distinct sketches need an aggregate of their own");
|
|
69
|
+
const { shards } = definition;
|
|
70
|
+
if (!Number.isSafeInteger(shards) || shards < 1 || shards > 64) add(`shards must be 1–64`);
|
|
71
|
+
};
|
|
72
|
+
/** Every problem in one model's declaration, its roots and references included. */
|
|
73
|
+
const problemsOf = (module, model, definition) => {
|
|
74
|
+
const problems = [];
|
|
75
|
+
const add = (message) => problems.push(`${module.id}.${model}: ${message}`);
|
|
76
|
+
const table = (name) => {
|
|
77
|
+
const target = module.schema[name];
|
|
78
|
+
return target?.kind === "table" ? target : void 0;
|
|
79
|
+
};
|
|
80
|
+
if (!NAME.test(model)) add("model names use lowercase letters, digits, and _");
|
|
81
|
+
fieldProblems(definition, add);
|
|
82
|
+
for (const [name, index] of Object.entries(definition.indexes)) {
|
|
83
|
+
const columns = [...index.eq, ...index.sort];
|
|
84
|
+
if (!INDEX_NAME.test(name)) add(`index "${name}" must match ${INDEX_NAME.source}`);
|
|
85
|
+
if (columns.length === 0) add(`index "${name}" has no fields`);
|
|
86
|
+
if (index.unique && index.sort.length > 0) add(`unique index "${name}" cannot sort`);
|
|
87
|
+
if (columns.filter((column) => {
|
|
88
|
+
const type = fieldType(definition, column);
|
|
89
|
+
if (type === void 0) add(`index "${name}" names undeclared field "${column}"`);
|
|
90
|
+
else if (type.type === "json") add(`index "${name}" names json field "${column}"`);
|
|
91
|
+
else if (type.multi && index.sort.includes(column)) add(`index "${name}" sorts by multi-valued field "${column}"`);
|
|
92
|
+
return type?.type !== "json" && type?.multi;
|
|
93
|
+
}).length > 1) add(`index "${name}" has more than one multi-valued field`);
|
|
94
|
+
if (index.root === void 0) continue;
|
|
95
|
+
const root = table(index.root.model);
|
|
96
|
+
if (root === void 0) add(`index "${name}" is rooted at unknown table "${index.root.model}"`);
|
|
97
|
+
else if (root.key.length > index.eq.length || root.key.some((field, position) => fieldType(definition, index.eq[position])?.type !== root.fields[field].type)) add(`index "${name}" eq must start with the key of "${index.root.model}"`);
|
|
98
|
+
}
|
|
99
|
+
if (definition.kind === "table") tableProblems(definition, add, table);
|
|
100
|
+
else aggregateProblems(definition, add);
|
|
101
|
+
for (const problem of retentionProblems(module.schema, model)) add(problem);
|
|
102
|
+
return problems;
|
|
103
|
+
};
|
|
104
|
+
/** Rejects invalid module schemas at startup, listing every problem. */
|
|
105
|
+
const validateSchema = (modules) => {
|
|
106
|
+
const problems = [];
|
|
107
|
+
const owners = /* @__PURE__ */ new Map();
|
|
108
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
109
|
+
const name = tableName(module, model);
|
|
110
|
+
const owner = owners.get(name);
|
|
111
|
+
if (owner !== void 0) problems.push(`${module.id}.${model}: table "${name}" is also declared by ${owner}`);
|
|
112
|
+
owners.set(name, `${module.id}.${model}`);
|
|
113
|
+
problems.push(...problemsOf(module, model, definition));
|
|
114
|
+
}
|
|
115
|
+
if (problems.length > 0) throw new DatabaseSchemaError(`Invalid database schema:\n- ${problems.join("\n- ")}`);
|
|
116
|
+
};
|
|
117
|
+
const indexesOf = (definition) => [...Object.entries(definition.indexes).map(([name, index]) => ({
|
|
118
|
+
name,
|
|
119
|
+
eq: [...index.eq],
|
|
120
|
+
sort: [...index.sort],
|
|
121
|
+
...index.unique ? { unique: true } : {}
|
|
122
|
+
})), ...Object.entries(definition.fields).flatMap(([name, field]) => field.unique ? [{
|
|
123
|
+
name,
|
|
124
|
+
eq: [name],
|
|
125
|
+
sort: [],
|
|
126
|
+
unique: true
|
|
127
|
+
}] : [])];
|
|
128
|
+
/** Validates the modules, then resolves them into physical tables with engine columns. */
|
|
129
|
+
const resolveSchema = (modules) => {
|
|
130
|
+
validateSchema(modules);
|
|
131
|
+
const references = [];
|
|
132
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
133
|
+
if (definition.kind !== "table") continue;
|
|
134
|
+
const table = tableName(module, model);
|
|
135
|
+
for (const [field, { references: to }] of Object.entries(definition.fields)) {
|
|
136
|
+
if (to === void 0) continue;
|
|
137
|
+
const { onDelete } = to;
|
|
138
|
+
const target = tableName(module, to.model);
|
|
139
|
+
const counter = onDelete === "none" ? {} : { counter: `_refs_${table}_${field}` };
|
|
140
|
+
references.push({
|
|
141
|
+
table,
|
|
142
|
+
field,
|
|
143
|
+
target,
|
|
144
|
+
onDelete,
|
|
145
|
+
...counter
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const models = /* @__PURE__ */ new Map();
|
|
150
|
+
for (const module of modules) for (const [model, definition] of Object.entries(module.schema)) {
|
|
151
|
+
const name = tableName(module, model);
|
|
152
|
+
const referencedBy = references.filter(({ target }) => target === name);
|
|
153
|
+
const columns = Object.entries(definition.fields).map(([field, { type, required, maxLength, ascii }]) => ({
|
|
154
|
+
name: field,
|
|
155
|
+
type,
|
|
156
|
+
nullable: required === false,
|
|
157
|
+
...maxLength === void 0 ? {} : { maxLength },
|
|
158
|
+
...ascii ? { ascii } : {}
|
|
159
|
+
}));
|
|
160
|
+
if (definition.kind === "table") for (const [field, { type, multi }] of Object.entries(definition.derived)) columns.push({
|
|
161
|
+
name: field,
|
|
162
|
+
type,
|
|
163
|
+
nullable: true,
|
|
164
|
+
...multi ? { multi } : {}
|
|
165
|
+
});
|
|
166
|
+
else columns.push(integer(SHARD_COLUMN), ...[...definition.counters, ...definition.gauges].map((metric) => integer(metric)), ...definition.distinct.map((metric) => ({
|
|
167
|
+
name: metric,
|
|
168
|
+
type: "string",
|
|
169
|
+
nullable: true
|
|
170
|
+
})));
|
|
171
|
+
for (const { counter } of referencedBy) if (counter !== void 0) columns.push(integer(counter, true));
|
|
172
|
+
columns.push(integer("_v", true));
|
|
173
|
+
models.set(name, {
|
|
174
|
+
module: module.id,
|
|
175
|
+
model,
|
|
176
|
+
definition,
|
|
177
|
+
table: {
|
|
178
|
+
name,
|
|
179
|
+
columns,
|
|
180
|
+
key: definition.kind === "aggregate" ? [...definition.key, SHARD_COLUMN] : [...definition.key],
|
|
181
|
+
indexes: indexesOf(definition),
|
|
182
|
+
...physicalRetention(definition)
|
|
183
|
+
},
|
|
184
|
+
references: references.filter(({ table }) => table === name),
|
|
185
|
+
referencedBy,
|
|
186
|
+
roots: new Map(Object.entries(definition.indexes).flatMap(([index, { root }]) => root === void 0 ? [] : [[index, tableName(module, root.model)]]))
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
models,
|
|
191
|
+
tables: [...models.values()].map(({ table }) => table)
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
//#endregion
|
|
195
|
+
export { SHARD_COLUMN, resolveSchema, validateSchema };
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
//#region src/engine/database/retention.ts
|
|
2
|
+
const MINUTE_MS = 6e4;
|
|
3
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
4
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
5
|
+
/** A model's retention as its physical table carries it, which each adapter maps natively. */
|
|
6
|
+
const physicalRetention = ({ retention }) => retention === void 0 ? {} : { retention: {
|
|
7
|
+
column: retention.field,
|
|
8
|
+
ms: retention.days * DAY_MS
|
|
9
|
+
} };
|
|
10
|
+
/** Models in a reference or a rooted index, which an expired row's delete would break. */
|
|
11
|
+
const linkedModels = (schema) => Object.entries(schema).flatMap(([name, { fields, indexes }]) => [...Object.values(fields).map(({ references }) => references), ...Object.values(indexes).map(({ root }) => root)].flatMap((link) => link ? [name, link.model] : []));
|
|
12
|
+
/**
|
|
13
|
+
* What is wrong with a model's retention: it counts from an integer field,
|
|
14
|
+
* over whole days, and expired rows are deleted without cascades, counter
|
|
15
|
+
* moves, or root bumps, so the model is in no reference or rooted index.
|
|
16
|
+
*/
|
|
17
|
+
const retentionProblems = (schema, model) => {
|
|
18
|
+
const definition = schema[model];
|
|
19
|
+
if (definition.retention === void 0) return [];
|
|
20
|
+
const { field, days } = definition.retention;
|
|
21
|
+
const declared = definition.fields[field] ?? (definition.kind === "table" ? definition.derived[field] : void 0);
|
|
22
|
+
return [
|
|
23
|
+
...declared?.type !== "integer" || "multi" in declared && declared.multi === true ? [`retention field "${field}" is not an integer field`] : [],
|
|
24
|
+
...Number.isSafeInteger(days) && days >= 1 ? [] : ["retention days must be a whole number of at least 1"],
|
|
25
|
+
...linkedModels(schema).includes(model) ? ["a model with retention is in no reference or rooted index"] : []
|
|
26
|
+
];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Rows a pass deletes from each table: one statement or two a table, so a
|
|
30
|
+
* pass stays well inside D1's 50 queries an invocation.
|
|
31
|
+
*/
|
|
32
|
+
const PASS_LIMIT = 500;
|
|
33
|
+
/** The lease row: when the next pass is due, in epoch ms. */
|
|
34
|
+
const LEASE_KEY = "retention.nextPassAt";
|
|
35
|
+
/**
|
|
36
|
+
* The adapter, pruning during its writes with no scheduler: once the lease
|
|
37
|
+
* row in `leaseTable` is due, the write that takes it first runs one bounded
|
|
38
|
+
* pass over the tables with retention, and other writers skip. The next pass
|
|
39
|
+
* is due in an hour, or in a minute while a pass still found a full batch of
|
|
40
|
+
* expired rows in some table; a pass that fails is due again at once. A
|
|
41
|
+
* backend that expires rows natively, or a schema without retention, gets its
|
|
42
|
+
* adapter back.
|
|
43
|
+
*/
|
|
44
|
+
const pruneDuringWrites = (adapter, tables, { leaseTable: table, now }) => {
|
|
45
|
+
const expiring = tables.filter(({ retention }) => retention !== void 0);
|
|
46
|
+
if (adapter.prune === void 0 || expiring.length === 0) return adapter;
|
|
47
|
+
const key = [LEASE_KEY];
|
|
48
|
+
let checkAt = 0;
|
|
49
|
+
const lease = async (row, due) => {
|
|
50
|
+
const value = String(due);
|
|
51
|
+
const guard = { v: row === null ? -1 : Number(row._v) };
|
|
52
|
+
const next = {
|
|
53
|
+
key: LEASE_KEY,
|
|
54
|
+
value,
|
|
55
|
+
_v: guard.v + 1
|
|
56
|
+
};
|
|
57
|
+
const op = row === null ? {
|
|
58
|
+
type: "insert",
|
|
59
|
+
table,
|
|
60
|
+
row: next
|
|
61
|
+
} : {
|
|
62
|
+
type: "patch",
|
|
63
|
+
table,
|
|
64
|
+
key,
|
|
65
|
+
set: { value },
|
|
66
|
+
guard,
|
|
67
|
+
previous: row
|
|
68
|
+
};
|
|
69
|
+
return (await adapter.write([op])).ok ? next : null;
|
|
70
|
+
};
|
|
71
|
+
const pass = async () => {
|
|
72
|
+
const at = now();
|
|
73
|
+
if (at < checkAt) return;
|
|
74
|
+
checkAt = at + MINUTE_MS;
|
|
75
|
+
const [row = null] = await adapter.get(table, [key]);
|
|
76
|
+
checkAt = row === null ? at : Number(row.value);
|
|
77
|
+
if (checkAt > at) return;
|
|
78
|
+
const held = await lease(row, at + HOUR_MS);
|
|
79
|
+
if (held === null) return;
|
|
80
|
+
checkAt = at + HOUR_MS;
|
|
81
|
+
const deleted = [];
|
|
82
|
+
try {
|
|
83
|
+
for (const t of expiring) deleted.push(await adapter.prune(t, at - t.retention.ms, PASS_LIMIT));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
checkAt = at + MINUTE_MS;
|
|
86
|
+
await lease(held, at).catch(() => null);
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
if (deleted.includes(PASS_LIMIT) && await lease(held, at + MINUTE_MS) !== null) checkAt = at + MINUTE_MS;
|
|
90
|
+
};
|
|
91
|
+
const warn = (error) => console.warn("[hot-updater] Pruning expired rows failed.", error);
|
|
92
|
+
return Object.assign(Object.create(adapter), { async write(ops) {
|
|
93
|
+
await pass().catch(warn);
|
|
94
|
+
return adapter.write(ops);
|
|
95
|
+
} });
|
|
96
|
+
};
|
|
97
|
+
//#endregion
|
|
98
|
+
exports.physicalRetention = physicalRetention;
|
|
99
|
+
exports.pruneDuringWrites = pruneDuringWrites;
|
|
100
|
+
exports.retentionProblems = retentionProblems;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
//#region src/engine/database/retention.ts
|
|
2
|
+
const MINUTE_MS = 6e4;
|
|
3
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
4
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
5
|
+
/** A model's retention as its physical table carries it, which each adapter maps natively. */
|
|
6
|
+
const physicalRetention = ({ retention }) => retention === void 0 ? {} : { retention: {
|
|
7
|
+
column: retention.field,
|
|
8
|
+
ms: retention.days * DAY_MS
|
|
9
|
+
} };
|
|
10
|
+
/** Models in a reference or a rooted index, which an expired row's delete would break. */
|
|
11
|
+
const linkedModels = (schema) => Object.entries(schema).flatMap(([name, { fields, indexes }]) => [...Object.values(fields).map(({ references }) => references), ...Object.values(indexes).map(({ root }) => root)].flatMap((link) => link ? [name, link.model] : []));
|
|
12
|
+
/**
|
|
13
|
+
* What is wrong with a model's retention: it counts from an integer field,
|
|
14
|
+
* over whole days, and expired rows are deleted without cascades, counter
|
|
15
|
+
* moves, or root bumps, so the model is in no reference or rooted index.
|
|
16
|
+
*/
|
|
17
|
+
const retentionProblems = (schema, model) => {
|
|
18
|
+
const definition = schema[model];
|
|
19
|
+
if (definition.retention === void 0) return [];
|
|
20
|
+
const { field, days } = definition.retention;
|
|
21
|
+
const declared = definition.fields[field] ?? (definition.kind === "table" ? definition.derived[field] : void 0);
|
|
22
|
+
return [
|
|
23
|
+
...declared?.type !== "integer" || "multi" in declared && declared.multi === true ? [`retention field "${field}" is not an integer field`] : [],
|
|
24
|
+
...Number.isSafeInteger(days) && days >= 1 ? [] : ["retention days must be a whole number of at least 1"],
|
|
25
|
+
...linkedModels(schema).includes(model) ? ["a model with retention is in no reference or rooted index"] : []
|
|
26
|
+
];
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Rows a pass deletes from each table: one statement or two a table, so a
|
|
30
|
+
* pass stays well inside D1's 50 queries an invocation.
|
|
31
|
+
*/
|
|
32
|
+
const PASS_LIMIT = 500;
|
|
33
|
+
/** The lease row: when the next pass is due, in epoch ms. */
|
|
34
|
+
const LEASE_KEY = "retention.nextPassAt";
|
|
35
|
+
/**
|
|
36
|
+
* The adapter, pruning during its writes with no scheduler: once the lease
|
|
37
|
+
* row in `leaseTable` is due, the write that takes it first runs one bounded
|
|
38
|
+
* pass over the tables with retention, and other writers skip. The next pass
|
|
39
|
+
* is due in an hour, or in a minute while a pass still found a full batch of
|
|
40
|
+
* expired rows in some table; a pass that fails is due again at once. A
|
|
41
|
+
* backend that expires rows natively, or a schema without retention, gets its
|
|
42
|
+
* adapter back.
|
|
43
|
+
*/
|
|
44
|
+
const pruneDuringWrites = (adapter, tables, { leaseTable: table, now }) => {
|
|
45
|
+
const expiring = tables.filter(({ retention }) => retention !== void 0);
|
|
46
|
+
if (adapter.prune === void 0 || expiring.length === 0) return adapter;
|
|
47
|
+
const key = [LEASE_KEY];
|
|
48
|
+
let checkAt = 0;
|
|
49
|
+
const lease = async (row, due) => {
|
|
50
|
+
const value = String(due);
|
|
51
|
+
const guard = { v: row === null ? -1 : Number(row._v) };
|
|
52
|
+
const next = {
|
|
53
|
+
key: LEASE_KEY,
|
|
54
|
+
value,
|
|
55
|
+
_v: guard.v + 1
|
|
56
|
+
};
|
|
57
|
+
const op = row === null ? {
|
|
58
|
+
type: "insert",
|
|
59
|
+
table,
|
|
60
|
+
row: next
|
|
61
|
+
} : {
|
|
62
|
+
type: "patch",
|
|
63
|
+
table,
|
|
64
|
+
key,
|
|
65
|
+
set: { value },
|
|
66
|
+
guard,
|
|
67
|
+
previous: row
|
|
68
|
+
};
|
|
69
|
+
return (await adapter.write([op])).ok ? next : null;
|
|
70
|
+
};
|
|
71
|
+
const pass = async () => {
|
|
72
|
+
const at = now();
|
|
73
|
+
if (at < checkAt) return;
|
|
74
|
+
checkAt = at + MINUTE_MS;
|
|
75
|
+
const [row = null] = await adapter.get(table, [key]);
|
|
76
|
+
checkAt = row === null ? at : Number(row.value);
|
|
77
|
+
if (checkAt > at) return;
|
|
78
|
+
const held = await lease(row, at + HOUR_MS);
|
|
79
|
+
if (held === null) return;
|
|
80
|
+
checkAt = at + HOUR_MS;
|
|
81
|
+
const deleted = [];
|
|
82
|
+
try {
|
|
83
|
+
for (const t of expiring) deleted.push(await adapter.prune(t, at - t.retention.ms, PASS_LIMIT));
|
|
84
|
+
} catch (error) {
|
|
85
|
+
checkAt = at + MINUTE_MS;
|
|
86
|
+
await lease(held, at).catch(() => null);
|
|
87
|
+
throw error;
|
|
88
|
+
}
|
|
89
|
+
if (deleted.includes(PASS_LIMIT) && await lease(held, at + MINUTE_MS) !== null) checkAt = at + MINUTE_MS;
|
|
90
|
+
};
|
|
91
|
+
const warn = (error) => console.warn("[hot-updater] Pruning expired rows failed.", error);
|
|
92
|
+
return Object.assign(Object.create(adapter), { async write(ops) {
|
|
93
|
+
await pass().catch(warn);
|
|
94
|
+
return adapter.write(ops);
|
|
95
|
+
} });
|
|
96
|
+
};
|
|
97
|
+
//#endregion
|
|
98
|
+
export { physicalRetention, pruneDuringWrites, retentionProblems };
|