-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaterialize.ts
More file actions
361 lines (346 loc) · 9.38 KB
/
Copy pathmaterialize.ts
File metadata and controls
361 lines (346 loc) · 9.38 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
import { createHash, randomBytes } from "node:crypto";
import { constants, createReadStream, createWriteStream } from "node:fs";
import {
access,
lstat,
mkdir,
mkdtemp,
open,
rename,
rm,
writeFile,
} from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { pipeline } from "node:stream/promises";
import fg from "fast-glob";
import { MANIFEST_FILENAME } from "./manifest";
import { getCacheLayout, toPosixPath } from "./paths";
import { assertSafeSourceId } from "./source-id";
type MaterializeParams = {
sourceId: string;
repoDir: string;
cacheDir: string;
include: string[];
exclude?: string[];
maxBytes: number;
maxFiles?: number;
};
type ManifestStats = {
bytes: number;
fileCount: number;
manifestSha256: string;
};
const normalizePath = (value: string) => toPosixPath(value);
const STREAM_COPY_THRESHOLD_MB = Number(
process.env.DOCS_CACHE_STREAM_THRESHOLD_MB ?? "2",
);
const STREAM_COPY_THRESHOLD_BYTES =
Number.isFinite(STREAM_COPY_THRESHOLD_MB) && STREAM_COPY_THRESHOLD_MB > 0
? Math.floor(STREAM_COPY_THRESHOLD_MB * 1024 * 1024)
: 1024 * 1024;
const ensureSafePath = (root: string, target: string) => {
const resolvedRoot = path.resolve(root);
const resolvedTarget = path.resolve(target);
if (!resolvedTarget.startsWith(resolvedRoot + path.sep)) {
throw new Error(`Path traversal detected: ${target}`);
}
};
const openFileNoFollow = async (filePath: string) => {
try {
return await open(filePath, constants.O_RDONLY | constants.O_NOFOLLOW);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ELOOP") {
return null;
}
if (code === "EINVAL" || code === "ENOSYS" || code === "ENOTSUP") {
const stats = await lstat(filePath);
if (stats.isSymbolicLink()) {
return null;
}
return await open(filePath, "r");
}
throw error;
}
};
const acquireLock = async (lockPath: string, timeoutMs = 5000) => {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
try {
const fd = await open(lockPath, "wx");
return {
release: async () => {
await fd.close();
await rm(lockPath, { force: true });
},
};
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== "EEXIST") {
throw error;
}
await new Promise((resolve) => setTimeout(resolve, 100));
}
}
throw new Error(`Failed to acquire lock for ${lockPath}.`);
};
export const materializeSource = async (params: MaterializeParams) => {
assertSafeSourceId(params.sourceId, "sourceId");
const layout = getCacheLayout(params.cacheDir, params.sourceId);
await mkdir(params.cacheDir, { recursive: true });
const tempDir = await mkdtemp(
path.join(params.cacheDir, `.tmp-${params.sourceId}-`),
);
let manifestStreamRef: ReturnType<typeof createWriteStream> | null = null;
const closeManifestStream = async () => {
const stream = manifestStreamRef;
if (!stream || stream.closed || stream.destroyed) {
return;
}
await new Promise<void>((resolve) => {
const cleanup = () => {
stream.off("close", onClose);
stream.off("error", onError);
resolve();
};
const onClose = () => cleanup();
const onError = () => cleanup();
stream.once("close", onClose);
stream.once("error", onError);
try {
stream.end();
} catch {
cleanup();
}
});
};
try {
const files = await fg(params.include, {
cwd: params.repoDir,
ignore: [".git/**", ...(params.exclude ?? [])],
dot: true,
onlyFiles: true,
followSymbolicLinks: false,
});
const entries = files
.map((relativePath) => ({
relativePath,
normalized: normalizePath(relativePath),
}))
.sort((left, right) => left.normalized.localeCompare(right.normalized));
const targetDirs = new Set<string>();
for (const { relativePath } of entries) {
targetDirs.add(path.dirname(relativePath));
}
await Promise.all(
Array.from(targetDirs, (dir) =>
mkdir(path.join(tempDir, dir), { recursive: true }),
),
);
let bytes = 0;
let fileCount = 0;
const concurrency = Math.max(
1,
Math.min(
entries.length,
Math.max(8, Math.min(128, os.cpus().length * 8)),
),
);
const manifestPath = path.join(tempDir, MANIFEST_FILENAME);
const manifestStream = createWriteStream(manifestPath, {
encoding: "utf8",
});
manifestStreamRef = manifestStream;
const manifestHash = createHash("sha256");
const writeManifestLine = async (line: string) => {
return new Promise<void>((resolve, reject) => {
const onError = (error: Error) => {
manifestStream.off("drain", onDrain);
reject(error);
};
const onDrain = () => {
manifestStream.off("error", onError);
resolve();
};
manifestStream.once("error", onError);
if (!manifestStream.write(line)) {
manifestStream.once("drain", onDrain);
} else {
manifestStream.off("error", onError);
resolve();
}
});
};
for (let i = 0; i < entries.length; i += concurrency) {
const batch = entries.slice(i, i + concurrency);
const results = await Promise.all(
batch.map(async (entry) => {
const filePath = path.join(params.repoDir, entry.relativePath);
const fileHandle = await openFileNoFollow(filePath);
if (!fileHandle) {
return null;
}
try {
const stats = await fileHandle.stat();
if (!stats.isFile()) {
return null;
}
const targetPath = path.join(tempDir, entry.relativePath);
ensureSafePath(tempDir, targetPath);
if (stats.size >= STREAM_COPY_THRESHOLD_BYTES) {
const reader = createReadStream(filePath, {
fd: fileHandle.fd,
autoClose: false,
});
const writer = createWriteStream(targetPath);
await pipeline(reader, writer);
} else {
const data = await fileHandle.readFile();
await writeFile(targetPath, data);
}
return {
path: entry.normalized,
size: stats.size,
};
} finally {
await fileHandle.close();
}
}),
);
for (const entry of results) {
if (!entry) {
continue;
}
if (params.maxFiles !== undefined && fileCount + 1 > params.maxFiles) {
throw new Error(
`Materialized content exceeds maxFiles (${params.maxFiles}).`,
);
}
bytes += entry.size;
if (bytes > params.maxBytes) {
throw new Error(
`Materialized content exceeds maxBytes (${params.maxBytes}).`,
);
}
const line = `${JSON.stringify(entry)}\n`;
manifestHash.update(line);
await writeManifestLine(line);
fileCount += 1;
}
}
await new Promise<void>((resolve, reject) => {
manifestStream.end(() => resolve());
manifestStream.once("error", reject);
});
const manifestSha256 = manifestHash.digest("hex");
const exists = async (target: string) => {
try {
await access(target);
return true;
} catch {
return false;
}
};
const replaceDirectory = async (source: string, target: string) => {
const lock = await acquireLock(`${target}.lock`);
try {
const hasTarget = await exists(target);
const backupPath = `${target}.bak-${randomBytes(8).toString("hex")}`;
if (hasTarget) {
await rename(target, backupPath);
}
try {
await rename(source, target);
} catch (error) {
if (hasTarget) {
try {
await rename(backupPath, target);
} catch (restoreError) {
const restoreMsg =
restoreError instanceof Error
? restoreError.message
: String(restoreError);
process.stderr.write(
`Warning: Failed to restore backup: ${restoreMsg}\n`,
);
}
}
throw error;
}
if (hasTarget) {
await rm(backupPath, { recursive: true, force: true });
}
} finally {
await lock.release();
}
};
await replaceDirectory(tempDir, layout.sourceDir);
return {
bytes,
fileCount,
manifestSha256,
};
} catch (error) {
try {
await closeManifestStream();
} catch {
// Ignore cleanup errors to preserve root cause.
}
await rm(tempDir, { recursive: true, force: true });
throw error;
}
};
export const computeManifestHash = async (
params: MaterializeParams,
): Promise<ManifestStats> => {
assertSafeSourceId(params.sourceId, "sourceId");
const files = await fg(params.include, {
cwd: params.repoDir,
ignore: [".git/**", ...(params.exclude ?? [])],
dot: true,
onlyFiles: true,
followSymbolicLinks: false,
});
files.sort((left, right) =>
normalizePath(left).localeCompare(normalizePath(right)),
);
let bytes = 0;
let fileCount = 0;
const manifestHash = createHash("sha256");
for (const relativePath of files) {
const relNormalized = normalizePath(relativePath);
const filePath = path.join(params.repoDir, relativePath);
const fileHandle = await openFileNoFollow(filePath);
if (!fileHandle) {
continue;
}
try {
const stats = await fileHandle.stat();
if (!stats.isFile()) {
continue;
}
if (params.maxFiles !== undefined && fileCount + 1 > params.maxFiles) {
throw new Error(
`Materialized content exceeds maxFiles (${params.maxFiles}).`,
);
}
bytes += stats.size;
if (bytes > params.maxBytes) {
throw new Error(
`Materialized content exceeds maxBytes (${params.maxBytes}).`,
);
}
const line = `${JSON.stringify({ path: relNormalized, size: stats.size })}\n`;
manifestHash.update(line);
fileCount += 1;
} finally {
await fileHandle.close();
}
}
return {
bytes,
fileCount,
manifestSha256: manifestHash.digest("hex"),
};
};