Skip to content

Commit 7e916f5

Browse files
dcousensprivatenumber
andauthoredOct 17, 2023
fix(cache): scope cache directory to user (#332)
Co-authored-by: Hiroki Osame <hiroki.osame@gmail.com>
1 parent 23e4694 commit 7e916f5

File tree

1 file changed

+40
-10
lines changed

1 file changed

+40
-10
lines changed
 

‎src/utils/transform/cache.ts

+40-10
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import type { Transformed } from './apply-transformers';
66

77
const getTime = () => Math.floor(Date.now() / 1e8);
88

9+
const tmpdir = os.tmpdir();
10+
const noop = () => {};
911
class FileCache<ReturnType> extends Map<string, ReturnType> {
1012
/**
1113
* By using tmpdir, the expectation is for the OS to clean any files
@@ -17,7 +19,16 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
1719
* Note on Windows, temp files are not cleaned up automatically.
1820
* https://superuser.com/a/1599897
1921
*/
20-
cacheDirectory = path.join(os.tmpdir(), 'tsx');
22+
cacheDirectory = path.join(
23+
// Write permissions by anyone
24+
tmpdir,
25+
26+
// Write permissions only by current user
27+
`tsx-${os.userInfo().uid}`,
28+
);
29+
30+
// Maintained so we can remove it on Windows
31+
oldCacheDirectory = path.join(tmpdir, 'tsx');
2132

2233
cacheFiles: {
2334
time: number;
@@ -40,7 +51,10 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
4051
};
4152
});
4253

43-
setImmediate(() => this.expireDiskCache());
54+
setImmediate(() => {
55+
this.expireDiskCache();
56+
this.removeOldCacheDirectory();
57+
});
4458
}
4559

4660
get(key: string) {
@@ -90,10 +104,7 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
90104
fs.promises.writeFile(
91105
path.join(this.cacheDirectory, `${time}-${key}`),
92106
JSON.stringify(value),
93-
).catch(
94-
95-
() => {},
96-
);
107+
).catch(noop);
97108
}
98109

99110
return this;
@@ -105,13 +116,32 @@ class FileCache<ReturnType> extends Map<string, ReturnType> {
105116
for (const cache of this.cacheFiles) {
106117
// Remove if older than ~7 days
107118
if ((time - cache.time) > 7) {
108-
fs.promises.unlink(path.join(this.cacheDirectory, cache.fileName)).catch(
109-
110-
() => {},
111-
);
119+
fs.promises.unlink(path.join(this.cacheDirectory, cache.fileName)).catch(noop);
112120
}
113121
}
114122
}
123+
124+
async removeOldCacheDirectory() {
125+
try {
126+
const exists = await fs.promises.access(this.oldCacheDirectory).then(() => true);
127+
if (exists) {
128+
if ('rm' in fs.promises) {
129+
await fs.promises.rm(
130+
this.oldCacheDirectory,
131+
{
132+
recursive: true,
133+
force: true,
134+
},
135+
);
136+
} else {
137+
await fs.promises.rmdir(
138+
this.oldCacheDirectory,
139+
{ recursive: true },
140+
);
141+
}
142+
}
143+
} catch {}
144+
}
115145
}
116146

117147
export default (

0 commit comments

Comments
 (0)
Please sign in to comment.