diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts index 09c1f39dd1..a8de518ed9 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts @@ -94,6 +94,21 @@ const makeBroker = (secrets: ServerSecretStore.ServerSecretStore["Service"]) => Effect.provide(NodeServices.layer), ); +/** + * Broker over an explicitly supplied settings service, so a test can interpose + * on `getSettings` and hold a handshake at a chosen read while another + * operation runs to completion. + */ +const makeBrokerWith = ( + secrets: ServerSecretStore.ServerSecretStore["Service"], + settingsService: ServerSettings.ServerSettingsService["Service"], +) => + makeHermesGatewayBroker.pipe( + Effect.provideService(ServerSecretStore.ServerSecretStore, secrets), + Effect.provideService(ServerSettings.ServerSettingsService, settingsService), + Effect.provide(NodeServices.layer), + ); + /** Ambient layer: one settings service shared by the test and its brokers. */ const testLayer = Layer.mergeAll( ServerSettings.layerTest({ providerInstances: hermesInstances }), @@ -329,6 +344,141 @@ it.effect("redeems an enrollment token exactly once under concurrent redemption" }).pipe(Effect.provide(testLayer)), ); +/** + * Secret store that can hold the *first* `set` — the credential write at the + * heart of the handshake — open until a test releases it. That is the exact + * point a competing enrollment or revocation used to be able to slip past a + * half-finished handshake. + */ +const gatedCredentialWriteSecretStore = () => + Effect.gen(function* () { + const inner = makeSecretStore(); + const reachedWrite = yield* Deferred.make(); + const releaseWrite = yield* Deferred.make(); + let gated = false; + const service: ServerSecretStore.ServerSecretStore["Service"] = { + ...inner, + set: (name, value) => + Effect.suspend(() => { + if (gated) return inner.set(name, value); + gated = true; + return Deferred.succeed(reachedWrite, undefined).pipe( + Effect.andThen(Deferred.await(releaseWrite)), + Effect.andThen(inner.set(name, value)), + ); + }), + }; + return { secrets: service, reachedWrite, releaseWrite } as const; + }); + +// The credential write and the acceptance that follows it are the mutation +// half of the handshake. Before they were fenced by the instance lock, a +// `createEnrollment` could complete entirely inside that window: it removed the +// outgoing credential and minted a replacement token, and then the suspended +// handshake resumed and wrote a *fresh* credential for the enrollment that had +// just been superseded — leaving the old enrollee able to authenticate forever. +it.effect("does not resurrect a credential for an enrollment superseded mid-handshake", () => + Effect.gen(function* () { + const { secrets, reachedWrite, releaseWrite } = yield* gatedCredentialWriteSecretStore(); + const broker = yield* makeBrokerWith(secrets, yield* ServerSettings.ServerSettingsService); + const enrollment = yield* enroll(broker, instanceId, "Superseded Hermes"); + + const handshake = yield* broker + .registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + recordingTransport().transport, + ) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + // The handshake is now parked with its token already consumed, holding the + // instance lock. + yield* Deferred.await(reachedWrite); + + const replacement = yield* enroll(broker, instanceId, "Superseded Hermes").pipe( + Effect.forkChild({ startImmediately: true }), + ); + // The replacement enrollment must not be able to interleave with the + // handshake's mutation section: it waits for the lock instead. + for (let i = 0; i < 20; i += 1) yield* Effect.yieldNow; + assert.isUndefined( + replacement.pollUnsafe(), + "a replacement enrollment must not run inside a handshake's mutation section", + ); + + yield* Deferred.succeed(releaseWrite, undefined); + const registered = yield* Fiber.join(handshake); + yield* Fiber.join(replacement); + + // Whichever order they serialize in, the enrollment that ran last wins: the + // superseded enrollee's credential is gone from the store... + assert.isTrue( + Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId))), + "the superseded enrollment's credential must not survive the replacement", + ); + // ...and cannot be replayed to authenticate. + if (registered._tag === "Success" && registered.success.accepted.credential) { + const replayed = yield* Effect.flip( + broker.registerConnection( + hello({ + type: "instance-credential", + instanceId, + credential: registered.success.accepted.credential, + }), + recordingTransport().transport, + ), + ); + assert.equal(replayed.code, "invalid-authentication"); + } + }).pipe(Effect.provide(testLayer)), +); + +// The mirror of the above for revocation. `registerConnection` used to read a +// non-revoked record, pause, and then call `connections.accept` after a +// concurrent `revokeInstance` had already persisted `revoked: true` and cleared +// the connection — re-establishing a live socket for a revoked instance that +// nothing would reap until the next reconnect. +it.effect("leaves no live connection when revocation races a handshake", () => + Effect.gen(function* () { + const { secrets, reachedWrite, releaseWrite } = yield* gatedCredentialWriteSecretStore(); + const broker = yield* makeBrokerWith(secrets, yield* ServerSettings.ServerSettingsService); + const enrollment = yield* enroll(broker, instanceId, "Revoked Race Hermes"); + const { closes, transport } = recordingTransport(); + + const handshake = yield* broker + .registerConnection( + hello({ type: "enrollment-token", token: enrollment.oneTimeToken }), + transport, + ) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + yield* Deferred.await(reachedWrite); + + const revoke = yield* broker + .revokeInstance(instanceId) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + for (let i = 0; i < 20; i += 1) yield* Effect.yieldNow; + assert.isUndefined( + revoke.pollUnsafe(), + "revocation must not run inside a handshake's mutation section", + ); + + yield* Deferred.succeed(releaseWrite, undefined); + yield* Fiber.join(handshake); + const revoked = yield* Fiber.join(revoke); + assert.equal(revoked._tag, "Success"); + + // Serializing the two is enough: the handshake may win the lock and be + // accepted, but revocation then runs to completion behind it and tears the + // socket down. What must never hold is a revoked instance with a live + // connection. + assert.equal((yield* broker.getInstanceStatus(instanceId)).status, "revoked"); + assert.isFalse( + yield* broker.isConnected(instanceId), + "a revoked instance must not be left connected", + ); + assert.deepEqual(closes, [4003]); + assert.isTrue(Option.isNone(yield* secrets.get(hermesGatewayCredentialSecretName(instanceId)))); + }).pipe(Effect.provide(testLayer)), +); + it.effect("expires enrollment tokens from memory without a redemption attempt", () => Effect.gen(function* () { const broker = yield* makeBroker(makeSecretStore()); diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.ts index b248bebcfc..2c0feffe92 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.ts @@ -29,12 +29,17 @@ * * Locking * ------- - * There is no global broker lock. Enrollment mutations serialize per-instance; - * `registerConnection` takes no enrollment lock at all, so a slow credential - * write during one instance's enrollment cannot block another instance's - * WebSocket handshake. Where two writers could still race — token redemption, - * connection replacement — correctness comes from compare-and-swap and - * generation fencing rather than from a mutex. + * There is no global broker lock. Everything that mutates one instance's + * enrollment — `createEnrollment`, `revokeInstance`, `removeInstance`, + * `renameInstance`, and the state-changing half of `registerConnection` — + * serializes on that instance's lock, so a slow credential write during one + * instance's enrollment still cannot block another instance's WebSocket + * handshake. `registerConnection` authenticates *before* taking the lock, so an + * unauthenticated caller cannot queue on it, and then re-validates the durable + * record and the credential once inside — the pre-lock read is only a filter. + * Where two writers could still race within a locked section — token + * redemption, connection replacement — correctness comes from compare-and-swap + * and generation fencing rather than from the mutex. * * @module HermesGatewayBroker */ @@ -803,28 +808,25 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { yield* probe.pipe(Effect.forever, Effect.ignoreCause({ log: true })); }); - const registerConnection = ( - hello: HermesGatewayConnectionHello, - transport: HermesGatewayTransport, - ) => + /** + * Handshake authentication: prove the caller holds a live credential or a + * live enrollment token, and resolve the instance it is speaking for. + * + * Deliberately a pure read. Nothing here mutates broker state, which is what + * makes it safe to run twice — once before the instance lock is taken, so an + * unauthenticated caller never joins the lock queue, and again inside it, so + * the facts the mutation section acts on were re-read after every competing + * enrollment or revocation had to finish. + */ + const authenticateHello = (hello: HermesGatewayConnectionHello) => Effect.gen(function* () { - const strictCapabilities = isStrictCapabilities(hello.capabilities) - ? hello.capabilities - : undefined; - - // ── Phase 1: authenticate. Nothing below this line mutates connection - // state, and nothing above it is allowed to. An earlier bug applied - // "incompatible version" state before checking the credential, letting - // an unauthenticated caller knock a healthy instance offline; the test - // "authenticates before applying incompatible connection state" guards - // this ordering. let instanceId: ProviderInstanceId; - let authenticatedEnrollment: PendingEnrollment | undefined; + let enrollment: PendingEnrollment | undefined; if (hello.authentication.type === "enrollment-token") { const authentication = hello.authentication; - const enrollment = yield* enrollmentStore.peek(authentication.token); - if (!enrollment) { + const pending = yield* enrollmentStore.peek(authentication.token); + if (!pending) { return yield* Effect.fail( rejection( hello.requestId, @@ -833,8 +835,8 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ); } - instanceId = enrollment.input.instanceId; - authenticatedEnrollment = enrollment; + instanceId = pending.input.instanceId; + enrollment = pending; } else { const authentication = hello.authentication; instanceId = authentication.instanceId; @@ -888,155 +890,214 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ); } - // ── Phase 2: the caller is authenticated. State changes may begin. - if ( - hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION || - strictCapabilities === undefined - ) { - const displaced = yield* connections.markUpgradeRequired({ - instanceId, - upgradeRequired: { - pluginVersion: hello.pluginVersion, - hermesVersion: hello.hermesVersion, - protocolVersion: hello.protocolVersion, - model: hello.model ?? null, - }, - }); - if (displaced) { - yield* teardownConnection( - instanceId, - displaced.transport, - 4004, - "The Hermes gateway plugin requires a protocol upgrade.", - ); - } - yield* publishStatus(instanceId, record); - // Names the fix, not just the mismatch: the rejection text is what a - // v3 (pre-media) plugin's operator sees in its logs. A right-version - // hello can still land here when its capabilities don't satisfy the - // v4 contract (e.g. `attachments: false`), so say which it was. - return yield* Effect.fail( - rejection( - hello.requestId, - "version-incompatible", - hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION - ? `Expected protocol version ${HERMES_GATEWAY_PROTOCOL_VERSION}, received ${hello.protocolVersion}. Upgrade the T3 Code gateway plugin on the Hermes host to reconnect.` - : `The advertised capabilities do not satisfy the version ${HERMES_GATEWAY_PROTOCOL_VERSION} contract. Upgrade the T3 Code gateway plugin on the Hermes host to reconnect.`, - ), - ); - } + return { instanceId, enrollment, record } as const; + }); - let credential: HermesGatewayCredential | undefined; - if (hello.authentication.type === "enrollment-token" && authenticatedEnrollment) { - const authentication = hello.authentication; - const consumed = yield* enrollmentStore.consume( - authentication.token, - authenticatedEnrollment, - ); - if (!consumed) { - return yield* Effect.fail( - rejection( - hello.requestId, - "enrollment-expired", - "The enrollment token is invalid, expired, or already used.", - ), - ); - } - instanceId = consumed.input.instanceId; - credential = HermesGatewayCredential.make( - Encoding.encodeBase64Url( - yield* crypto - .randomBytes(CREDENTIAL_BYTES) + const registerConnection = ( + hello: HermesGatewayConnectionHello, + transport: HermesGatewayTransport, + ) => + Effect.gen(function* () { + const strictCapabilities = isStrictCapabilities(hello.capabilities) + ? hello.capabilities + : undefined; + + // ── Phase 1: authenticate, unlocked. Nothing below this line mutates + // connection state, and nothing above it is allowed to. An earlier bug + // applied "incompatible version" state before checking the credential, + // letting an unauthenticated caller knock a healthy instance offline; + // the test "authenticates before applying incompatible connection state" + // guards this ordering. Running it before the lock also keeps a caller + // with a junk credential from queueing behind an in-flight enrollment. + const preliminary = yield* authenticateHello(hello); + + // ── Phase 2: the caller is authenticated. State changes may begin — + // under the instance's enrollment lock, so `createEnrollment`, + // `revokeInstance`, and `removeInstance` cannot interleave with token + // redemption, credential persistence, or acceptance. + // + // Everything inside is bounded and takes no other lock: settings reads + // are a `Ref.get`, and `teardownConnection` only fails correlated + // requests and closes the *displaced* socket — never the one currently + // handshaking, which is not in the registry yet. So the WS accept path + // cannot deadlock against a displaced connection's teardown. + return yield* withInstanceLock( + preliminary.instanceId, + Effect.gen(function* () { + // Re-read every fact behind the lock. The pre-lock pass was only a + // filter: between it and here a `createEnrollment` may have removed + // the credential and superseded the token, or a `revokeInstance` may + // have marked the instance revoked and cleared its connection. Both + // are now visible, and both reject. + const { + instanceId, + enrollment: authenticatedEnrollment, + record, + } = yield* authenticateHello(hello); + if (instanceId !== preliminary.instanceId) { + // The lock we hold is the wrong one, so this cannot proceed + // safely. Only reachable if a token were re-pointed at another + // instance, which minting never does. + return yield* Effect.fail( + rejection( + hello.requestId, + "invalid-authentication", + "The Hermes gateway enrollment changed during the handshake.", + ), + ); + } + + if ( + hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION || + strictCapabilities === undefined + ) { + const displaced = yield* connections.markUpgradeRequired({ + instanceId, + upgradeRequired: { + pluginVersion: hello.pluginVersion, + hermesVersion: hello.hermesVersion, + protocolVersion: hello.protocolVersion, + model: hello.model ?? null, + }, + }); + if (displaced) { + yield* teardownConnection( + instanceId, + displaced.transport, + 4004, + "The Hermes gateway plugin requires a protocol upgrade.", + ); + } + yield* publishStatus(instanceId, record); + // Names the fix, not just the mismatch: the rejection text is what + // a v3 (pre-media) plugin's operator sees in its logs. A + // right-version hello can still land here when its capabilities + // don't satisfy the v4 contract (e.g. `attachments: false`), so + // say which it was. + return yield* Effect.fail( + rejection( + hello.requestId, + "version-incompatible", + hello.protocolVersion !== HERMES_GATEWAY_PROTOCOL_VERSION + ? `Expected protocol version ${HERMES_GATEWAY_PROTOCOL_VERSION}, received ${hello.protocolVersion}. Upgrade the T3 Code gateway plugin on the Hermes host to reconnect.` + : `The advertised capabilities do not satisfy the version ${HERMES_GATEWAY_PROTOCOL_VERSION} contract. Upgrade the T3 Code gateway plugin on the Hermes host to reconnect.`, + ), + ); + } + + let credential: HermesGatewayCredential | undefined; + if (hello.authentication.type === "enrollment-token" && authenticatedEnrollment) { + const authentication = hello.authentication; + const consumed = yield* enrollmentStore.consume( + authentication.token, + authenticatedEnrollment, + ); + if (!consumed) { + return yield* Effect.fail( + rejection( + hello.requestId, + "enrollment-expired", + "The enrollment token is invalid, expired, or already used.", + ), + ); + } + credential = HermesGatewayCredential.make( + Encoding.encodeBase64Url( + yield* crypto + .randomBytes(CREDENTIAL_BYTES) + .pipe( + Effect.mapError(() => + rejection( + hello.requestId, + "internal-error", + "Failed to generate the Hermes gateway credential.", + ), + ), + ), + ), + ); + yield* secretStore + .set(credentialSecretName(instanceId), textEncoder.encode(credential)) .pipe( Effect.mapError(() => rejection( hello.requestId, "internal-error", - "Failed to generate the Hermes gateway credential.", + "Failed to persist the Hermes gateway credential.", ), ), - ), - ), - ); - yield* secretStore - .set(credentialSecretName(instanceId), textEncoder.encode(credential)) - .pipe( - Effect.mapError(() => - rejection( - hello.requestId, - "internal-error", - "Failed to persist the Hermes gateway credential.", - ), - ), - ); - } + ); + } - // ── Delivery connections: authenticated, but never the primary. - // - // An out-of-process cron run dials in only to hand over a `home.deliver` - // and leave. Registering it would displace the instance's live gateway - // socket ("replaced by a newer connection") and bump the generation, - // knocking the real plugin offline for the duration of a cron job. So it - // is accepted and then deliberately left out of the connection registry: - // no generation, no liveness ping, no status publish, nothing to - // disconnect. The existing primary is untouched. - if (hello.role === "delivery") { - return { - instanceId, - generation: null, - role: "delivery", - accepted: { - type: "connection.accepted", - requestId: hello.requestId, - protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + // ── Delivery connections: authenticated, but never the primary. + // + // An out-of-process cron run dials in only to hand over a + // `home.deliver` and leave. Registering it would displace the + // instance's live gateway socket ("replaced by a newer connection") + // and bump the generation, knocking the real plugin offline for the + // duration of a cron job. So it is accepted and then deliberately + // left out of the connection registry: no generation, no liveness + // ping, no status publish, nothing to disconnect. The existing + // primary is untouched. + if (hello.role === "delivery") { + return { + instanceId, + generation: null, + role: "delivery", + accepted: { + type: "connection.accepted", + requestId: hello.requestId, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId, + nickname: record.nickname, + ...(credential ? { credential } : {}), + }, + } as const satisfies HermesGatewayConnectionRegistration; + } + + const observed: HermesObservedConnection = { + pluginVersion: hello.pluginVersion, + hermesVersion: hello.hermesVersion, + capabilities: strictCapabilities, + model: hello.model ?? null, + connectedAt: DateTime.formatIso(yield* DateTime.now), + activeSessionCount: 0, + }; + const accepted = yield* connections.accept({ instanceId, transport, observed }); + if (accepted.displaced) { + yield* teardownConnection( + instanceId, + accepted.displaced.transport, + 4001, + "The Hermes gateway connection was replaced by a newer connection.", + ); + } + + const registration = { instanceId, - nickname: record.nickname, - ...(credential ? { credential } : {}), - }, - } as const satisfies HermesGatewayConnectionRegistration; - } + generation: accepted.generation, + role: "gateway", + accepted: { + type: "connection.accepted", + requestId: hello.requestId, + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + instanceId, + nickname: record.nickname, + ...(credential ? { credential } : {}), + }, + } as const satisfies HermesGatewayConnectionRegistration; - const observed: HermesObservedConnection = { - pluginVersion: hello.pluginVersion, - hermesVersion: hello.hermesVersion, - capabilities: strictCapabilities, - model: hello.model ?? null, - connectedAt: DateTime.formatIso(yield* DateTime.now), - activeSessionCount: 0, - }; - const accepted = yield* connections.accept({ instanceId, transport, observed }); - if (accepted.displaced) { - yield* teardownConnection( - instanceId, - accepted.displaced.transport, - 4001, - "The Hermes gateway connection was replaced by a newer connection.", - ); - } + // Liveness probing belongs to this connection's scope, so it is + // interrupted the moment the connection is retired. + const liveness = yield* connections.liveness(instanceId); + if (liveness?.connection?.generation === accepted.generation) { + yield* pingLoop(registration, transport).pipe(Effect.forkIn(liveness.connection.scope)); + } - const registration = { - instanceId, - generation: accepted.generation, - role: "gateway", - accepted: { - type: "connection.accepted", - requestId: hello.requestId, - protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, - instanceId, - nickname: record.nickname, - ...(credential ? { credential } : {}), - }, - } as const satisfies HermesGatewayConnectionRegistration; - - // Liveness probing belongs to this connection's scope, so it is - // interrupted the moment the connection is retired. - const liveness = yield* connections.liveness(instanceId); - if (liveness?.connection?.generation === accepted.generation) { - yield* pingLoop(registration, transport).pipe(Effect.forkIn(liveness.connection.scope)); - } - - yield* publishStatus(instanceId, record); - return registration; + yield* publishStatus(instanceId, record); + return registration; + }), + ); }); const receive = (registration: HermesGatewayConnectionRegistration, message: PluginMessage) => diff --git a/apps/server/src/provider/Layers/RequestCorrelator.test.ts b/apps/server/src/provider/Layers/RequestCorrelator.test.ts new file mode 100644 index 0000000000..d49f5ff744 --- /dev/null +++ b/apps/server/src/provider/Layers/RequestCorrelator.test.ts @@ -0,0 +1,184 @@ +import { assert, it } from "@effect/vitest"; +import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; +import * as TestClock from "effect/testing/TestClock"; + +import { ProviderAdapterRequestError } from "../Errors.ts"; +import { makeRequestCorrelator } from "./RequestCorrelator.ts"; + +const TIMEOUT = Duration.seconds(30); + +const makeCorrelator = () => + makeRequestCorrelator({ + provider: "test", + timeout: TIMEOUT, + maxAge: Duration.seconds(90), + }); + +const owner = "owner-a"; + +it.effect("resolves a correlated response and releases the pending entry", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const pending = yield* correlator + .request({ owner, requestId: "r1", method: "test.method", send: Effect.void }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + assert.equal(yield* correlator.pendingCount, 1); + + assert.isTrue(yield* correlator.complete("r1", { requestId: "r1" })); + assert.deepEqual(yield* Fiber.join(pending), { requestId: "r1" }); + assert.equal(yield* correlator.pendingCount, 0); + }), +); + +it.effect("releases the pending entry when the send fails", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const failure = yield* Effect.flip( + correlator.request({ + owner, + requestId: "r-send-fail", + method: "test.method", + send: Effect.fail( + new ProviderAdapterRequestError({ + provider: "test", + method: "test.method", + detail: "the transport refused the write", + }), + ), + }), + ); + assert.include(failure.detail, "refused"); + assert.equal(yield* correlator.pendingCount, 0); + }), +); + +// The send used to sit outside `restore`, so a transport write that never +// returned could not be interrupted: `Fiber.interrupt` would hang forever +// waiting for the uninterruptible region to finish. The write is now inside the +// restored region, so an interrupt lands — and the entry is still released. +it.effect("interrupts a request whose transport write never returns", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const writeStarted = yield* Deferred.make(); + const neverCompletes = yield* Deferred.make(); + + const pending = yield* correlator + .request({ + owner, + requestId: "r-stalled-write", + method: "test.method", + send: Deferred.succeed(writeStarted, undefined).pipe( + Effect.andThen(Deferred.await(neverCompletes)), + ), + }) + .pipe(Effect.forkChild({ startImmediately: true })); + + yield* Deferred.await(writeStarted); + assert.equal(yield* correlator.pendingCount, 1); + + // Would never return before the fix. + yield* Fiber.interrupt(pending); + assert.equal( + yield* correlator.pendingCount, + 0, + "an interrupted request must not leave a pending entry behind", + ); + }), +); + +// `Effect.timeout` only wrapped `Deferred.await`, so the clock did not start +// until the write returned: a request over a wedged socket outlived its own +// timeout for as long as the socket stayed wedged. The timeout now covers the +// send too. +it.effect("times out a request whose transport write stalls", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const writeStarted = yield* Deferred.make(); + const neverCompletes = yield* Deferred.make(); + + const pending = yield* correlator + .request({ + owner, + requestId: "r-stalled-timeout", + method: "test.method", + send: Deferred.succeed(writeStarted, undefined).pipe( + Effect.andThen(Deferred.await(neverCompletes)), + ), + }) + .pipe(Effect.result, Effect.forkChild({ startImmediately: true })); + + yield* Deferred.await(writeStarted); + yield* TestClock.adjust(Duration.seconds(31)); + + const outcome = yield* Fiber.join(pending); + assert.equal(outcome._tag, "Failure"); + if (outcome._tag === "Failure") assert.include(outcome.failure.detail, "timed out"); + assert.equal(yield* correlator.pendingCount, 0); + }), +); + +// A response can land the instant the write completes. Registration happens +// uninterruptibly before the send, so `complete` always finds an entry — +// moving the send inside `restore` must not have opened that window. +it.effect("completes a response that arrives from inside the transport write", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const pending = yield* correlator + .request({ + owner, + requestId: "r-immediate", + method: "test.method", + // The transport answers synchronously, before `send` even returns. + send: correlator.complete("r-immediate", { requestId: "r-immediate" }).pipe( + Effect.flatMap((completed) => + completed + ? Effect.void + : Effect.fail( + new ProviderAdapterRequestError({ + provider: "test", + method: "test.method", + detail: "the response found no pending entry", + }), + ), + ), + ), + }) + .pipe(Effect.forkChild({ startImmediately: true })); + + assert.deepEqual(yield* Fiber.join(pending), { requestId: "r-immediate" }); + assert.equal(yield* correlator.pendingCount, 0); + }), +); + +it.effect("fails every request routed over a dead owner", () => + Effect.gen(function* () { + const correlator = yield* makeCorrelator(); + const first = yield* correlator + .request({ owner, requestId: "r-own-1", method: "test.method", send: Effect.void }) + .pipe(Effect.forkChild({ startImmediately: true })); + const second = yield* correlator + .request({ owner, requestId: "r-own-2", method: "test.method", send: Effect.void }) + .pipe(Effect.forkChild({ startImmediately: true })); + const other = yield* correlator + .request({ + owner: "owner-b", + requestId: "r-own-3", + method: "test.method", + send: Effect.void, + }) + .pipe(Effect.forkChild({ startImmediately: true })); + yield* Effect.yieldNow; + + yield* correlator.failOwner(owner, "the connection dropped"); + assert.include((yield* Effect.flip(Fiber.join(first))).detail, "dropped"); + assert.include((yield* Effect.flip(Fiber.join(second))).detail, "dropped"); + assert.isUndefined(other.pollUnsafe(), "another owner's request must be untouched"); + + yield* correlator.complete("r-own-3", { requestId: "r-own-3" }); + assert.deepEqual(yield* Fiber.join(other), { requestId: "r-own-3" }); + }), +); diff --git a/apps/server/src/provider/Layers/RequestCorrelator.ts b/apps/server/src/provider/Layers/RequestCorrelator.ts index 2f1a693cfc..a6687e92d0 100644 --- a/apps/server/src/provider/Layers/RequestCorrelator.ts +++ b/apps/server/src/provider/Layers/RequestCorrelator.ts @@ -61,11 +61,24 @@ export const makeRequestCorrelator = ( const deferred = yield* Deferred.make(); const registeredAtMillis = yield* Clock.currentTimeMillis; - // Registration and the send must not be interruptible independently of - // the cleanup that removes the entry. `uninterruptibleMask` closes the - // window: the registration is applied, `restore` re-enables interrupts - // only inside the awaiting pipeline, and `ensuring` guarantees release - // regardless of how that pipeline exits. + // Registration must not be interruptible independently of the cleanup + // that removes the entry. `uninterruptibleMask` closes that window: the + // registration is applied uninterruptibly — so a response arriving the + // instant the request is written always finds an entry to complete — + // and `ensuring` guarantees release regardless of how the rest exits. + // + // Everything after registration — the send *and* the await — lives + // inside `restore`, with the timeout inside it too. Both placements + // matter: + // + // - Send outside `restore`: a transport write that never returns is + // unkillable, and the response timeout does not start counting + // until the write returns, so a request over a wedged socket hangs + // for as long as the socket does. + // - Timeout outside `restore`: `Effect.timeout` races internally, and + // that race inherits the surrounding uninterruptible region — so an + // interrupt cannot land on the awaiting fiber even though the body + // it wraps was restored. return yield* Effect.uninterruptibleMask((restore) => Effect.gen(function* () { yield* Ref.update(pending, (current) => @@ -77,10 +90,12 @@ export const makeRequestCorrelator = ( }), ); - yield* input.send.pipe(Effect.tapError(() => release(input.requestId))); - - return yield* restore(Deferred.await(deferred)).pipe( - Effect.timeout(input.timeout ?? options.timeout), + return yield* restore( + input.send.pipe( + Effect.andThen(Deferred.await(deferred)), + Effect.timeout(input.timeout ?? options.timeout), + ), + ).pipe( Effect.mapError((error) => error._tag === "TimeoutError" ? requestError(input.method, `${options.provider} request timed out.`)