-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
cache.ts
273 lines (245 loc) · 7.81 KB
/
cache.ts
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
import { workspaceRoot } from '../utils/workspace-root';
import {
copy,
lstat,
mkdir,
mkdirSync,
pathExists,
readFile,
remove,
writeFile,
} from 'fs-extra';
import { dirname, join, resolve } from 'path';
import { DefaultTasksRunnerOptions } from './default-tasks-runner';
import { execFile, spawn } from 'child_process';
import { cacheDir } from '../utils/cache-directory';
import { platform } from 'os';
import { Task } from '../config/task-graph';
import * as fastGlob from 'fast-glob';
export type CachedResult = {
terminalOutput: string;
outputsPath: string;
code: number;
remote: boolean;
};
export type TaskWithCachedResult = { task: Task; cachedResult: CachedResult };
export class Cache {
root = workspaceRoot;
cachePath = this.createCacheDir();
terminalOutputsDir = this.createTerminalOutputsDir();
useFsExtraToCopyAndRemove = platform() === 'win32';
constructor(private readonly options: DefaultTasksRunnerOptions) {}
removeOldCacheRecords() {
/**
* Even though spawning a process is fast, we don't want to do it every time
* the user runs a command. Instead, we want to do it once in a while.
*/
const shouldSpawnProcess = Math.floor(Math.random() * 50) === 1;
if (shouldSpawnProcess) {
const scriptPath = require.resolve('./remove-old-cache-records.js');
try {
const p = spawn('node', [scriptPath, `"${this.cachePath}"`], {
stdio: 'ignore',
detached: true,
});
p.unref();
} catch (e) {
console.log(`Unable to start remove-old-cache-records script:`);
console.log(e.message);
}
}
}
async get(task: Task): Promise<CachedResult | null> {
const res = await this.getFromLocalDir(task);
if (res) {
return { ...res, remote: false };
} else if (this.options.remoteCache) {
// didn't find it locally but we have a remote cache
// attempt remote cache
await this.options.remoteCache.retrieve(task.hash, this.cachePath);
// try again from local cache
const res2 = await this.getFromLocalDir(task);
return res2 ? { ...res2, remote: true } : null;
} else {
return null;
}
}
async put(
task: Task,
terminalOutput: string | null,
outputs: string[],
code: number
) {
return this.tryAndRetry(async () => {
const td = join(this.cachePath, task.hash);
const tdCommit = join(this.cachePath, `${task.hash}.commit`);
// might be left overs from partially-completed cache invocations
await remove(tdCommit);
await this.remove(td);
await mkdir(td);
await writeFile(
join(td, 'terminalOutput'),
terminalOutput ?? 'no terminal output'
);
await mkdir(join(td, 'outputs'));
const expandedOutputs = await this.expandOutputsInWorkspace(outputs);
await Promise.all(
expandedOutputs.map(async (f) => {
const src = join(this.root, f);
if (await pathExists(src)) {
const isFile = (await lstat(src)).isFile();
const cached = join(td, 'outputs', f);
const directory = isFile ? dirname(cached) : cached;
await mkdir(directory, { recursive: true });
await this.copy(src, cached);
}
})
);
// we need this file to account for partial writes to the cache folder.
// creating this file is atomic, whereas creating a folder is not.
// so if the process gets terminated while we are copying stuff into cache,
// the cache entry won't be used.
await writeFile(join(td, 'code'), code.toString());
await writeFile(tdCommit, 'true');
if (this.options.remoteCache) {
await this.options.remoteCache.store(task.hash, this.cachePath);
}
if (terminalOutput) {
const outputPath = this.temporaryOutputPath(task);
await writeFile(outputPath, terminalOutput);
}
});
}
async copyFilesFromCache(
hash: string,
cachedResult: CachedResult,
outputs: string[]
) {
return this.tryAndRetry(async () => {
const expandedOutputs = await this.expandOutputsInCache(
outputs,
cachedResult
);
await Promise.all(
expandedOutputs.map(async (f) => {
const cached = join(cachedResult.outputsPath, f);
if (await pathExists(cached)) {
const isFile = (await lstat(cached)).isFile();
const src = join(this.root, f);
await this.remove(src);
// Ensure parent directory is created if src is a file
const directory = isFile ? resolve(src, '..') : src;
await mkdir(directory, { recursive: true });
await this.copy(cached, src);
}
})
);
});
}
temporaryOutputPath(task: Task) {
return join(this.terminalOutputsDir, task.hash);
}
private async expandOutputsInWorkspace(outputs: string[]) {
return this._expandOutputs(outputs, workspaceRoot);
}
private async expandOutputsInCache(
outputs: string[],
cachedResult: CachedResult
) {
return this._expandOutputs(outputs, cachedResult.outputsPath);
}
private async _expandOutputs(outputs: string[], cwd: string) {
return (
await Promise.all(
outputs.map(async (entry) => {
if (await pathExists(join(cwd, entry))) {
return entry;
}
return fastGlob(entry, { cwd, dot: true });
})
)
).flat();
}
private async copy(src: string, destination: string): Promise<void> {
// 'cp -a /path/dir/ dest/' operates differently to 'cp -a /path/dir dest/'
// --> which means actual build works but subsequent populate from cache (using cp -a) does not
// --> the fix is to remove trailing slashes to ensure consistent & expected behaviour
src = src.replace(/[\/\\]$/, '');
if (this.useFsExtraToCopyAndRemove) {
return copy(src, destination);
}
return new Promise((res, rej) => {
execFile('cp', ['-a', src, dirname(destination)], (error) => {
if (!error) {
res();
} else {
this.useFsExtraToCopyAndRemove = true;
copy(src, destination).then(res, rej);
}
});
});
}
private async remove(path: string): Promise<void> {
if (this.useFsExtraToCopyAndRemove) {
return remove(path);
}
return new Promise<void>((res, rej) => {
execFile('rm', ['-rf', path], (error) => {
if (!error) {
res();
} else {
this.useFsExtraToCopyAndRemove = true;
remove(path).then(res, rej);
}
});
});
}
private async getFromLocalDir(task: Task) {
const tdCommit = join(this.cachePath, `${task.hash}.commit`);
const td = join(this.cachePath, task.hash);
if (await pathExists(tdCommit)) {
const terminalOutput = await readFile(
join(td, 'terminalOutput'),
'utf-8'
);
let code = 0;
try {
code = Number(await readFile(join(td, 'code'), 'utf-8'));
} catch {}
return {
terminalOutput,
outputsPath: join(td, 'outputs'),
code,
};
} else {
return null;
}
}
private createCacheDir() {
mkdirSync(cacheDir, { recursive: true });
return cacheDir;
}
private createTerminalOutputsDir() {
const path = join(this.cachePath, 'terminalOutputs');
mkdirSync(path, { recursive: true });
return path;
}
private tryAndRetry<T>(fn: () => Promise<T>): Promise<T> {
let attempts = 0;
const baseTimeout = 100;
const _try = async () => {
try {
attempts++;
return await fn();
} catch (e) {
if (attempts === 10) {
// After enough attempts, throw the error
throw e;
}
await new Promise((res) => setTimeout(res, baseTimeout * attempts));
return await _try();
}
};
return _try();
}
}