-
Notifications
You must be signed in to change notification settings - Fork 5
/
keys.ts
538 lines (524 loc) Β· 13.7 KB
/
keys.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/**
* APIs for dealing with Deno KV keys.
*
* # equals()
*
* {@linkcode equals} compares if two {@linkcode Deno.KvKey}s are equal. Because
* key parts can be an {@linkcode Uint8Array} they need to be compared deeply
* in a way that avoids security exploits.
*
* **Example**
*
* ```ts
* import { equals } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const keyA = ["a", "b"];
* const keyB = ["a", "b"];
* if (equals(keyA, keyB)) {
* console.log("keys match");
* }
* ```
*
* # keys()
*
* {@linkcode keys} is like Deno KV `.list()` except instead of returning an
* async iterator of entries, it return an array of {@linkcode Deno.KvKey}s.
*
* # partEquals()
*
* {@linkcode partEquals} compares if two {@linkcode Deno.KvKeyPart}s are equal.
* Because key parts can be an {@linkcode Uint8Array} they need to be compared
* deeply in a way that avoids security exploits.
*
* **Example**
*
* ```ts
* import { partEquals } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const keyA = ["a", "b"];
* const keyB = ["a", "b"];
* if (partEquals(keyA[0], keyB[0])) {
* console.log("keys match");
* }
* ```
*
* # startsWith()
*
* {@linkcode startsWith} determines if the `key` starts with the `prefix`
* provided, returning `true` if does, otherwise `false`.
*
* **Example**
*
* ```ts
* import { startsWith } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const key = ["a", "b"];
* const prefix = ["a"];
* if (equals(key, prefix)) {
* console.log("key starts with prefix");
* }
* ```
*
* # tree()
*
* {@linkcode tree} resolves with all keys (or keys that match the optional
* `prefix`) organized into a tree structure.
*
* **Example**
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `tree()`:
*
* ```ts
* import { unique } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await tree(kv, ["a"]));
* // {
* // prefix: ["a"],
* // children: [
* // {
* // part: "b",
* // hasValue: true,
* // children: [{ part: "c", hasValue: true }]
* // }, {
* // part: "d",
* // children: [
* // { part: "e", hasValue: true },
* // { part: "f", hasValue: true }
* // ]
* // }
* // ]
* // }
* await kv.close();
* ```
*
* # unique()
*
* {@linkcode unique} resolves with an array of unique sub keys/prefixes for the
* provided prefix. This is useful when storing keys and values in a
* hierarchical/tree view, where you are retrieving a list and you want to know
* all the unique _descendants_ of a key in order to be able to enumerate them.
*
* **Example**
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `unique()`:
*
* ```ts
* import { unique } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await unique(kv, ["a"]));
* // ["a", "b"]
* // ["a", "d"]
* await kv.close();
* ```
*
* # uniqueCount()
*
* {@linkcode uniqueCount} resolves with an array of values which contain the
* unique sub keys/prefixes for the provided prefix along with a count of how
* many keys there are. This is useful when storing keys and values in a
* hierarchical/tree view, where you are retrieving a list and you want to know
* all the unique _descendants_ of a key (and the count of keys that match that
* prefix) in order to be able to enumerate them or provide information about
* them.
*
* @module
*/
import { timingSafeEqual } from "jsr:@std/crypto@0.224/timing-safe-equal";
import { BLOB_KEY, BLOB_META_KEY } from "./blob_util.ts";
function addIfUnique(set: Set<Deno.KvKeyPart>, item: Uint8Array) {
for (const i of set) {
if (ArrayBuffer.isView(i) && timingSafeEqual(i, item)) {
return;
}
}
set.add(item);
}
function addOrIncrement(
map: Map<Deno.KvKeyPart, { count: number; isBlob?: boolean }>,
item: Uint8Array,
next: Deno.KvKeyPart | undefined,
) {
let count = 0;
let isBlob = false;
if (next) {
if (next === BLOB_KEY) {
isBlob = true;
} else if (next !== BLOB_META_KEY) {
count = 1;
}
}
for (const [k, v] of map) {
if (ArrayBuffer.isView(k) && timingSafeEqual(k, item)) {
if (isBlob) {
v.isBlob = true;
}
v.count = count;
return;
}
}
map.set(item, isBlob ? { count, isBlob } : { count });
}
/** Determines if one {@linkcode Deno.KvKeyPart} equals another. This is more
* focused than just comparison as it compares `Uint8Array` parts in a way that
* avoids potential code exploits.
*
* @example
*
* ```ts
* import { partEquals } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const keyA = ["a", "b"];
* const keyB = ["a", "b"];
* if (partEquals(keyA[0], keyB[0])) {
* console.log("keys match");
* }
* ```
*/
export function partEquals(a: Deno.KvKeyPart, b: Deno.KvKeyPart): boolean {
if (ArrayBuffer.isView(a)) {
if (!ArrayBuffer.isView(b)) {
return false;
}
if (!timingSafeEqual(a, b)) {
return false;
}
} else if (a !== b) {
return false;
}
return true;
}
/** Determines if one {@linkcode Deno.KvKey} equals another. This is more
* focused than a deeply equals comparison and compares key parts that are
* `Uint8Array` in a way that avoids potential code exploits.
*
* @example
*
* ```ts
* import { equals } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const keyA = ["a", "b"];
* const keyB = ["a", "b"];
* if (equals(keyA, keyB)) {
* console.log("keys match");
* }
* ```
*/
export function equals(a: Deno.KvKey, b: Deno.KvKey): boolean {
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; i++) {
const partA = a[i];
const partB = b[i];
if (!partEquals(partA, partB)) {
return false;
}
}
return true;
}
/** Determines if one {@linkcode Deno.KvKey} matches the prefix of another.
*
* @example
*
* ```ts
* import { startsWith } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const key = ["a", "b"];
* const prefix = ["a"];
* if (equals(key, prefix)) {
* console.log("key starts with prefix");
* }
* ```
*/
export function startsWith(key: Deno.KvKey, prefix: Deno.KvKey): boolean {
if (prefix.length > key.length) {
return false;
}
return equals(prefix, key.slice(0, prefix.length));
}
/** Return an array of keys that match the `selector` in the target `kv`
* store.
*
* @example
*
* ```ts
* import { keys } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await keys(kv, { prefix: ["hello"] }));
* await kv.close();
* ```
*/
export async function keys(
kv: Deno.Kv,
selector: Deno.KvListSelector,
options?: Deno.KvListOptions,
): Promise<Deno.KvKey[]> {
const list = kv.list(selector, options);
const keys: Deno.KvKey[] = [];
for await (const { key } of list) {
keys.push(key);
}
return keys;
}
/** Resolves with an array of unique sub keys/prefixes for the provided prefix.
*
* This is useful when storing keys and values in a hierarchical/tree view,
* where you are retrieving a list and you want to know all the unique
* _descendants_ of a key in order to be able to enumerate them.
*
* @example
*
* The following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* The following results when using `unique()`:
*
* ```ts
* import { unique } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await unique(kv, ["a"]));
* // ["a", "b"]
* // ["a", "d"]
* await kv.close();
* ```
*
* If you omit a `prefix`, all unique root keys are resolved.
*/
export async function unique(
kv: Deno.Kv,
prefix: Deno.KvKey = [],
options?: Deno.KvListOptions,
): Promise<Deno.KvKey[]> {
const list = kv.list({ prefix }, options);
const prefixLength = prefix.length;
const prefixes = new Set<Deno.KvKeyPart>();
for await (const { key } of list) {
if (key.length <= prefixLength) {
throw new TypeError(`Unexpected key length of ${key.length}.`);
}
const part = key[prefixLength];
if (part === BLOB_KEY || part === BLOB_META_KEY) {
continue;
}
if (ArrayBuffer.isView(part)) {
addIfUnique(prefixes, part);
} else {
prefixes.add(part);
}
}
return [...prefixes].map((part) => [...prefix, part]);
}
/** Elements of an array that gets resolved when calling
* {@linkcode uniqueCount}. */
export interface UniqueCountElement {
/** The key of the element. */
key: Deno.KvKey;
/** The number of sub-keys the key has. */
count: number;
/** Indicates if the value of the key is a kv-toolbox blob value. */
isBlob?: boolean;
}
/** Resolves with an array of unique sub keys/prefixes for the provided prefix
* along with the number of sub keys that match that prefix. The `count`
* represents the number of sub keys, a value of `0` indicates that only the
* exact key exists with no sub keys.
*
* This is useful when storing keys and values in a hierarchical/tree view,
* where you are retrieving a list including counts and you want to know all the
* unique _descendants_ of a key in order to be able to enumerate them.
*
* If you omit a `prefix`, all unique root keys are resolved.
*
* @example
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `uniqueCount()`:
*
* ```ts
* import { uniqueCount } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await uniqueCount(kv, ["a"]));
* // { key: ["a", "b"], count: 1 }
* // { key: ["a", "d"], count: 2 }
* await kv.close();
* ```
*/
export async function uniqueCount(
kv: Deno.Kv,
prefix: Deno.KvKey = [],
options?: Deno.KvListOptions,
): Promise<UniqueCountElement[]> {
const list = kv.list({ prefix }, options);
const prefixLength = prefix.length;
const prefixCounts = new Map<
Deno.KvKeyPart,
{ count: number; isBlob?: boolean }
>();
for await (const { key } of list) {
if (key.length <= prefixLength) {
throw new TypeError(`Unexpected key length of ${key.length}.`);
}
const part = key[prefixLength];
if (part === BLOB_KEY || part === BLOB_META_KEY) {
continue;
}
const next = key[prefixLength + 1];
if (ArrayBuffer.isView(part)) {
addOrIncrement(prefixCounts, part, next);
} else {
if (!prefixCounts.has(part)) {
prefixCounts.set(part, { count: 0 });
}
if (next) {
const count = prefixCounts.get(part)!;
if (next === BLOB_KEY) {
count.isBlob = true;
} else if (next !== BLOB_META_KEY) {
count.count++;
}
}
}
}
return [...prefixCounts].map(([part, count]) => ({
key: [...prefix, part],
...count,
}));
}
/** A node of a query of a Deno KV store, providing the key part and any
* children. */
interface KeyTreeNode {
/** The unique {@linkcode Deno.KvKeyPart} that represents the node. */
part: Deno.KvKeyPart;
/** Indicates if the key represented by the node has a value. This property
* is only present if `true`. */
hasValue?: true;
/** An array of children nodes, if any, associated with the key part. */
children?: KeyTreeNode[];
}
/** The root node of a key query of the Deno KV store where the keys are
* organized into a tree structure. */
export interface KeyTree {
/** The prefix, if any, of the tree structure. If there is no prefix, then
* this is the root of the Deno KV store. */
prefix?: Deno.KvKey;
/** An array of children nodes, if any, associated with the root of the
* query. */
children?: KeyTreeNode[];
}
/** Query a Deno KV store for keys and resolve with any matching keys
* organized into a tree structure.
*
* The root of the tree will be either the root of Deno KV store or if a prefix
* is supplied, keys that match the prefix. Each child node indicates if it
* also has a value and any children of that node.
*
* @example
*
* If you had the following keys stored in a datastore:
*
* ```ts
* ["a", "b"]
* ["a", "b", "c"]
* ["a", "d", "e"]
* ["a", "d", "f"]
* ```
*
* And you would get the following results when using `tree()`:
*
* ```ts
* import { unique } from "jsr:@kitsonk/kv-toolbox/keys";
*
* const kv = await Deno.openKv();
* console.log(await tree(kv, ["a"]));
* // {
* // prefix: ["a"],
* // children: [
* // {
* // part: "b",
* // hasValue: true,
* // children: [{ part: "c", hasValue: true }]
* // }, {
* // part: "d",
* // children: [
* // { part: "e", hasValue: true },
* // { part: "f", hasValue: true }
* // ]
* // }
* // ]
* // }
* await kv.close();
* ```
*/
export async function tree(
kv: Deno.Kv,
prefix: Deno.KvKey = [],
options?: Deno.KvListOptions,
): Promise<KeyTree> {
const root: KeyTree = prefix.length ? { prefix: [...prefix] } : {};
const prefixLength = prefix.length;
const list = kv.list({ prefix }, options);
for await (const { key } of list) {
if (!root.children) {
root.children = [];
}
const suffix: Deno.KvKey = key.slice(prefixLength);
let children = root.children;
let node: KeyTreeNode | undefined;
for (const part of suffix) {
if (node) {
if (!node.children) {
node.children = [];
}
children = node.children;
}
const child = children.find(({ part: p }) => partEquals(part, p));
if (child) {
node = child;
} else {
node = { part };
children.push(node);
}
}
if (node) {
node.hasValue = true;
}
}
return root;
}