Open History to see the last commit
1import { encodeSpeechPcmRequest } from "@t3tools/shared/speech";
2// @effect-diagnostics nodeBuiltinImport:off globalFetch:off globalFetchInEffect:off - real HTTP streaming boundary test.
3import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import { it as effectIt } from "@effect/vitest";
6import { expect, vi } from "vite-plus/test";
7import {
8 AuthSessionId,
9 AuthOrchestrationOperateScope,
10 DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
11 SPEECH_MAX_OPTIONS_BYTES,
12 DEFAULT_SERVER_SETTINGS,
13 EnvironmentAuthenticatedAuth,
14 EnvironmentAuthenticatedPrincipal,
15 EnvironmentVoiceHttpApi,
16} from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as Layer from "effect/Layer";
19import * as Schema from "effect/Schema";
20import * as HttpRouter from "effect/http/HttpRouter";
21import * as HttpServer from "effect/http/HttpServer";
22import * as HttpApi from "effect/http-api/HttpApi";
23import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
24import type * as NetAddress from "effect/net/NetAddress";
25import * as SpeechService from "./SpeechService.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import * as TextGeneration from "../textGeneration/TextGeneration.ts";
28import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
29import { speechHttpApiLayer } from "./http.ts";
30
31const decodeSessionId = Schema.decodeUnknownSync(AuthSessionId);
32
33const dependencies = Layer.mergeAll(
34 Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
35 Layer.mock(ServerSettings.ServerSettingsService)({
36 getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
37 }),
38 Layer.succeed(
39 TextGeneration.TextGeneration,
40 TextGeneration.TextGeneration.of({
41 generateCommitMessage: () => Effect.die("not used"),
42 generatePrContent: () => Effect.die("not used"),
43 generateBranchName: () => Effect.die("not used"),
44 generateThreadTitle: () => Effect.die("not used"),
45 generateReviewGuide: () => Effect.die("not used"),
46 generateTranscriptionPostProcessing: () => Effect.die("not used"),
47 }),
48 ),
49);
50
51effectIt.live("rejects oversized chunked audio without invoking transcription", () =>
52 Effect.gen(function* () {
53 const transcribe = vi.fn(() => Effect.succeed("unexpected"));
54 const auth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
55 effect.pipe(
56 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
57 sessionId: decodeSessionId("voice-test"),
58 subject: "test",
59 method: "bearer-access-token",
60 scopes: new Set([AuthOrchestrationOperateScope]),
61 }),
62 ),
63 );
64 const routes = HttpApiBuilder.layer(
65 HttpApi.make("environment").add(EnvironmentVoiceHttpApi),
66 ).pipe(
67 Layer.provide(speechHttpApiLayer),
68 Layer.provide(auth),
69 Layer.provide(
70 Layer.succeed(SpeechService.SpeechService, {
71 status: Effect.succeed({ supported: false as const, reason: "test" }),
72 prepareModel: Effect.void,
73 models: () => Effect.succeed({ models: [] }),
74 downloadModel: () => Effect.succeed({ models: [] }),
75 selectModel: () => Effect.succeed({ models: [] }),
76 cancelDownload: () => Effect.succeed({ models: [] }),
77 updateAcceleration: () => Effect.succeed({ supported: false as const, reason: "test" }),
78 updateModelUnloadTimeout: () =>
79 Effect.succeed({ supported: false as const, reason: "test" }),
80 transcribe,
81 startStream: () => Effect.die("not used"),
82 removeModel: () => Effect.succeed({ models: [] }),
83 }),
84 ),
85 );
86 yield* Effect.gen(function* () {
87 yield* Layer.build(HttpRouter.serve(routes, { disableLogger: true, disableListenLog: true }));
88 const server = yield* HttpServer.HttpServer;
89 const address = server.address as NetAddress.InetAddress;
90 const host = address._tag === "InetAddressV6" ? "[::1]" : "127.0.0.1";
91 const url = `http://${host}:${address.port}/api/voice/transcribe`;
92 const select = yield* Effect.promise(() =>
93 fetch(new URL("models/select", url), {
94 method: "POST",
95 headers: { "content-type": "application/json" },
96 body: JSON.stringify({ modelId: "test" }),
97 }),
98 );
99 expect(select.status).toBe(403);
100 yield* Effect.promise(() =>
101 expect(
102 fetch(url, {
103 method: "POST",
104 headers: { "content-type": "application/octet-stream" },
105 body: new ReadableStream({
106 start(controller) {
107 controller.enqueue(
108 new Uint8Array(SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4),
109 );
110 controller.enqueue(new Uint8Array(4));
111 controller.close();
112 },
113 }),
114 duplex: "half",
115 }),
116 ).resolves.toMatchObject({ status: 413 }),
117 );
118 expect(transcribe).not.toHaveBeenCalled();
119 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeHttpServer.layerTest, dependencies)));
120 }),
121);
122
123effectIt.effect.each([
124 {
125 error: new SpeechService.SpeechInvalidAudioError({ byteLength: 3, message: "invalid PCM" }),
126 reason: "invalid_audio",
127 },
128 {
129 error: new SpeechService.SpeechUnsupportedPlatformError({
130 platform: "win32",
131 architecture: "arm64",
132 }),
133 reason: "speech_unavailable",
134 },
135 {
136 malformedOptions: true,
137 error: new SpeechService.SpeechInvalidAudioError({ byteLength: 3, message: "invalid PCM" }),
138 reason: "invalid_audio",
139 },
140 {
141 oversized: true,
142 error: new SpeechService.SpeechInvalidAudioError({ byteLength: 3, message: "invalid PCM" }),
143 reason: "invalid_audio",
144 },
145 {
146 error: new SpeechService.SpeechBusyError({ operation: "transcription" }),
147 reason: "speech_busy",
148 },
149])(
150 "returns a typed client error for $reason instead of HTTP 500",
151 ({ error, reason, ...options }) =>
152 Effect.gen(function* () {
153 // Only authentication and the native service are replaced; exercise the actual HTTP handlers and codecs.
154 const auth = Layer.succeed(EnvironmentAuthenticatedAuth, (effect) =>
155 effect.pipe(
156 Effect.provideService(EnvironmentAuthenticatedPrincipal, {
157 sessionId: decodeSessionId("voice-test"),
158 subject: "test",
159 method: "bearer-access-token",
160 scopes: new Set([AuthOrchestrationOperateScope]),
161 }),
162 ),
163 );
164 const transcribe = vi.fn(() => Effect.fail(error));
165 const service = Layer.succeed(SpeechService.SpeechService, {
166 status: Effect.succeed({ supported: false as const, reason: "test" }),
167 prepareModel: Effect.void,
168 models: () => Effect.succeed({ models: [] }),
169 downloadModel: () => Effect.fail(error),
170 selectModel: () => Effect.fail(error),
171 cancelDownload: () => Effect.fail(error),
172 updateAcceleration: () => Effect.fail(error),
173 updateModelUnloadTimeout: () => Effect.fail(error),
174 transcribe,
175 startStream: () => Effect.fail(error),
176 removeModel: () => Effect.fail(error),
177 });
178 const api = HttpApi.make("environment").add(EnvironmentVoiceHttpApi);
179 const { handler, dispose } = HttpRouter.toWebHandler(
180 HttpApiBuilder.layer(api).pipe(
181 Layer.provide(speechHttpApiLayer),
182 Layer.provide(auth),
183 Layer.provide(service),
184 Layer.provide(HttpServer.layerServices),
185 Layer.provide(dependencies),
186 Layer.provide(NodeServices.layer),
187 ),
188 { disableLogger: true },
189 );
190 yield* Effect.addFinalizer(() => Effect.promise(dispose));
191 const request = new Request("http://localhost/api/voice/transcribe", {
192 method: "POST",
193 headers: { "content-type": "application/octet-stream" },
194 body:
195 "malformedOptions" in options
196 ? new Uint8Array([255, 255, 255, 255])
197 : encodeSpeechPcmRequest(new Uint8Array(3), DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS),
198 });
199 const decode = vi.spyOn(request, "arrayBuffer");
200 if ("oversized" in options)
201 request.headers.set(
202 "content-length",
203 String(SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 5),
204 );
205 const context = yield* Layer.build(Layer.mergeAll(dependencies, NodeServices.layer));
206 const response = yield* Effect.promise(() => handler(request, context));
207 if ("oversized" in options) expect(decode).not.toHaveBeenCalled();
208 if ("malformedOptions" in options || "oversized" in options) {
209 expect(transcribe).not.toHaveBeenCalled();
210 } else {
211 expect(transcribe).toHaveBeenCalledWith(
212 new Uint8Array(3),
213 DEFAULT_SPEECH_TRANSCRIPTION_OPTIONS,
214 );
215 }
216 expect(response.status).toBe(400);
217 expect(yield* Effect.promise(() => response.json())).toMatchObject({
218 code: "invalid_request",
219 reason,
220 });
221 }).pipe(Effect.scoped),
222);