-
Notifications
You must be signed in to change notification settings - Fork 358
/
Copy pathcache-management.ts
265 lines (221 loc) · 7.21 KB
/
cache-management.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
import { homedir } from "node:os";
import { join, basename } from "node:path";
import { stat, readdir, readFile, realpath, lstat } from "node:fs/promises";
import type { Stats } from "node:fs";
import type { RepoType, RepoId } from "../types/public";
function getDefaultHome(): string {
return join(homedir(), ".cache");
}
function getDefaultCachePath(): string {
return join(process.env["HF_HOME"] ?? join(process.env["XDG_CACHE_HOME"] ?? getDefaultHome(), "huggingface"), "hub");
}
function getHuggingFaceHubCache(): string {
return process.env["HUGGINGFACE_HUB_CACHE"] ?? getDefaultCachePath();
}
export function getHFHubCachePath(): string {
return process.env["HF_HUB_CACHE"] ?? getHuggingFaceHubCache();
}
const FILES_TO_IGNORE: string[] = [".DS_Store"];
export const REPO_ID_SEPARATOR: string = "--";
export function getRepoFolderName({ name, type }: RepoId): string {
const parts = [`${type}s`, ...name.split("/")];
return parts.join(REPO_ID_SEPARATOR);
}
export interface CachedFileInfo {
path: string;
/**
* Underlying file - which `path` is symlinked to
*/
blob: {
size: number;
path: string;
lastModifiedAt: Date;
lastAccessedAt: Date;
};
}
export interface CachedRevisionInfo {
commitOid: string;
path: string;
size: number;
files: CachedFileInfo[];
refs: string[];
lastModifiedAt: Date;
}
export interface CachedRepoInfo {
id: RepoId;
path: string;
size: number;
filesCount: number;
revisions: CachedRevisionInfo[];
lastAccessedAt: Date;
lastModifiedAt: Date;
}
export interface HFCacheInfo {
size: number;
repos: CachedRepoInfo[];
warnings: Error[];
}
export async function scanCacheDir(cacheDir: string | undefined = undefined): Promise<HFCacheInfo> {
if (!cacheDir) cacheDir = getHFHubCachePath();
const s = await stat(cacheDir);
if (!s.isDirectory()) {
throw new Error(
`Scan cache expects a directory but found a file: ${cacheDir}. Please use \`cacheDir\` argument or set \`HF_HUB_CACHE\` environment variable.`
);
}
const repos: CachedRepoInfo[] = [];
const warnings: Error[] = [];
const directories = await readdir(cacheDir);
for (const repo of directories) {
// skip .locks folder
if (repo === ".locks") continue;
// get the absolute path of the repo
const absolute = join(cacheDir, repo);
// ignore non-directory element
const s = await stat(absolute);
if (!s.isDirectory()) {
continue;
}
try {
const cached = await scanCachedRepo(absolute);
repos.push(cached);
} catch (err: unknown) {
warnings.push(err as Error);
}
}
return {
repos: repos,
size: [...repos.values()].reduce((sum, repo) => sum + repo.size, 0),
warnings: warnings,
};
}
export async function scanCachedRepo(repoPath: string): Promise<CachedRepoInfo> {
// get the directory name
const name = basename(repoPath);
if (!name.includes(REPO_ID_SEPARATOR)) {
throw new Error(`Repo path is not a valid HuggingFace cache directory: ${name}`);
}
// parse the repoId from directory name
const [type, ...remaining] = name.split(REPO_ID_SEPARATOR);
const repoType = parseRepoType(type);
const repoId = remaining.join("/");
const snapshotsPath = join(repoPath, "snapshots");
const refsPath = join(repoPath, "refs");
const snapshotStat = await stat(snapshotsPath);
if (!snapshotStat.isDirectory()) {
throw new Error(`Snapshots dir doesn't exist in cached repo ${snapshotsPath}`);
}
// Check if the refs directory exists and scan it
const refsByHash: Map<string, string[]> = new Map();
const refsStat = await stat(refsPath);
if (refsStat.isDirectory()) {
await scanRefsDir(refsPath, refsByHash);
}
// Scan snapshots directory and collect cached revision information
const cachedRevisions: CachedRevisionInfo[] = [];
const blobStats: Map<string, Stats> = new Map(); // Store blob stats
const snapshotDirs = await readdir(snapshotsPath);
for (const dir of snapshotDirs) {
if (FILES_TO_IGNORE.includes(dir)) continue; // Ignore unwanted files
const revisionPath = join(snapshotsPath, dir);
const revisionStat = await stat(revisionPath);
if (!revisionStat.isDirectory()) {
throw new Error(`Snapshots folder corrupted. Found a file: ${revisionPath}`);
}
const cachedFiles: CachedFileInfo[] = [];
await scanSnapshotDir(revisionPath, cachedFiles, blobStats);
const revisionLastModified =
cachedFiles.length > 0
? Math.max(...[...cachedFiles].map((file) => file.blob.lastModifiedAt.getTime()))
: revisionStat.mtimeMs;
cachedRevisions.push({
commitOid: dir,
files: cachedFiles,
refs: refsByHash.get(dir) || [],
size: [...cachedFiles].reduce((sum, file) => sum + file.blob.size, 0),
path: revisionPath,
lastModifiedAt: new Date(revisionLastModified),
});
refsByHash.delete(dir);
}
// Verify that all refs refer to a valid revision
if (refsByHash.size > 0) {
throw new Error(
`Reference(s) refer to missing commit hashes: ${JSON.stringify(Object.fromEntries(refsByHash))} (${repoPath})`
);
}
const repoStats = await stat(repoPath);
const repoLastAccessed =
blobStats.size > 0 ? Math.max(...[...blobStats.values()].map((stat) => stat.atimeMs)) : repoStats.atimeMs;
const repoLastModified =
blobStats.size > 0 ? Math.max(...[...blobStats.values()].map((stat) => stat.mtimeMs)) : repoStats.mtimeMs;
// Return the constructed CachedRepoInfo object
return {
id: {
name: repoId,
type: repoType,
},
path: repoPath,
filesCount: blobStats.size,
revisions: cachedRevisions,
size: [...blobStats.values()].reduce((sum, stat) => sum + stat.size, 0),
lastAccessedAt: new Date(repoLastAccessed),
lastModifiedAt: new Date(repoLastModified),
};
}
export async function scanRefsDir(refsPath: string, refsByHash: Map<string, string[]>): Promise<void> {
const refFiles = await readdir(refsPath, { withFileTypes: true });
for (const refFile of refFiles) {
const refFilePath = join(refsPath, refFile.name);
if (refFile.isDirectory()) continue; // Skip directories
const commitHash = await readFile(refFilePath, "utf-8");
const refName = refFile.name;
if (!refsByHash.has(commitHash)) {
refsByHash.set(commitHash, []);
}
refsByHash.get(commitHash)?.push(refName);
}
}
export async function scanSnapshotDir(
revisionPath: string,
cachedFiles: CachedFileInfo[],
blobStats: Map<string, Stats>
): Promise<void> {
const files = await readdir(revisionPath, { withFileTypes: true });
for (const file of files) {
if (file.isDirectory()) continue; // Skip directories
const filePath = join(revisionPath, file.name);
const blobPath = await realpath(filePath);
const blobStat = await getBlobStat(blobPath, blobStats);
cachedFiles.push({
path: filePath,
blob: {
path: blobPath,
size: blobStat.size,
lastAccessedAt: new Date(blobStat.atimeMs),
lastModifiedAt: new Date(blobStat.mtimeMs),
},
});
}
}
export async function getBlobStat(blobPath: string, blobStats: Map<string, Stats>): Promise<Stats> {
const blob = blobStats.get(blobPath);
if (!blob) {
const statResult = await lstat(blobPath);
blobStats.set(blobPath, statResult);
return statResult;
}
return blob;
}
export function parseRepoType(type: string): RepoType {
switch (type) {
case "models":
return "model";
case "datasets":
return "dataset";
case "spaces":
return "space";
default:
throw new TypeError(`Invalid repo type: ${type}`);
}
}