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

protocol.ts

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