Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

261 lines9.9 KB

1import { decodeSpeechPcmRequest } from "@t3tools/shared/speech";
2import {
3 AuthFilesystemReadScope,
4 AuthOrchestrationOperateScope,
5 AuthSettingsWriteScope,
6 type AuthEnvironmentScope,
7 EnvironmentAuthenticatedPrincipal,
8 EnvironmentHttpApi,
9 type EnvironmentSpeechModels,
10 EnvironmentVoiceBodyLimit,
11 requiredScopesForServerSettingsPatch,
12 SPEECH_MAX_OPTIONS_BYTES,
13 TextGenerationError,
14} from "@t3tools/contracts";
15import * as ByteSize from "effect/ByteSize";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Redacted from "effect/Redacted";
20import * as Schema from "effect/Schema";
21import * as HttpServerRequest from "effect/http/HttpServerRequest";
22import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
23​
24import {
25 annotateEnvironmentRequest,
26 failEnvironmentInternal,
27 failEnvironmentInvalidRequest,
28 requireEnvironmentScope,
29} from "../auth/http.ts";
30import * as SpeechPostProcessing from "./postProcessing.ts";
31import * as CloudSpeech from "./CloudSpeech.ts";
32import * as SpeechService from "./SpeechService.ts";
33​
34const MAX_TRANSCRIBE_BODY_BYTES = SpeechService.MAX_SPEECH_BYTES + SPEECH_MAX_OPTIONS_BYTES + 4;
35const parseAudio = Option.liftThrowable(decodeSpeechPcmRequest);
36const isTextGenerationError = Schema.is(TextGenerationError);
37​
38const bodyLimit = Layer.succeed(EnvironmentVoiceBodyLimit, (effect) =>
39 Effect.gen(function* () {
40 const request = yield* HttpServerRequest.HttpServerRequest;
41 if (Number(request.headers["content-length"]) > MAX_TRANSCRIBE_BODY_BYTES)
42 return yield* failEnvironmentInvalidRequest("invalid_audio");
43 return yield* effect.pipe(
44 Effect.provideService(
45 HttpServerRequest.MaxBodySize,
46 ByteSize.bytes(MAX_TRANSCRIBE_BODY_BYTES),
47 ),
48 );
49 }),
50);
51​
52const mapSpeechError = <A, R>(effect: Effect.Effect<A, SpeechService.SpeechError, R>) =>
53 effect.pipe(
54 Effect.catchTags({
55 SpeechInvalidAudioError: () => failEnvironmentInvalidRequest("invalid_audio"),
56 SpeechUnsupportedPlatformError: () => failEnvironmentInvalidRequest("speech_unavailable"),
57 SpeechBusyError: () => failEnvironmentInvalidRequest("speech_busy"),
58 SpeechDownloadCancelledError: () => failEnvironmentInvalidRequest("speech_busy"),
59 SpeechModelNotFoundError: () => failEnvironmentInvalidRequest("invalid_command"),
60 SpeechOperationError: (error) => failEnvironmentInternal("internal_error", error),
61 }),
62 );
63​
64// A linked model's origin is a path on this machine; only filesystem readers may see it.
65// Untraced: it runs inside each handler's own span.
66const withoutHostPaths = Effect.fnUntraced(function* <Fields extends EnvironmentSpeechModels>({
67 models,
68 ...fields
69}: Fields) {
70 const session = yield* EnvironmentAuthenticatedPrincipal;
71 return {
72 ...fields,
73 models: session.scopes.has(AuthFilesystemReadScope)
74 ? models
75 : models.map(({ linkedFrom: _, ...model }) => model),
76 };
77});
78​
79export const speechHttpApiLayer = HttpApiBuilder.group(
80 EnvironmentHttpApi,
81 "voice",
82 Effect.fnUntraced(function* (handlers) {
83 const speech = yield* SpeechService.SpeechService;
84 const cloud = yield* CloudSpeech.CloudSpeech;
85 const postProcessing = yield* SpeechPostProcessing.SpeechPostProcessing;
86 const guard = Effect.fnUntraced(function* (
87 endpoint: string,
88 scope: AuthEnvironmentScope = AuthOrchestrationOperateScope,
89 ) {
90 yield* annotateEnvironmentRequest(endpoint);
91 yield* requireEnvironmentScope(scope);
92 });
93 return handlers
94 .handle(
95 "cloudKeys",
96 Effect.fn("environment.voice.cloudKeys")(function* (args) {
97 yield* guard(args.endpoint.name);
98 return yield* cloud.configured.pipe(
99 Effect.catch((error) => failEnvironmentInternal("internal_error", error)),
100 );
101 }),
102 )
103 .handle(
104 "setCloudKey",
105 Effect.fn("environment.voice.setCloudKey")(function* (args) {
106 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
107 // The key is a setting, so saving it needs what the same settings patch would.
108 const { key } = args.payload;
109 const value = key === null || Redacted.isRedacted(key) ? "" : key;
110 for (const scope of requiredScopesForServerSettingsPatch({
111 cloudSpeechCredentials: { [args.params.provider]: value },
112 })) {
113 yield* requireEnvironmentScope(scope);
114 }
115 yield* cloud
116 .setKey(args.params.provider, args.payload.key)
117 .pipe(Effect.catch((error) => failEnvironmentInternal("internal_error", error)));
118 }),
119 )
120 .handle(
121 "cloudModels",
122 Effect.fn("environment.voice.cloudModels")(function* (args) {
123 yield* guard(args.endpoint.name);
124 return { models: yield* cloud.models };
125 }),
126 )
127 .handle(
128 "transcribeCloud",
129 Effect.fn("environment.voice.transcribeCloud")(function* (args) {
130 yield* guard(args.endpoint.name);
131 const decoded = parseAudio(args.payload);
132 if (Option.isNone(decoded)) return yield* failEnvironmentInvalidRequest("invalid_audio");
133 const text = yield* cloud
134 .transcribe(
135 args.params.provider,
136 decoded.value.pcm,
137 decoded.value.options,
138 args.query.model,
139 )
140 .pipe(
141 Effect.catchTags({
142 ServerSettingsError: (error) => failEnvironmentInternal("internal_error", error),
143 SpeechInvalidAudioError: () => failEnvironmentInvalidRequest("invalid_audio"),
144 }),
145 );
146 return { text };
147 }),
148 )
149 .handle(
150 "status",
151 Effect.fn("environment.voice.status")(function* (args) {
152 yield* guard(args.endpoint.name);
153 return yield* speech.status.pipe(mapSpeechError);
154 }),
155 )
156 .handle(
157 "prepareModel",
158 Effect.fn("environment.voice.prepareModel")(function* (args) {
159 yield* guard(args.endpoint.name);
160 yield* speech.prepareModel.pipe(mapSpeechError);
161 }),
162 )
163 .handle(
164 "models",
165 Effect.fn("environment.voice.models")(function* (args) {
166 yield* guard(args.endpoint.name);
167 return yield* speech
168 .models(args.query.benchmarks === "1")
169 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
170 }),
171 )
172 .handle(
173 "downloadModel",
174 Effect.fn("environment.voice.downloadModel")(function* (args) {
175 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
176 return yield* speech
177 .downloadModel(args.payload.modelId)
178 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
179 }),
180 )
181 .handle(
182 "selectModel",
183 Effect.fn("environment.voice.selectModel")(function* (args) {
184 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
185 return yield* speech
186 .selectModel(args.payload.modelId)
187 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
188 }),
189 )
190 .handle(
191 "cancelModelDownload",
192 Effect.fn("environment.voice.cancelModelDownload")(function* (args) {
193 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
194 return yield* speech
195 .cancelDownload(args.payload.modelId)
196 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
197 }),
198 )
199 .handle(
200 "removeModel",
201 Effect.fn("environment.voice.removeModel")(function* (args) {
202 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
203 return yield* speech
204 .removeModel(args.payload.modelId)
205 .pipe(mapSpeechError, Effect.flatMap(withoutHostPaths));
206 }),
207 )
208 .handle(
209 "linkModels",
210 Effect.fn("environment.voice.linkModels")(function* (args) {
211 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
212 // The request names a path on this machine and the result reveals what is there.
213 yield* requireEnvironmentScope(AuthFilesystemReadScope);
214 return yield* speech.linkModels(args.payload.path).pipe(mapSpeechError);
215 }),
216 )
217 .handle(
218 "updateAcceleration",
219 Effect.fn("environment.voice.updateAcceleration")(function* (args) {
220 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
221 return yield* speech.updateAcceleration(args.payload.acceleration).pipe(mapSpeechError);
222 }),
223 )
224 .handle(
225 "updateModelUnloadTimeout",
226 Effect.fn("environment.voice.updateModelUnloadTimeout")(function* (args) {
227 yield* guard(args.endpoint.name, AuthSettingsWriteScope);
228 return yield* speech.updateModelUnloadTimeout(args.payload.timeout).pipe(mapSpeechError);
229 }),
230 )
231 .handle(
232 "transcribe",
233 Effect.fn("environment.voice.transcribe")(function* (args) {
234 yield* guard(args.endpoint.name);
235 const decoded = parseAudio(args.payload);
236 if (Option.isNone(decoded)) return yield* failEnvironmentInvalidRequest("invalid_audio");
237 const text = yield* speech
238 .transcribe(decoded.value.pcm, decoded.value.options)
239 .pipe(mapSpeechError);
240 return { text };
241 }),
242 )
243 .handle(
244 "postProcess",
245 Effect.fn("environment.voice.postProcess")(function* (args) {
246 yield* guard(args.endpoint.name);
247 return yield* postProcessing
248 .process(args.payload)
249 .pipe(
250 Effect.catch((error) =>
251 failEnvironmentInternal(
252 "internal_error",
253 error,
254 isTextGenerationError(error.cause) ? error.cause.detail : undefined,
255 ),
256 ),
257 );
258 }),
259 );
260 }),
261).pipe(Layer.provide(bodyLimit), Layer.provide(SpeechPostProcessing.layer));