-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathblob_util.ts
More file actions
454 lines (433 loc) Β· 11.8 KB
/
blob_util.ts
File metadata and controls
454 lines (433 loc) Β· 11.8 KB
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
/**
* This is an internal module which contains some of the blob writing
* functionality and is not part of the public API of kv-toolbox.
*
* @module
*/
import type { BatchedAtomicOperation } from "./batched_atomic.ts";
import { keys } from "./keys.ts";
/**
* When a blob entry was originally a {@linkcode Blob} or {@linkcode File} a
* sub-entry will be set with the value of this meta data.
*/
export type BlobMeta = {
kind: "blob";
encrypted?: boolean;
type: string;
size?: number;
} | {
kind: "file";
encrypted?: boolean;
type: string;
lastModified: number;
name: string;
size?: number;
} | {
kind: "buffer";
encrypted?: boolean;
size?: number;
};
/**
* When there are parts of a blob, this key will be set as a sub-key of the blob
* blob entry, which will have additional sub-keys with the parts of the blob
* stored as {@linkcode Uint8Array} with a key of an incrementing number.
*/
export const BLOB_KEY = "__kv_toolbox_blob__";
/**
* If there is meta data associated with a blob entry, like for something that
* was originally a {@linkcode Blob} or {@linkcode File}, then this will be set
* as a sub-key of that blob key with a value of the meta data.
*/
export const BLOB_META_KEY = "__kv_toolbox_meta__";
export const CHUNK_SIZE = 63_000;
export const BATCH_SIZE = 10;
function isBlobMetaKey(key: Deno.KvKey): boolean {
return key.length > 2 && key[key.length - 1] === BLOB_META_KEY;
}
function isMaybeEntryBlobMeta(
entry: Deno.KvEntryMaybe<unknown>,
): entry is Deno.KvEntry<BlobMeta> {
return isBlobMetaKey(entry.key) && entry.value !== null;
}
function deleteKeys(
operation: BatchedAtomicOperation,
key: Deno.KvKey,
count: number,
length: number,
): BatchedAtomicOperation {
while (++count <= length) {
operation.delete([...key, BLOB_KEY, count]);
}
return operation;
}
function writeArrayBuffer(
operation: BatchedAtomicOperation,
key: Deno.KvKey,
blob: ArrayBufferLike | ArrayBufferView,
start = 0,
options?: { expireIn?: number },
): [count: number, operation: BatchedAtomicOperation] {
const buffer = new Uint8Array(ArrayBuffer.isView(blob) ? blob.buffer : blob);
let offset = 0;
let count = start;
while (buffer.byteLength > offset) {
count++;
const chunk = buffer.subarray(offset, offset + CHUNK_SIZE);
operation.set([...key, BLOB_KEY, count], chunk, options);
offset += CHUNK_SIZE;
}
return [count, operation];
}
function writeBlob(
operation: BatchedAtomicOperation,
key: Deno.KvKey,
blob: Blob,
options: { expireIn?: number; encrypted?: boolean } = {},
): Promise<[count: number, operation: BatchedAtomicOperation, size: number]> {
let meta: BlobMeta;
if (blob instanceof File) {
meta = {
kind: "file",
type: blob.type,
lastModified: blob.lastModified,
name: blob.name,
size: blob.size,
};
} else {
meta = {
kind: "blob",
type: blob.type,
size: blob.size,
};
}
if (options.encrypted) {
meta.encrypted = options.encrypted;
}
operation.set([...key, BLOB_META_KEY], meta, options);
return writeStream(operation, key, blob.stream(), options);
}
async function writeStream(
operation: BatchedAtomicOperation,
key: Deno.KvKey,
stream: ReadableStream<Uint8Array>,
options?: { expireIn?: number },
): Promise<[count: number, operation: BatchedAtomicOperation, size: number]> {
let start = 0;
let size = 0;
for await (const chunk of stream) {
size += chunk.byteLength;
[start, operation] = writeArrayBuffer(
operation,
key,
chunk,
start,
options,
);
}
return [start, operation, size];
}
export function asMeta(
kv: Deno.Kv,
key: Deno.KvKey,
options: { consistency?: Deno.KvConsistencyLevel | undefined },
): Promise<Deno.KvEntryMaybe<BlobMeta>> {
return kv.get<BlobMeta>([...key, BLOB_META_KEY], options);
}
export async function asUint8Array(
kv: Deno.Kv,
key: Deno.KvKey,
options: { consistency?: Deno.KvConsistencyLevel | undefined },
): Promise<Uint8Array | null> {
const prefix = [...key, BLOB_KEY];
const prefixLength = prefix.length;
const list = kv.list<Uint8Array>({ prefix }, {
...options,
batchSize: BATCH_SIZE,
});
let found = false;
let value = new Uint8Array();
let i = 1;
for await (const item of list) {
if (
item.value && item.key.length === prefixLength + 1 &&
item.key[prefixLength] === i
) {
i++;
found = true;
if (!(item.value instanceof Uint8Array)) {
throw new TypeError("KV value is not a Uint8Array.");
}
const v = new Uint8Array(value.length + item.value.length);
v.set(value, 0);
v.set(item.value, value.length);
value = v;
} else {
break;
}
}
return found ? value : null;
}
export async function asBlob(
kv: Deno.Kv,
key: Deno.KvKey,
options: { consistency?: Deno.KvConsistencyLevel | undefined },
maybeMeta: Deno.KvEntryMaybe<BlobMeta>,
): Promise<File | Blob | null> {
const prefix = [...key, BLOB_KEY];
const prefixLength = prefix.length;
const list = kv.list<Uint8Array>({ prefix }, {
...options,
batchSize: BATCH_SIZE,
});
let found = false;
const parts: Uint8Array[] = [];
let i = 1;
for await (const item of list) {
if (
item.value && item.key.length === prefixLength + 1 &&
item.key[prefixLength] === i
) {
i++;
found = true;
if (!(item.value instanceof Uint8Array)) {
throw new TypeError("KV value is not a Uint8Array.");
}
parts.push(item.value);
} else {
// encountered an unexpected key part, abort
break;
}
}
if (!found) {
return null;
}
if (maybeMeta.value) {
const { value } = maybeMeta;
if (value.kind === "file") {
return new File(parts, value.name, {
lastModified: value.lastModified,
type: value.type,
});
}
if (value.kind === "blob") {
return new Blob(parts, { type: value.type });
}
}
return new Blob(parts);
}
export function asStream(
kv: Deno.Kv,
key: Deno.KvKey,
options: { consistency?: Deno.KvConsistencyLevel | undefined },
) {
const prefix = [...key, BLOB_KEY];
const prefixLength = prefix.length;
let i = 1;
let list: Deno.KvListIterator<Uint8Array> | null = null;
return new ReadableStream({
type: "bytes",
autoAllocateChunkSize: CHUNK_SIZE,
async pull(controller) {
if (!list) {
return controller.error(new Error("Internal error - list not set"));
}
const next = await list.next();
if (
next.value && next.value.value &&
next.value.key.length === prefixLength + 1 &&
next.value.key[prefixLength] === i
) {
i++;
if (next.value.value instanceof Uint8Array) {
controller.enqueue(next.value.value);
} else {
controller.error(new TypeError("KV value is not a Uint8Array."));
}
} else {
controller.close();
}
if (next.done) {
controller.close();
}
},
start() {
list = kv.list<Uint8Array>({ prefix }, {
...options,
batchSize: BATCH_SIZE,
});
},
});
}
export async function setBlob(
operation: BatchedAtomicOperation,
key: Deno.KvKey,
blob: ArrayBufferLike | ArrayBufferView | ReadableStream<Uint8Array> | Blob,
itemCount: number,
options: { expireIn?: number; encrypted?: boolean } = {},
) {
let count;
let size;
if (blob instanceof ReadableStream) {
[count, operation, size] = await writeStream(operation, key, blob, options);
const meta: BlobMeta = { kind: "buffer", size };
if (options.encrypted) {
meta.encrypted = options.encrypted;
}
operation = operation.set([...key, BLOB_META_KEY], meta);
} else if (blob instanceof Blob) {
[count, operation] = await writeBlob(
operation,
key,
blob,
options,
);
} else if (
ArrayBuffer.isView(blob) || blob instanceof ArrayBuffer ||
blob instanceof SharedArrayBuffer
) {
[count, operation] = writeArrayBuffer(operation, key, blob, 0, options);
const meta: BlobMeta = { kind: "buffer", size: blob.byteLength };
if (options.encrypted) {
meta.encrypted = options.encrypted;
}
operation = operation.set([...key, BLOB_META_KEY], meta);
} else {
throw new TypeError(
"Blob must be typed array, array buffer, ReadableStream, Blob, or File",
);
}
operation = deleteKeys(operation, key, count, itemCount);
return operation;
}
export async function removeBlob(kv: Deno.Kv, key: Deno.KvKey) {
const parts = await keys(kv, { prefix: [...key, BLOB_KEY] });
if (parts.length) {
let op = kv.atomic().delete([...key, BLOB_META_KEY]);
for (const key of parts) {
op = op.delete(key);
}
await op.commit();
}
}
const AsyncIterator = Object.getPrototypeOf(async function* () {}).constructor;
export class BlobListIterator extends AsyncIterator implements
Deno.KvListIterator<
BlobMeta | Uint8Array | Blob | File | ReadableStream<Uint8Array>
> {
#iterator: Deno.KvListIterator<unknown>;
#count = 0;
#cursor?: string;
#kv: Deno.Kv;
#limit?: number;
#options: Deno.KvListOptions;
#valueKind: "meta" | "bytes" | "blob" | "stream";
get cursor(): string {
if (!this.#cursor) {
throw new Error("Cannot get cursor before first iteration");
}
return this.#cursor;
}
constructor(
kv: Deno.Kv,
prefix: Deno.KvListSelector,
options: Deno.KvListOptions = {},
valueKind: "meta" | "bytes" | "blob" | "stream",
) {
super();
this.#kv = kv;
this.#valueKind = valueKind;
const { limit, cursor, ...optionsRest } = options;
this.#options = optionsRest;
this.#iterator = kv.list<BlobMeta>(prefix, { cursor, ...optionsRest });
this.#limit = limit;
}
async next(): Promise<
IteratorResult<
Deno.KvEntry<
BlobMeta | Uint8Array | Blob | File | ReadableStream<Uint8Array>
>,
undefined
>
> {
for await (const entry of this.#iterator) {
if (isMaybeEntryBlobMeta(entry)) {
this.#count++;
if (this.#limit && this.#count > this.#limit) {
break;
}
this.#cursor = this.#iterator.cursor;
const key: Deno.KvKey = entry.key.slice(0, -1);
if (this.#valueKind === "meta") {
return {
value: {
value: entry.value as BlobMeta,
key,
versionstamp: entry.versionstamp,
},
done: false,
};
}
if (this.#valueKind === "bytes") {
const value = await asUint8Array(
this.#kv,
key,
this.#options,
);
if (!value) {
throw new Error("Unexpected null for blob value");
}
return {
value: {
value,
key,
versionstamp: entry.versionstamp,
},
done: false,
};
}
if (this.#valueKind === "blob") {
const value = await asBlob(
this.#kv,
key,
this.#options,
entry,
);
if (!value) {
throw new Error("Unexpected null for blob value");
}
return {
value: {
value,
key,
versionstamp: entry.versionstamp,
},
done: false,
};
}
if (this.#valueKind === "stream") {
const value = asStream(
this.#kv,
key,
this.#options,
);
return {
value: {
value,
key,
versionstamp: entry.versionstamp,
},
done: false,
};
}
}
}
return { value: undefined, done: true };
}
[Symbol.asyncIterator](): AsyncIterableIterator<
Deno.KvEntry<
BlobMeta | Uint8Array | Blob | File | ReadableStream<Uint8Array>
>
> {
return this;
}
}