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

protocol.ts

574 lines18.8 KB

1import * as Cause from "effect/Cause";
2import * as Effect from "effect/Effect";
3import * as Deferred from "effect/Deferred";
4import * as Queue from "effect/Queue";
5import * as Ref from "effect/Ref";
6import * as Schema from "effect/Schema";
7import * as Scope from "effect/Scope";
8import * as Stream from "effect/Stream";
9import * as Stdio from "effect/Stdio";
10import * as RpcClient from "effect/unstable/rpc/RpcClient";
11import * as RpcClientError from "effect/unstable/rpc/RpcClientError";
12import * as RpcMessage from "effect/unstable/rpc/RpcMessage";
13import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";
14import * as RpcServer from "effect/unstable/rpc/RpcServer";
15​
16import * as AcpSchema from "./_generated/schema.gen.ts";
17import { CLIENT_METHODS } from "./_generated/meta.gen.ts";
18import * as AcpError from "./errors.ts";
19const isAcpError = Schema.is(AcpError.AcpError);
20​
21export interface AcpProtocolLogEvent {
22 readonly direction: "incoming" | "outgoing";
23 readonly stage: "raw" | "decoded" | "decode_failed";
24 readonly payload: unknown;
26​
27export type AcpIncomingNotification =
28 | {
29 readonly _tag: "SessionUpdate";
30 readonly method: typeof CLIENT_METHODS.session_update;
31 readonly params: AcpSchema.SessionNotification;
32 }
33 | {
34 readonly _tag: "ElicitationComplete";
35 readonly method: typeof CLIENT_METHODS.session_elicitation_complete;
36 readonly params: AcpSchema.ElicitationCompleteNotification;
37 }
38 | {
39 readonly _tag: "ExtNotification";
40 readonly method: string;
41 readonly params: unknown;
42 };
43​
44export interface AcpPatchedProtocolOptions {
45 readonly stdio: Stdio.Stdio;
46 readonly terminationError?: Effect.Effect<AcpError.AcpError>;
47 readonly serverRequestMethods: ReadonlySet<string>;
48 readonly logIncoming?: boolean;
49 readonly logOutgoing?: boolean;
50 readonly logger?: (event: AcpProtocolLogEvent) => Effect.Effect<void, never>;
51 readonly onNotification?: (
52 notification: AcpIncomingNotification,
53 ) => Effect.Effect<void, AcpError.AcpError, never>;
54 readonly onExtRequest?: (
55 method: string,
56 params: unknown,
57 ) => Effect.Effect<unknown, AcpError.AcpError, never>;
58 readonly onTermination?: (error: AcpError.AcpError) => Effect.Effect<void, never, never>;
60​
61export interface AcpPatchedProtocol {
62 readonly clientProtocol: RpcClient.Protocol["Service"];
63 readonly serverProtocol: RpcServer.Protocol["Service"];
64 readonly incoming: Stream.Stream<AcpIncomingNotification>;
65 readonly request: (method: string, payload: unknown) => Effect.Effect<unknown, AcpError.AcpError>;
66 readonly notify: (method: string, payload: unknown) => Effect.Effect<void, AcpError.AcpError>;
68​
69interface AcpPendingRequest {
70 readonly deferred: Deferred.Deferred<unknown, AcpError.AcpError>;
71 readonly method: string;
73​
74const decodeSessionUpdate = Schema.decodeUnknownEffect(AcpSchema.SessionNotification);
75const decodeElicitationComplete = Schema.decodeUnknownEffect(
76 AcpSchema.ElicitationCompleteNotification,
77);
78const parserFactory = RpcSerialization.ndJsonRpc();
79​
80export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(function* (
81 options: AcpPatchedProtocolOptions,
82): Effect.fn.Return<AcpPatchedProtocol, never, Scope.Scope> {
83 const parser = parserFactory.makeUnsafe();
84 const serverQueue = yield* Queue.unbounded<RpcMessage.FromClientEncoded>();
85 const clientQueue = yield* Queue.unbounded<RpcMessage.FromServerEncoded>();
86 const notificationQueue = yield* Queue.unbounded<AcpIncomingNotification>();
87 const disconnects = yield* Queue.unbounded<number>();
88 const outgoing = yield* Queue.unbounded<string | Uint8Array, Cause.Done<void>>();
89 const nextRequestId = yield* Ref.make(1);
90 const terminationHandled = yield* Ref.make(false);
91 const extPending = yield* Ref.make(new Map<string, AcpPendingRequest>());
92​
93 const logProtocol = (event: AcpProtocolLogEvent) => {
94 if (event.direction === "incoming" && !options.logIncoming) {
95 return Effect.void;
96 }
97 if (event.direction === "outgoing" && !options.logOutgoing) {
98 return Effect.void;
99 }
100 return (
101 options.logger?.(event) ??
102 Effect.logDebug("ACP protocol event").pipe(Effect.annotateLogs({ event }))
103 );
104 };
105​
106 const offerOutgoing = Effect.fn("offerOutgoing")(function* (
107 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
108 ) {
109 yield* logProtocol({
110 direction: "outgoing",
111 stage: "decoded",
112 payload: message,
113 });
114​
115 const method = message._tag === "Request" ? message.tag : undefined;
116 const encodedRequestId =
117 message._tag === "Request"
118 ? message.id
119 : "requestId" in message
120 ? message.requestId
121 : undefined;
122 const requestId = encodedRequestId === "" ? undefined : encodedRequestId;
123 const encoded = yield* Effect.try({
124 try: () => parser.encode(message),
125 catch: (cause) => AcpError.AcpProtocolParseError.fromEncodingError(method, requestId, cause),
126 });
127​
128 if (encoded) {
129 yield* logProtocol({
130 direction: "outgoing",
131 stage: "raw",
132 payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded),
133 });
134​
135 yield* Queue.offer(outgoing, encoded).pipe(Effect.asVoid);
136 }
137 });
138​
139 const resolveExtPending = (
140 requestId: AcpError.AcpRequestId,
141 onFound: (pendingRequest: AcpPendingRequest) => Effect.Effect<void>,
142 ) =>
143 Ref.modify(extPending, (pending) => {
144 const pendingKey = String(requestId);
145 const pendingRequest = pending.get(pendingKey);
146 if (!pendingRequest) {
147 return [Effect.void, pending] as const;
148 }
149 const next = new Map(pending);
150 next.delete(pendingKey);
151 return [onFound(pendingRequest), next] as const;
152 }).pipe(Effect.flatten);
153​
154 const removeExtPending = (requestId: AcpError.AcpRequestId) =>
155 Ref.update(extPending, (pending) => {
156 const pendingKey = String(requestId);
157 if (!pending.has(pendingKey)) {
158 return pending;
159 }
160 const next = new Map(pending);
161 next.delete(pendingKey);
162 return next;
163 });
164​
165 const completeExtPendingFailure = (requestId: AcpError.AcpRequestId, error: AcpError.AcpError) =>
166 resolveExtPending(requestId, ({ deferred }) => Deferred.fail(deferred, error));
167​
168 const completeExtPendingSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
169 resolveExtPending(requestId, ({ deferred }) => Deferred.succeed(deferred, value));
170​
171 const failAllExtPending = (error: AcpError.AcpError) =>
172 Ref.getAndSet(extPending, new Map()).pipe(
173 Effect.flatMap((pending) =>
174 Effect.forEach([...pending.values()], ({ deferred }) => Deferred.fail(deferred, error), {
175 discard: true,
176 }),
177 ),
178 );
179​
180 const dispatchNotification = (notification: AcpIncomingNotification) =>
181 Queue.offer(notificationQueue, notification).pipe(
182 Effect.andThen(
183 options.onNotification
184 ? options.onNotification(notification).pipe(Effect.catch(() => Effect.void))
185 : Effect.void,
186 ),
187 Effect.asVoid,
188 );
189​
190 const emitClientProtocolError = (error: AcpError.AcpError) =>
191 Queue.offer(clientQueue, {
192 _tag: "ClientProtocolError",
193 error: new RpcClientError.RpcClientError({
194 reason: new RpcClientError.RpcClientDefect({
195 message: "ACP protocol terminated.",
196 cause: error,
197 }),
198 }),
199 }).pipe(Effect.asVoid);
200​
201 const handleTermination = (classify: () => Effect.Effect<AcpError.AcpError | undefined>) =>
202 Ref.modify(terminationHandled, (handled) => {
203 if (handled) {
204 return [Effect.void, true] as const;
205 }
206 return [
207 Effect.gen(function* () {
208 yield* Queue.offer(disconnects, 0);
209 const error = yield* classify();
210 if (!error) {
211 return;
212 }
213 yield* failAllExtPending(error);
214 yield* emitClientProtocolError(error);
215 if (options.onTermination) {
216 yield* options.onTermination(error);
217 }
218 }),
219 true,
220 ] as const;
221 }).pipe(Effect.flatten);
222​
223 const respondWithSuccess = (requestId: AcpError.AcpRequestId, value: unknown) =>
224 offerOutgoing({
225 _tag: "Exit",
226 requestId,
227 exit: {
228 _tag: "Success",
229 value,
230 },
231 });
232​
233 const respondWithError = (requestId: AcpError.AcpRequestId, error: AcpError.AcpRequestError) =>
234 offerOutgoing({
235 _tag: "Exit",
236 requestId,
237 exit: {
238 _tag: "Failure",
239 cause: [
240 {
241 _tag: "Fail",
242 error: error.toProtocolError(),
243 },
244 ],
245 },
246 });
247​
248 const handleExtRequest = (message: RpcMessage.RequestEncoded) => {
249 if (!options.onExtRequest) {
250 return respondWithError(message.id, AcpError.AcpRequestError.methodNotFound(message.tag));
251 }
252 return options.onExtRequest(message.tag, message.payload).pipe(
253 Effect.matchEffect({
254 onFailure: (error) =>
255 respondWithError(
256 message.id,
257 AcpError.AcpRequestError.fromExtensionHandlerError(error, message.tag),
258 ),
259 onSuccess: (value) => respondWithSuccess(message.id, value),
260 }),
261 );
262 };
263​
264 const handleRequestEncoded = (message: RpcMessage.RequestEncoded) => {
265 if (message.id === "") {
266 if (message.tag === CLIENT_METHODS.session_update) {
267 return decodeSessionUpdate(message.payload).pipe(
268 Effect.map(
269 (params) =>
270 ({
271 _tag: "SessionUpdate",
272 method: CLIENT_METHODS.session_update,
273 params,
274 }) satisfies AcpIncomingNotification,
275 ),
276 Effect.mapError((cause) =>
277 AcpError.AcpProtocolParseError.fromSchemaError(
278 "decode-notification-payload",
279 CLIENT_METHODS.session_update,
280 cause,
281 ),
282 ),
283 Effect.flatMap(dispatchNotification),
284 );
285 }
286 if (message.tag === CLIENT_METHODS.session_elicitation_complete) {
287 return decodeElicitationComplete(message.payload).pipe(
288 Effect.map(
289 (params) =>
290 ({
291 _tag: "ElicitationComplete",
292 method: CLIENT_METHODS.session_elicitation_complete,
293 params,
294 }) satisfies AcpIncomingNotification,
295 ),
296 Effect.mapError((cause) =>
297 AcpError.AcpProtocolParseError.fromSchemaError(
298 "decode-notification-payload",
299 CLIENT_METHODS.session_elicitation_complete,
300 cause,
301 ),
302 ),
303 Effect.flatMap(dispatchNotification),
304 );
305 }
306 return dispatchNotification({
307 _tag: "ExtNotification",
308 method: message.tag,
309 params: message.payload,
310 });
311 }
312​
313 if (!options.serverRequestMethods.has(message.tag)) {
314 return handleExtRequest(message).pipe(
315 Effect.catchTags({
316 AcpProtocolParseError: (error) =>
317 Effect.logWarning(error).pipe(
318 Effect.annotateLogs({
319 method: message.tag,
320 requestId: message.id,
321 operation: error.operation,
322 }),
323 Effect.andThen(
324 respondWithError(
325 message.id,
326 AcpError.AcpRequestError.fromExtensionResponseEncodingError(
327 message.tag,
328 message.id,
329 error,
330 ),
331 ),
332 ),
333 ),
334 }),
335 Effect.asVoid,
336 );
337 }
338​
339 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
340 };
341​
342 const handleExitEncoded = (message: RpcMessage.ResponseExitEncoded) =>
343 Ref.get(extPending).pipe(
344 Effect.flatMap((pending) => {
345 const pendingRequest = pending.get(String(message.requestId));
346 if (!pendingRequest) {
347 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
348 }
349 if (message.exit._tag === "Success") {
350 return completeExtPendingSuccess(message.requestId, message.exit.value);
351 }
352 const failure = message.exit.cause.find((entry) => entry._tag === "Fail");
353 if (failure && isProtocolError(failure.error)) {
354 return completeExtPendingFailure(
355 message.requestId,
356 AcpError.AcpRequestError.fromProtocolError(failure.error, {
357 method: pendingRequest.method,
358 requestId: message.requestId,
359 cause: message.exit.cause,
360 }),
361 );
362 }
363 return completeExtPendingFailure(
364 message.requestId,
365 AcpError.AcpRequestError.fromExtensionResponseFailure(
366 pendingRequest.method,
367 message.requestId,
368 message.exit.cause,
369 ),
370 );
371 }),
372 );
373​
374 const routeDecodedMessage = (
375 message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded,
376 ): Effect.Effect<void, AcpError.AcpError> => {
377 switch (message._tag) {
378 case "Request":
379 return handleRequestEncoded(message);
380 case "Exit":
381 return handleExitEncoded(message);
382 case "Chunk":
383 return Ref.get(extPending).pipe(
384 Effect.flatMap((pending) => {
385 const pendingRequest = pending.get(String(message.requestId));
386 return pendingRequest
387 ? completeExtPendingFailure(
388 message.requestId,
389 AcpError.AcpRequestError.unsupportedStreamingResponse(
390 pendingRequest.method,
391 message.requestId,
392 ),
393 )
394 : Queue.offer(clientQueue, message).pipe(Effect.asVoid);
395 }),
396 );
397 case "Defect":
398 case "ClientProtocolError":
399 case "Pong":
400 return Queue.offer(clientQueue, message).pipe(Effect.asVoid);
401 case "Ack":
402 case "Interrupt":
403 case "Ping":
404 case "Eof":
405 return Queue.offer(serverQueue, message).pipe(Effect.asVoid);
406 }
407 };
408​
409 yield* options.stdio.stdin.pipe(
410 Stream.runForEach((data) =>
411 logProtocol({
412 direction: "incoming",
413 stage: "raw",
414 payload: typeof data === "string" ? data : new TextDecoder().decode(data),
415 }).pipe(
416 Effect.flatMap(() =>
417 Effect.try({
418 try: () =>
419 parser.decode(data) as ReadonlyArray<
420 RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded
421 >,
422 catch: (cause) =>
423 new AcpError.AcpProtocolParseError({
424 operation: "decode-wire-message",
425 cause,
426 }),
427 }),
428 ),
429 Effect.tap((messages) =>
430 logProtocol({
431 direction: "incoming",
432 stage: "decoded",
433 payload: messages,
434 }),
435 ),
436 Effect.tapErrorTag("AcpProtocolParseError", (error) =>
437 logProtocol({
438 direction: "incoming",
439 stage: "decode_failed",
440 payload: {
441 operation: error.operation,
442 ...(error.method === undefined ? {} : { method: error.method }),
443 ...(error.requestId === undefined ? {} : { requestId: error.requestId }),
444 ...(error.issueCount === undefined ? {} : { issueCount: error.issueCount }),
445 ...(error.issueKinds === undefined ? {} : { issueKinds: error.issueKinds }),
446 ...(error.maximumPathDepth === undefined
447 ? {}
448 : { maximumPathDepth: error.maximumPathDepth }),
449 },
450 }),
451 ),
452 Effect.flatMap((messages) =>
453 Effect.forEach(messages, routeDecodedMessage, {
454 discard: true,
455 }),
456 ),
457 ),
458 ),
459 Effect.matchEffect({
460 onFailure: (error) => {
461 const normalized: AcpError.AcpError = isAcpError(error)
462 ? error
463 : new AcpError.AcpTransportError({
464 operation: "read-input-stream",
465 cause: error,
466 });
467 return handleTermination(() => Effect.succeed(normalized));
468 },
469 onSuccess: () =>
470 handleTermination(
471 () =>
472 options.terminationError ?? Effect.succeed(new AcpError.AcpInputStreamEndedError({})),
473 ),
474 }),
475 Effect.forkScoped,
476 );
477​
478 yield* Stream.fromQueue(outgoing).pipe(Stream.run(options.stdio.stdout()), Effect.forkScoped);
479​
480 const clientProtocol = RpcClient.Protocol.of({
481 run: (_clientId, f) =>
482 Stream.fromQueue(clientQueue).pipe(
483 Stream.runForEach((message) => f(message)),
484 Effect.forever,
485 ),
486 send: (_clientId, request) =>
487 offerOutgoing(request).pipe(
488 Effect.mapError(
489 (error) =>
490 new RpcClientError.RpcClientError({
491 reason: new RpcClientError.RpcClientDefect({
492 message: "Failed to send ACP protocol message.",
493 cause: error,
494 }),
495 }),
496 ),
497 ),
498 supportsAck: true,
499 supportsTransferables: false,
500 });
501​
502 const serverProtocol = RpcServer.Protocol.of({
503 run: (f) =>
504 Stream.fromQueue(serverQueue).pipe(
505 Stream.runForEach((message) => f(0, message)),
506 Effect.forever,
507 ),
508 disconnects,
509 send: (_clientId, response) => offerOutgoing(response).pipe(Effect.orDie),
510 end: (_clientId) => Queue.end(outgoing),
511 clientIds: Effect.succeed(new Set([0])),
512 initialMessage: Effect.succeedNone,
513 supportsAck: true,
514 supportsTransferables: false,
515 supportsSpanPropagation: true,
516 });
517​
518 const sendNotification = Effect.fn("sendNotification")(function* (
519 method: string,
520 payload: unknown,
521 ) {
522 yield* offerOutgoing({
523 _tag: "Request",
524 id: "",
525 tag: method,
526 payload,
527 headers: [],
528 });
529 });
530​
531 const sendRequest = Effect.fn("sendRequest")(function* (method: string, payload: unknown) {
532 const requestId = yield* Ref.modify(
533 nextRequestId,
534 (current) => [current, current + 1] as const,
535 );
536 const deferred = yield* Deferred.make<unknown, AcpError.AcpError>();
537 yield* Ref.update(extPending, (pending) =>
538 new Map(pending).set(String(requestId), { deferred, method }),
539 );
540 yield* offerOutgoing({
541 _tag: "Request",
542 id: requestId,
543 tag: method,
544 payload,
545 headers: [],
546 }).pipe(Effect.tapError(() => removeExtPending(requestId)));
547 return yield* Deferred.await(deferred).pipe(
548 Effect.onInterrupt(() => removeExtPending(requestId)),
549 );
550 });
551​
552 return {
553 clientProtocol,
554 serverProtocol,
555 get incoming() {
556 return Stream.fromQueue(notificationQueue);
557 },
558 request: sendRequest,
559 notify: sendNotification,
560 } satisfies AcpPatchedProtocol;
561});
562​
563function isProtocolError(
564 value: unknown,
565): value is { code: number; message: string; data?: unknown } {
566 return (
567 typeof value === "object" &&
568 value !== null &&
569 "code" in value &&
570 typeof value.code === "number" &&
571 "message" in value &&
572 typeof value.message === "string"
573 );