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

effect@4.0.0-rc.115.patch

352 lines16.5 KB

1diff --git a/dist/unstable/ai/McpServer.js b/dist/unstable/ai/McpServer.js
2index e8b9be4..9cffc5c 100644
3--- a/dist/unstable/ai/McpServer.js
4+++ b/dist/unstable/ai/McpServer.js
5@@ -450,6 +450,26 @@ const runWithProtocolState = /*#__PURE__*/Effect.fnUntraced(function* (options,
6 const defaultLogLevel = yield* CurrentLogLevel;
7 const isHttp = Option.isSome(yield* Effect.serviceOption(HttpRouter.HttpRouter));
8 const sessions = protocolState.sessions;
9+ if (isHttp && options.path !== undefined) {
10+ const router = yield* HttpRouter.HttpRouter;
11+ yield* router.add("DELETE", options.path, Effect.gen(function* () {
12+ const request = yield* HttpServerRequest.HttpServerRequest;
13+ const sessionId = request.headers[MCP_SESSION_ID_HEADER];
14+ if (sessionId === undefined) {
15+ return HttpServerResponse.empty({
16+ status: 400
17+ });
18+ }
19+ if (!sessions.bySessionId.delete(sessionId)) {
20+ return HttpServerResponse.empty({
21+ status: 404
22+ });
23+ }
24+ return HttpServerResponse.empty({
25+ status: 204
26+ });
27+ }));
28+ }
29 const clientProtocols = new Map();
30 const activeRequests = new Map();
31 const clientProfiles = new Map();
32@@ -948,7 +968,7 @@ export const layerHttp = options => {
33 const methodNotAllowed = request => isAllowedMcpOrigin(request, options.allowedOrigins) ? Effect.succeed(methodNotAllowedResponse) : Effect.succeed(HttpServerResponse.empty({
34 status: 403
35 }));
36- const routes = Layer.mergeAll(HttpRouter.add("GET", options.path, methodNotAllowed), HttpRouter.add("PUT", options.path, methodNotAllowed), HttpRouter.add("PATCH", options.path, methodNotAllowed), HttpRouter.add("DELETE", options.path, methodNotAllowed), HttpRouter.add("OPTIONS", options.path, methodNotAllowed));
37+ const routes = Layer.mergeAll(HttpRouter.add("GET", options.path, methodNotAllowed), HttpRouter.add("PUT", options.path, methodNotAllowed), HttpRouter.add("PATCH", options.path, methodNotAllowed), HttpRouter.add("OPTIONS", options.path, methodNotAllowed));
38 return Layer.merge(layerWithProtocolState(options), routes).pipe(Layer.provide(layerMcpProtocolHttp(options)), Layer.provide(protocolState), Layer.provide(RpcSerialization.layerJsonRpc()));
39 };
40 const layerMcpProtocolHttp = options => Layer.effect(RpcServer.Protocol)(Effect.gen(function* () {
41diff --git a/dist/unstable/http/HttpClientResponse.js b/dist/unstable/http/HttpClientResponse.js
42index 59a2b12..ef54250 100644
43--- a/dist/unstable/http/HttpClientResponse.js
44+++ b/dist/unstable/http/HttpClientResponse.js
45@@ -180,7 +180,7 @@ class WebHttpClientResponse extends Inspectable.Class {
46 if (this.cachedCookies) {
47 return this.cachedCookies;
48 }
49- return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie());
50+ return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie?.() ?? []);
51 }
52 get remoteAddress() {
53 return Option.none();
54diff --git a/dist/unstable/rpc/RpcClient.d.ts b/dist/unstable/rpc/RpcClient.d.ts
55index 1a471aa..7233784 100644
56--- a/dist/unstable/rpc/RpcClient.d.ts
57+++ b/dist/unstable/rpc/RpcClient.d.ts
58@@ -2,6 +2,7 @@ import * as Cause from "../../Cause.ts";
59 import * as Context from "../../Context.ts";
60 import type * as Duration from "../../Duration.ts";
61 import * as Effect from "../../Effect.ts";
62+import * as Exit from "../../Exit.ts";
63 import * as Layer from "../../Layer.ts";
64 import * as Queue from "../../Queue.ts";
65 import * as Schedule from "../../Schedule.ts";
66@@ -280,9 +281,40 @@ export declare const layerProtocolWorker: (options: {
67 readonly targetUtilization?: number | undefined;
68 readonly timeToLive: Duration.Input;
69 }) => Layer.Layer<Protocol, WorkerError, Worker.WorkerPlatform | Worker.Spawner>;
70+declare const RequestHooks_base: Context.ServiceClass<RequestHooks, "effect/rpc/RpcClient/RequestHooks", {
71+ readonly onRequestStart?: ((info: {
72+ readonly id: RequestId;
73+ readonly tag: string;
74+ readonly stream: boolean;
75+ }) => Effect.Effect<void>) | undefined;
76+ readonly onRequestChunk?: ((info: {
77+ readonly id: RequestId;
78+ readonly tag: string;
79+ readonly chunkCount: number;
80+ }) => Effect.Effect<void>) | undefined;
81+ readonly onRequestExit?: ((info: {
82+ readonly id: RequestId;
83+ readonly tag: string;
84+ readonly stream: boolean;
85+ readonly exit: Exit.Exit<unknown, unknown>;
86+ }) => Effect.Effect<void>) | undefined;
87+ readonly onRequestInterrupt?: ((info: {
88+ readonly id: RequestId;
89+ readonly tag?: string | undefined;
90+ }) => Effect.Effect<void>) | undefined;
91+}>;
92+/**
93+ * @since 4.0.0
94+ * @category RequestHooks
95+ */
96+export declare class RequestHooks extends RequestHooks_base {
97+}
98 declare const ConnectionHooks_base: Context.ServiceClass<ConnectionHooks, "effect/rpc/RpcClient/ConnectionHooks", {
99 readonly onConnect: Effect.Effect<void>;
100 readonly onDisconnect: Effect.Effect<void>;
101+ readonly onPing?: Effect.Effect<void> | undefined;
102+ readonly onPong?: Effect.Effect<void> | undefined;
103+ readonly onPingTimeout?: Effect.Effect<void> | undefined;
104 }>;
105 /**
106 * Represents optional client protocol hooks that run when a transport connects
107diff --git a/dist/unstable/rpc/RpcClient.js b/dist/unstable/rpc/RpcClient.js
108index c586c60..49886d8 100644
109--- a/dist/unstable/rpc/RpcClient.js
110+++ b/dist/unstable/rpc/RpcClient.js
111@@ -49,6 +49,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
112 const services = yield* Effect.context();
113 const scope = Context.get(services, Scope.Scope);
114 const entries = new Map();
115+ const hooks = yield* Effect.serviceOption(RequestHooks);
116 let isShutdown = false;
117 yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {
118 isShutdown = true;
119@@ -86,6 +87,11 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
120 return Effect.interrupt;
121 }
122 const id = generateRequestId();
123+ const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({
124+ id,
125+ tag: rpc._tag,
126+ stream: false
127+ }) : Effect.void;
128 const send = middleware(message => options.onFromClient({
129 message,
130 context,
131@@ -103,7 +109,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
132 headers: Headers.merge(parentFiber.getRef(CurrentHeaders), headers)
133 });
134 if (discard) {
135- return send;
136+ return onStart.pipe(Effect.andThen(send));
137 }
138 let fiber;
139 return Effect.onInterrupt(Effect.callback(resume => {
140@@ -121,7 +127,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
141 }
142 };
143 entries.set(id, entry);
144- fiber = send.pipe(span ? Effect.withParentSpan(span, {
145+ fiber = onStart.pipe(Effect.andThen(send), span ? Effect.withParentSpan(span, {
146 captureStackTrace: false
147 }) : identity, Effect.runForkWith(parentFiber.context));
148 fiber.addObserver(exit => {
149@@ -130,8 +136,9 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
150 }
151 });
152 }), interruptors => {
153+ const entry = entries.get(id);
154 entries.delete(id);
155- return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context));
156+ return Effect.andThen(Fiber.interrupt(fiber), sendInterrupt(id, Array.from(interruptors), context, entry?.rpc._tag));
157 });
158 });
159 const onStreamRequest = Effect.fnUntraced(function* (rpc, middleware, payload, headers, streamBufferSize, context) {
160@@ -143,11 +150,17 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
161 });
162 const fiber = Fiber.getCurrent();
163 const id = generateRequestId();
164+ const onStart = Option.isSome(hooks) && hooks.value.onRequestStart ? hooks.value.onRequestStart({
165+ id,
166+ tag: rpc._tag,
167+ stream: true
168+ }) : Effect.void;
169 const scope = Context.getUnsafe(fiber.context, Scope.Scope);
170 yield* Scope.addFinalizerExit(scope, exit => {
171- if (!entries.has(id)) return Effect.void;
172+ const entry = entries.get(id);
173+ if (!entry) return Effect.void;
174 entries.delete(id);
175- return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context);
176+ return sendInterrupt(id, Exit.isFailure(exit) ? Array.from(Cause.interruptors(exit.cause)) : [], context, entry.rpc._tag);
177 });
178 const queue = yield* Queue.bounded(streamBufferSize);
179 entries.set(id, {
180@@ -155,9 +168,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
181 rpc,
182 queue,
183 scope,
184- context
185+ context,
186+ chunkCount: 0
187 });
188- yield* middleware(message => options.onFromClient({
189+ yield* onStart.pipe(Effect.andThen(middleware(message => options.onFromClient({
190 message,
191 context,
192 discard: false
193@@ -172,7 +186,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
194 sampled: span.sampled
195 } : {}),
196 headers: Headers.merge(fiber.getRef(CurrentHeaders), headers)
197- }).pipe(span ? Effect.withParentSpan(span, {
198+ }))).pipe(span ? Effect.withParentSpan(span, {
199 captureStackTrace: false
200 }) : identity, Effect.catchCause(error => Queue.failCause(queue, error)), Effect.interruptible, Effect.forkIn(scope, {
201 startImmediately: true
202@@ -202,7 +216,10 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
203 });
204 };
205 };
206- const sendInterrupt = (requestId, interruptors, context) => Effect.callback(resume => {
207+ const sendInterrupt = (requestId, interruptors, context, tag) => (Option.isSome(hooks) && hooks.value.onRequestInterrupt ? hooks.value.onRequestInterrupt({
208+ id: requestId,
209+ tag
210+ }) : Effect.void).pipe(Effect.andThen(Effect.callback(resume => {
211 const parentFiber = Fiber.getCurrent();
212 const fiber = options.onFromClient({
213 message: {
214@@ -216,7 +233,7 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
215 fiber.addObserver(() => {
216 resume(Effect.void);
217 });
218- });
219+ })));
220 const write = message => {
221 switch (message._tag) {
222 case "Chunk":
223@@ -224,7 +241,13 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
224 const requestId = message.requestId;
225 const entry = entries.get(requestId);
226 if (!entry || entry._tag !== "Queue") return Effect.void;
227- return Queue.offerAll(entry.queue, message.values).pipe(supportsAck ? Effect.flatMap(() => options.onFromClient({
228+ const chunkCount = entry.chunkCount += message.values.length;
229+ const onChunk = Option.isSome(hooks) && hooks.value.onRequestChunk ? hooks.value.onRequestChunk({
230+ id: requestId,
231+ tag: entry.rpc._tag,
232+ chunkCount
233+ }) : Effect.void;
234+ return Queue.offerAll(entry.queue, message.values).pipe(Effect.andThen(onChunk), supportsAck ? Effect.flatMap(() => options.onFromClient({
235 message: {
236 _tag: "Ack",
237 requestId: message.requestId
238@@ -239,11 +262,18 @@ export const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (gro
239 const entry = entries.get(requestId);
240 if (!entry) return Effect.void;
241 entries.delete(requestId);
242+ const onExit = Option.isSome(hooks) && hooks.value.onRequestExit ? hooks.value.onRequestExit({
243+ id: requestId,
244+ tag: entry.rpc._tag,
245+ stream: entry._tag === "Queue",
246+ exit: message.exit
247+ }) : Effect.void;
248 if (entry._tag === "Effect") {
249- entry.resume(message.exit);
250- return Effect.void;
251+ return onExit.pipe(Effect.andThen(Effect.sync(() => {
252+ entry.resume(message.exit);
253+ })));
254 }
255- return message.exit._tag === "Success" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause);
256+ return onExit.pipe(Effect.andThen(message.exit._tag === "Success" ? Queue.end(entry.queue) : Queue.failCause(entry.queue, message.exit.cause)));
257 }
258 case "Defect":
259 {
260@@ -598,7 +628,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
261 // `parser` is replaced on every connect, and a stateful serialization
262 // encodes against the connection it is writing to, so the ping is encoded
263 // when it is sent rather than once up front.
264- const pinger = yield* makePinger(Effect.suspend(() => writer.write(parser.encode(constPing))));
265+ const pinger = yield* makePinger(Effect.suspend(() => writer.write(parser.encode(constPing))), Option.isSome(hooks) ? hooks.value : undefined);
266 let currentError;
267 const broadcast = response => Effect.forEach(clientIds, clientId => writeResponse(clientId, response));
268 const broadcastError = error => {
269@@ -618,8 +648,7 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
270 body: () => {
271 const response = responses[i++];
272 if (response._tag === "Pong") {
273- pinger.onPong();
274- return Effect.void;
275+ return pinger.onPong;
276 }
277 if (Object.hasOwn(response, "requestId")) {
278 const requestId = response.requestId;
279@@ -664,12 +693,12 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
280 yield* processData(frames[i]);
281 }
282 }
283- }).pipe(Effect.scoped, Effect.raceFirst(Effect.flatMap(pinger.timeout, () => Effect.fail(new Socket.SocketError({
284+ }).pipe(Effect.scoped, Effect.raceFirst(Effect.flatMap(pinger.timeout, () => (Option.isSome(hooks) && hooks.value.onPingTimeout ? hooks.value.onPingTimeout : Effect.void).pipe(Effect.andThen(Effect.fail(new Socket.SocketError({
285 reason: new Socket.SocketOpenError({
286 kind: "Timeout",
287 cause: new Error("ping timeout")
288 })
289- })))));
290+ })))))));
291 }).pipe(Option.isSome(hooks) ? Effect.ensuring(hooks.value.onDisconnect) : identity, Effect.tapCause(cause => {
292 const error = Cause.findError(cause);
293 const hasError = Result.isSuccess(error);
294@@ -710,20 +739,28 @@ export const makeProtocolSocket = options => Protocol.make(Effect.fnUntraced(fun
295 };
296 }));
297 const defaultRetryPolicy = /*#__PURE__*/Schedule.min([/*#__PURE__*/Schedule.exponential(500, 1.5), /*#__PURE__*/Schedule.spaced(5000)]);
298-const makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing) {
299+const makePinger = /*#__PURE__*/Effect.fnUntraced(function* (writePing, hooks) {
300 let recievedPong = true;
301+ let missedPongs = 0;
302 const latch = Latch.makeUnsafe();
303 const reset = () => {
304 recievedPong = true;
305+ missedPongs = 0;
306 latch.closeUnsafe();
307 };
308- const onPong = () => {
309+ const onPong = Effect.sync(() => {
310 recievedPong = true;
311- };
312+ missedPongs = 0;
313+ }).pipe(Effect.andThen(hooks?.onPong ?? Effect.void));
314 yield* Effect.suspend(() => {
315- if (!recievedPong) return latch.open;
316+ if (!recievedPong) {
317+ missedPongs += 1;
318+ if (missedPongs >= 3) return latch.open;
319+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
320+ }
321 recievedPong = false;
322- return writePing;
323+ missedPongs = 0;
324+ return (hooks?.onPing ?? Effect.void).pipe(Effect.andThen(writePing));
325 }).pipe(Effect.delay("5 seconds"), Effect.ignore, Effect.forever, Effect.interruptible, Effect.forkScoped);
326 return {
327 timeout: latch.await,
328@@ -874,6 +911,11 @@ export const makeProtocolWorker = options => Protocol.make(Effect.fnUntraced(fun
329 * @since 4.0.0
330 */
331 export const layerProtocolWorker = /*#__PURE__*/flow(makeProtocolWorker, /*#__PURE__*/Layer.effect(Protocol));
332+/**
333+ * @since 4.0.0
334+ * @category RequestHooks
335+ */
336+export class RequestHooks extends /*#__PURE__*/Context.Service()("effect/rpc/RpcClient/RequestHooks") {}
337 /**
338 * Represents optional client protocol hooks that run when a transport connects
339 * and disconnects.
340diff --git a/src/unstable/http/HttpClientResponse.ts b/src/unstable/http/HttpClientResponse.ts
341index cbf047f..c7d5cc2 100644
342--- a/src/unstable/http/HttpClientResponse.ts
343+++ b/src/unstable/http/HttpClientResponse.ts
344@@ -321,7 +321,7 @@ class WebHttpClientResponse extends Inspectable.Class implements HttpClientRespo
345 if (this.cachedCookies) {
346 return this.cachedCookies
347 }
348- return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie())
349+ return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie?.() ?? [])
350 }
352 get remoteAddress(): Option.Option<string> {