Skip to content

Commit 29cca8e

Browse files
authored
Merge branch 'main' into fix/opencode-go-limits-credential-db
2 parents ae90397 + 8ddf200 commit 29cca8e

10 files changed

Lines changed: 454 additions & 16 deletions

File tree

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { assert, describe, it } from "@effect/vitest";
2+
import * as Cause from "effect/Cause";
3+
import * as Effect from "effect/Effect";
4+
import * as ErrorReporter from "effect/ErrorReporter";
5+
import * as Exit from "effect/Exit";
6+
import * as Fiber from "effect/Fiber";
7+
import * as Layer from "effect/Layer";
8+
import * as Logger from "effect/Logger";
9+
import * as Queue from "effect/Queue";
10+
import * as Schema from "effect/Schema";
11+
import * as Stream from "effect/Stream";
12+
import { Rpc, RpcClient, RpcGroup, RpcServer } from "effect/rpc";
13+
14+
import { WS_RPC_SERVER_OPTIONS } from "../ws.ts";
15+
import * as DefectReporter from "./DefectReporter.ts";
16+
17+
class TestRpcs extends RpcGroup.make(
18+
Rpc.make("subscribe", { success: Schema.Number, stream: true }),
19+
Rpc.make("boom", { success: Schema.Void }),
20+
) {}
21+
type TestRpc = RpcGroup.Rpcs<typeof TestRpcs>;
22+
23+
/** Runs `body` with every error log captured. */
24+
const withErrorLogs = <A, E, R>(
25+
body: (logs: Queue.Queue<Cause.Cause<unknown>>) => Effect.Effect<A, E, R>,
26+
) =>
27+
Effect.gen(function* () {
28+
const logs = yield* Queue.unbounded<Cause.Cause<unknown>>();
29+
const logger = Logger.make(({ cause, logLevel }) => {
30+
if (logLevel === "Error") Queue.offerUnsafe(logs, cause);
31+
});
32+
return yield* body(logs).pipe(
33+
Effect.provide(Logger.layer([logger], { mergeWithExisting: false })),
34+
);
35+
});
36+
37+
const errorMessage = (cause: Cause.Cause<unknown>) => (Cause.squash(cause) as Error).message;
38+
39+
describe("DefectReporter", () => {
40+
it.effect("a dying RPC handler fails alone, and its defect is logged", () =>
41+
withErrorLogs((logs) =>
42+
Effect.gen(function* () {
43+
const subscription = yield* Queue.unbounded<number>();
44+
// The same client/server pairing as RpcTest.makeClient, with ws.ts's options.
45+
let client!: Effect.Success<
46+
ReturnType<typeof RpcClient.makeNoSerialization<TestRpc, never>>
47+
>;
48+
const server = yield* RpcServer.makeNoSerialization(TestRpcs, {
49+
...WS_RPC_SERVER_OPTIONS,
50+
onFromServer: (response) => client.write(response),
51+
}).pipe(
52+
// Provided to the handlers, as ws.ts does.
53+
Effect.provide(
54+
TestRpcs.toLayer({
55+
subscribe: () => Stream.fromQueue(subscription),
56+
boom: () => Effect.die(new Error("handler bug")),
57+
}).pipe(Layer.provide(DefectReporter.layer)),
58+
),
59+
);
60+
client = yield* RpcClient.makeNoSerialization(TestRpcs, {
61+
supportsAck: true,
62+
onFromClient: ({ message }) => server.write(0, message),
63+
});
64+
65+
const received = yield* Queue.unbounded<number>();
66+
const sibling = yield* client.client.subscribe().pipe(
67+
Stream.runForEach((value) => Queue.offer(received, value)),
68+
Effect.forkScoped,
69+
);
70+
yield* Queue.offer(subscription, 1);
71+
assert.equal(yield* Queue.take(received), 1);
72+
73+
const boom = yield* Effect.exit(client.client.boom());
74+
assert.isTrue(Exit.hasDies(boom));
75+
// The server reports before it answers, so the log is already written.
76+
const logged = yield* Queue.clear(logs);
77+
assert.deepEqual(logged.map(errorMessage), ["handler bug"]);
78+
79+
// The sibling subscription on the same client keeps delivering.
80+
yield* Queue.offer(subscription, 2);
81+
const next = yield* Queue.take(received).pipe(
82+
Effect.raceFirst(Fiber.await(sibling).pipe(Effect.as("subscription ended"))),
83+
);
84+
assert.equal(next, 2);
85+
assert.equal(yield* Queue.size(logs), 0);
86+
}),
87+
).pipe(Effect.scoped),
88+
);
89+
90+
it.effect("logs defects, not typed failures or interrupts", () =>
91+
withErrorLogs((logs) =>
92+
Effect.gen(function* () {
93+
yield* ErrorReporter.report(Cause.fail(new Error("expected")));
94+
yield* ErrorReporter.report(Cause.interrupt());
95+
yield* ErrorReporter.report(Cause.die(new Error("bug")));
96+
97+
// Reporters log synchronously, so the logs are already written.
98+
assert.deepEqual((yield* Queue.clear(logs)).map(errorMessage), ["bug"]);
99+
}).pipe(Effect.provide(DefectReporter.layer)),
100+
),
101+
);
102+
});
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import * as Cause from "effect/Cause";
2+
import * as Effect from "effect/Effect";
3+
import * as ErrorReporter from "effect/ErrorReporter";
4+
5+
/**
6+
* Logs the defects of WebSocket RPC handlers. RpcServer reports every failed
7+
* handler exit; typed failures are expected responses, so only dies are logged.
8+
*/
9+
const reporter: ErrorReporter.ErrorReporter = {
10+
[ErrorReporter.TypeId]: ErrorReporter.TypeId,
11+
report: ({ cause, fiber }) => {
12+
for (const reason of cause.reasons) {
13+
if (reason._tag !== "Die" || ErrorReporter.isIgnored(reason.defect)) continue;
14+
// Reporters are called synchronously from the failing fiber. Logging with
15+
// its context keeps its loggers and annotations, and a fork cannot throw
16+
// back into the server that reported.
17+
Effect.runForkWith(fiber.context)(
18+
Effect.logError("Unhandled defect", Cause.fromReasons([reason])),
19+
);
20+
}
21+
},
22+
};
23+
24+
export const layer = ErrorReporter.layer([reporter]);

‎apps/server/src/ws.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@ import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
210210
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
211211
import * as DirectEndpoints from "./environment/DirectEndpoints.ts";
212212
import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
213+
import * as DefectReporter from "./observability/DefectReporter.ts";
213214
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
214215
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
215216
import { requiredScopeForDeviceList, rpcAuthorizationError } from "./auth/RpcAuthorization.ts";
@@ -3787,6 +3788,14 @@ const layerWsRpc = (
37873788
}),
37883789
);
37893790

3791+
// A defect in a handler's effect fails only its own request. RpcServer's default
3792+
// sends a socket-level Defect frame instead, and the client ends every pending
3793+
// request on the socket with it. DefectReporter logs these defects.
3794+
export const WS_RPC_SERVER_OPTIONS = {
3795+
disableTracing: true,
3796+
disableFatalDefects: true,
3797+
} as const;
3798+
37903799
export const layer = Layer.unwrap(
37913800
Effect.gen(function* () {
37923801
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
@@ -3830,7 +3839,7 @@ export const layer = Layer.unwrap(
38303839
yield* analytics.record("client.connected", clientAnalyticsProps);
38313840
const rpcWebSocketHttpEffect = yield* Effect.gen(function* () {
38323841
const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket;
3833-
yield* RpcServer.make(ServerWsRpcGroup, { disableTracing: true }).pipe(
3842+
yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe(
38343843
Effect.provideService(RpcServer.Protocol, withTerminalOutputWindow(protocol)),
38353844
Effect.provide(RpcAuthorization.layer(session.scopes)),
38363845
Effect.forkScoped,
@@ -3847,6 +3856,9 @@ export const layer = Layer.unwrap(
38473856
serverBrowser,
38483857
).pipe(
38493858
Layer.provideMerge(RpcSerialization.layerJson),
3859+
// Request fibers run in the handlers' context, so this reporter sees
3860+
// their defects, not the rest of the server's.
3861+
Layer.provide(DefectReporter.layer),
38503862
Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)),
38513863
Layer.provide(AgentSessionScanner.layer),
38523864
Layer.provide(ProviderMaintenanceRunner.layer),

‎packages/effect-acp/src/_internal/shared.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as Cause from "effect/Cause";
12
import * as Effect from "effect/Effect";
23
import * as Schema from "effect/Schema";
34
import { RpcClientError } from "effect/rpc";
@@ -29,6 +30,19 @@ export const callRpc = <A>(
2930
}),
3031
);
3132

33+
/**
34+
* Runs a notification handler so it cannot stop the caller: a typed failure is
35+
* dropped, as notifications have no reply, and a defect is logged.
36+
*/
37+
export const isolateNotificationHandler = <E, R>(effect: Effect.Effect<void, E, R>) =>
38+
effect.pipe(
39+
Effect.catchCause((cause) =>
40+
Cause.hasDies(cause)
41+
? Effect.logError("ACP notification handler failed", cause)
42+
: Effect.void,
43+
),
44+
);
45+
3246
export const runHandler = Effect.fnUntraced(function* <A, B, Args extends ReadonlyArray<unknown>>(
3347
handler: ((payload: A, ...args: Args) => Effect.Effect<B, AcpError.AcpError>) | undefined,
3448
payload: A,
@@ -39,6 +53,9 @@ export const runHandler = Effect.fnUntraced(function* <A, B, Args extends Readon
3953
return yield* Effect.fail(AcpError.AcpRequestError.methodNotFound(method).toProtocolError());
4054
}
4155
return yield* handler(payload, ...args).pipe(
56+
Effect.tapDefect((defect) =>
57+
Effect.logError(`ACP request handler failed for '${method}'`, defect),
58+
),
4259
Effect.mapError((error) =>
4360
AcpError.AcpRequestError.fromCoreHandlerError(error, method).toProtocolError(),
4461
),

‎packages/effect-acp/src/agent.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ const SessionCancelNotification = jsonRpcNotification(
3535
const ExtPingNotification = jsonRpcNotification("x/ping", Schema.Struct({ count: Schema.Number }));
3636
const ExtRequest = jsonRpcRequest("x/test", Schema.Struct({ hello: Schema.String }));
3737
const ExtResponse = jsonRpcResponse(Schema.Struct({ ok: Schema.Boolean }));
38+
/** A response whose cause is a handler's defect, as RpcServer encodes it. */
39+
const DieResponse = Schema.Struct({
40+
id: Schema.Number,
41+
error: Schema.Struct({
42+
_tag: Schema.Literal("Cause"),
43+
data: Schema.Tuple([Schema.Struct({ _tag: Schema.Literal("Die") })]),
44+
}),
45+
});
3846
const decodeRequestPermissionRequest = Schema.decodeEffect(
3947
Schema.fromJsonString(RequestPermissionRequest),
4048
);
@@ -296,3 +304,33 @@ it.effect("effect-acp agent uses distinct ids for RPC calls and extension reques
296304
}).pipe(Effect.provide(context), Effect.ensuring(Scope.close(scope, Exit.void)));
297305
}),
298306
);
307+
308+
it.effect("effect-acp agent answers a request whose handler dies with an error for it", () =>
309+
Effect.gen(function* () {
310+
const { stdio, input, output } = yield* makeInMemoryStdio();
311+
const scope = yield* Scope.make();
312+
const context = yield* Layer.buildWithScope(AcpAgent.layer(stdio), scope);
313+
const agent = yield* Effect.service(AcpAgent.AcpAgent).pipe(Effect.provide(context));
314+
yield* agent.handleInitialize(() => Effect.die(new Error("handler bug")));
315+
316+
yield* Queue.offer(
317+
input,
318+
yield* encodeJsonl(InitializeRequest, {
319+
jsonrpc: "2.0",
320+
id: 7,
321+
method: "initialize",
322+
params: {
323+
protocolVersion: 2,
324+
capabilities: {},
325+
info: { name: "effect-acp-test", version: "0.0.0" },
326+
},
327+
headers: [],
328+
}),
329+
);
330+
const response = yield* Queue.take(output).pipe(
331+
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(DieResponse))),
332+
);
333+
assert.equal(response.id, 7);
334+
yield* Scope.close(scope, Exit.void);
335+
}),
336+
);

‎packages/effect-acp/src/agent.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Context from "effect/Context";
22
import * as Effect from "effect/Effect";
3+
import * as ErrorReporter from "effect/ErrorReporter";
34
import * as Layer from "effect/Layer";
45
import * as Schema from "effect/Schema";
56
import * as Scope from "effect/Scope";
@@ -18,6 +19,7 @@ import {
1819
callRpc,
1920
decodeExtNotificationRegistration,
2021
decodeExtRequestRegistration,
22+
isolateNotificationHandler,
2123
runHandler,
2224
} from "./_internal/shared.ts";
2325

@@ -280,7 +282,11 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
280282
),
281283
),
282284
Effect.flatMap((decoded) =>
283-
Effect.forEach(cancelHandlers, (handler) => handler(decoded), { discard: true }),
285+
Effect.forEach(
286+
cancelHandlers,
287+
(handler) => isolateNotificationHandler(handler(decoded)),
288+
{ discard: true },
289+
),
284290
),
285291
);
286292
}
@@ -421,7 +427,10 @@ export const make = Effect.fn("effect-acp/AcpAgent.make")(function* (
421427
}),
422428
);
423429

424-
yield* RpcServer.make(AcpRpcs.AgentRpcs).pipe(
430+
yield* RpcServer.make(AcpRpcs.AgentRpcs, { disableFatalDefects: true }).pipe(
431+
// runHandler logs handler defects with their method. A reporter inherited
432+
// from the caller (a WebSocket request, say) would log them again.
433+
Effect.provideService(ErrorReporter.CurrentErrorReporters, new Set()),
425434
Effect.provideService(RpcServer.Protocol, transport.serverProtocol),
426435
Effect.provide(layerAgentHandler),
427436
Effect.forkScoped,

0 commit comments

Comments
 (0)