Repository navigation
Expand file tree
/
Copy pathhost-file-store.ts
More file actions
127 lines (126 loc) · 4.16 KB
/
Copy pathhost-file-store.ts
File metadata and controls
127 lines (126 loc) · 4.16 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
import { createHash, randomUUID } from "node:crypto";
import { mkdir, open, link, unlink } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import {
createStorage,
storageConfigForProfile,
type StorageRuntime,
} from "../adapters/storage.js";
import { configuredFileStore } from "./file-store-config.js";
import { validateObjectKey } from "./storage-policy.js";
export function createHostFileStore(runtime: StorageRuntime) {
const backend = createStorage(runtime);
const sha = (bytes: Uint8Array) =>
createHash("sha256").update(bytes).digest("hex");
async function read(
storeId: string,
key: string,
size: number,
hash: string,
) {
validateObjectKey(key);
if (
!Number.isSafeInteger(size) ||
size < 0 ||
size > 32 * 1024 ** 2 ||
!/^[a-f0-9]{64}$/.test(hash)
)
throw new Error("Invalid stored object metadata");
const bytes = await backend.read(
storageConfigForProfile(runtime, { id: storeId }),
key,
size,
);
if (bytes.length !== size || sha(bytes) !== hash)
throw new Error("Stored object integrity check failed");
return bytes;
}
return {
currentId: runtime.configuration.currentId,
read,
/** Complete immutable bytes become visible atomically, before publishing database references. */
async putImmutable(key: string, data: Uint8Array, mime: string) {
validateObjectKey(key);
if (data.length > 32 * 1024 ** 2)
throw new Error("Stored object exceeds 32 MiB");
const bytes = Buffer.from(data);
const storeId = runtime.configuration.currentId;
const c = configuredFileStore(runtime.configuration, storeId);
let exists = false;
if (c.provider === "local") {
const root = storageConfigForProfile(runtime, { id: storeId }).root!;
const target = resolve(root, key);
await mkdir(dirname(target), { recursive: true, mode: 0o700 });
const temporary = `${target}.pending-${randomUUID()}`;
try {
const handle = await open(temporary, "wx", 0o600);
try {
await handle.writeFile(bytes);
await handle.sync();
} finally {
await handle.close();
}
try {
await link(temporary, target);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
exists = true;
}
} finally {
await unlink(temporary).catch(() => {});
}
} else {
const client = new S3Client({
region: c.region,
endpoint: c.endpoint,
forcePathStyle: c.forcePathStyle,
// The SDK adds credential metadata; keep deployment configuration immutable.
credentials: { ...c.credentials },
requestHandler: { connectionTimeout: 5000, requestTimeout: 30000 },
});
try {
await client.send(
new PutObjectCommand({
Bucket: c.bucket,
Key: key,
Body: bytes,
ContentType: mime,
ContentLength: bytes.length,
IfNoneMatch: "*",
ChecksumSHA256: createHash("sha256")
.update(bytes)
.digest("base64"),
}),
);
} catch (error) {
if (
(error as { $metadata?: { httpStatusCode?: number } }).$metadata
?.httpStatusCode !== 412
)
throw error;
exists = true;
} finally {
client.destroy();
}
}
const hash = sha(bytes);
// Verify both a pre-existing immutable object and newly completed uploads before committing references.
await read(storeId, key, bytes.length, hash);
return {
storeId,
key,
size: bytes.length,
sha256: hash,
existed: exists,
};
},
async remove(storeId: string, key: string) {
await backend.remove(
storageConfigForProfile(runtime, { id: storeId }),
key,
);
},
};
}
export type HostFileStore = ReturnType<typeof createHostFileStore>;