-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-cache.ts
More file actions
302 lines (269 loc) · 8.35 KB
/
binary-cache.ts
File metadata and controls
302 lines (269 loc) · 8.35 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
/**
* @fileoverview On-disk cache metadata helpers for dlx binaries.
*
* - `getDlxCachePath` — root of the binary cache (alias of getSocketDlxDir)
* - `getBinaryCacheMetadataPath` — path to a cache entry's .dlx-metadata.json
* - `isBinaryCacheValid` — TTL-based liveness check
* - `writeBinaryCacheMetadata` — atomic write of cache metadata
* - `cleanDlxCache` — TTL-based eviction sweep
* - `listDlxCache` — enumerate cached binaries with their metadata
*
* Split out of `dlx/binary.ts` for size hygiene.
*/
/* oxlint-disable socket/prefer-exists-sync -- DLX binary metadata uses stat for size/mtime; not existence-only checks. */
import process from 'node:process'
import { existsSync } from 'node:fs'
import { DLX_BINARY_CACHE_TTL } from '../constants/time'
import { readJson } from '../fs/read-json'
import { safeDelete } from '../fs/safe'
import { isPlainObject } from '../objects/predicates'
import { getSocketDlxDir } from '../paths/socket'
import { ArrayIsArray, ArrayPrototypeFind } from '../primordials/array'
import { DateNow } from '../primordials/date'
import { JSONStringify } from '../primordials/json'
import { StringPrototypeStartsWith } from '../primordials/string'
import { getNodeFs } from '../node/fs'
import { getNodePath } from '../node/path'
import type { DlxMetadata } from './binary-types'
/**
* Clean expired entries from the DLX cache.
*
* @example
* ```typescript
* // Remove cache entries older than the default TTL
* const removed = await cleanDlxCache()
*
* // Remove entries older than 1 hour
* const removed2 = await cleanDlxCache(60 * 60 * 1000)
* ```
*/
export async function cleanDlxCache(
maxAge: number = DLX_BINARY_CACHE_TTL,
): Promise<number> {
const cacheDir = getDlxCachePath()
const fs = getNodeFs()
if (!fs.existsSync(cacheDir)) {
return 0
}
let cleaned = 0
const now = DateNow()
const path = getNodePath()
const entries = await fs.promises.readdir(cacheDir)
for (const entry of entries) {
const entryPath = path.join(cacheDir, entry)
const metaPath = getBinaryCacheMetadataPath(entryPath)
try {
// eslint-disable-next-line no-await-in-loop
if (!(await existsSync(entryPath))) {
continue
}
// eslint-disable-next-line no-await-in-loop
const metadata = await readJson(metaPath, { throws: false })
if (!metadata || typeof metadata !== 'object' || ArrayIsArray(metadata)) {
continue
}
const timestamp = (metadata as Record<string, unknown>)['timestamp']
// If timestamp is missing or invalid, treat as expired (age = infinity)
const age =
typeof timestamp === 'number' && timestamp > 0
? now - timestamp
: Number.POSITIVE_INFINITY
// Treat future timestamps (clock skew) as expired
if (age < 0 || age > maxAge) {
// Remove entire cache entry directory.
// eslint-disable-next-line no-await-in-loop
await safeDelete(entryPath, { force: true, recursive: true })
cleaned += 1
}
} catch {
// If we can't read metadata, check if directory is empty or corrupted.
try {
// eslint-disable-next-line no-await-in-loop
const contents = await fs.promises.readdir(entryPath)
if (!contents.length) {
// Remove empty directory.
// eslint-disable-next-line no-await-in-loop
await safeDelete(entryPath)
cleaned += 1
}
} catch {}
}
}
return cleaned
}
/**
* Get metadata file path for a cached binary.
*
* @example
* ```typescript
* const metaPath = getBinaryCacheMetadataPath('/tmp/dlx-cache/a1b2c3d4')
* // '/tmp/dlx-cache/a1b2c3d4/.dlx-metadata.json'
* ```
*/
export function getBinaryCacheMetadataPath(cacheEntryPath: string): string {
return getNodePath().join(cacheEntryPath, '.dlx-metadata.json')
}
/**
* Get the DLX binary cache directory path.
* Alias of `getSocketDlxDir` — DLX binary cache uses the same directory
* as dlx-package for unified DLX storage.
*
* @example
* ```typescript
* const cachePath = getDlxCachePath()
* ```
*/
export const getDlxCachePath = getSocketDlxDir
/**
* Check if a cached binary is still valid.
*
* @example
* ```typescript
* const ttl = 7 * 24 * 60 * 60 * 1000
* const valid = await isBinaryCacheValid('/tmp/dlx-cache/a1b2c3d4', ttl)
* if (!valid) {
* // Re-download the binary
* }
* ```
*/
export async function isBinaryCacheValid(
cacheEntryPath: string,
cacheTtl: number,
): Promise<boolean> {
const fs = getNodeFs()
try {
const metaPath = getBinaryCacheMetadataPath(cacheEntryPath)
if (!fs.existsSync(metaPath)) {
return false
}
const metadata = await readJson(metaPath, { throws: false })
if (!isPlainObject(metadata)) {
return false
}
const now = DateNow()
const timestamp = (metadata as Record<string, unknown>)['timestamp']
// If timestamp is missing or invalid, cache is invalid
if (typeof timestamp !== 'number' || timestamp <= 0) {
return false
}
const age = now - timestamp
// Reject future timestamps (clock skew or corruption)
if (age < 0) {
return false
}
return age < cacheTtl
} catch {
return false
}
}
/**
* Get information about cached binaries.
*
* @example
* ```typescript
* const entries = await listDlxCache()
* for (const entry of entries) {
* console.log(`${entry.name}: ${entry.size} bytes`)
* }
* ```
*/
export async function listDlxCache(): Promise<
Array<{
age: number
integrity: string
name: string
size: number
url: string
}>
> {
const cacheDir = getDlxCachePath()
const fs = getNodeFs()
if (!fs.existsSync(cacheDir)) {
return []
}
const results = []
const now = DateNow()
const path = getNodePath()
const entries = await fs.promises.readdir(cacheDir)
for (const entry of entries) {
const entryPath = path.join(cacheDir, entry)
try {
// eslint-disable-next-line no-await-in-loop
if (!(await existsSync(entryPath))) {
continue
}
const metaPath = getBinaryCacheMetadataPath(entryPath)
// eslint-disable-next-line no-await-in-loop
const metadata = await readJson(metaPath, { throws: false })
if (!metadata || typeof metadata !== 'object' || ArrayIsArray(metadata)) {
continue
}
const metaObj = metadata as Record<string, unknown>
// Get URL from unified schema (source.url) or legacy schema (url).
// Allow empty URL for backward compatibility with partial metadata.
const source = metaObj['source'] as Record<string, unknown> | undefined
const url =
(source?.['url'] as string) || (metaObj['url'] as string) || ''
// Find the binary file in the directory.
// eslint-disable-next-line no-await-in-loop
const files = await fs.promises.readdir(entryPath)
const binaryFile = ArrayPrototypeFind(
files,
f => !StringPrototypeStartsWith(f, '.'),
)
if (binaryFile) {
const binaryPath = path.join(entryPath, binaryFile)
// eslint-disable-next-line no-await-in-loop
const binaryStats = await fs.promises.stat(binaryPath)
results.push({
age: now - ((metaObj['timestamp'] as number) || 0),
integrity: (metaObj['integrity'] as string) || '',
name: binaryFile,
size: binaryStats.size,
url,
})
}
} catch {}
}
return results
}
/**
* Write metadata for a cached binary.
* Uses unified schema shared with C++ decompressor and CLI dlxBinary.
*
* @example
* ```typescript
* await writeBinaryCacheMetadata(
* '/tmp/dlx-cache/a1b2c3d4',
* 'a1b2c3d4',
* 'https://example.com/tool',
* 'sha512-abc123...',
* 15000000
* )
* ```
*/
export async function writeBinaryCacheMetadata(
cacheEntryPath: string,
cacheKey: string,
url: string,
integrity: string,
size: number,
): Promise<void> {
const metaPath = getBinaryCacheMetadataPath(cacheEntryPath)
const metadata: DlxMetadata = {
version: '1.0.0',
cache_key: cacheKey,
timestamp: DateNow(),
integrity,
size,
source: {
type: 'download',
url,
},
}
const fs = getNodeFs()
// Use atomic write-then-rename pattern to prevent corruption on crash
const tmpPath = `${metaPath}.tmp.${process.pid}`
await fs.promises.writeFile(tmpPath, JSONStringify(metadata, null, 2))
await fs.promises.rename(tmpPath, metaPath)
}