Open History to see the last commit
1import {
2 AuthOrchestrationOperateScope,
3 SPEECH_STREAM_PATH,
4 SPEECH_STREAM_MAX_CHUNK_BYTES,
5 SpeechStreamCommand,
6 SPEECH_MAX_OPTIONS_BYTES,
7 type SpeechStreamEvent,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import * as Queue from "effect/Queue";
13import * as Schema from "effect/Schema";
14import * as Scope from "effect/Scope";
15import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/http";
16import * as Socket from "effect/socket/Socket";
17import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
18import * as SpeechService from "./SpeechService.ts";
19
20// A recording client streams audio continuously; behind a proxy a vanished
21// client never closes the server side, so silence is the only sign it is gone.
22const SPEECH_SOCKET_IDLE_TIMEOUT = "15 seconds";
23
24const decodeCommand = Schema.decodeUnknownEffect(Schema.fromJsonString(SpeechStreamCommand));
25
26/** One socket owns one stream. Audio is processed and acknowledged in arrival order. */
27export const runSpeechSocket = Effect.fn("speech.runSocket")(function* (
28 socket: Socket.Socket,
29 speech: Pick<SpeechService.SpeechService["Service"], "startStream">,
30) {
31 const scope = yield* Scope.Scope;
32 const writer = yield* socket.writer;
33 const send = (event: SpeechStreamEvent) => writer.write(JSON.stringify(event));
34 let stream: SpeechService.SpeechStream | undefined;
35 let ended = false;
36 const fail = Effect.fn("speech.failSocket")(function* (message: string) {
37 if (ended) return;
38 ended = true;
39 yield* send({ type: "error", message });
40 yield* writer.write(new Socket.CloseEvent(1008, "Speech stream ended"));
41 });
42 const receive = (data: string | Uint8Array) => {
43 if (ended) return Effect.void;
44 return Effect.gen(function* () {
45 if (typeof data === "string") {
46 if (new TextEncoder().encode(data).byteLength > SPEECH_MAX_OPTIONS_BYTES)
47 return yield* fail("Invalid speech stream command.");
48 const command = yield* decodeCommand(data);
49 if (command.type === "start") {
50 if (stream) return yield* fail("Speech stream already started.");
51 stream = yield* speech.startStream(command.options).pipe(Scope.provide(scope));
52 yield* send({ type: "ready" });
53 return;
54 }
55 if (!stream) return yield* fail("Start speech transcription before finishing.");
56 const text = yield* stream.finish;
57 ended = true;
58 yield* send({ type: "finished", text });
59 yield* writer.write(new Socket.CloseEvent(1000));
60 } else {
61 if (data.byteLength > SPEECH_STREAM_MAX_CHUNK_BYTES)
62 return yield* fail("Speech audio chunk is too large.");
63 if (!stream) return yield* fail("Start speech transcription before sending audio.");
64 const update = yield* stream.feed(data);
65 yield* send({ type: "update", ...update });
66 }
67 }).pipe(
68 Effect.catch((cause) =>
69 Effect.logError("live transcription operation failed", { cause }).pipe(
70 Effect.andThen(fail("Live transcription failed. Please try recording again.")),
71 ),
72 ),
73 );
74 };
75 const reader = yield* socket.reader;
76 // Silence only counts while every received frame has been answered.
77 let unanswered = 0;
78 const activity = yield* Queue.sliding<void>(1);
79 const idle = Effect.gen(function* () {
80 while (true) {
81 const heard = yield* Queue.take(activity).pipe(
82 Effect.timeoutOption(SPEECH_SOCKET_IDLE_TIMEOUT),
83 );
84 if (Option.isNone(heard) && unanswered === 0) return;
85 }
86 });
87 const read = Effect.gen(function* () {
88 const pending = yield* Queue.bounded<string | Uint8Array>(2);
89 yield* Effect.forever(
90 Queue.take(pending).pipe(
91 Effect.flatMap(receive),
92 Effect.andThen(() => {
93 unanswered--;
94 return Queue.offer(activity, undefined);
95 }),
96 ),
97 ).pipe(Effect.forkScoped);
98 while (true) {
99 const frames = yield* reader.pull;
100 unanswered += frames.length;
101 yield* Queue.offer(activity, undefined);
102 yield* Effect.forEach(frames, (frame) => Queue.offer(pending, frame), {
103 discard: true,
104 });
105 }
106 });
107 yield* Effect.raceFirst(read, idle).pipe(
108 Effect.timeoutOrElse({
109 duration: "10 minutes",
110 // The socket read loop is already interrupted here; its writer can no longer send.
111 orElse: () => Effect.void,
112 }),
113 Effect.ignore,
114 );
115});
116
117export const speechStreamRouteLayer = Layer.unwrap(
118 Effect.gen(function* () {
119 const auth = yield* EnvironmentAuth.EnvironmentAuth;
120 const speech = yield* SpeechService.SpeechService;
121 return HttpRouter.add(
122 "GET",
123 SPEECH_STREAM_PATH,
124 Effect.gen(function* () {
125 const request = yield* HttpServerRequest.HttpServerRequest;
126 const session = yield* auth
127 .authenticateWebSocketUpgrade(request, "media")
128 .pipe(Effect.result);
129 if (session._tag === "Failure") return HttpServerResponse.empty({ status: 401 });
130 if (!session.success.scopes.includes(AuthOrchestrationOperateScope))
131 return HttpServerResponse.empty({ status: 403 });
132 const socket = yield* request.upgrade;
133 yield* runSpeechSocket(socket, speech).pipe(Effect.scoped);
134 return HttpServerResponse.empty();
135 }),
136 );
137 }),
138);