Skip to content

Commit 8fc126c

Browse files
committed
fix: WebSocket RPC hang — nested Effect.gen deadlock in request fiber
Root cause: yield*-ing an Effect.gen from inside another Effect.gen within the HTTP request fiber caused the inner generator to never start executing. The first yield* statement inside makeWsRpcContext never ran, silently hanging every /ws connection after auth. Fix: - Replaced Effect.gen in makeWsRpcContext with flat pipeline composition (Effect.flatMap/Effect.andThen chaining) - Moved Effect.context<never>() capture to startup via a new WsAppServices service that pre-builds the full app-level context once at boot - Fixed vendored Effect API mismatches: Context.Tag -> Context.Service, removed nonexistent Effect.tapErrorCause calls Also includes layer-wiring fixes for startup services and auth session infrastructure.
1 parent b0955e9 commit 8fc126c

20 files changed

Lines changed: 807 additions & 119 deletions
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as NetService from "@t3tools/shared/Net";
4+
import * as Duration from "effect/Duration";
5+
import * as Effect from "effect/Effect";
6+
import * as Layer from "effect/Layer";
7+
import * as LogLevel from "effect/LogLevel";
8+
import * as Option from "effect/Option";
9+
10+
import { ServerConfig } from "../src/config.ts";
11+
import { resolveServerConfig, type CliServerFlags } from "../src/cli/config.ts";
12+
import { SeededWorkItemWritebackLive } from "../src/orchestration/Layers/SeededWorkItemWriteback.ts";
13+
import { debugWsRuntimeLayer } from "../src/server.ts";
14+
import { debugBuildWsRpcContext } from "../src/ws.ts";
15+
16+
const cliRuntimeLayer = Layer.mergeAll(
17+
NodeServices.layer,
18+
NetService.layer,
19+
SeededWorkItemWritebackLive,
20+
);
21+
22+
const flags: CliServerFlags = {
23+
mode: Option.none(),
24+
port: Option.none(),
25+
host: Option.none(),
26+
baseDir: Option.none(),
27+
cwd: Option.some(process.cwd()),
28+
devUrl: Option.none(),
29+
noBrowser: Option.some(true),
30+
bootstrapFd: Option.none(),
31+
autoBootstrapProjectFromCwd: Option.some(false),
32+
logWebSocketEvents: Option.some(true),
33+
tailscaleServeEnabled: Option.none(),
34+
tailscaleServePort: Option.none(),
35+
};
36+
37+
const session = {
38+
sessionId: "debug-session",
39+
subject: "debug-subject",
40+
method: "browser-session-cookie",
41+
scopes: [],
42+
} as const;
43+
44+
const program = Effect.gen(function* () {
45+
const config = yield* resolveServerConfig(flags, Option.some(LogLevel.Debug));
46+
yield* Effect.logDebug("[DEBUG-ws-rpc-harness] config resolved", {
47+
cwd: config.cwd,
48+
baseDir: config.baseDir,
49+
port: config.port,
50+
});
51+
52+
const runtimeContext = yield* Layer.build(
53+
debugWsRuntimeLayer.pipe(Layer.provide(Layer.succeed(ServerConfig, config))),
54+
).pipe(
55+
Effect.scoped,
56+
Effect.timeoutOption(Duration.seconds(3)),
57+
);
58+
59+
if (Option.isNone(runtimeContext)) {
60+
yield* Effect.logError("[DEBUG-ws-rpc-harness] runtime layer build timed out", {
61+
sessionId: session.sessionId,
62+
});
63+
return;
64+
}
65+
66+
yield* Effect.logInfo("[DEBUG-ws-rpc-harness] runtime layer built", {
67+
sessionId: session.sessionId,
68+
});
69+
70+
const result = yield* debugBuildWsRpcContext(session).pipe(
71+
Effect.provide(runtimeContext.value),
72+
Effect.timeoutOption(Duration.seconds(3)),
73+
);
74+
75+
if (Option.isNone(result)) {
76+
yield* Effect.logError("[DEBUG-ws-rpc-harness] ws rpc context build timed out", {
77+
sessionId: session.sessionId,
78+
});
79+
return;
80+
}
81+
82+
yield* Effect.logInfo("[DEBUG-ws-rpc-harness] ws rpc context built", {
83+
sessionId: session.sessionId,
84+
});
85+
}).pipe(Effect.provide(cliRuntimeLayer));
86+
87+
NodeRuntime.runMain(program);

‎apps/server/src/auth/EnvironmentAuth.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,21 @@ const AUTHORIZATION_PREFIX = "Bearer ";
194194
const DPOP_AUTHORIZATION_PREFIX = "DPoP ";
195195
const WEBSOCKET_TICKET_QUERY_PARAM = "wsTicket";
196196

197+
function describePresentedCredentials(
198+
request: HttpServerRequest.HttpServerRequest,
199+
sessionCookieName: string,
200+
) {
201+
const hasSessionCookie = typeof request.cookies[sessionCookieName] === "string";
202+
const hasBearerToken = parseBearerToken(request) !== null;
203+
const hasDpopToken = parseDpopToken(request) !== null;
204+
return {
205+
hasSessionCookie,
206+
hasBearerToken,
207+
hasDpopToken,
208+
credentialSource: hasSessionCookie ? "cookie" : hasBearerToken ? "bearer" : hasDpopToken ? "dpop" : "none",
209+
} as const;
210+
}
211+
197212
const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => {
198213
const leftCanManage = left.scopes.includes(AuthAccessWriteScope);
199214
const rightCanManage = right.scopes.includes(AuthAccessWriteScope);
@@ -300,10 +315,27 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
300315
const bearerToken = parseBearerToken(request);
301316
const dpopToken = parseDpopToken(request);
302317
const credential = cookieToken ?? bearerToken ?? dpopToken;
318+
const presentedCredentials = describePresentedCredentials(request, sessions.cookieName);
303319
if (!credential) {
304-
return Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" }));
320+
return Effect.logDebug("auth.request missing credential", {
321+
path: request.originalUrl,
322+
...presentedCredentials,
323+
}).pipe(
324+
Effect.andThen(
325+
Effect.fail(new ServerAuthInvalidCredentialError({ reason: "missing_credential" })),
326+
),
327+
);
305328
}
306329
return authenticateToken(credential).pipe(
330+
Effect.tap((session) =>
331+
Effect.logDebug("auth.request authenticated", {
332+
path: request.originalUrl,
333+
...presentedCredentials,
334+
sessionId: session.sessionId,
335+
sessionMethod: session.method,
336+
scopeCount: session.scopes.length,
337+
}),
338+
),
307339
Effect.flatMap((session) => {
308340
if (session.proofKeyThumbprint) {
309341
if (!dpopToken || dpopToken !== credential) {
@@ -397,6 +429,13 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
397429
sessionToken: session.token,
398430
}) satisfies BootstrapExchangeResult,
399431
),
432+
Effect.tap((result) =>
433+
Effect.logDebug("auth.browserSession issued", {
434+
sessionMethod: result.response.sessionMethod,
435+
scopeCount: result.response.scopes.length,
436+
expiresAt: DateTime.formatIso(result.response.expiresAt),
437+
}),
438+
),
400439
Effect.withSpan("EnvironmentAuth.createBrowserSession"),
401440
);
402441

@@ -657,6 +696,14 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
657696
expiresAt: DateTime.toUtc(issued.expiresAt),
658697
}) satisfies AuthWebSocketTicketResult,
659698
),
699+
Effect.tap((issued) =>
700+
Effect.logDebug("auth.webSocketTicket issued", {
701+
sessionId: session.sessionId,
702+
sessionMethod: session.method,
703+
scopeCount: session.scopes.length,
704+
expiresAt: DateTime.formatIso(issued.expiresAt),
705+
}),
706+
),
660707
Effect.withSpan("EnvironmentAuth.issueWebSocketTicket"),
661708
);
662709

@@ -669,6 +716,9 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
669716
if (Option.isSome(requestUrl)) {
670717
const websocketTicket = requestUrl.value.searchParams.get(WEBSOCKET_TICKET_QUERY_PARAM);
671718
if (websocketTicket && websocketTicket.trim().length > 0) {
719+
yield* Effect.logDebug("auth.websocket upgrade using ticket", {
720+
path: request.originalUrl,
721+
});
672722
return yield* sessions.verifyWebSocketToken(websocketTicket).pipe(
673723
Effect.map((session) => ({
674724
sessionId: session.sessionId,
@@ -677,11 +727,23 @@ export const make = Effect.fn("makeEnvironmentAuth")(function* () {
677727
scopes: session.scopes,
678728
...(session.expiresAt ? { expiresAt: session.expiresAt } : {}),
679729
})),
730+
Effect.tap((session) =>
731+
Effect.logDebug("auth.websocket ticket authenticated", {
732+
path: request.originalUrl,
733+
sessionId: session.sessionId,
734+
sessionMethod: session.method,
735+
scopeCount: session.scopes.length,
736+
}),
737+
),
680738
mapSessionVerificationErrors,
681739
);
682740
}
683741
}
684742

743+
yield* Effect.logDebug("auth.websocket upgrade falling back to request auth", {
744+
path: request.originalUrl,
745+
...describePresentedCredentials(request, sessions.cookieName),
746+
});
685747
return yield* authenticateRequest(request);
686748
});
687749

‎apps/server/src/auth/SessionStore.ts‎

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -240,12 +240,22 @@ export const make = Effect.fn("makeSessionStore")(function* () {
240240
});
241241

242242
const markConnected: SessionStoreShape["markConnected"] = (sessionId) =>
243-
Ref.modify(connectedSessionsRef, (current) => {
244-
const next = new Map(current);
245-
const wasDisconnected = !next.has(sessionId);
246-
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
247-
return [wasDisconnected, next] as const;
248-
}).pipe(
243+
Effect.logDebug("session.markConnected start", { sessionId }).pipe(
244+
Effect.andThen(
245+
Ref.modify(connectedSessionsRef, (current) => {
246+
const next = new Map(current);
247+
const wasDisconnected = !next.has(sessionId);
248+
next.set(sessionId, (next.get(sessionId) ?? 0) + 1);
249+
return [wasDisconnected, next] as const;
250+
}),
251+
),
252+
).pipe(
253+
Effect.tap((wasDisconnected) =>
254+
Effect.logDebug("session.markConnected state updated", {
255+
sessionId,
256+
wasDisconnected,
257+
}),
258+
),
249259
Effect.flatMap((wasDisconnected) =>
250260
wasDisconnected
251261
? DateTime.now.pipe(
@@ -259,6 +269,12 @@ export const make = Effect.fn("makeSessionStore")(function* () {
259269
: Effect.void,
260270
),
261271
Effect.flatMap(() => loadActiveSession(sessionId)),
272+
Effect.tap((session) =>
273+
Effect.logDebug("session.markConnected loaded active session", {
274+
sessionId,
275+
hasActiveSession: Option.isSome(session),
276+
}),
277+
),
262278
Effect.flatMap((session) =>
263279
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
264280
),
@@ -274,17 +290,27 @@ export const make = Effect.fn("makeSessionStore")(function* () {
274290
);
275291

276292
const markDisconnected: SessionStoreShape["markDisconnected"] = (sessionId) =>
277-
Ref.update(connectedSessionsRef, (current) => {
278-
const next = new Map(current);
279-
const remaining = (next.get(sessionId) ?? 0) - 1;
280-
if (remaining > 0) {
281-
next.set(sessionId, remaining);
282-
} else {
283-
next.delete(sessionId);
284-
}
285-
return next;
286-
}).pipe(
293+
Effect.logDebug("session.markDisconnected start", { sessionId }).pipe(
294+
Effect.andThen(
295+
Ref.update(connectedSessionsRef, (current) => {
296+
const next = new Map(current);
297+
const remaining = (next.get(sessionId) ?? 0) - 1;
298+
if (remaining > 0) {
299+
next.set(sessionId, remaining);
300+
} else {
301+
next.delete(sessionId);
302+
}
303+
return next;
304+
}),
305+
),
306+
).pipe(
287307
Effect.flatMap(() => loadActiveSession(sessionId)),
308+
Effect.tap((session) =>
309+
Effect.logDebug("session.markDisconnected loaded active session", {
310+
sessionId,
311+
hasActiveSession: Option.isSome(session),
312+
}),
313+
),
288314
Effect.flatMap((session) =>
289315
Option.isSome(session) ? emitUpsert(session.value) : Effect.void,
290316
),

‎apps/server/src/auth/http.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,15 @@ export const authHttpApiLayer = HttpApiBuilder.group(
196196
function* (args) {
197197
yield* annotateEnvironmentRequest(args.endpoint.name);
198198
const request = yield* HttpServerRequest.HttpServerRequest;
199-
return yield* serverAuth.getSessionState(request);
199+
const sessionState = yield* serverAuth.getSessionState(request);
200+
yield* Effect.logDebug("auth.session resolved", {
201+
authenticated: sessionState.authenticated,
202+
hasSessionCookie:
203+
typeof request.cookies[sessionState.auth.sessionCookieName] === "string",
204+
hasAuthorizationHeader: request.headers.authorization !== undefined,
205+
sessionMethods: sessionState.auth.sessionMethods.join(","),
206+
});
207+
return sessionState;
200208
},
201209
Effect.catchTag("ServerAuthInternalError", (error) =>
202210
failEnvironmentInternal("internal_error", error),
@@ -226,6 +234,12 @@ export const authHttpApiLayer = HttpApiBuilder.group(
226234
Effect.succeed(HttpServerResponse.mergeCookies(response, sessionCookies)),
227235
);
228236
yield* appendCredentialResponseHeaders;
237+
yield* Effect.logDebug("auth.browserSession response prepared", {
238+
sessionCookieName: sessions.cookieName,
239+
authenticated: result.response.authenticated,
240+
sessionMethod: result.response.sessionMethod,
241+
scopeCount: result.response.scopes.length,
242+
});
229243
return result.response;
230244
},
231245
Effect.catchTags({
@@ -304,7 +318,14 @@ export const authHttpApiLayer = HttpApiBuilder.group(
304318
yield* annotateEnvironmentRequest(args.endpoint.name);
305319
const session = yield* EnvironmentAuthenticatedPrincipal;
306320
yield* appendCredentialResponseHeaders;
307-
return yield* serverAuth.issueWebSocketTicket(session);
321+
const issued = yield* serverAuth.issueWebSocketTicket(session);
322+
yield* Effect.logDebug("auth.webSocketTicket response prepared", {
323+
sessionId: session.sessionId,
324+
sessionMethod: session.method,
325+
scopeCount: session.scopes.size,
326+
expiresAt: DateTime.formatIso(issued.expiresAt),
327+
});
328+
return issued;
308329
},
309330
Effect.catchTag("ServerAuthInternalError", (error) =>
310331
failEnvironmentInternal("websocket_ticket_issuance_failed", error),

‎apps/server/src/provider/providerMaintenanceRunner.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,9 +191,11 @@ function makeUpdateState(input: {
191191
}
192192

193193
export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
194+
yield* Effect.logDebug("providerMaintenanceRunner.make start");
194195
const providerRegistry = yield* ProviderRegistry;
195196
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
196197
const httpClient = yield* HttpClient.HttpClient;
198+
yield* Effect.logDebug("providerMaintenanceRunner.make dependencies ready");
197199
const runMaintenanceCommand = (command: string, args: ReadonlyArray<string>) =>
198200
runProviderMaintenanceCommandWithSpawner({
199201
spawner,

‎apps/server/src/review/BackgroundAgentService.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,11 @@ function fail(
9898
}
9999

100100
export const make = Effect.fn("makeBackgroundAgentService")(function* () {
101-
const git = yield* GitVcsDriver.GitVcsDriver;
102-
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
103-
const review = yield* ReviewService.ReviewService;
101+
yield* Effect.logDebug("backgroundAgentService.make start");
102+
const git = yield* GitVcsDriver;
103+
const gitWorkflow = yield* GitWorkflowService;
104+
const review = yield* ReviewService;
105+
yield* Effect.logDebug("backgroundAgentService.make dependencies ready");
104106

105107
const runBackgroundAgent = Effect.fn("BackgroundAgentService.runBackgroundAgent")(
106108
(input: RunBackgroundAgentInput): Stream.Stream<BackgroundAgentResponseEvent, ChangeRequestRunBackgroundAgentError> =>

‎apps/server/src/review/ReviewService.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,13 +62,15 @@ export class ReviewService extends Context.Service<ReviewService, ReviewServiceS
6262
) {}
6363

6464
export const make = Effect.fn("makeReviewService")(function* () {
65+
yield* Effect.logDebug("reviewService.make start");
6566
const config = yield* ServerConfig;
6667
const fileSystem = yield* FileSystem.FileSystem;
6768
const path = yield* Path.Path;
6869
const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry;
6970
const git = yield* GitVcsDriver.GitVcsDriver;
7071
const draftStore = yield* ReviewDraftStore.ReviewDraftStore;
7172
const githubCliOption = yield* Effect.serviceOption(GitHubCli.GitHubCli);
73+
yield* Effect.logDebug("reviewService.make dependencies ready");
7274

7375
function mapGitHubCommentToReviewComment(
7476
comment: GitHubCli.GitHubPullRequestReviewComment,

0 commit comments

Comments
 (0)