Open History to see the last commit
1import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { expect, it } from "@effect/vitest";
4import * as Digest from "effect/crypto/Digest";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Hex from "effect/encoding/Hex";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as Stream from "effect/Stream";
13import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
14
15import * as HostProcess from "@t3tools/shared/HostProcess";
16
17import * as ServerConfig from "../config.ts";
18import * as SpeechModelStore from "./SpeechModelStore.ts";
19
20const bytes = Uint8Array.from({ length: 64 }, (_, index) => (index * 7) % 256);
21const SPLIT = 20;
22
23const harness = Effect.gen(function* () {
24 const digest = yield* Digest.Digest;
25 const model = {
26 id: "fixture/speech-model",
27 revision: "a".repeat(40),
28 filename: "model.gguf",
29 size: bytes.length,
30 sha256: Hex.encode(yield* digest.digest(Digest.sha256, bytes).pipe(Effect.orDie)),
31 };
32 const config = yield* ServerConfig.ServerConfig;
33 const path = yield* Path.Path;
34 const fs = yield* FileSystem.FileSystem;
35 const directory = path.join(config.stateDir, "speech", "models");
36 const stale = path.join(directory, model.filename);
37 yield* fs.makeDirectory(directory, { recursive: true });
38 yield* fs.writeFile(stale, new Uint8Array(bytes.length));
39 const requests: HttpClientRequest.HttpClientRequest[] = [];
40 const transportFailure = (request: HttpClientRequest.HttpClientRequest) =>
41 new HttpClientError.HttpClientError({
42 reason: new HttpClientError.TransportError({ request, cause: new Error("reset") }),
43 });
44 const bodies = {
45 current: (
46 request: HttpClientRequest.HttpClientRequest,
47 ): Stream.Stream<Uint8Array, HttpClientError.HttpClientError> =>
48 Stream.fail(transportFailure(request)),
49 };
50 const client = HttpClient.make((request) =>
51 Effect.sync(() => {
52 requests.push(request);
53 const body = bodies.current(request);
54 const from = Number(/^bytes=(\d+)-$/.exec(request.headers["range"] ?? "")?.[1] ?? 0);
55 const resumed = from > 0;
56 return Object.defineProperty(
57 HttpClientResponse.fromWeb(
58 request,
59 new Response(null, {
60 status: resumed ? 206 : 200,
61 headers: resumed
62 ? {
63 "content-range": `bytes ${from}-${bytes.length - 1}/${bytes.length}`,
64 "content-length": String(bytes.length - from),
65 }
66 : { "content-length": String(bytes.length) },
67 }),
68 ),
69 "stream",
70 { value: body },
71 );
72 }),
73 );
74 const openStore = SpeechModelStore.SpeechModelStore.pipe(
75 Effect.provide(
76 SpeechModelStore.layer.pipe(Layer.provide(Layer.succeed(HttpClient.HttpClient, client))),
77 ),
78 );
79 const store = yield* openStore;
80 return {
81 model,
82 directory,
83 stale,
84 fs,
85 requests,
86 bodies,
87 transportFailure,
88 store,
89 openStore,
90 };
91});
92
93const dependencies = ServerConfig.layerTest("/tmp", { prefix: "speech-model-store-" }).pipe(
94 Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
95);
96
97it.effect("resumes an interrupted transfer, replaces a corrupt same-size file, and marks it", () =>
98 Effect.gen(function* () {
99 const h = yield* harness;
100 h.bodies.current = (request) =>
101 request.headers["range"]
102 ? Stream.succeed(bytes.subarray(SPLIT))
103 : Stream.concat(
104 Stream.succeed(bytes.subarray(0, SPLIT)),
105 Stream.fail(h.transportFailure(request)),
106 );
107 expect(yield* h.store.isReady(h.model)).toBe(true);
108 expect(yield* h.store.installedPath(h.model)).toBeUndefined();
109 expect(yield* h.store.isReady(h.model)).toBe(false);
110
111 const progress: number[] = [];
112 const installed = yield* h.store.download(h.model, {
113 onProgress: (downloaded) => progress.push(downloaded),
114 });
115 expect(installed).toBe(h.stale);
116 expect(h.requests.map((request) => request.headers["range"])).toEqual([
117 undefined,
118 `bytes=${SPLIT}-`,
119 ]);
120 const pinnedUrl = `https://huggingface.co/${h.model.id}/resolve/${h.model.revision}/${h.model.filename}`;
121 expect(h.requests.map((request) => request.url)).toEqual([pinnedUrl, pinnedUrl]);
122 expect(progress.at(0)).toBe(0);
123 expect(progress.at(-1)).toBe(bytes.length);
124 expect([...(yield* h.fs.readFile(installed))]).toEqual([...bytes]);
125 expect((yield* h.fs.readDirectory(h.directory)).sort()).toEqual([
126 "model.gguf",
127 "model.gguf.verified",
128 ]);
129 expect(yield* h.store.isReady(h.model)).toBe(true);
130 expect(yield* h.store.installedPath(h.model)).toBe(installed);
131 const requestsBeforeReuse = h.requests.length;
132 expect(yield* h.store.download(h.model)).toBe(installed);
133 expect(h.requests).toHaveLength(requestsBeforeReuse);
134 }).pipe(Effect.provide(dependencies)),
135);
136
137it.effect("rejects a same-size download whose SHA-256 differs from the catalog", () =>
138 Effect.gen(function* () {
139 const h = yield* harness;
140 h.bodies.current = () => Stream.succeed(new Uint8Array(bytes.length));
141 const result = yield* Effect.result(h.store.download(h.model));
142 expect(result).toMatchObject({ _tag: "Failure", failure: { reason: "verification" } });
143 expect(yield* h.fs.readDirectory(h.directory)).toEqual(["model.gguf"]);
144 expect(yield* h.store.installedPath(h.model)).toBeUndefined();
145 }).pipe(Effect.provide(dependencies)),
146);
147
148it.effect("resumes bytes a failed download already received on the next download", () =>
149 Effect.gen(function* () {
150 const h = yield* harness;
151 h.bodies.current = (request) =>
152 request.headers["range"]
153 ? Stream.fail(h.transportFailure(request))
154 : Stream.concat(
155 Stream.succeed(bytes.subarray(0, SPLIT)),
156 Stream.fail(h.transportFailure(request)),
157 );
158 const failed = yield* Effect.result(h.store.download(h.model));
159 expect(failed._tag).toBe("Failure");
160
161 h.bodies.current = (request) =>
162 Stream.succeed(request.headers["range"] ? bytes.subarray(SPLIT) : bytes);
163 const firstRetry = h.requests.length;
164 const installed = yield* h.store.download(h.model);
165 expect([...(yield* h.fs.readFile(installed))]).toEqual([...bytes]);
166 expect(h.requests[firstRetry]?.headers["range"]).toBe(`bytes=${SPLIT}-`);
167 }).pipe(Effect.provide(dependencies)),
168);
169
170it.effect(
171 "keeps a cancelled download's bytes across a restart and cleans only stale partials",
172 () =>
173 Effect.gen(function* () {
174 const h = yield* harness;
175 const written = yield* Deferred.make<void>();
176 h.bodies.current = () =>
177 Stream.succeed(bytes.subarray(0, SPLIT)).pipe(
178 Stream.concat(Stream.fromEffect(Deferred.succeed(written, undefined)).pipe(Stream.drain)),
179 Stream.concat(Stream.never),
180 );
181 const fiber = yield* h.store.download(h.model).pipe(Effect.forkChild);
182 yield* Deferred.await(written);
183 yield* Fiber.interrupt(fiber);
184 expect([...(yield* h.fs.readFile(h.stale))]).toEqual([...new Uint8Array(bytes.length)]);
185 const orphan = `${h.stale}.f660de6c-e172-4146-8ffe-d3c32eb48cd4.part`;
186 yield* h.fs.writeFile(orphan, bytes.subarray(0, SPLIT));
187 yield* h.fs.writeFileString(`${h.stale}.notes.part`, "not a download");
188 const store = yield* h.openStore;
189 expect((yield* h.fs.readDirectory(h.directory)).sort()).toEqual([
190 "model.gguf",
191 "model.gguf.notes.part",
192 "model.gguf.part",
193 ]);
194
195 h.bodies.current = (request) =>
196 Stream.succeed(request.headers["range"] ? bytes.subarray(SPLIT) : bytes);
197 const resumedFrom = h.requests.length;
198 expect([...(yield* h.fs.readFile(yield* store.download(h.model)))]).toEqual([...bytes]);
199 expect(h.requests[resumedFrom]?.headers["range"]).toBe(`bytes=${SPLIT}-`);
200 }).pipe(Effect.provide(dependencies)),
201);
202
203it.effect("keeps retrying while each dropped connection still delivers bytes", () =>
204 Effect.gen(function* () {
205 const h = yield* harness;
206 h.bodies.current = (request) => {
207 const from = Number(/^bytes=(\d+)-$/.exec(request.headers["range"] ?? "")?.[1] ?? 0);
208 return Stream.concat(
209 Stream.succeed(bytes.subarray(from, from + 8)),
210 from + 8 >= bytes.length ? Stream.empty : Stream.fail(h.transportFailure(request)),
211 );
212 };
213 expect([...(yield* h.fs.readFile(yield* h.store.download(h.model)))]).toEqual([...bytes]);
214 expect(h.requests).toHaveLength(bytes.length / 8);
215 }).pipe(Effect.provide(dependencies)),
216);
217
218it.effect("links through stray whitespace pasted around an existing folder", () =>
219 Effect.gen(function* () {
220 const h = yield* harness;
221 const path = yield* Path.Path;
222 const elsewhere = yield* h.fs.makeTempDirectoryScoped({ prefix: "speech-pasted-" });
223 yield* h.fs.writeFile(path.join(elsewhere, "model.gguf"), bytes);
224
225 expect(yield* h.store.link([h.model], ` ${elsewhere} \n`)).toEqual([h.model.id]);
226 }).pipe(Effect.provide(dependencies)),
227);
228
229it.effect("links a verified model file from another folder and never deletes it", () =>
230 Effect.gen(function* () {
231 const h = yield* harness;
232 const path = yield* Path.Path;
233 const elsewhere = yield* h.fs.makeTempDirectoryScoped({ prefix: "speech-other-app-" });
234 const spaced = path.join(elsewhere, "models ");
235 const nested = path.join(spaced, "hub", "snapshots");
236 yield* h.fs.makeDirectory(nested, { recursive: true });
237 const impostor = path.join(elsewhere, "same-size.gguf");
238 const existing = path.join(nested, "renamed-by-the-other-app.gguf");
239 yield* h.fs.writeFile(impostor, new Uint8Array(bytes.length));
240 yield* h.fs.writeFile(existing, bytes);
241
242 expect(yield* h.store.link([h.model], impostor)).toEqual([]);
243 expect(yield* h.store.linkedFrom(h.model)).toBeUndefined();
244
245 expect(yield* h.store.link([h.model], spaced)).toEqual([h.model.id]);
246 expect(yield* h.store.linkedFrom(h.model)).toBe(existing);
247 expect(yield* h.store.installedPath(h.model)).toBe(h.stale);
248 expect(h.requests).toHaveLength(0);
249 // Pointing at T3 Code's own folder must not turn the link into a link to itself.
250 expect(yield* h.store.link([h.model], h.directory)).toEqual([]);
251 expect(yield* h.store.installedPath(h.model)).toBe(h.stale);
252
253 const partial = `${h.stale}.part`;
254 const unrelated = path.join(h.directory, "other.gguf.part");
255 yield* h.fs.writeFile(partial, Uint8Array.of(1, 2, 3, 4));
256 yield* h.fs.writeFile(unrelated, Uint8Array.of(5));
257
258 yield* h.store.remove(h.model);
259 expect(yield* h.store.isReady(h.model)).toBe(false);
260 expect(yield* h.fs.exists(partial)).toBe(false);
261 expect(yield* h.fs.exists(unrelated)).toBe(true);
262 expect([...(yield* h.fs.readFile(existing))]).toEqual([...bytes]);
263 }).pipe(Effect.scoped, Effect.provide(dependencies)),
264);
265
266it.effect("installs from a Hugging Face cache copy instead of downloading", () =>
267 Effect.gen(function* () {
268 const h = yield* harness;
269 const path = yield* Path.Path;
270 const home = yield* h.fs.makeTempDirectoryScoped({ prefix: "speech-home-" });
271 const snapshot = path.join(
272 home,
273 ".cache/huggingface/hub/models--fixture--speech-model/snapshots",
274 h.model.revision,
275 );
276 yield* h.fs.makeDirectory(snapshot, { recursive: true });
277 const cached = path.join(snapshot, h.model.filename);
278 yield* h.fs.writeFile(cached, bytes);
279 const store = yield* h.openStore.pipe(Effect.provideService(HostProcess.HomeDirectory, home));
280
281 expect(yield* store.download(h.model)).toBe(h.stale);
282 expect(yield* store.linkedFrom(h.model)).toBe(cached);
283 expect(h.requests).toHaveLength(0);
284 }).pipe(Effect.scoped, Effect.provide(dependencies)),
285);