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 Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import type { HttpClientError } from "effect/http";
9import { HttpClient, HttpClientRequest } from "effect/http";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Path from "effect/Path";
13import type { PlatformError } from "effect/PlatformError";
14import * as Schema from "effect/Schema";
15import * as Stream from "effect/Stream";
16
17import * as ServerConfig from "../config.ts";
18import type { SpeechModel } from "./model.ts";
19
20type ModelFile = Pick<SpeechModel, "id" | "filename" | "revision" | "size" | "sha256">;
21
22class SpeechModelDownloadError extends Schema.TaggedError<SpeechModelDownloadError>()(
23 "SpeechModelDownloadError",
24 {
25 modelId: Schema.String,
26 reason: Schema.Literals(["status", "range", "size", "verification"]),
27 status: Schema.optional(Schema.Number),
28 },
29) {
30 override get message(): string {
31 return `Speech model download failed: ${this.reason}${this.status === undefined ? "" : ` ${this.status}`}.`;
32 }
33}
34
35type SpeechModelDownloadProgress = {
36 readonly onProgress?: (downloaded: number) => void;
37 readonly onVerificationStart?: () => void;
38};
39
40export class SpeechModelStore extends Context.Service<
41 SpeechModelStore,
42 {
43 /** Cheap size check for status polls; never hashes the file. */
44 readonly isReady: (model: ModelFile) => Effect.Effect<boolean>;
45 /** The installed file once its SHA-256 has been verified, hashing it on first use. */
46 readonly installedPath: (model: ModelFile) => Effect.Effect<string | undefined>;
47 readonly download: (
48 model: ModelFile,
49 progress?: SpeechModelDownloadProgress,
50 ) => Effect.Effect<
51 string,
52 SpeechModelDownloadError | PlatformError | HttpClientError.HttpClientError
53 >;
54 readonly remove: (model: ModelFile) => Effect.Effect<void, PlatformError>;
55 }
56>()("t3/speech/SpeechModelStore") {}
57
58const DOWNLOAD_ATTEMPTS = 3;
59const PARTIAL_FILENAME =
60 /\.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;
61
62const make = Effect.gen(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const http = yield* HttpClient.HttpClient;
66 const random = yield* SecureRandom.SecureRandom;
67 const config = yield* ServerConfig.ServerConfig;
68 const directory = path.join(config.stateDir, "speech", "models");
69 // The server already owns this state directory; no download can be active before the store opens.
70 for (const name of yield* fs.readDirectory(directory).pipe(Effect.orElseSucceed(() => []))) {
71 if (PARTIAL_FILENAME.test(name)) {
72 yield* fs.remove(path.join(directory, name), { force: true }).pipe(Effect.ignore);
73 }
74 }
75 const modelPath = (model: ModelFile) => path.join(directory, model.filename);
76 // Files whose digest failed, by identity, so status polls stop calling them ready.
77 const corrupt = new Map<string, string>();
78
79 const identity = (model: ModelFile, info: FileSystem.File.Info) =>
80 [
81 model.sha256,
82 info.size,
83 Option.getOrUndefined(info.mtime)?.getTime(),
84 info.dev,
85 Option.getOrUndefined(info.ino),
86 ].join(":");
87
88 const statFile = (file: string) => fs.stat(file).pipe(Effect.orElseSucceed(() => undefined));
89
90 const expectedFile = (model: ModelFile, file: string) =>
91 statFile(file).pipe(
92 Effect.map((info) =>
93 info?.type === "File" && Number(info.size) === model.size ? info : undefined,
94 ),
95 );
96
97 const digestMatches = Effect.fn("SpeechModelStore.digest")(
98 function* (model: ModelFile, file: string) {
99 const hash = NodeCrypto.createHash("sha256");
100 yield* fs
101 .stream(file)
102 .pipe(Stream.runForEach((chunk) => Effect.sync(() => void hash.update(chunk))));
103 return hash.digest("hex") === model.sha256;
104 },
105 Effect.orElseSucceed(() => false),
106 );
107
108 // A verified file is trusted while its size, mtime, device and inode are unchanged.
109 const verifiedPath = Effect.fn("SpeechModelStore.verifiedPath")(function* (
110 model: ModelFile,
111 file: string,
112 onVerificationStart?: () => void,
113 ) {
114 const info = yield* expectedFile(model, file);
115 if (!info) return undefined;
116 const marker = identity(model, info);
117 if (corrupt.get(file) === marker) return undefined;
118 const recorded = yield* fs
119 .readFileString(`${file}.verified`)
120 .pipe(Effect.orElseSucceed(() => undefined));
121 if (recorded === marker) return file;
122 onVerificationStart?.();
123 const valid = yield* digestMatches(model, file);
124 if (!valid) corrupt.set(file, marker);
125 const current = yield* expectedFile(model, file);
126 if (!valid || !current || identity(model, current) !== marker) return undefined;
127 yield* fs.writeFileString(`${file}.verified`, marker, { mode: 0o600 }).pipe(Effect.ignore);
128 return file;
129 });
130
131 const fetchInto = Effect.fn("SpeechModelStore.fetch")(function* (
132 model: ModelFile,
133 url: string,
134 partialPath: string,
135 offset: number,
136 onProgress?: (downloaded: number) => void,
137 ) {
138 const request = HttpClientRequest.get(url).pipe(
139 offset > 0 ? HttpClientRequest.setHeader("Range", `bytes=${offset}-`) : (r) => r,
140 );
141 const response = yield* http.execute(request);
142 const resumed = offset > 0 && response.status === 206;
143 if (!resumed && response.status !== 200)
144 return yield* new SpeechModelDownloadError({
145 modelId: model.id,
146 reason: "status",
147 status: response.status,
148 });
149 if (resumed) {
150 const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers["content-range"] ?? "");
151 if (
152 !range ||
153 Number(range[1]) !== offset ||
154 Number(range[2]) !== model.size - 1 ||
155 Number(range[3]) !== model.size
156 )
157 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "range" });
158 }
159 const start = resumed ? offset : 0;
160 const contentLength = response.headers["content-length"];
161 if (
162 contentLength !== undefined &&
163 Number.isFinite(Number(contentLength)) &&
164 Number(contentLength) !== model.size - start
165 )
166 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "size" });
167 let downloaded = start;
168 onProgress?.(downloaded);
169 yield* response.stream.pipe(
170 Stream.tap((chunk) => {
171 downloaded += chunk.byteLength;
172 if (downloaded > model.size)
173 return Effect.fail(new SpeechModelDownloadError({ modelId: model.id, reason: "size" }));
174 onProgress?.(downloaded);
175 return Effect.void;
176 }),
177 Stream.run(fs.sink(partialPath, { flag: resumed ? "a" : "w", mode: 0o600 })),
178 );
179 return downloaded;
180 });
181
182 const download: SpeechModelStore["Service"]["download"] = Effect.fn("SpeechModelStore.download")(
183 function* (model, progress = {}) {
184 yield* Effect.annotateCurrentSpan({ modelId: model.id });
185 const finalPath = modelPath(model);
186 yield* fs.makeDirectory(directory, { recursive: true });
187 if (yield* verifiedPath(model, finalPath, progress.onVerificationStart)) return finalPath;
188 const partialPath = `${finalPath}.${yield* random.uuidV4()}.part`;
189 const url = `https://huggingface.co/${model.id}/resolve/${model.revision}/${model.filename}`;
190 return yield* Effect.gen(function* () {
191 for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt += 1) {
192 const offset = Number((yield* statFile(partialPath))?.size ?? 0);
193 if (offset === model.size) break;
194 // Transport and disk failures resume from the partial file; a bad response does not.
195 const downloaded = yield* fetchInto(
196 model,
197 url,
198 partialPath,
199 offset,
200 progress.onProgress,
201 ).pipe(
202 Effect.catchIf(
203 (error) => attempt < DOWNLOAD_ATTEMPTS && error._tag !== "SpeechModelDownloadError",
204 () => Effect.succeed(-1),
205 ),
206 );
207 if (downloaded === model.size) break;
208 }
209 progress.onVerificationStart?.();
210 const complete = yield* expectedFile(model, partialPath);
211 if (!complete || !(yield* digestMatches(model, partialPath)))
212 return yield* new SpeechModelDownloadError({ modelId: model.id, reason: "verification" });
213 yield* fs.rename(partialPath, finalPath);
214 // Rename changes file metadata, so record the verified file's final identity.
215 const info = yield* fs.stat(finalPath);
216 yield* fs
217 .writeFileString(`${finalPath}.verified`, identity(model, info), { mode: 0o600 })
218 .pipe(Effect.ignore);
219 return finalPath;
220 }).pipe(
221 Effect.onExit((exit) =>
222 Exit.isSuccess(exit)
223 ? Effect.void
224 : fs.remove(partialPath, { force: true }).pipe(Effect.ignore),
225 ),
226 );
227 },
228 );
229
230 return SpeechModelStore.of({
231 isReady: Effect.fn("SpeechModelStore.isReady")((model) =>
232 expectedFile(model, modelPath(model)).pipe(
233 Effect.map(
234 (info) => info !== undefined && corrupt.get(modelPath(model)) !== identity(model, info),
235 ),
236 ),
237 ),
238 installedPath: Effect.fn("SpeechModelStore.installedPath")((model) =>
239 verifiedPath(model, modelPath(model)),
240 ),
241 download,
242 remove: Effect.fn("SpeechModelStore.remove")(function* (model) {
243 const file = modelPath(model);
244 yield* fs.remove(file, { force: true });
245 yield* fs.remove(`${file}.verified`, { force: true });
246 }),
247 });
248});
249
250export const layer = Layer.effect(SpeechModelStore, make);