@effect-dynamodb/schema 1.38.0 → 1.40.0
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/Aggregate.d.ts +11 -4
- package/dist/Aggregate.d.ts.map +1 -1
- package/dist/Aggregate.js +21 -2
- package/dist/Aggregate.js.map +1 -1
- package/dist/DynamoModel.d.ts +13 -0
- package/dist/DynamoModel.d.ts.map +1 -1
- package/dist/DynamoModel.js.map +1 -1
- package/dist/DynamoSchema.d.ts +33 -17
- package/dist/DynamoSchema.d.ts.map +1 -1
- package/dist/DynamoSchema.js +19 -13
- package/dist/DynamoSchema.js.map +1 -1
- package/dist/Entity.d.ts +121 -18
- package/dist/Entity.d.ts.map +1 -1
- package/dist/Entity.js +238 -2
- package/dist/Entity.js.map +1 -1
- package/dist/Errors.d.ts +0 -27
- package/dist/Errors.d.ts.map +1 -1
- package/dist/Errors.js +0 -24
- package/dist/Errors.js.map +1 -1
- package/dist/KeyComposer.d.ts +368 -14
- package/dist/KeyComposer.d.ts.map +1 -1
- package/dist/KeyComposer.js +835 -87
- package/dist/KeyComposer.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/AggregateEdges.d.ts +3 -3
- package/dist/internal/AggregateSchemas.d.ts +181 -14
- package/dist/internal/AggregateSchemas.d.ts.map +1 -1
- package/dist/internal/AggregateSchemas.js +505 -45
- package/dist/internal/AggregateSchemas.js.map +1 -1
- package/dist/internal/AggregateTypes.d.ts +396 -36
- package/dist/internal/AggregateTypes.d.ts.map +1 -1
- package/dist/internal/CompositeCodec.d.ts +274 -6
- package/dist/internal/CompositeCodec.d.ts.map +1 -1
- package/dist/internal/CompositeCodec.js +829 -25
- package/dist/internal/CompositeCodec.js.map +1 -1
- package/dist/internal/EffectInstances.d.ts +81 -0
- package/dist/internal/EffectInstances.d.ts.map +1 -0
- package/dist/internal/EffectInstances.js +656 -0
- package/dist/internal/EffectInstances.js.map +1 -0
- package/dist/internal/EntitySchemas.d.ts +103 -27
- package/dist/internal/EntitySchemas.d.ts.map +1 -1
- package/dist/internal/EntitySchemas.js +778 -131
- package/dist/internal/EntitySchemas.js.map +1 -1
- package/dist/internal/EntityTypes.d.ts +67 -11
- package/dist/internal/EntityTypes.d.ts.map +1 -1
- package/dist/internal/FailingAsBefore.d.ts +25 -0
- package/dist/internal/FailingAsBefore.d.ts.map +1 -0
- package/dist/internal/FailingAsBefore.js +42 -0
- package/dist/internal/FailingAsBefore.js.map +1 -0
- package/dist/internal/InstanceReads.d.ts +33 -0
- package/dist/internal/InstanceReads.d.ts.map +1 -0
- package/dist/internal/InstanceReads.js +165 -0
- package/dist/internal/InstanceReads.js.map +1 -0
- package/dist/internal/KeyText136.d.ts +58 -131
- package/dist/internal/KeyText136.d.ts.map +1 -1
- package/dist/internal/KeyText136.js +154 -264
- package/dist/internal/KeyText136.js.map +1 -1
- package/dist/internal/NumericKey.d.ts +29 -2
- package/dist/internal/NumericKey.d.ts.map +1 -1
- package/dist/internal/NumericKey.js +64 -1
- package/dist/internal/NumericKey.js.map +1 -1
- package/dist/internal/PackedCodec.d.ts +8 -1
- package/dist/internal/PackedCodec.d.ts.map +1 -1
- package/dist/internal/PackedCodec.js +49 -13
- package/dist/internal/PackedCodec.js.map +1 -1
- package/dist/internal/SchemaAccessors.d.ts +160 -1
- package/dist/internal/SchemaAccessors.d.ts.map +1 -1
- package/dist/internal/SchemaAccessors.js +994 -1
- package/dist/internal/SchemaAccessors.js.map +1 -1
- package/dist/internal/Shards.d.ts +47 -0
- package/dist/internal/Shards.d.ts.map +1 -0
- package/dist/internal/Shards.js +60 -0
- package/dist/internal/Shards.js.map +1 -0
- package/dist/internal/SharedKeyAttribute.d.ts +102 -0
- package/dist/internal/SharedKeyAttribute.d.ts.map +1 -0
- package/dist/internal/SharedKeyAttribute.js +288 -0
- package/dist/internal/SharedKeyAttribute.js.map +1 -0
- package/dist/internal/SparseKey.d.ts +46 -0
- package/dist/internal/SparseKey.d.ts.map +1 -0
- package/dist/internal/SparseKey.js +69 -0
- package/dist/internal/SparseKey.js.map +1 -0
- package/package.json +2 -1
package/dist/KeyComposer.js
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { DateTime } from "effect";
|
|
9
9
|
import { applyCasing, composeClusteredSortKey, composeCollectionKey, composeIsolatedSortKey, composeKey, KEY_DELIMITER, } from "./DynamoSchema.js";
|
|
10
|
-
import { encodeBigInt, encodeNumber } from "./internal/NumericKey.js";
|
|
10
|
+
import { encodeBigInt, encodeNumber, isStoredNaN } from "./internal/NumericKey.js";
|
|
11
|
+
import { MAX_SHARD_COUNT, ShardSourceError, shardMarker, shardOf } from "./internal/Shards.js";
|
|
11
12
|
import { concatBytes, interleave, prefixSegment, toBytes, } from "./internal/ZOrderCurve.js";
|
|
12
13
|
import { declareDimension } from "./internal/ZOrderDimension.js";
|
|
13
14
|
/** Is this sort key half a Z-order one? */
|
|
@@ -28,6 +29,61 @@ export const assertCollectionCasingAgreement = (collectionName, members) => {
|
|
|
28
29
|
`\`casing\` on every member.`);
|
|
29
30
|
}
|
|
30
31
|
};
|
|
32
|
+
/**
|
|
33
|
+
* Fail when a collection's members would read different partitions (#183). They
|
|
34
|
+
* share one physical index and one logical key, so they must agree on how many
|
|
35
|
+
* partitions it is spread over and on the layout being migrated from. `by` may
|
|
36
|
+
* differ: each member hashes its own source, into the same partitions.
|
|
37
|
+
*/
|
|
38
|
+
export const assertCollectionShardsAgreement = (collectionName, members) => {
|
|
39
|
+
const layout = (member) => `${member.index.shards?.count ?? "unsharded"}/${member.index.shards?.previous ?? "none"}`;
|
|
40
|
+
if (new Set(members.map(layout)).size > 1) {
|
|
41
|
+
const shown = members.map((member) => {
|
|
42
|
+
const { count, previous } = member.index.shards ?? {};
|
|
43
|
+
return `${member.key}: ${count === undefined ? "unsharded" : `count ${count}`}${previous === undefined ? "" : `, previous ${previous}`}`;
|
|
44
|
+
});
|
|
45
|
+
throw new Error(`[EDD-9103] Collection "${collectionName}" members spread its index differently ` +
|
|
46
|
+
`(${shown.join("; ")}). They share one logical partition, so a query has to read one ` +
|
|
47
|
+
`set of partitions: give the collection's index the same \`shards\` count and \`previous\` ` +
|
|
48
|
+
`on every member.`);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const shardsMalformed = (index, why) => new Error(`[EDD-9099] Index "${index}" declares malformed shards: ${why}`);
|
|
52
|
+
/** Normalise and check a declared `shards` (the rest is `Entity.make`'s, which has the model). */
|
|
53
|
+
const normalizeShards = (index, declared) => {
|
|
54
|
+
const config = typeof declared === "number" ? { count: declared } : declared;
|
|
55
|
+
if (typeof config !== "object" || config === null || Array.isArray(config)) {
|
|
56
|
+
throw shardsMalformed(index, "pass a count, or { count, by?, previous? }.");
|
|
57
|
+
}
|
|
58
|
+
const unknownKeys = Object.keys(config).filter((key) => key !== "count" && key !== "by" && key !== "previous");
|
|
59
|
+
if (unknownKeys.length > 0) {
|
|
60
|
+
throw shardsMalformed(index, `unknown option ${unknownKeys.map((key) => `"${key}"`).join(", ")}: it takes count, by and previous.`);
|
|
61
|
+
}
|
|
62
|
+
const { count, by, previous } = config;
|
|
63
|
+
if (typeof count !== "number" ||
|
|
64
|
+
!Number.isInteger(count) ||
|
|
65
|
+
count < 2 ||
|
|
66
|
+
count > MAX_SHARD_COUNT) {
|
|
67
|
+
throw shardsMalformed(index, `count ${JSON.stringify(count)} must be an integer from 2 to ${MAX_SHARD_COUNT}.`);
|
|
68
|
+
}
|
|
69
|
+
if (previous !== undefined) {
|
|
70
|
+
if (typeof previous !== "number" || !Number.isInteger(previous) || previous < 1) {
|
|
71
|
+
throw shardsMalformed(index, `previous ${JSON.stringify(previous)} must be a positive integer: 1 for the unsharded key, or the old count.`);
|
|
72
|
+
}
|
|
73
|
+
if (previous === count) {
|
|
74
|
+
throw shardsMalformed(index, `previous ${previous} equals count: it names the layout being migrated from, which has to differ.`);
|
|
75
|
+
}
|
|
76
|
+
if (previous > MAX_SHARD_COUNT) {
|
|
77
|
+
throw shardsMalformed(index, `previous ${previous} is above ${MAX_SHARD_COUNT}.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
count,
|
|
82
|
+
by: by === undefined ? undefined : [...by],
|
|
83
|
+
previous,
|
|
84
|
+
source: undefined,
|
|
85
|
+
};
|
|
86
|
+
};
|
|
31
87
|
/** Normalize a GsiConfig (entity input) to an IndexDefinition (internal format). */
|
|
32
88
|
export const normalizeGsiConfig = (config) => {
|
|
33
89
|
// Detect old format and give helpful migration error
|
|
@@ -54,6 +110,7 @@ export const normalizeGsiConfig = (config) => {
|
|
|
54
110
|
: { field: sk.field, composite: [...sk.composite] },
|
|
55
111
|
...(config.casing !== undefined && { casing: config.casing }),
|
|
56
112
|
...(config.indexPolicy !== undefined && { indexPolicy: config.indexPolicy }),
|
|
113
|
+
...(config.shards !== undefined && { shards: normalizeShards(config.name, config.shards) }),
|
|
57
114
|
};
|
|
58
115
|
};
|
|
59
116
|
const zorderMalformed = (index, why) => new Error(`[EDD-9086] Index "${index}" declares a malformed Z-order sort key: ${why}`);
|
|
@@ -141,8 +198,30 @@ export const tryExtractComposites = (composite, record) => {
|
|
|
141
198
|
}
|
|
142
199
|
return values;
|
|
143
200
|
};
|
|
201
|
+
/** A value's composite text, its numbers by `number` and `bigint`. */
|
|
202
|
+
const serializeWith = (value, number, bigint) => {
|
|
203
|
+
if (typeof value === "string")
|
|
204
|
+
return value;
|
|
205
|
+
if (typeof value === "number")
|
|
206
|
+
return number(value);
|
|
207
|
+
if (typeof value === "bigint")
|
|
208
|
+
return bigint(value);
|
|
209
|
+
if (isStoredNaN(value))
|
|
210
|
+
return number(Number.NaN);
|
|
211
|
+
if (typeof value === "boolean")
|
|
212
|
+
return value ? "true" : "false";
|
|
213
|
+
// DateTime types → ISO string (Zoned normalized to UTC for sort order)
|
|
214
|
+
if (typeof value === "object" && value !== null && DateTime.isDateTime(value)) {
|
|
215
|
+
return DateTime.formatIso(value);
|
|
216
|
+
}
|
|
217
|
+
// Native Date
|
|
218
|
+
if (value instanceof Date)
|
|
219
|
+
return value.toISOString();
|
|
220
|
+
return String(value);
|
|
221
|
+
};
|
|
144
222
|
/**
|
|
145
|
-
* Serialize a value for
|
|
223
|
+
* Serialize a value for a composite key under `escapeKeys: true`. {@link compositeText} is the
|
|
224
|
+
* text under a schema's setting.
|
|
146
225
|
*
|
|
147
226
|
* Numeric values are encoded so their key text sorts in numeric order
|
|
148
227
|
* (`internal/NumericKey.ts` has the format):
|
|
@@ -159,33 +238,41 @@ export const tryExtractComposites = (composite, record) => {
|
|
|
159
238
|
* - DateTime.Utc → ISO string
|
|
160
239
|
* - Date → ISO string
|
|
161
240
|
*/
|
|
162
|
-
export const serializeValue = (value) =>
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
241
|
+
export const serializeValue = (value) => serializeWith(value, encodeNumber, encodeBigInt);
|
|
242
|
+
/**
|
|
243
|
+
* A composite value's text with `escapeKeys` off, the text 1.36 composed: a number zero-padded to
|
|
244
|
+
* 16 characters and a bigint to 38 (`String(n)` padded, so `-3` is `00000000000000-3` and `2.5` is
|
|
245
|
+
* `00000000000002.5`). Never throws: `NaN` is `0000000000000NaN`.
|
|
246
|
+
*/
|
|
247
|
+
export const serializeValue136 = (value) => serializeWith(value, (n) => String(n).padStart(16, "0"), (n) => String(n).padStart(38, "0"));
|
|
248
|
+
/**
|
|
249
|
+
* A composite value's serialized text under the schema's setting, before casing and escaping. A
|
|
250
|
+
* `number`'s `NaN` has no place in key order under any setting, and no stored form: `[EDD-9096]`.
|
|
251
|
+
* With `escapeKeys` off every other value keeps the text 1.36 gave it. That includes the `NaN` of a
|
|
252
|
+
* number its field stores as a string (`NumericKey.STORED_NAN`, which the composite key form hands
|
|
253
|
+
* on for a `Schema.NumberFromString`): a row holds it under `0000000000000NaN`, as 1.39.0 wrote
|
|
254
|
+
* it, and is read, updated and deleted by that key. With `escapeKeys` on it's refused like any
|
|
255
|
+
* `NaN`. {@link DynamoSchema.DynamoSchema.text136} composes 1.36's text for a `number`'s `NaN` too,
|
|
256
|
+
* for `rekey` to find a row stored under it.
|
|
257
|
+
*/
|
|
258
|
+
export const compositeText = (schema, value) => {
|
|
259
|
+
if (schema.escapeKeys === true || schema.numericKeyText === true)
|
|
260
|
+
return serializeValue(value);
|
|
261
|
+
if (schema.text136 !== true && typeof value === "number" && Number.isNaN(value)) {
|
|
262
|
+
return serializeValue(value);
|
|
174
263
|
}
|
|
175
|
-
|
|
176
|
-
if (value instanceof Date)
|
|
177
|
-
return value.toISOString();
|
|
178
|
-
return String(value);
|
|
264
|
+
return serializeValue136(value);
|
|
179
265
|
};
|
|
180
|
-
/** The highest code point a
|
|
266
|
+
/** The highest code point a key composite's text escapes: `%`. */
|
|
181
267
|
const ESCAPED_MAX = 0x25;
|
|
182
268
|
/**
|
|
183
|
-
* A composite value's serialized text as a
|
|
269
|
+
* A composite value's serialized text as a key holds it (#171, #183): cased,
|
|
184
270
|
* then each code point U+0000–U+0025 — control characters, space, `!`, `"`,
|
|
185
271
|
* `#`, `$` and `%` — escaped as `%` and two hex digits (space → `%20`, `#` →
|
|
186
272
|
* `%23`, `%` → `%25`), the hex digits in upper case, or lower case under
|
|
187
273
|
* `"lowercase"` casing. Any other text is unchanged, so a value without such a
|
|
188
|
-
* character keeps its 1.36 key text.
|
|
274
|
+
* character keeps its 1.36 key text. The same rule holds in a partition key and
|
|
275
|
+
* a sort key, so the two build identical text from identical values.
|
|
189
276
|
*
|
|
190
277
|
* Every escaped value sorts as its cased value and starts with its cased
|
|
191
278
|
* prefixes' text: an unescaped character sorts above `%`, and an escape starts
|
|
@@ -197,7 +284,7 @@ const ESCAPED_MAX = 0x25;
|
|
|
197
284
|
* Casing comes first so the hex digits are the only text it can't reach: the
|
|
198
285
|
* composer cases the key again, which leaves cased text as it is.
|
|
199
286
|
*/
|
|
200
|
-
export const
|
|
287
|
+
export const escapeKeyText = (text, casing) => {
|
|
201
288
|
const cased = applyCasing(text, casing);
|
|
202
289
|
let escaped = "";
|
|
203
290
|
let from = 0;
|
|
@@ -211,10 +298,33 @@ export const sortKeyText = (text, casing) => {
|
|
|
211
298
|
}
|
|
212
299
|
return from === 0 ? cased : `${escaped}${cased.slice(from)}`;
|
|
213
300
|
};
|
|
214
|
-
/**
|
|
215
|
-
export const
|
|
216
|
-
/**
|
|
217
|
-
|
|
301
|
+
/** The text {@link escapeKeyText} escaped back, cased: for `rekey`, reading a value out of a key. */
|
|
302
|
+
export const unescapeKeyText = (text) => text.replace(/%([0-9a-fA-F]{2})/g, (_, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
303
|
+
/**
|
|
304
|
+
* @deprecated since 1.39.0: escaping is `escapeKeys: true`'s, in every key. Use {@link keyText},
|
|
305
|
+
* which follows the setting, or {@link escapeKeyText}, the same function under its new name.
|
|
306
|
+
*/
|
|
307
|
+
export const sortKeyText = (text, casing) => escapeKeyText(text, casing);
|
|
308
|
+
/**
|
|
309
|
+
* @deprecated since 1.39.0: escaping is `escapeKeys: true`'s, in every key. Use
|
|
310
|
+
* {@link keyValueText}, which follows the setting.
|
|
311
|
+
*/
|
|
312
|
+
export const serializeSortKeyValue = (value, casing) => escapeKeyText(serializeValue(value), casing);
|
|
313
|
+
/**
|
|
314
|
+
* A composite's serialized text in a key: cased, and with `escapeKeys: true`
|
|
315
|
+
* {@link escapeKeyText}. Every key composite passes through here, in every key.
|
|
316
|
+
*/
|
|
317
|
+
export const keyText = (schema, text, casing) => (schema.escapeKeys === true ? escapeKeyText(text, casing) : applyCasing(text, casing));
|
|
318
|
+
/** A composite value's text in a key: {@link compositeText}, then {@link keyText}. */
|
|
319
|
+
export const keyValueText = (schema, value, casing) => keyText(schema, compositeText(schema, value), casing);
|
|
320
|
+
/** {@link extractComposites} under the schema's setting, each value's {@link keyValueText}. */
|
|
321
|
+
export const extractKeyComposites = (schema, index, composite, record) => composite.map((attr) => {
|
|
322
|
+
const value = record[attr];
|
|
323
|
+
if (value === undefined || value === null) {
|
|
324
|
+
throw new Error(`Missing composite attribute "${attr}" in record`);
|
|
325
|
+
}
|
|
326
|
+
return keyValueText(schema, value, index.casing ?? schema.casing);
|
|
327
|
+
});
|
|
218
328
|
/**
|
|
219
329
|
* Compose a partition key for an entity index.
|
|
220
330
|
*
|
|
@@ -222,16 +332,172 @@ const extractSortKeyComposites = (composite, record, casing) => extractComposite
|
|
|
222
332
|
* For collection indexes: `$schema#v<version>#collectionName#attr1#attr2`
|
|
223
333
|
*/
|
|
224
334
|
export const composePk = (schema, entityType, index, record) => {
|
|
225
|
-
const composites =
|
|
226
|
-
|
|
335
|
+
const composites = extractKeyComposites(schema, index, index.pk.composite, record);
|
|
336
|
+
return composePkText(schema, entityType, index, composites, index.pk.composite, composedShardMarker(entityType, index, record));
|
|
337
|
+
};
|
|
338
|
+
/**
|
|
339
|
+
* The text of a partition key: the entity type or collection name, the marker
|
|
340
|
+
* of a sharded index (design §2), then the composites.
|
|
341
|
+
*/
|
|
342
|
+
const composePkText = (schema, entityType, index, composites, names, marker) => {
|
|
227
343
|
const collection = index.collection;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
344
|
+
// Collection index — PK uses collection name; regular index — entity type.
|
|
345
|
+
const label = collection === undefined
|
|
346
|
+
? entityType
|
|
347
|
+
: Array.isArray(collection)
|
|
348
|
+
? collection[0]
|
|
349
|
+
: collection;
|
|
350
|
+
const spelled = marker === undefined ? label : `${label}${KEY_DELIMITER}${marker}`;
|
|
351
|
+
const options = { casing: index.casing, names: [...names] };
|
|
352
|
+
return collection === undefined
|
|
353
|
+
? composeKey(schema, spelled, composites, options)
|
|
354
|
+
: composeCollectionKey(schema, spelled, composites, options);
|
|
355
|
+
};
|
|
356
|
+
/**
|
|
357
|
+
* The marker of the shard `record` hashes to; `undefined` on an unsharded index.
|
|
358
|
+
* Throws `[EDD-9100]` when the source is missing: a sharded index never composes
|
|
359
|
+
* an unsharded partition key, so a write can't go wrong by forgetting it.
|
|
360
|
+
*/
|
|
361
|
+
const composedShardMarker = (entityType, index, record) => {
|
|
362
|
+
const shards = index.shards;
|
|
363
|
+
if (shards === undefined)
|
|
364
|
+
return undefined;
|
|
365
|
+
const source = boundShardSource(index, shards);
|
|
366
|
+
const absent = source.filter((attr) => record[attr] === undefined || record[attr] === null);
|
|
367
|
+
if (absent.length > 0) {
|
|
368
|
+
throw new ShardSourceError({
|
|
369
|
+
message: `[EDD-9100] Entity "${entityType}": index "${index.index}" is sharded, and its partition ` +
|
|
370
|
+
`key can't be composed without the shard source: ${absent.map((attr) => `"${attr}"`).join(", ")} ` +
|
|
371
|
+
`missing. A sharded index never composes an unsharded key, so nothing was written. ` +
|
|
372
|
+
`Include ${absent.length === 1 ? "it" : "them"} in the write.`,
|
|
373
|
+
});
|
|
232
374
|
}
|
|
233
|
-
|
|
234
|
-
|
|
375
|
+
return shardMarker(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count));
|
|
376
|
+
};
|
|
377
|
+
/**
|
|
378
|
+
* `index` as its unsharded layout: what a `previous: 1` migration reads, and the
|
|
379
|
+
* only layout rows under another setting's key text can be in. Reads only.
|
|
380
|
+
*/
|
|
381
|
+
export const unshardedView = (index) => {
|
|
382
|
+
if (index.shards === undefined)
|
|
383
|
+
return index;
|
|
384
|
+
const { shards: _shards, ...view } = index;
|
|
385
|
+
return view;
|
|
386
|
+
};
|
|
387
|
+
/**
|
|
388
|
+
* The partition key a stored row's values compose now, for `rekey` (#183): by the
|
|
389
|
+
* structural rule an update composes with, truncated included. `undefined` when
|
|
390
|
+
* they can't compose one: a hole, no leading composite, or the source missing.
|
|
391
|
+
*/
|
|
392
|
+
export const composeStoredPk = (schema, entityType, index, record) => {
|
|
393
|
+
const outcome = classifyHalf(index.pk.composite, record, "sparse", false);
|
|
394
|
+
if (outcome.kind !== "set")
|
|
395
|
+
return undefined;
|
|
396
|
+
const shards = index.shards;
|
|
397
|
+
if (shards !== undefined &&
|
|
398
|
+
!boundShardSource(index, shards).every((attr) => hasValue(record[attr]))) {
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
return outcome.length === index.pk.composite.length
|
|
402
|
+
? composePk(schema, entityType, index, record)
|
|
403
|
+
: composePkPrefixUpTo(schema, entityType, index, record, outcome.length);
|
|
404
|
+
};
|
|
405
|
+
/**
|
|
406
|
+
* The index key a row's values compose now, truncating a half whose trailing
|
|
407
|
+
* composites are absent as the structural rule does (`DESIGN.md §7`). `undefined`
|
|
408
|
+
* when a half can't compose (a hole, or no leading value) or the sort key is a
|
|
409
|
+
* binary Z-order address.
|
|
410
|
+
*/
|
|
411
|
+
export const tryComposeStructuralKeys = (schema, entityType, entityVersion, index, record) => {
|
|
412
|
+
if (isZOrderHalf(index.sk))
|
|
413
|
+
return undefined;
|
|
414
|
+
const pk = classifyHalf(index.pk.composite, record, "sparse", false);
|
|
415
|
+
const sk = classifyHalf(index.sk.composite, record, "sparse", false);
|
|
416
|
+
if (pk.kind !== "set" || sk.kind !== "set")
|
|
417
|
+
return undefined;
|
|
418
|
+
return {
|
|
419
|
+
pk: pk.length === index.pk.composite.length
|
|
420
|
+
? composePk(schema, entityType, index, record)
|
|
421
|
+
: composePkPrefixUpTo(schema, entityType, index, record, pk.length),
|
|
422
|
+
sk: sk.length === index.sk.composite.length
|
|
423
|
+
? composeSk(schema, entityType, entityVersion, index, record)
|
|
424
|
+
: composeSkPrefixUpTo(schema, entityType, entityVersion, index, record, sk.length),
|
|
425
|
+
};
|
|
426
|
+
};
|
|
427
|
+
/**
|
|
428
|
+
* Does stored partition key text lie in `index`'s current layout (#183): shard
|
|
429
|
+
* marker with this count, whatever shard? A row whose values can't compose its key
|
|
430
|
+
* can only be left alone when this holds.
|
|
431
|
+
*/
|
|
432
|
+
export const isCurrentShardLayout = (schema, entityType, index, stored) => index.shards !== undefined &&
|
|
433
|
+
stored.startsWith(composePkText(schema, entityType, index, [], [], `!${index.shards.count}.`));
|
|
434
|
+
const boundShardSource = (index, shards) => {
|
|
435
|
+
if (shards.source === undefined) {
|
|
436
|
+
throw new Error(`KeyComposer: sharded index "${index.index}" was never bound to an entity — Entity.make ` +
|
|
437
|
+
`binds a sharded index's source to the primary key composites or \`by\`.`);
|
|
438
|
+
}
|
|
439
|
+
return shards.source;
|
|
440
|
+
};
|
|
441
|
+
/**
|
|
442
|
+
* Do the pins in `record` name every attribute of the shard source? A pin is a
|
|
443
|
+
* partition key composite or part of the sort key's leading run of present values:
|
|
444
|
+
* what a key condition can select. A value elsewhere in `record` selects nothing,
|
|
445
|
+
* and reading one shard for it would lose the rows of the others.
|
|
446
|
+
*/
|
|
447
|
+
const pinsShardSource = (index, source, record) => {
|
|
448
|
+
const pins = new Set(index.pk.composite);
|
|
449
|
+
if (!isZOrderHalf(index.sk)) {
|
|
450
|
+
for (const attr of index.sk.composite) {
|
|
451
|
+
if (!hasValue(record[attr]))
|
|
452
|
+
break;
|
|
453
|
+
pins.add(attr);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
return source.every((attr) => pins.has(attr) && hasValue(record[attr]));
|
|
457
|
+
};
|
|
458
|
+
/**
|
|
459
|
+
* The partitions a query of `index` reads for the pinned composites in `record`,
|
|
460
|
+
* in merge order: the current layout's by shard number (one, when every attribute
|
|
461
|
+
* of the shard source is pinned, whether that source is `by` or the primary key),
|
|
462
|
+
* then the `previous` layout's, which are never pruned: the old source isn't
|
|
463
|
+
* recorded. Every read path uses this; {@link composePk} composes the one key a
|
|
464
|
+
* write stores.
|
|
465
|
+
*/
|
|
466
|
+
export const composeReadPartitions = (schema, entityType, index, record,
|
|
467
|
+
/** `false`: read every shard, whatever is pinned (a collection's members may differ). */
|
|
468
|
+
options) => {
|
|
469
|
+
const shards = index.shards;
|
|
470
|
+
if (shards === undefined) {
|
|
471
|
+
return { partitions: [composePk(schema, entityType, index, record)], fanOut: undefined };
|
|
472
|
+
}
|
|
473
|
+
const source = boundShardSource(index, shards);
|
|
474
|
+
const composites = extractKeyComposites(schema, index, index.pk.composite, record);
|
|
475
|
+
const partition = (count, shard) => composePkText(schema, entityType, index, composites, index.pk.composite, shardMarker(count, shard));
|
|
476
|
+
const layout = (count) => Array.from({ length: count }, (_, i) => partition(count, i));
|
|
477
|
+
const pruned = options?.prune !== false && pinsShardSource(index, source, record);
|
|
478
|
+
const current = pruned
|
|
479
|
+
? [
|
|
480
|
+
partition(shards.count, shardOf(source.map((attr) => serializeValue(record[attr])), shards.count)),
|
|
481
|
+
]
|
|
482
|
+
: layout(shards.count);
|
|
483
|
+
const unsharded = shards.previous === 1
|
|
484
|
+
? composePkText(schema, entityType, index, composites, index.pk.composite, undefined)
|
|
485
|
+
: undefined;
|
|
486
|
+
const previous = unsharded !== undefined
|
|
487
|
+
? [unsharded]
|
|
488
|
+
: shards.previous === undefined
|
|
489
|
+
? []
|
|
490
|
+
: layout(shards.previous);
|
|
491
|
+
return {
|
|
492
|
+
partitions: [...current, ...previous],
|
|
493
|
+
fanOut: {
|
|
494
|
+
count: shards.count,
|
|
495
|
+
source,
|
|
496
|
+
previous: shards.previous,
|
|
497
|
+
pruned,
|
|
498
|
+
everyPartition: pruned ? [...layout(shards.count), ...previous] : undefined,
|
|
499
|
+
},
|
|
500
|
+
};
|
|
235
501
|
};
|
|
236
502
|
/**
|
|
237
503
|
* Compose a sort key for an entity index.
|
|
@@ -242,7 +508,7 @@ export const composePk = (schema, entityType, index, record) => {
|
|
|
242
508
|
*/
|
|
243
509
|
export const composeSk = (schema, entityType, entityVersion, index, record) => {
|
|
244
510
|
assertStringHalf(index, "composeSk");
|
|
245
|
-
const composites =
|
|
511
|
+
const composites = extractKeyComposites(schema, index, index.sk.composite, record);
|
|
246
512
|
const names = [...index.sk.composite];
|
|
247
513
|
const collection = index.collection;
|
|
248
514
|
const collectionType = index.type ?? "isolated";
|
|
@@ -301,7 +567,7 @@ export const composeZOrderSk = (schema, index, record) => {
|
|
|
301
567
|
if (value === undefined || value === null) {
|
|
302
568
|
throw new Error(`Missing composite attribute "${part.field}" in record`);
|
|
303
569
|
}
|
|
304
|
-
return prefixSegment(
|
|
570
|
+
return prefixSegment(keyValueText(schema, value, casing), part.hash);
|
|
305
571
|
});
|
|
306
572
|
const levels = layout.dimensions.map((dim) => {
|
|
307
573
|
const value = record[dim.field];
|
|
@@ -353,6 +619,23 @@ export const tryComposeIndexKeys = (schema, entityType, entityVersion, index, re
|
|
|
353
619
|
return undefined;
|
|
354
620
|
return composeIndexKeys(schema, entityType, entityVersion, index, record);
|
|
355
621
|
};
|
|
622
|
+
/**
|
|
623
|
+
* The halves of a secondary index `record` holds every value of, for a write that leaves what it
|
|
624
|
+
* doesn't name as it's stored (an upsert). A half missing a value is left out, never truncated; a
|
|
625
|
+
* sharded index's partition half also needs what it hashes.
|
|
626
|
+
*/
|
|
627
|
+
export const composeKnownHalves = (schema, entityType, entityVersion, index, record) => {
|
|
628
|
+
const shardSource = index.shards === undefined ? [] : boundShardSource(index, index.shards);
|
|
629
|
+
const complete = (composite) => composite.every((attr) => hasValue(record[attr]));
|
|
630
|
+
return {
|
|
631
|
+
...(complete([...index.pk.composite, ...shardSource])
|
|
632
|
+
? { [index.pk.field]: composePk(schema, entityType, index, record) }
|
|
633
|
+
: {}),
|
|
634
|
+
...(complete(index.sk.composite)
|
|
635
|
+
? { [index.sk.field]: composeSkValue(schema, entityType, entityVersion, index, record) }
|
|
636
|
+
: {}),
|
|
637
|
+
};
|
|
638
|
+
};
|
|
356
639
|
/**
|
|
357
640
|
* Compose keys for all indexes of an entity.
|
|
358
641
|
* Returns a flat record of all key field -> value mappings.
|
|
@@ -384,19 +667,7 @@ export const composeAllKeys = (schema, entityType, entityVersion, indexes, recor
|
|
|
384
667
|
*/
|
|
385
668
|
const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
|
|
386
669
|
const slice = index.pk.composite.slice(0, stopBefore);
|
|
387
|
-
|
|
388
|
-
const collection = index.collection;
|
|
389
|
-
if (collection !== undefined) {
|
|
390
|
-
const collectionName = Array.isArray(collection) ? collection[0] : collection;
|
|
391
|
-
return composeCollectionKey(schema, collectionName, composites, {
|
|
392
|
-
casing: index.casing,
|
|
393
|
-
names: [...slice],
|
|
394
|
-
});
|
|
395
|
-
}
|
|
396
|
-
return composeKey(schema, entityType, composites, {
|
|
397
|
-
casing: index.casing,
|
|
398
|
-
names: [...slice],
|
|
399
|
-
});
|
|
670
|
+
return composePkText(schema, entityType, index, extractKeyComposites(schema, index, slice, record), slice, composedShardMarker(entityType, index, record));
|
|
400
671
|
};
|
|
401
672
|
/**
|
|
402
673
|
* Compose a sort key from the leading prefix `[sk_0, ..., sk_(stopBefore-1)]`
|
|
@@ -414,7 +685,7 @@ const composePkPrefixUpTo = (schema, entityType, index, record, stopBefore) => {
|
|
|
414
685
|
export const composeSkPrefixUpTo = (schema, entityType, entityVersion, index, record, stopBefore) => {
|
|
415
686
|
assertStringHalf(index, "composeSkPrefixUpTo");
|
|
416
687
|
const slice = index.sk.composite.slice(0, stopBefore);
|
|
417
|
-
const composites =
|
|
688
|
+
const composites = extractKeyComposites(schema, index, slice, record);
|
|
418
689
|
const collection = index.collection;
|
|
419
690
|
const collectionType = index.type ?? "isolated";
|
|
420
691
|
if (collection !== undefined) {
|
|
@@ -518,6 +789,223 @@ const classifyZOrderHalf = (fields, record, policy, halfHasRemoved) => {
|
|
|
518
789
|
return "drop";
|
|
519
790
|
return "noop";
|
|
520
791
|
};
|
|
792
|
+
const hasValue = (value) => value !== undefined && value !== null;
|
|
793
|
+
const FINE = { kind: "fine" };
|
|
794
|
+
const sameKeyValue = (a, b) => {
|
|
795
|
+
if (typeof a === "string" || typeof b === "string")
|
|
796
|
+
return a === b;
|
|
797
|
+
return a.length === b.length && a.every((byte, i) => byte === b[i]);
|
|
798
|
+
};
|
|
799
|
+
/** Is `stored` a leading run of `composites`' text, under any form? */
|
|
800
|
+
const isLeadingRun = (judging, index, half, composites, record, stored) => {
|
|
801
|
+
if (typeof stored !== "string")
|
|
802
|
+
return false;
|
|
803
|
+
for (const form of judging.forms) {
|
|
804
|
+
for (let length = 0; length < composites.length; length++) {
|
|
805
|
+
try {
|
|
806
|
+
const text = half === "pk"
|
|
807
|
+
? composePkPrefixUpTo(form.pk, judging.entityType, index, record, length)
|
|
808
|
+
: composeSkPrefixUpTo(form.sk, judging.entityType, judging.entityVersion, index, record, length);
|
|
809
|
+
if (text === stored)
|
|
810
|
+
return true;
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
// No text under this form: `NaN` under `escapeKeys: true`.
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return false;
|
|
818
|
+
};
|
|
819
|
+
/**
|
|
820
|
+
* Whether `stored` differs from what `record` composes only in the text of `attr`, the composite
|
|
821
|
+
* whose key may lag. An update that can't compose a half holding it leaves the key, so this is what
|
|
822
|
+
* a healthy row looks like, and comparing the whole key would rewrite it on every run after any
|
|
823
|
+
* write. Everything around the segment has to match exactly, and the segment has to be one segment.
|
|
824
|
+
* A Z-order address has no segments to read apart, so any address it holds will do.
|
|
825
|
+
*/
|
|
826
|
+
const differsOnlyInLaggingText = (judging, index, half, composites, record, stored, attr) => {
|
|
827
|
+
if (half === "sk" && isZOrderHalf(index.sk))
|
|
828
|
+
return true;
|
|
829
|
+
if (typeof stored !== "string")
|
|
830
|
+
return false;
|
|
831
|
+
const { schema, entityType, entityVersion } = judging;
|
|
832
|
+
const blank = { ...record, [attr]: "" };
|
|
833
|
+
const position = composites.indexOf(attr) + 1;
|
|
834
|
+
const head = half === "pk"
|
|
835
|
+
? composePkPrefixUpTo(schema, entityType, index, blank, position)
|
|
836
|
+
: composeSkPrefixUpTo(schema, entityType, entityVersion, index, blank, position);
|
|
837
|
+
const whole = half === "pk"
|
|
838
|
+
? composePk(schema, entityType, index, blank)
|
|
839
|
+
: composeSkValue(schema, entityType, entityVersion, index, blank);
|
|
840
|
+
if (typeof whole !== "string")
|
|
841
|
+
return false;
|
|
842
|
+
const tail = whole.slice(head.length);
|
|
843
|
+
if (stored.length <= head.length + tail.length)
|
|
844
|
+
return false;
|
|
845
|
+
if (!stored.startsWith(head) || !stored.endsWith(tail))
|
|
846
|
+
return false;
|
|
847
|
+
return !stored.slice(head.length, stored.length - tail.length).includes("#");
|
|
848
|
+
};
|
|
849
|
+
/**
|
|
850
|
+
* Judge one half of a stored row's index against what its values compose, for `rekey`'s report and
|
|
851
|
+
* `repairIndexKeys` (`rekey-repair.md`). Reads nothing and writes nothing. `stored` is what the
|
|
852
|
+
* half's attribute holds as read; `record` is the row's key form.
|
|
853
|
+
*
|
|
854
|
+
* A half with every composite on the row should hold what a `put` of them writes: the same
|
|
855
|
+
* composers, so a Z-order half is all or nothing and compares bytes, and a value within one
|
|
856
|
+
* quantization level is no difference. A half with one missing is the update path's business: under
|
|
857
|
+
* `preserve` it's left whatever it holds, which is what the policy promises; under `sparse` it holds
|
|
858
|
+
* what the structural rule composes (a trailing composite absent is a truncation, shape 3), or
|
|
859
|
+
* nothing. A half with no key whose index a `put` wouldn't have written whole has nothing missing.
|
|
860
|
+
*
|
|
861
|
+
* A half holding `updatedAt` is compared without that composite's text, so a key that only lags
|
|
862
|
+
* stays `fine` and a key that holds anything else is rewritten once, from the row's value, and is
|
|
863
|
+
* `fine` from then on, whatever later writes do to `updatedAt`.
|
|
864
|
+
*
|
|
865
|
+
* Not judged, so `fine`: values that compose no key (`NaN`, a Z-order value a dimension can't place,
|
|
866
|
+
* a shard it can't compute), which a `put` refuses too; and a sharded partition key that's stored,
|
|
867
|
+
* since `rekey` already rewrites or reports those.
|
|
868
|
+
*/
|
|
869
|
+
export const judgeIndexHalf = (judging, index, half, stored, record) => {
|
|
870
|
+
const { schema, entityType, entityVersion, primaryComposites, stamped, lagTolerated } = judging;
|
|
871
|
+
const composites = half === "pk" ? index.pk.composite : index.sk.composite;
|
|
872
|
+
if (half === "pk" && index.shards !== undefined && stored !== undefined)
|
|
873
|
+
return FINE;
|
|
874
|
+
const shardSource = index.shards === undefined ? [] : boundShardSource(index, index.shards);
|
|
875
|
+
const policy = resolveIndexPolicy(index.indexPolicy)[half];
|
|
876
|
+
try {
|
|
877
|
+
if (composites.every((attr) => hasValue(record[attr]))) {
|
|
878
|
+
const full = half === "pk"
|
|
879
|
+
? composePk(schema, entityType, index, record)
|
|
880
|
+
: composeSkValue(schema, entityType, entityVersion, index, record);
|
|
881
|
+
if (stored !== undefined) {
|
|
882
|
+
if (sameKeyValue(stored, full))
|
|
883
|
+
return FINE;
|
|
884
|
+
if (lagTolerated !== null &&
|
|
885
|
+
composites.includes(lagTolerated) &&
|
|
886
|
+
differsOnlyInLaggingText(judging, index, half, composites, record, stored, lagTolerated)) {
|
|
887
|
+
return FINE;
|
|
888
|
+
}
|
|
889
|
+
return {
|
|
890
|
+
kind: "set",
|
|
891
|
+
drift: isLeadingRun(judging, index, half, composites, record, stored)
|
|
892
|
+
? "truncated"
|
|
893
|
+
: "lagging",
|
|
894
|
+
value: full,
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
// `put` writes an index whole or not at all.
|
|
898
|
+
const wholeIndex = [...index.pk.composite, ...index.sk.composite, ...shardSource].every((attr) => hasValue(record[attr]));
|
|
899
|
+
if (!wholeIndex)
|
|
900
|
+
return FINE;
|
|
901
|
+
const outsidePrimary = new Set(composites.filter((attr) => !primaryComposites.has(attr) && !stamped.has(attr)));
|
|
902
|
+
if (policy === "sparse" && outsidePrimary.size >= 2)
|
|
903
|
+
return { kind: "ambiguous" };
|
|
904
|
+
return { kind: "set", drift: "missing", value: full };
|
|
905
|
+
}
|
|
906
|
+
if (policy === "preserve" || stored === undefined)
|
|
907
|
+
return FINE;
|
|
908
|
+
if (half === "sk" && isZOrderHalf(index.sk))
|
|
909
|
+
return { kind: "remove" };
|
|
910
|
+
const outcome = classifyHalf(composites, record, "sparse", false);
|
|
911
|
+
if (outcome.kind !== "set")
|
|
912
|
+
return { kind: "remove" };
|
|
913
|
+
const truncated = half === "pk"
|
|
914
|
+
? composePkPrefixUpTo(schema, entityType, index, record, outcome.length)
|
|
915
|
+
: composeSkPrefixUpTo(schema, entityType, entityVersion, index, record, outcome.length);
|
|
916
|
+
return sameKeyValue(stored, truncated)
|
|
917
|
+
? FINE
|
|
918
|
+
: { kind: "set", drift: "lagging", value: truncated };
|
|
919
|
+
}
|
|
920
|
+
catch {
|
|
921
|
+
return FINE;
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
/**
|
|
925
|
+
* The per-half gate's question for a half with composites: does this writer name
|
|
926
|
+
* none of them, while the half can't be recomposed from what it knows? Then the
|
|
927
|
+
* half belongs to some other writer, and its stored key stays as it is.
|
|
928
|
+
*/
|
|
929
|
+
const writerLeavesHalf = (composites, updatePayload, keyRecord) => composites.every((attr) => !(attr in updatePayload)) &&
|
|
930
|
+
composites.some((attr) => !hasValue(keyRecord[attr]));
|
|
931
|
+
/**
|
|
932
|
+
* Whether a write leaves a half holding a value it stamps itself (`DESIGN.md` §7, "Composites the
|
|
933
|
+
* library stamps"). Every update stamps it, so the stamp says nothing about who owns the half, and
|
|
934
|
+
* asking the skip-predicate would make every unrelated update "touch" it: under `sparse` that drops
|
|
935
|
+
* the row, the bug #183 stopped. Only the half's other composites count. All of them known: the
|
|
936
|
+
* half moves with the write. One unknown: the key lags until a write can compose it, under either
|
|
937
|
+
* policy. A composite the writer explicitly clears isn't left: that's the structural rule's.
|
|
938
|
+
*/
|
|
939
|
+
const writerLeavesStampedHalf = (composites, stamped, updatePayload, keyRecord) => {
|
|
940
|
+
const others = composites.filter((attr) => !(attr in stamped));
|
|
941
|
+
return (others.some((attr) => !hasValue(updatePayload[attr]) && !hasValue(keyRecord[attr])) &&
|
|
942
|
+
others.every((attr) => !(attr in updatePayload) || hasValue(updatePayload[attr])));
|
|
943
|
+
};
|
|
944
|
+
/**
|
|
945
|
+
* The PK half's outcome on a sharded index, from what {@link classifyHalf} says
|
|
946
|
+
* of its composites and what the update did to the shard source (design §5). On
|
|
947
|
+
* an unsharded index, that outcome as it is.
|
|
948
|
+
*
|
|
949
|
+
* A write that would leave the shard stale or need an unsharded key throws
|
|
950
|
+
* `[EDD-9100]`; a `by` attribute explicitly gone drops the entry, which writes no
|
|
951
|
+
* unsharded key; and an update that doesn't touch the source leaves the stored
|
|
952
|
+
* key alone.
|
|
953
|
+
*/
|
|
954
|
+
const shardedPkOutcome = (entityType, index, outcome, update) => {
|
|
955
|
+
const shards = index.shards;
|
|
956
|
+
if (shards === undefined)
|
|
957
|
+
return outcome;
|
|
958
|
+
const { merged, updatePayload, policy } = update;
|
|
959
|
+
const pkComposites = index.pk.composite;
|
|
960
|
+
const refuse = () => {
|
|
961
|
+
if (update.onMissing === "keep")
|
|
962
|
+
return { kind: "noop" };
|
|
963
|
+
const absent = boundShardSource(index, shards).filter((attr) => !hasValue(merged[attr]));
|
|
964
|
+
const missing = absent.length > 0 ? absent : pkComposites.filter((a) => !hasValue(merged[a]));
|
|
965
|
+
throw new ShardSourceError({
|
|
966
|
+
message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
|
|
967
|
+
`sharded by, and its partition key can't be composed without ` +
|
|
968
|
+
`${missing.map((attr) => `"${attr}"`).join(", ")}. The stored shard would go stale, so ` +
|
|
969
|
+
`nothing was written. Include ${missing.length === 1 ? "it" : "them"} in the update.`,
|
|
970
|
+
});
|
|
971
|
+
};
|
|
972
|
+
if (update.byRemoved)
|
|
973
|
+
return { kind: "drop" };
|
|
974
|
+
if (outcome.kind === "drop") {
|
|
975
|
+
const pkExplicitlyGone = update.pkHasRemoved ||
|
|
976
|
+
pkComposites.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
|
|
977
|
+
return update.byTouched && !pkExplicitlyGone ? refuse() : outcome;
|
|
978
|
+
}
|
|
979
|
+
if (outcome.kind === "noop")
|
|
980
|
+
return update.byTouched ? refuse() : outcome;
|
|
981
|
+
if (boundShardSource(index, shards).every((attr) => hasValue(merged[attr]))) {
|
|
982
|
+
// The shard follows `by`, and the sort key would stay at the old value: no pin
|
|
983
|
+
// could reach the row, since each searches the shard its own value hashes to and
|
|
984
|
+
// only the old value's text is stored. The update may name the value the row
|
|
985
|
+
// already holds, but nothing was read to tell.
|
|
986
|
+
if (update.byTouched && update.skKept) {
|
|
987
|
+
if (update.onMissing === "keep")
|
|
988
|
+
return { kind: "noop" };
|
|
989
|
+
const missing = index.sk.composite.filter((attr) => !hasValue(merged[attr]));
|
|
990
|
+
throw new ShardSourceError({
|
|
991
|
+
message: `[EDD-9100] Entity "${entityType}": this update changes what index "${index.index}" is ` +
|
|
992
|
+
`sharded by, and its sort key can't be composed without ` +
|
|
993
|
+
`${missing.map((attr) => `"${attr}"`).join(", ")}. The stored sort key would stay at ` +
|
|
994
|
+
`the old value in the new value's shard, where no query could find it, so nothing was ` +
|
|
995
|
+
`written. Include ${missing.length === 1 ? "it" : "them"} in the update, or .remove() ` +
|
|
996
|
+
`${missing.length === 1 ? "it" : "them"} to take the item out of the index.`,
|
|
997
|
+
});
|
|
998
|
+
}
|
|
999
|
+
return outcome;
|
|
1000
|
+
}
|
|
1001
|
+
if (update.byCleared && policy === "sparse")
|
|
1002
|
+
return { kind: "drop" };
|
|
1003
|
+
// The source is incomplete: an update changing the partition or part of `by`
|
|
1004
|
+
// can't compute the shard; any other leaves the stored key alone.
|
|
1005
|
+
return update.byTouched || pkComposites.some((attr) => hasValue(updatePayload[attr]))
|
|
1006
|
+
? refuse()
|
|
1007
|
+
: { kind: "noop" };
|
|
1008
|
+
};
|
|
521
1009
|
/**
|
|
522
1010
|
* Resolve the per-half policy for an index. Defaults each half to `"preserve"`
|
|
523
1011
|
* when omitted (or when `indexPolicy` is omitted entirely).
|
|
@@ -537,10 +1025,11 @@ const resolveIndexPolicy = (policy) => ({
|
|
|
537
1025
|
* protection: prevent writer A from clobbering keys for halves it doesn't
|
|
538
1026
|
* own when writer B does own them. The skip-predicate states that purpose
|
|
539
1027
|
* directly: skip iff multi-writer protection actually applies (the half has
|
|
540
|
-
* composites, no composite was explicitly removed,
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
* cannot be safely skipped, it is evaluated
|
|
1028
|
+
* composites, no composite was explicitly removed, none is in `updatePayload`,
|
|
1029
|
+
* and at least one is unknown to `keyRecord` — so this writer is genuinely not
|
|
1030
|
+
* claiming ownership of this half on this call, and can't recompose it to the
|
|
1031
|
+
* value it already holds). If the half cannot be safely skipped, it is evaluated
|
|
1032
|
+
* by the structural rule.
|
|
544
1033
|
*
|
|
545
1034
|
* Pre-v1.7.3 the predicate was inverted ("list cases for which to evaluate"
|
|
546
1035
|
* as a chain of `||` clauses) and had to enumerate every shape: payload
|
|
@@ -550,7 +1039,9 @@ const resolveIndexPolicy = (policy) => ({
|
|
|
550
1039
|
* PK-composites-only case (#43), v1.7.2 then missed the empty-composite-half
|
|
551
1040
|
* case (#46) because every `.some(...)` clause trivially returned `false`
|
|
552
1041
|
* for an empty composite array. The skip-predicate closes the entire class
|
|
553
|
-
* of degenerate-case bugs structurally.
|
|
1042
|
+
* of degenerate-case bugs structurally. Through v1.37 its `keyRecord` arm asked
|
|
1043
|
+
* whether *every* composite was absent, so one entity-PK composite woke a half
|
|
1044
|
+
* that mixes it with a mutable composite (#183: `DESIGN.md §7`, shape 10).
|
|
554
1045
|
*
|
|
555
1046
|
* **Two-way payload classification.**
|
|
556
1047
|
* - **present** (`attr: <value>` in payload, or inherited from `keyRecord`)
|
|
@@ -590,6 +1081,10 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
|
|
|
590
1081
|
const sets = {};
|
|
591
1082
|
const removes = [];
|
|
592
1083
|
const removedSet = options?.removedSet;
|
|
1084
|
+
const stamped = options?.stamped;
|
|
1085
|
+
const leavesHalf = (composites) => stamped !== undefined && composites.some((attr) => attr in stamped)
|
|
1086
|
+
? writerLeavesStampedHalf(composites, stamped, updatePayload, keyRecord)
|
|
1087
|
+
: writerLeavesHalf(composites, updatePayload, keyRecord);
|
|
593
1088
|
for (const [indexName, index] of Object.entries(indexes)) {
|
|
594
1089
|
if (indexName === "primary")
|
|
595
1090
|
continue;
|
|
@@ -607,24 +1102,34 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
|
|
|
607
1102
|
// skipping would just leave a missing key forever — closes #46),
|
|
608
1103
|
// - AND no composite of this half was explicitly removed (cascade
|
|
609
1104
|
// intent must always evaluate),
|
|
610
|
-
// - AND
|
|
611
|
-
//
|
|
612
|
-
//
|
|
613
|
-
//
|
|
614
|
-
// entity-PK composites are
|
|
1105
|
+
// - AND no composite is in `updatePayload` (this writer names none of
|
|
1106
|
+
// them, so it claims no ownership of this half — #41),
|
|
1107
|
+
// - AND some composite is unknown to `keyRecord` (so the half can't be
|
|
1108
|
+
// recomposed to the value it already has). Every composite known
|
|
1109
|
+
// means a SET the writer can't get wrong: entity-PK composites are
|
|
1110
|
+
// immutable, which keeps #43's PK-composites-only half composing on
|
|
1111
|
+
// every write. One known composite proves nothing: a half mixing an
|
|
1112
|
+
// entity-PK composite with a mutable one is not this writer's to
|
|
1113
|
+
// truncate or drop on an unrelated write (see `DESIGN.md §7`, shape 10).
|
|
615
1114
|
//
|
|
616
|
-
//
|
|
617
|
-
// touched-predicate `||`-chain extended with `composites.length === 0`:
|
|
618
|
-
// every fix the touched-predicate accumulated falls out of one of the
|
|
619
|
-
// skip-predicate's three structural conditions. See `DESIGN.md §7`.
|
|
1115
|
+
// See `DESIGN.md §7`.
|
|
620
1116
|
const pkHasRemoved = removedSet !== undefined && pkComposites.some((attr) => removedSet.has(attr));
|
|
621
1117
|
const skHasRemoved = removedSet !== undefined && skComposites.some((attr) => removedSet.has(attr));
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
const
|
|
626
|
-
|
|
627
|
-
|
|
1118
|
+
// A `by` attribute (#183) is a dependency of the PK half, when the writer
|
|
1119
|
+
// touches it: the shard follows its value. Its presence in `keyRecord` is no
|
|
1120
|
+
// evidence of a change. The retain path's holds the whole item.
|
|
1121
|
+
const by = index.shards?.by ?? [];
|
|
1122
|
+
const byTouched = by.some((attr) => hasValue(updatePayload[attr]));
|
|
1123
|
+
const byCleared = by.some((attr) => attr in updatePayload && !hasValue(updatePayload[attr]));
|
|
1124
|
+
const byRemoved = removedSet !== undefined && by.some((attr) => removedSet.has(attr));
|
|
1125
|
+
// An empty PK half is a constant prefix, unless `by` makes its marker vary.
|
|
1126
|
+
const skipPk = (pkComposites.length > 0
|
|
1127
|
+
? !pkHasRemoved && leavesHalf(pkComposites)
|
|
1128
|
+
: by.length > 0 && by.some((attr) => !hasValue(keyRecord[attr]))) &&
|
|
1129
|
+
!byTouched &&
|
|
1130
|
+
!byCleared &&
|
|
1131
|
+
!byRemoved;
|
|
1132
|
+
const skipSk = skComposites.length > 0 && !skHasRemoved && leavesHalf(skComposites);
|
|
628
1133
|
if (skipPk && skipSk)
|
|
629
1134
|
continue;
|
|
630
1135
|
// Build merged record for value extraction. Two-way classification: any
|
|
@@ -646,9 +1151,24 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
|
|
|
646
1151
|
delete merged[attr];
|
|
647
1152
|
}
|
|
648
1153
|
}
|
|
1154
|
+
Object.assign(merged, stamped);
|
|
649
1155
|
const policy = resolveIndexPolicy(index.indexPolicy);
|
|
1156
|
+
// A Z-order half is never a `by` source, so only a text half can disagree.
|
|
1157
|
+
const skKept = !skipSk &&
|
|
1158
|
+
!isZOrderHalf(index.sk) &&
|
|
1159
|
+
classifyHalf(skComposites, merged, policy.sk, skHasRemoved).kind === "noop";
|
|
650
1160
|
if (!skipPk) {
|
|
651
|
-
const pkOutcome = classifyHalf(pkComposites, merged, policy.pk, pkHasRemoved)
|
|
1161
|
+
const pkOutcome = shardedPkOutcome(entityType, index, classifyHalf(pkComposites, merged, policy.pk, pkHasRemoved), {
|
|
1162
|
+
merged,
|
|
1163
|
+
updatePayload,
|
|
1164
|
+
policy: policy.pk,
|
|
1165
|
+
pkHasRemoved,
|
|
1166
|
+
byTouched,
|
|
1167
|
+
byCleared,
|
|
1168
|
+
byRemoved,
|
|
1169
|
+
onMissing: options?.onMissingShardSource ?? "fail",
|
|
1170
|
+
skKept,
|
|
1171
|
+
});
|
|
652
1172
|
if (pkOutcome.kind === "drop") {
|
|
653
1173
|
removes.push(index.pk.field);
|
|
654
1174
|
}
|
|
@@ -683,7 +1203,21 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
|
|
|
683
1203
|
// noop — emit nothing for this half.
|
|
684
1204
|
}
|
|
685
1205
|
}
|
|
686
|
-
|
|
1206
|
+
// No part of the primary key is ever set or removed by an update, whatever the index
|
|
1207
|
+
// structure (`DESIGN.md §7`). A half stored in a table key attribute (a local index's
|
|
1208
|
+
// partition key, an inverted index, a sort key shared with the table) composes the
|
|
1209
|
+
// table's text from what an update can't change, so there is nothing to write; dropping
|
|
1210
|
+
// the entry takes only the other half. A half reads as dropped here only for a row an
|
|
1211
|
+
// earlier release's `.remove()` left without a composite, which a move from other key text
|
|
1212
|
+
// recomposes from: it keeps its key.
|
|
1213
|
+
const primary = indexes.primary;
|
|
1214
|
+
if (primary === undefined)
|
|
1215
|
+
return { sets, removes };
|
|
1216
|
+
const tableKey = new Set([primary.pk.field, primary.sk.field]);
|
|
1217
|
+
return {
|
|
1218
|
+
sets: Object.fromEntries(Object.entries(sets).filter(([field]) => !tableKey.has(field))),
|
|
1219
|
+
removes: removes.filter((field) => !tableKey.has(field)),
|
|
1220
|
+
};
|
|
687
1221
|
};
|
|
688
1222
|
// ---------------------------------------------------------------------------
|
|
689
1223
|
// Vector index partition composition
|
|
@@ -703,13 +1237,9 @@ export const composeGsiKeysForUpdatePolicyAware = (schema, entityType, entityVer
|
|
|
703
1237
|
* sparse index semantics leave it out of the index.
|
|
704
1238
|
*/
|
|
705
1239
|
export const tryComposeVectorPartition = (schema, entityType, index, record) => {
|
|
706
|
-
|
|
707
|
-
if (composites === undefined)
|
|
1240
|
+
if (tryExtractComposites(index.partition, record) === undefined)
|
|
708
1241
|
return undefined;
|
|
709
|
-
return
|
|
710
|
-
casing: index.casing,
|
|
711
|
-
names: [...index.partition],
|
|
712
|
-
});
|
|
1242
|
+
return composeVectorPartition(schema, entityType, index, record);
|
|
713
1243
|
};
|
|
714
1244
|
/**
|
|
715
1245
|
* Throwing variant of {@link tryComposeVectorPartition}. Used on the search
|
|
@@ -717,7 +1247,7 @@ export const tryComposeVectorPartition = (schema, entityType, index, record) =>
|
|
|
717
1247
|
* sparse-index outcome.
|
|
718
1248
|
*/
|
|
719
1249
|
export const composeVectorPartition = (schema, entityType, index, record) => {
|
|
720
|
-
const composites =
|
|
1250
|
+
const composites = extractKeyComposites(schema, index, index.partition, record);
|
|
721
1251
|
return composeKey(schema, entityType, composites, {
|
|
722
1252
|
casing: index.casing,
|
|
723
1253
|
names: [...index.partition],
|
|
@@ -778,6 +1308,204 @@ export const composeSortKeyBeginsWith = (schema, entityType, entityVersion, inde
|
|
|
778
1308
|
const complete = availableSkCount(index, record) === index.sk.composite.length;
|
|
779
1309
|
return complete ? prefix : `${prefix}${KEY_DELIMITER}`;
|
|
780
1310
|
};
|
|
1311
|
+
/**
|
|
1312
|
+
* Above every key below a complete sort key prefix: the delimiter is followed by
|
|
1313
|
+
* a composite's label, and no label reaches U+FFFF.
|
|
1314
|
+
*/
|
|
1315
|
+
export const SORT_KEY_MAX = "\uFFFF";
|
|
1316
|
+
/**
|
|
1317
|
+
* @internal The key spaces of an index's partition and sort keys ({@link KeySpace}), as {@link composePk} and
|
|
1318
|
+
* {@link composeSk} write them. Each walked composite's value is composed as U+FFFF, which no
|
|
1319
|
+
* casing or escaping changes and no label holds, and the text is cut there. The walk goes on past a
|
|
1320
|
+
* composite whose values `valuesOf` says can't hold the delimiter: its value ends where the next
|
|
1321
|
+
* label starts. It stops at the first that can (`"open"`): a partition key's values aren't
|
|
1322
|
+
* escaped, so text after one can always match another key's. Without `valuesOf`, at the first
|
|
1323
|
+
* composite. A composite limited to `values` is their key text under the schema's setting, or
|
|
1324
|
+
* with `everyForm` under every setting a row can have been written under (`escapeKeys` on, off,
|
|
1325
|
+
* and the 1.37 numeric text): the fixed text is the same under all of them.
|
|
1326
|
+
*/
|
|
1327
|
+
export const composeKeySpace = (schema, entityType, entityVersion, index, valuesOf = () => "open", options) => {
|
|
1328
|
+
const casing = index.casing ?? schema.casing;
|
|
1329
|
+
const forms = options?.everyForm === true
|
|
1330
|
+
? [
|
|
1331
|
+
{ ...schema, escapeKeys: true },
|
|
1332
|
+
{ ...schema, escapeKeys: false },
|
|
1333
|
+
{ ...schema, escapeKeys: false, numericKeyText: true },
|
|
1334
|
+
]
|
|
1335
|
+
: [schema];
|
|
1336
|
+
const valueText = (values) => {
|
|
1337
|
+
if (values === "text")
|
|
1338
|
+
return { kind: "text" };
|
|
1339
|
+
if (values === "number")
|
|
1340
|
+
return { kind: "number" };
|
|
1341
|
+
const texts = new Set();
|
|
1342
|
+
for (const value of values.values) {
|
|
1343
|
+
for (const form of forms) {
|
|
1344
|
+
try {
|
|
1345
|
+
// The composer cases the whole key again, which leaves cased text as it is.
|
|
1346
|
+
texts.add(applyCasing(keyValueText(form, value, casing), casing));
|
|
1347
|
+
}
|
|
1348
|
+
catch {
|
|
1349
|
+
// A value no key can hold (`NaN`) is no key's.
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
return { kind: "oneOf", texts: [...texts] };
|
|
1354
|
+
};
|
|
1355
|
+
const half = (composite, compose) => {
|
|
1356
|
+
const walked = [];
|
|
1357
|
+
const values = [];
|
|
1358
|
+
let open = false;
|
|
1359
|
+
for (const name of composite) {
|
|
1360
|
+
walked.push(name);
|
|
1361
|
+
const of = valuesOf(name);
|
|
1362
|
+
if (of === "open") {
|
|
1363
|
+
open = true;
|
|
1364
|
+
break;
|
|
1365
|
+
}
|
|
1366
|
+
values.push(valueText(of));
|
|
1367
|
+
}
|
|
1368
|
+
if (walked.length === 0)
|
|
1369
|
+
return { text: compose([], {}), after: [], values: [], open: false };
|
|
1370
|
+
const record = Object.create(null);
|
|
1371
|
+
for (const name of walked)
|
|
1372
|
+
record[name] = SORT_KEY_MAX;
|
|
1373
|
+
const [text = "", ...rest] = compose(walked, record).split(SORT_KEY_MAX);
|
|
1374
|
+
// The text after an open value isn't the key's: anything follows it.
|
|
1375
|
+
return { text, after: open ? rest.slice(0, -1) : rest, values, open };
|
|
1376
|
+
};
|
|
1377
|
+
return {
|
|
1378
|
+
pk: half(index.pk.composite, (composite, record) => composePk(schema, entityType, { ...index, pk: { ...index.pk, composite: [...composite] } }, record)),
|
|
1379
|
+
sk: half(index.sk.composite, (composite, record) => composeSk(schema, entityType, entityVersion, { ...index, sk: { ...index.sk, composite: [...composite] } }, record)),
|
|
1380
|
+
};
|
|
1381
|
+
};
|
|
1382
|
+
const ANY_CHARACTER = { chars: "", negated: true };
|
|
1383
|
+
const NOT_DELIMITER = { chars: KEY_DELIMITER, negated: true };
|
|
1384
|
+
/** The first character of a number's or a bigint's key text, under any setting. */
|
|
1385
|
+
const NUMBER_FIRST = { chars: "0123456789-:;", negated: false };
|
|
1386
|
+
/** Any other character of it: `NumericKey`'s, and 1.36's (`1e+21`, `Infinity`), in any casing. */
|
|
1387
|
+
const NUMBER_REST = { chars: "0123456789-+.:;)*eEiInNfFtTyY", negated: false };
|
|
1388
|
+
/** Whether some character is in both. */
|
|
1389
|
+
const classesMeet = (a, b) => {
|
|
1390
|
+
if (a.negated && b.negated)
|
|
1391
|
+
return true;
|
|
1392
|
+
if (!a.negated && !b.negated)
|
|
1393
|
+
return [...a.chars].some((char) => b.chars.includes(char));
|
|
1394
|
+
const [set, not] = a.negated ? [b, a] : [a, b];
|
|
1395
|
+
return [...set.chars].some((char) => !not.chars.includes(char));
|
|
1396
|
+
};
|
|
1397
|
+
/**
|
|
1398
|
+
* The keys of a {@link KeySpace} as an automaton: `edges[state]` are the moves on one character,
|
|
1399
|
+
* `empty[state]` those on none. It starts at state 0 and accepts at `accept`.
|
|
1400
|
+
*/
|
|
1401
|
+
const keyAutomaton = (space) => {
|
|
1402
|
+
const edges = [];
|
|
1403
|
+
const empty = [];
|
|
1404
|
+
const state = () => {
|
|
1405
|
+
edges.push([]);
|
|
1406
|
+
empty.push([]);
|
|
1407
|
+
return edges.length - 1;
|
|
1408
|
+
};
|
|
1409
|
+
let at = state();
|
|
1410
|
+
/** The characters of `text`, one by one, from `from`: the state after them. */
|
|
1411
|
+
const spell = (from, text) => {
|
|
1412
|
+
let to = from;
|
|
1413
|
+
for (const char of text) {
|
|
1414
|
+
const next = state();
|
|
1415
|
+
edges[to].push([{ chars: char, negated: false }, next]);
|
|
1416
|
+
to = next;
|
|
1417
|
+
}
|
|
1418
|
+
return to;
|
|
1419
|
+
};
|
|
1420
|
+
at = spell(at, space.text);
|
|
1421
|
+
space.after.forEach((text, i) => {
|
|
1422
|
+
const value = space.values?.[i] ?? { kind: "text" };
|
|
1423
|
+
const end = state();
|
|
1424
|
+
if (value.kind === "text") {
|
|
1425
|
+
const loop = state();
|
|
1426
|
+
empty[at].push(loop);
|
|
1427
|
+
edges[loop].push([NOT_DELIMITER, loop]);
|
|
1428
|
+
empty[loop].push(end);
|
|
1429
|
+
}
|
|
1430
|
+
else if (value.kind === "number") {
|
|
1431
|
+
const digits = state();
|
|
1432
|
+
edges[at].push([NUMBER_FIRST, digits]);
|
|
1433
|
+
edges[digits].push([NUMBER_REST, digits]);
|
|
1434
|
+
empty[digits].push(end);
|
|
1435
|
+
}
|
|
1436
|
+
else {
|
|
1437
|
+
for (const option of value.texts)
|
|
1438
|
+
empty[spell(at, option)].push(end);
|
|
1439
|
+
}
|
|
1440
|
+
at = spell(end, text);
|
|
1441
|
+
});
|
|
1442
|
+
if (space.open)
|
|
1443
|
+
edges[at].push([ANY_CHARACTER, at]);
|
|
1444
|
+
return { edges, empty, accept: at };
|
|
1445
|
+
};
|
|
1446
|
+
/**
|
|
1447
|
+
* @internal Whether a key of one {@link KeySpace} can be a key of the other. Each is literal text
|
|
1448
|
+
* with values between, each value what its {@link KeyValueText} allows, and an open space ends in
|
|
1449
|
+
* any text at all. The two are read character against character, together, until both can end.
|
|
1450
|
+
*/
|
|
1451
|
+
export const keySpacesMeet = (a, b) => {
|
|
1452
|
+
const x = keyAutomaton(a);
|
|
1453
|
+
const y = keyAutomaton(b);
|
|
1454
|
+
const width = y.edges.length;
|
|
1455
|
+
const seen = new Set();
|
|
1456
|
+
const queue = [];
|
|
1457
|
+
const visit = (i, j) => {
|
|
1458
|
+
const key = i * width + j;
|
|
1459
|
+
if (seen.has(key))
|
|
1460
|
+
return;
|
|
1461
|
+
seen.add(key);
|
|
1462
|
+
queue.push([i, j]);
|
|
1463
|
+
};
|
|
1464
|
+
visit(0, 0);
|
|
1465
|
+
for (let k = 0; k < queue.length; k++) {
|
|
1466
|
+
const [i, j] = queue[k];
|
|
1467
|
+
if (i === x.accept && j === y.accept)
|
|
1468
|
+
return true;
|
|
1469
|
+
for (const to of x.empty[i])
|
|
1470
|
+
visit(to, j);
|
|
1471
|
+
for (const to of y.empty[j])
|
|
1472
|
+
visit(i, to);
|
|
1473
|
+
for (const [left, toLeft] of x.edges[i]) {
|
|
1474
|
+
for (const [right, toRight] of y.edges[j]) {
|
|
1475
|
+
if (classesMeet(left, right))
|
|
1476
|
+
visit(toLeft, toRight);
|
|
1477
|
+
}
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
return false;
|
|
1481
|
+
};
|
|
1482
|
+
/**
|
|
1483
|
+
* The condition selecting a complete sort key prefix on a secondary index, with
|
|
1484
|
+
* `escapeKeys: true`: the key itself, where the structural rule truncates a row whose
|
|
1485
|
+
* trailing composites are absent (`DESIGN.md §7`), and every key below it. A longer sibling
|
|
1486
|
+
* value stays out: its text extends the prefix with a character above the delimiter (escaping
|
|
1487
|
+
* puts everything up to `%` out of reach of a value).
|
|
1488
|
+
*
|
|
1489
|
+
* With `escapeKeys` off that range would hold `new york` for `new`, so a pin sends 1.36's
|
|
1490
|
+
* `begins_with` on the prefix and the delimiter, and a row truncated at the prefix isn't among
|
|
1491
|
+
* what it reads, as in 1.36.
|
|
1492
|
+
*/
|
|
1493
|
+
export const pinCondition = (schema, prefix) => schema.escapeKeys === true
|
|
1494
|
+
? subtreeCondition(prefix)
|
|
1495
|
+
: { beginsWith: `${prefix}${KEY_DELIMITER}` };
|
|
1496
|
+
/** The range {@link pinCondition} sends with `escapeKeys: true`. */
|
|
1497
|
+
export const subtreeCondition = (prefix) => ({
|
|
1498
|
+
between: [prefix, `${prefix}${KEY_DELIMITER}${SORT_KEY_MAX}`],
|
|
1499
|
+
});
|
|
1500
|
+
/** The prefix a {@link subtreeCondition} selects; `undefined` for any other condition. */
|
|
1501
|
+
export const subtreePrefix = (condition) => {
|
|
1502
|
+
if (!("between" in condition))
|
|
1503
|
+
return undefined;
|
|
1504
|
+
const [lower, upper] = condition.between;
|
|
1505
|
+
return typeof lower === "string" && upper === `${lower}${KEY_DELIMITER}${SORT_KEY_MAX}`
|
|
1506
|
+
? lower
|
|
1507
|
+
: undefined;
|
|
1508
|
+
};
|
|
781
1509
|
/**
|
|
782
1510
|
* The sort key condition a query accessor sends for the leading SK composites
|
|
783
1511
|
* present in `record` (the caller has checked at least one is):
|
|
@@ -788,15 +1516,21 @@ export const composeSortKeyBeginsWith = (schema, entityType, entityVersion, inde
|
|
|
788
1516
|
* matching `"ab"`, and `seq: 3` matching 3.14 and 3.5, whose key text
|
|
789
1517
|
* extends 3's. On the primary index `=` also leaves out the item's history
|
|
790
1518
|
* rows, whose keys extend the current one.
|
|
791
|
-
* - **Partial prefix** —
|
|
792
|
-
*
|
|
1519
|
+
* - **Partial prefix, secondary index** — {@link pinCondition}: with `escapeKeys: true` a row
|
|
1520
|
+
* truncated at this prefix belongs to these pins, and `begins_with` on the
|
|
1521
|
+
* prefix and delimiter can't reach it (the key ends where the operand goes on).
|
|
1522
|
+
* - **Partial prefix, primary index** — `{ beginsWith }` on
|
|
1523
|
+
* {@link composeSortKeyBeginsWith}: the prefix and the delimiter, so it stops on
|
|
1524
|
+
* a segment boundary. Primary keys are never truncated.
|
|
793
1525
|
*/
|
|
794
1526
|
export const composeSortKeyCondition = (schema, entityType, entityVersion, index, record) => {
|
|
795
1527
|
assertStringHalf(index, "composeSortKeyCondition");
|
|
796
1528
|
const prefix = composeSortKeyPrefix(schema, entityType, entityVersion, index, record);
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
1529
|
+
if (availableSkCount(index, record) === index.sk.composite.length)
|
|
1530
|
+
return { eq: prefix };
|
|
1531
|
+
return index.index === undefined
|
|
1532
|
+
? { beginsWith: `${prefix}${KEY_DELIMITER}` }
|
|
1533
|
+
: pinCondition(schema, prefix);
|
|
800
1534
|
};
|
|
801
1535
|
/**
|
|
802
1536
|
* Compose a partial sort key prefix for query operations.
|
|
@@ -819,7 +1553,7 @@ export const composeSortKeyPrefix = (schema, entityType, entityVersion, index, r
|
|
|
819
1553
|
const value = record[attr];
|
|
820
1554
|
if (value === undefined || value === null)
|
|
821
1555
|
break;
|
|
822
|
-
available.push(
|
|
1556
|
+
available.push(keyValueText(schema, value, casing));
|
|
823
1557
|
names.push(attr);
|
|
824
1558
|
}
|
|
825
1559
|
const collection = index.collection;
|
|
@@ -845,7 +1579,7 @@ export const composeSortKeyPrefix = (schema, entityType, entityVersion, index, r
|
|
|
845
1579
|
// Event item SK format: `<currentSk>#e#<orderBy value's sort key text>`.
|
|
846
1580
|
// Casing is applied to both the `#e#` infix and the value for consistency with
|
|
847
1581
|
// the rest of the SK — matches how every other composite segment is cased —
|
|
848
|
-
// and the value is escaped as every
|
|
1582
|
+
// and the value is escaped as every key composite is (`keyText`).
|
|
849
1583
|
// ---------------------------------------------------------------------------
|
|
850
1584
|
const EVENT_SK_INFIX = "e";
|
|
851
1585
|
/**
|
|
@@ -853,8 +1587,22 @@ const EVENT_SK_INFIX = "e";
|
|
|
853
1587
|
*
|
|
854
1588
|
* Given `currentSk = "$app#v1#telemetry_1"` and `orderByValue = 42`, returns
|
|
855
1589
|
* `"$app#v1#telemetry_1#e#0000000000000042"` (with default lowercase casing).
|
|
1590
|
+
* `orderByValue` is what {@link eventOrderByValue} picks for the schema's setting.
|
|
1591
|
+
*/
|
|
1592
|
+
export const composeEventSk = (first, ...rest) => {
|
|
1593
|
+
if (typeof first === "string") {
|
|
1594
|
+
const casing = (rest[1] ?? "lowercase");
|
|
1595
|
+
return `${first}#${applyCasing(EVENT_SK_INFIX, casing)}#${escapeKeyText(serializeValue(rest[0]), casing)}`;
|
|
1596
|
+
}
|
|
1597
|
+
const casing = (rest[2] ?? first.casing);
|
|
1598
|
+
return `${rest[0]}#${applyCasing(EVENT_SK_INFIX, casing)}#${keyValueText(first, rest[1], casing)}`;
|
|
1599
|
+
};
|
|
1600
|
+
/**
|
|
1601
|
+
* The value of the `orderBy` attribute an event's sort key holds: its key form with numeric key
|
|
1602
|
+
* text, its encoded value (a `NumberFromString` `"10"` as the string `10`) with `escapeKeys` off,
|
|
1603
|
+
* as 1.36 composed it.
|
|
856
1604
|
*/
|
|
857
|
-
export const
|
|
1605
|
+
export const eventOrderByValue = (schema, encoded, keyForm) => (schema.escapeKeys === true || schema.numericKeyText === true ? keyForm : encoded);
|
|
858
1606
|
/**
|
|
859
1607
|
* Compose the prefix used to scope `.history()` queries to event items only.
|
|
860
1608
|
*
|