forked from freshframework/fresh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkvfs.ts
More file actions
70 lines (54 loc) · 1.71 KB
/
Copy pathkvfs.ts
File metadata and controls
70 lines (54 loc) · 1.71 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
import { BUILD_ID } from "../server/build_id.ts";
const CHUNKSIZE = 65536;
const NAMESPACE = ["_frsh", "js", BUILD_ID];
// @ts-ignore as `Deno.openKv` is still unstable.
const kv = await Deno.openKv?.().catch((e) => {
console.error(e);
return null;
});
export const isSupported = () => kv != null;
export const getFile = async (file: string) => {
if (!isSupported()) return null;
const filepath = [...NAMESPACE, file];
const metadata = await kv!.get(filepath).catch(() => null);
if (metadata?.versionstamp == null) {
return null;
}
console.log(` 🚣 Streaming from Deno.KV ${file}`);
return new ReadableStream<Uint8Array>({
start: async (sink) => {
for await (const chunk of kv!.list({ prefix: filepath })) {
sink.enqueue(chunk.value as Uint8Array);
}
sink.close();
},
});
};
export const saveFile = async (file: string, content: Uint8Array) => {
if (!isSupported()) return null;
const filepath = [...NAMESPACE, file];
const metadata = await kv!.get(filepath);
// Current limitation: As of May 2023, KV Transactions only support a maximum of 10 operations.
let transaction = kv!.atomic();
let chunks = 0;
for (; chunks * CHUNKSIZE < content.length; chunks++) {
transaction = transaction.set(
[...filepath, chunks],
content.slice(chunks * CHUNKSIZE, (chunks + 1) * CHUNKSIZE),
);
}
const result = await transaction
.set(filepath, chunks)
.check(metadata)
.commit();
return result.ok;
};
export const housekeep = async () => {
if (!isSupported()) return null;
for await (
const item of kv!.list({ prefix: ["_frsh", "js"] })
) {
if (item.key.includes(BUILD_ID)) continue;
await kv!.delete(item.key);
}
};