Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest.
2import * as NodeCrypto from "node:crypto";
3import * as Context from "effect/Context";
4import * as SecureRandom from "effect/crypto/SecureRandom";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import type { HttpClientError } from "effect/http";
8import { HttpClient, HttpClientRequest } from "effect/http";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import type { PlatformError } from "effect/PlatformError";
13import * as Schema from "effect/Schema";
14import * as Stream from "effect/Stream";
15
16import * as HostProcess from "@t3tools/shared/HostProcess";
17
18import * as ServerConfig from "../config.ts";
19import { expandHomePath } from "../os-jank.ts";
20import type { SpeechModel } from "./model.ts";
21
22type ModelFile = Pick<SpeechModel, "id" | "filename" | "revision" | "size" | "sha256">;
23
24class SpeechModelDownloadError extends Schema.TaggedError<SpeechModelDownloadError>()(
25 "SpeechModelDownloadError",
26 {
27 modelId: Schema.String,
28 reason: Schema.Literals(["status", "range", "size", "verification"]),
29 status: Schema.optional(Schema.Number),
30 },
31) {
32 override get message(): string {
33 return `Speech model download failed: ${this.reason}${this.status === undefined ? "" : ` ${this.status}`}.`;
34 }
35}
36
37type SpeechModelDownloadProgress = {
38 readonly onProgress?: (downloaded: number) => void;
39 readonly onVerificationStart?: () => void;
40};
41
42export class SpeechModelStore extends Context.Service<
43 SpeechModelStore,
44 {
45 /** Cheap size check for status polls; never hashes the file. */
46 readonly isReady: (model: ModelFile) => Effect.Effect<boolean>;
47 /** The installed file once its SHA-256 has been verified, hashing it on first use. */
48 readonly installedPath: (model: ModelFile) => Effect.Effect<string | undefined>;
49 /** Links a copy the Hugging Face cache or Handy already holds; fetches only without one. */
50 readonly download: (
51 model: ModelFile,
52 progress?: SpeechModelDownloadProgress,
53 ) => Effect.Effect<
54 string,
55 SpeechModelDownloadError | PlatformError | HttpClientError.HttpClientError
56 >;
57 /**
58 * Installs catalog files already on this machine as symlinks, never copies.
59 * `source` is a file or a folder to search; returns the ids it installed.
60 */
61 readonly link: (
62 models: ReadonlyArray<ModelFile>,
63 source: string,
64 ) => Effect.Effect<ReadonlyArray<string>, PlatformError>;
65 /** The outside file a linked model points at. */
66 readonly linkedFrom: (model: ModelFile) => Effect.Effect<string | undefined>;
67 /** Removes T3 Code's file or link; a linked file itself is left in place. */
68 readonly remove: (model: ModelFile) => Effect.Effect<void, PlatformError>;
69 }
70>()("t3/speech/SpeechModelStore") {}
71
72const DOWNLOAD_ATTEMPTS = 3;
73const PARTIAL_FILENAME =
74 /\.gguf\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.part$/i;
75
76const LINK_SEARCH_DEPTH = 5;
77const LINK_SEARCH_ENTRIES = 5_000;
78
79const make = Effect.gen(function* () {
80 const fs = yield* FileSystem.FileSystem;
81 const path = yield* Path.Path;
82 const home = yield* HostProcess.HomeDirectory;
83 const platform = yield* HostProcess.Platform;
84 const http = yield* HttpClient.HttpClient;
85 const random = yield* SecureRandom.SecureRandom;
86 const config = yield* ServerConfig.ServerConfig;
87 const directory = path.join(config.stateDir, "speech", "models");
88 // The server already owns this state directory; no download can be active before the store opens.
89 for (const name of yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []))) {
90 if (PARTIAL_FILENAME.test(name)) {
91 yield* fs.remove(path.join(directory, name), { force: true }).pipe(Effect.ignore);
92 }
93 }
94 const modelPath = (model: ModelFile) => path.join(directory, model.filename);
95 const appDataDirectories =
96 platform === "darwin"
97 ? [path.join(home, "Library", "Application Support")]
98 : platform === "win32"
99 ? [path.join(home, "AppData", "Roaming")]
100 : [path.join(home, ".local", "share"), path.join(home, ".config")];
101 // Where the Hugging Face cache and Handy keep these same pinned files.
102 const knownCopies = (model: ModelFile) => [
103 path.join(
104 home,
105 ".cache",
106 "huggingface",
107 "hub",
108 `models--${model.id.replace("/", "--")}`,
109 "snapshots",
110 model.revision,
111 model.filename,
112 ),
113 ...appDataDirectories.map((appData) =>
114 path.join(appData, "com.pais.handy", "models", model.filename),
115 ),
116 ];
117 // Files whose digest failed, by identity, so status polls stop calling them ready.
118 const corrupt = new Map<string, string>();
119
120 const identity = (model: ModelFile, info: FileSystem.File.Info) =>
121 [
122 model.sha256,
123 info.size,
124 Option.getOrUndefined(info.mtime)?.getTime(),
125 info.dev,
126 Option.getOrUndefined(info.ino),
127 ].join(":");
128
129 const statFile = (file: string) => fs.stat(file).pipe(Effect.orElseSucceed(() => undefined));
130
131 const expectedFile = (model: ModelFile, file: string) =>
132 statFile(file).pipe(
133 Effect.map((info) =>
134 info?.type === "File" && Number(info.size) === model.size ? info : undefined,
135 ),
136 );
137
138 const digestMatches = Effect.fn("SpeechModelStore.digest")(
139 function* (model: ModelFile, file: string) {
140 const hash = NodeCrypto.createHash("sha256");
141 yield* fs
142 .stream(file)
143 .pipe(Stream.runForEach((chunk) => Effect.sync(() => void hash.update(chunk))));
144 return hash.digest("hex") === model.sha256;
145 },
146 Effect.orElseSucceed(() => false),
147 );
148
149 // A verified file is trusted while its size, mtime, device and inode are unchanged.
150 const verifiedPath = Effect.fn("SpeechModelStore.verifiedPath")(function* (
151 model: ModelFile,
152 file: string,
153 onVerificationStart?: () => void,
154 ) {
155 const info = yield* expectedFile(model, file);
156 if (!info) return undefined;
157 const marker = identity(model, info);
158 if (corrupt.get(file) === marker) return undefined;
159 const recorded = yield* fs
160 .readFileString(`${file}.verified`)
161 .pipe(Effect.orElseSucceed(() => undefined));
162 if (recorded === marker) return file;
163 onVerificationStart?.();
164 const valid = yield* digestMatches(model, file);
165 if (!valid) corrupt.set(file, marker);
166 const current = yield* expectedFile(model, file);
167 if (!valid || !current || identity(model, current) !== marker) return undefined;
168 yield* fs.writeFileString(`${file}.verified`, marker, { mode: 0o600 }).pipe(Effect.ignore);
169 return file;
170 });
171
172 const fetchInto = Effect.fn("SpeechModelStore.fetch")(function* (
173 model: ModelFile,
174 url: string,
175 partialPath: string,
176 offset: number,
177 onProgress?: (downloaded: number) => void,
178 ) {
179 const request = HttpClientRequest.get(url).pipe(
180 offset > 0 ? HttpClientRequest.setHeader("Range", `bytes=${offset}-`) : (r) => r,
181 );
182 const response = yield* http.execute(request);
183 const resumed = offset > 0 && response.status === 206;
184 if (!resumed && response.status !== 200)
185 return yield* new SpeechModelDownloadError({
186 modelId: model.id,
187 reason: "status",
188 status: response.status,
189 });
190 if (resumed) {
191 const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers["content-range"] ?? "");
192 if (
193 !range ||
194 Number(range[1]) !== offset ||
195 Number(range[2]) !== model.size - 1 ||
196 Number(range[3]) !== model.size
197 )
198 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "range" });
199 }
200 const start = resumed ? offset : 0;
201 const contentLength = response.headers["content-length"];
202 if (
203 contentLength !== undefined &&
204 Number.isFinite(Number(contentLength)) &&
205 Number(contentLength) !== model.size - start
206 )
207 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "size" });
208 let downloaded = start;
209 onProgress?.(downloaded);
210 yield* response.stream.pipe(
211 Stream.tap((chunk) => {
212 downloaded += chunk.byteLength;
213 if (downloaded > model.size)
214 return Effect.fail(new SpeechModelDownloadError({ modelId: model.id, reason: "size" }));
215 onProgress?.(downloaded);
216 return Effect.void;
217 }),
218 Stream.run(fs.sink(partialPath, { flag: resumed ? "a" : "w", mode: 0o600 })),
219 );
220 return downloaded;
221 });
222
223 const filesUnder = Effect.fn("SpeechModelStore.filesUnder")(function* (source: string) {
224 const files: Array<{ readonly file: string; readonly size: number }> = [];
225 const pending = [{ entry: source, depth: LINK_SEARCH_DEPTH }];
226 for (let visited = 0; pending.length > 0 && visited < LINK_SEARCH_ENTRIES; visited += 1) {
227 const { entry, depth } = pending.pop()!;
228 const info = yield* statFile(entry);
229 if (info?.type === "File") files.push({ file: entry, size: Number(info.size) });
230 if (info?.type !== "Directory" || depth === 0) continue;
231 for (const name of yield* fs.readDirectory(entry).pipe(Effect.orElseSucceed(() => [])))
232 pending.push({ entry: path.join(entry, name), depth: depth - 1 });
233 }
234 return files;
235 });
236
237 const realPath = (file: string) => fs.realPath(file).pipe(Effect.orElseSucceed(() => undefined));
238
239 const link: SpeechModelStore["Service"]["link"] = Effect.fn("SpeechModelStore.link")(
240 function* (models, source) {
241 const resolve = (input: string) =>
242 expandHomePath(input).pipe(
243 Effect.map((expanded) => path.resolve(expanded)),
244 Effect.provideService(Path.Path, path),
245 Effect.provideService(HostProcess.HomeDirectory, home),
246 );
247 const literal = yield* resolve(source);
248 // A pasted path often carries stray edge whitespace; a name that really has it wins.
249 const root =
250 (yield* statFile(literal)) || source.trim() === source
251 ? literal
252 : yield* resolve(source.trim());
253 yield* fs.makeDirectory(directory, { recursive: true });
254 const linked: string[] = [];
255 for (const { file, size } of yield* filesUnder(root)) {
256 for (const model of models) {
257 if (model.size !== size || linked.includes(model.id)) continue;
258 const finalPath = modelPath(model);
259 // Pointing at T3 Code's own model folder must not replace a file with a link to itself.
260 if ((yield* realPath(file)) === (yield* realPath(finalPath))) continue;
261 if (yield* verifiedPath(model, finalPath)) continue;
262 const hashed = yield* expectedFile(model, file);
263 if (!hashed || !(yield* digestMatches(model, file))) continue;
264 // Staged then renamed, so a failed link never removes the file already installed.
265 const staged = `${finalPath}.${yield* random.uuidV4()}.part`;
266 // Windows grants symlinks only to privileged accounts; a hard link also shares the bytes.
267 const hardLinked = yield* fs.symlink(file, staged).pipe(
268 Effect.as(false),
269 Effect.catch(() => fs.link(file, staged).pipe(Effect.as(true))),
270 );
271 const current = yield* expectedFile(model, staged);
272 const marker = identity(model, hashed);
273 if (!current || identity(model, current) !== marker) {
274 yield* fs.remove(staged, { force: true });
275 continue;
276 }
277 yield* fs.rename(staged, finalPath);
278 // A hard link cannot be read back, so its origin is recorded beside it.
279 yield* (
280 hardLinked
281 ? fs.writeFileString(`${finalPath}.source`, file, { mode: 0o600 })
282 : fs.remove(`${finalPath}.source`, { force: true })
283 ).pipe(Effect.ignore);
284 yield* fs
285 .writeFileString(`${finalPath}.verified`, marker, { mode: 0o600 })
286 .pipe(Effect.ignore);
287 linked.push(model.id);
288 }
289 }
290 return linked;
291 },
292 );
293
294 const download: SpeechModelStore["Service"]["download"] = Effect.fn("SpeechModelStore.download")(
295 function* (model, progress = {}) {
296 yield* Effect.annotateCurrentSpan({ modelId: model.id });
297 const finalPath = modelPath(model);
298 yield* fs.makeDirectory(directory, { recursive: true });
299 if (yield* verifiedPath(model, finalPath, progress.onVerificationStart)) return finalPath;
300 for (const copy of knownCopies(model)) {
301 const linked = yield* link([model], copy).pipe(Effect.orElseSucceed(() => []));
302 if (linked.length > 0) return finalPath;
303 }
304 // A fixed name lets a later download, or one after a restart, resume the bytes received.
305 const partialPath = `${finalPath}.part`;
306 const url = `https://huggingface.co/${model.id}/resolve/${model.revision}/${model.filename}`;
307 return yield* Effect.gen(function* () {
308 // Transport and disk failures resume from the partial file; a bad response does not.
309 // Only attempts that receive nothing count against the budget.
310 for (let failures = 0; ;) {
311 const offset = Number((yield* statFile(partialPath))?.size ?? 0);
312 if (offset === model.size) break;
313 const downloaded = yield* fetchInto(
314 model,
315 url,
316 partialPath,
317 offset,
318 progress.onProgress,
319 ).pipe(
320 Effect.catchIf(
321 (error) => error._tag !== "SpeechModelDownloadError",
322 (error) => Effect.succeed(error),
323 ),
324 );
325 if (downloaded === model.size) break;
326 const received = Number((yield* statFile(partialPath))?.size ?? 0);
327 failures = received > offset ? 0 : failures + 1;
328 if (failures < DOWNLOAD_ATTEMPTS) continue;
329 if (typeof downloaded === "number") break;
330 return yield* downloaded;
331 }
332 progress.onVerificationStart?.();
333 const complete = yield* expectedFile(model, partialPath);
334 if (!complete || !(yield* digestMatches(model, partialPath)))
335 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "verification" });
336 yield* fs.rename(partialPath, finalPath);
337 yield* fs.remove(`${finalPath}.source`, { force: true }).pipe(Effect.ignore);
338 // Rename changes file metadata, so record the verified file's final identity.
339 const info = yield* fs.stat(finalPath);
340 yield* fs
341 .writeFileString(`${finalPath}.verified`, identity(model, info), { mode: 0o600 })
342 .pipe(Effect.ignore);
343 return finalPath;
344 }).pipe(
345 // Bytes that do not match the catalog are discarded; an error status keeps them.
346 Effect.tapError((error) =>
347 error._tag === "SpeechModelDownloadError" && error.reason !== "status"
348 ? fs.remove(partialPath, { force: true }).pipe(Effect.ignore)
349 : Effect.void,
350 ),
351 );
352 },
353 );
354
355 return SpeechModelStore.of({
356 link,
357 linkedFrom: Effect.fn("SpeechModelStore.linkedFrom")((model) =>
358 fs.readLink(modelPath(model)).pipe(
359 Effect.catch(() => fs.readFileString(`${modelPath(model)}.source`)),
360 Effect.orElseSucceed(() => undefined),
361 ),
362 ),
363 isReady: Effect.fn("SpeechModelStore.isReady")((model) =>
364 expectedFile(model, modelPath(model)).pipe(
365 Effect.map(
366 (info) => info !== undefined && corrupt.get(modelPath(model)) !== identity(model, info),
367 ),
368 ),
369 ),
370 installedPath: Effect.fn("SpeechModelStore.installedPath")((model) =>
371 verifiedPath(model, modelPath(model)),
372 ),
373 download,
374 remove: Effect.fn("SpeechModelStore.remove")(function* (model) {
375 const file = modelPath(model);
376 yield* fs.remove(file, { force: true });
377 yield* fs.remove(`${file}.verified`, { force: true });
378 yield* fs.remove(`${file}.source`, { force: true });
379 yield* fs.remove(`${file}.part`, { force: true });
380 }),
381 });
382});
383
384export const layer = Layer.effect(SpeechModelStore, make);