-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.js
85 lines (67 loc) · 2.04 KB
/
cache.js
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
const s3 = require("./s3");
const { join: path_join } = require("path");
const fs = require("fs");
const { execFileSync } = require("child_process");
/**
* check if the cache exist
*/
const lookUp = async (key) => {
return { cacheHit: await s3.exist(key) };
};
/**
* push files to the cache
*
* for each path, create a zip file in a tmp dir
* then zip all of them
* and push the resulting file to s3 with the cache key as name
*/
const put = async (key, paths) => {
const tmpDir = fs.mkdtempSync("s3-cache");
try {
for (const path of paths) {
if (!fs.existsSync(path)) throw new Error(`file don't exist: ${path}`);
const pathKey = path.replace(/\//g, "_") + ".zip";
execFileSync("zip", [path_join(tmpDir, pathKey), "-r", path]);
}
execFileSync("zip", ["__payload.zip", "-r", "."], { cwd: tmpDir });
const payload = fs.readFileSync(path_join(tmpDir, "__payload.zip"));
await s3.put(key, payload);
return {
payloadSize:
(new Uint8Array(payload).length / 1024 / 1024).toFixed(3) + "Mb",
};
} finally {
fs.rmSync(tmpDir, { recursive: true });
}
};
/**
* get files from the cache
*/
const get = async (key, paths) => {
const payload = await s3.get(key);
if (payload) {
const tmpDir = fs.mkdtempSync("s3-cache");
try {
fs.writeFileSync(
path_join(tmpDir, "__payload.zip"),
Buffer.from(payload)
);
execFileSync("unzip", ["__payload.zip"], { cwd: tmpDir });
for (const filename of paths) {
const pathKey = filename.replace(/\//g, "_") + ".zip";
if (!fs.existsSync(path_join(tmpDir, pathKey)))
throw new Error(`file don't exist in the cache: ${filename}`);
execFileSync("unzip", ["-o", path_join(tmpDir, pathKey)]);
}
return {
cacheHit: true,
payloadSize:
(new Uint8Array(payload).length / 1024 / 1024).toFixed(3) + "Mb",
};
} finally {
fs.rmSync(tmpDir, { recursive: true });
}
}
return { cacheHit: false };
};
module.exports = { get, put, lookUp };