* Surface unreachable upstreams as network error * Test queue timeout with a controlled clock * Classify transport failures without hiding invocation defects * Name the integration and origin in the unreachable-upstream message Executor sends the request, not the user's browser, so "check your network" pointed at the wrong place. Name the integration and the origin that could not be reached and tell the user to verify the base URL and that the service is online. Only the host is lifted off the transport failure; the path, query, and headers stay out of the message. * Record the cause of unreachable upstreams without the request Classifying transport failures as a typed tool result took them off the hosts' defect path, which was the only place the cause was logged. Lift the errno-style code (ECONNREFUSED, ENOTFOUND, UND_ERR_SOCKET, ...) off the fetch cause chain, log a warning and annotate the span with the integration, host, and code, and return the same sanitized pair in the tool result details. The raw TransportError stays out of details on purpose: it carries the whole request, including resolved auth headers. ---------
Unified · Split
| @@ -0,0 +1,6 @@ | |||
| 1 | --- | ||
| 2 | "executor": patch | ||
| 3 | "@executor-js/plugin-openapi": patch | ||
| 4 | --- | ||
| 5 | |||
| 6 | OpenAPI tools that cannot reach the upstream server now return an `upstream_unreachable` error instead of `Internal tool error [id]`. The message names the integration and origin that could not be reached, `details` carries the sanitized `host` and errno-style `code` (`ECONNREFUSED`, `ENOTFOUND`, …), and the failure is logged with the same classification. | ||
| @@ -0,0 +1,226 @@ | |||
| 1 | // Cross-target: an artifact whose OpenAPI query cannot reach its upstream gets | ||
| 2 | // an actionable network error, not the opaque defect mask. This walks the real | ||
| 3 | // path from a saved artifact through the nested shell, execute-action, sandbox, | ||
| 4 | // OpenAPI transport, and back into ArtifactError. | ||
| 5 | import { randomBytes } from "node:crypto"; | ||
| 6 | import { createServer } from "node:http"; | ||
| 7 | |||
| 8 | import { expect } from "@effect/vitest"; | ||
| 9 | import { Effect } from "effect"; | ||
| 10 | import type { Page } from "playwright"; | ||
| 11 | import { composePluginApi } from "@executor-js/api/server"; | ||
| 12 | import { openApiHttpPlugin } from "@executor-js/plugin-openapi/api"; | ||
| 13 | import { ConnectionName, IntegrationSlug, type ArtifactId } from "@executor-js/sdk/shared"; | ||
| 14 | |||
| 15 | import { scenario } from "../src/scenario"; | ||
| 16 | import { Api, Browser, Mcp, Target } from "../src/services"; | ||
| 17 | import { visit } from "../src/surfaces/browser"; | ||
| 18 | import type { McpSession } from "../src/surfaces/mcp"; | ||
| 19 | |||
| 20 | const api = composePluginApi([openApiHttpPlugin()] as const); | ||
| 21 | |||
| 22 | const unique = (prefix: string) => `${prefix}_${randomBytes(4).toString("hex")}`; | ||
| 23 | |||
| 24 | type DroppingUpstream = { | ||
| 25 | readonly url: string; | ||
| 26 | readonly requests: () => number; | ||
| 27 | readonly close: () => void; | ||
| 28 | }; | ||
| 29 | |||
| 30 | // Accept the request, then drop the socket before sending response headers. | ||
| 31 | // This produces a real transport failure without relying on a hardcoded or | ||
| 32 | // temporarily-unused port. | ||
| 33 | const serveDroppingUpstream = () => | ||
| 34 | Effect.acquireRelease( | ||
| 35 | Effect.callback<DroppingUpstream>((resume) => { | ||
| 36 | let hits = 0; | ||
| 37 | const server = createServer((_request, response) => { | ||
| 38 | hits += 1; | ||
| 39 | response.destroy(); | ||
| 40 | }); | ||
| 41 | server.listen(0, "127.0.0.1", () => { | ||
| 42 | const address = server.address(); | ||
| 43 | const port = typeof address === "object" && address ? address.port : 0; | ||
| 44 | resume( | ||
| 45 | Effect.succeed({ | ||
| 46 | url: `http://127.0.0.1:${port}`, | ||
| 47 | requests: () => hits, | ||
| 48 | close: () => { | ||
| 49 | server.close(); | ||
| 50 | server.closeAllConnections(); | ||
| 51 | }, | ||
| 52 | }), | ||
| 53 | ); | ||
| 54 | }); | ||
| 55 | }), | ||
| 56 | (server) => Effect.sync(server.close), | ||
| 57 | ); | ||
| 58 | |||
| 59 | const unreachableSpec = (baseUrl: string): string => | ||
| 60 | JSON.stringify({ | ||
| 61 | openapi: "3.0.3", | ||
| 62 | info: { title: "Unreachable API", version: "1.0.0" }, | ||
| 63 | servers: [{ url: baseUrl }], | ||
| 64 | paths: { | ||
| 65 | "/things": { | ||
| 66 | get: { | ||
| 67 | tags: ["things"], | ||
| 68 | operationId: "listThings", | ||
| 69 | summary: "List things", | ||
| 70 | responses: { | ||
| 71 | "200": { | ||
| 72 | description: "Things", | ||
| 73 | content: { | ||
| 74 | "application/json": { | ||
| 75 | schema: { type: "array", items: { type: "object" } }, | ||
| 76 | }, | ||
| 77 | }, | ||
| 78 | }, | ||
| 79 | }, | ||
| 80 | }, | ||
| 81 | }, | ||
| 82 | }, | ||
| 83 | }); | ||
| 84 | |||
| 85 | const createConnectionCode = (slug: string) => ` | ||
| 86 | const created = await tools.executor.coreTools.connections.create({ | ||
| 87 | owner: "org", | ||
| 88 | name: "public", | ||
| 89 | integration: ${JSON.stringify(slug)}, | ||
| 90 | template: "none", | ||
| 91 | }); | ||
| 92 | return JSON.stringify(created.ok ? { ok: true } : { ok: false, error: created.error }); | ||
| 93 | `; | ||
| 94 | |||
| 95 | const executeApproved = (session: McpSession, code: string) => | ||
| 96 | Effect.gen(function* () { | ||
| 97 | let result = yield* session.call("execute", { code }); | ||
| 98 | let guard = 0; | ||
| 99 | while (result.text.includes("executionId:") && guard < 10) { | ||
| 100 | result = yield* session.approvePaused(result.text); | ||
| 101 | guard += 1; | ||
| 102 | } | ||
| 103 | expect(result.ok, `execute completed (got: ${result.text.slice(0, 400)})`).toBe(true); | ||
| 104 | return result.text; | ||
| 105 | }); | ||
| 106 | |||
| 107 | const artifactSource = (slug: string) => ` | ||
| 108 | function App() { | ||
| 109 | const query = useQuery(tools.${slug}.things.listThings.queryOptions({})); | ||
| 110 | const result = query.data; | ||
| 111 | return ( | ||
| 112 | <div className="flex h-full flex-col gap-4"> | ||
| 113 | <h2>Upstream status</h2> | ||
| 114 | <div data-testid="upstream-state" className="min-h-0 flex-1"> | ||
| 115 | {query.isLoading ? ( | ||
| 116 | <ArtifactLoading /> | ||
| 117 | ) : query.error ? ( | ||
| 118 | <ArtifactError error={query.error} onRetry={query.refetch} /> | ||
| 119 | ) : result?.ok === false ? ( | ||
| 120 | <ArtifactError error={result.error} onRetry={query.refetch} /> | ||
| 121 | ) : ( | ||
| 122 | <p>Unexpected upstream success</p> | ||
| 123 | )} | ||
| 124 | </div> | ||
| 125 | </div> | ||
| 126 | ); | ||
| 127 | } | ||
| 128 | `; | ||
| 129 | |||
| 130 | const structuredOf = (result: { readonly raw: unknown }): Record<string, unknown> => | ||
| 131 | ((result.raw as { structuredContent?: Record<string, unknown> }).structuredContent ?? | ||
| 132 | {}) as Record<string, unknown>; | ||
| 133 | |||
| 134 | const artifactContent = (page: Page) => | ||
| 135 | page.frameLocator('[data-testid="artifact-shell-frame"]').frameLocator("iframe"); | ||
| 136 | |||
| 137 | scenario( | ||
| 138 | "Artifacts · an unreachable OpenAPI host shows actionable retry guidance instead of an internal error", | ||
| 139 | { timeout: 180_000 }, | ||
| 140 | Effect.scoped( | ||
| 141 | Effect.gen(function* () { | ||
| 142 | const target = yield* Target; | ||
| 143 | const browser = yield* Browser; | ||
| 144 | const mcp = yield* Mcp; | ||
| 145 | const { client: makeClient } = yield* Api; | ||
| 146 | |||
| 147 | const identity = yield* target.newIdentity(); | ||
| 148 | const client = yield* makeClient(api, identity); | ||
| 149 | const session = mcp.session(identity); | ||
| 150 | const upstream = yield* serveDroppingUpstream(); | ||
| 151 | const slug = unique("unreachable"); | ||
| 152 | const title = `Unreachable upstream ${randomBytes(4).toString("hex")}`; | ||
| 153 | let artifactId: ArtifactId | undefined; | ||
| 154 | |||
| 155 | yield* Effect.ensuring( | ||
| 156 | Effect.gen(function* () { | ||
| 157 | yield* client.openapi.addSpec({ | ||
| 158 | payload: { | ||
| 159 | spec: { kind: "blob", value: unreachableSpec(upstream.url) }, | ||
| 160 | slug, | ||
| 161 | baseUrl: upstream.url, | ||
| 162 | }, | ||
| 163 | }); | ||
| 164 | |||
| 165 | const created = yield* executeApproved(session, createConnectionCode(slug)); | ||
| 166 | expect(created, `the no-auth connection was created: ${created}`).toContain('"ok":true'); | ||
| 167 | |||
| 168 | const rendered = yield* session.call("create-artifact", { | ||
| 169 | code: artifactSource(slug), | ||
| 170 | title, | ||
| 171 | description: "Shows whether the upstream API is reachable", | ||
| 172 | connections: { [slug]: `${slug}.org.public` }, | ||
| 173 | }); | ||
| 174 | expect(rendered.ok, `create-artifact succeeded: ${rendered.text}`).toBe(true); | ||
| 175 | |||
| 176 | const structured = structuredOf(rendered); | ||
| 177 | artifactId = structured.artifactId as ArtifactId; | ||
| 178 | expect(artifactId, "the artifact was persisted").toBeTruthy(); | ||
| 179 | |||
| 180 | yield* browser.session(identity, async ({ page, step }) => { | ||
| 181 | await step("Open the artifact that reads from the unreachable API", async () => { | ||
| 182 | await visit(page, String(structured.url)); | ||
| 183 | await page.getByRole("heading", { name: title }).waitFor({ timeout: 20_000 }); | ||
| 184 | }); | ||
| 185 | |||
| 186 | await step( | ||
| 187 | "The artifact explains that the upstream host could not be reached", | ||
| 188 | async () => { | ||
| 189 | const state = artifactContent(page).getByTestId("upstream-state"); | ||
| 190 | await state.locator('[data-slot="artifact-error"]').waitFor({ timeout: 30_000 }); | ||
| 191 | const message = await state.innerText(); | ||
| 192 | |||
| 193 | expect(message, "the user gets actionable network guidance").toContain( | ||
| 194 | `Could not reach the upstream server for "${slug}"`, | ||
| 195 | ); | ||
| 196 | expect(message, "the opaque defect mask never reaches the artifact").not.toContain( | ||
| 197 | "Internal tool error", | ||
| 198 | ); | ||
| 199 | expect(message, "the request path is not leaked").not.toContain("/things"); | ||
| 200 | }, | ||
| 201 | ); | ||
| 202 | }); | ||
| 203 | |||
| 204 | expect(upstream.requests(), "the artifact made a real upstream request").toBeGreaterThan( | ||
| 205 | 0, | ||
| 206 | ); | ||
| 207 | }), | ||
| 208 | Effect.gen(function* () { | ||
| 209 | if (artifactId !== undefined) { | ||
| 210 | yield* client.artifacts.remove({ params: { artifactId } }).pipe(Effect.ignore); | ||
| 211 | } | ||
| 212 | yield* client.connections | ||
| 213 | .remove({ | ||
| 214 | params: { | ||
| 215 | owner: "org", | ||
| 216 | integration: IntegrationSlug.make(slug), | ||
| 217 | name: ConnectionName.make("public"), | ||
| 218 | }, | ||
| 219 | }) | ||
| 220 | .pipe(Effect.ignore); | ||
| 221 | yield* client.openapi.removeSpec({ params: { slug } }).pipe(Effect.ignore); | ||
| 222 | }), | ||
| 223 | ); | ||
| 224 | }), | ||
| 225 | ), | ||
| 226 | ); | ||
| @@ -629,6 +629,22 @@ export const resolveOpenApiBackedTools = ({ · 628 unmodified lines | |||
| 629 | }; | 629 | }; |
| 630 | }); | 630 | }); |
| 631 | 631 | ||
| 632 | // Transport failures used to escape as defects, which the hosts log with a | ||
| 633 | // correlation id. As a typed tool failure nothing else records them, so log | ||
| 634 | // and annotate the span with the sanitized classification operators need to | ||
| 635 | // tell DNS from refused from TLS. | ||
| 636 | const recordUpstreamUnreachable = (integration: string, error: OpenApiInvocationError) => { | ||
| 637 | const annotations = { | ||
| 638 | "plugin.openapi.integration": integration, | ||
| 639 | "plugin.openapi.upstream.host": error.upstreamHost ?? "unknown", | ||
| 640 | "plugin.openapi.upstream.transport_code": error.transportCode ?? "unknown", | ||
| 641 | }; | ||
| 642 | return Effect.logWarning("OpenAPI upstream unreachable").pipe( | ||
| 643 | Effect.annotateLogs(annotations), | ||
| 644 | Effect.andThen(Effect.annotateCurrentSpan(annotations)), | ||
| 645 | ); | ||
| 646 | }; | ||
| 647 | |||
| 632 | export const invokeOpenApiBackedTool = (input: { | 648 | export const invokeOpenApiBackedTool = (input: { |
| 633 | readonly ctx: PluginCtx<OpenapiStore>; | 649 | readonly ctx: PluginCtx<OpenapiStore>; |
| 634 | readonly toolRow: { readonly integration: string; readonly name: string }; | 650 | readonly toolRow: { readonly integration: string; readonly name: string }; |
| @@ -727,7 +743,28 @@ export const invokeOpenApiBackedTool = (input: { · 92 unmodified lines | |||
| 727 | details: error.cause ?? error, | 743 | details: error.cause ?? error, |
| 728 | }), | 744 | }), |
| 729 | }) | 745 | }) |
| 730 | : Effect.fail(error), | 746 | : error.reason === "transport_error" |
| 747 | ? recordUpstreamUnreachable(integration, error).pipe( | ||
| 748 | Effect.as({ | ||
| 749 | ok: false as const, | ||
| 750 | failure: ToolResult.fail({ | ||
| 751 | code: "upstream_unreachable", | ||
| 752 | // Executor sends the request, not the user's browser, so | ||
| 753 | // point at what the user can act on: the configured | ||
| 754 | // origin and the service behind it. | ||
| 755 | message: `Could not reach the upstream server for "${integration}"${error.upstreamHost ? ` at ${error.upstreamHost}` : ""}. Verify the integration's base URL and that the service is online, then try again.`, | ||
| 756 | // Unlike the timeout branches, `error.cause` is withheld: | ||
| 757 | // the TransportError carries the whole request, including | ||
| 758 | // resolved auth headers. Absent fields are dropped, not | ||
| 759 | // `undefined`: the result must stay a JSON value. | ||
| 760 | details: { | ||
| 761 | ...(error.upstreamHost !== undefined ? { host: error.upstreamHost } : {}), | ||
| 762 | ...(error.transportCode !== undefined ? { code: error.transportCode } : {}), | ||
| 763 | }, | ||
| 764 | }), | ||
| 765 | }), | ||
| 766 | ) | ||
| 767 | : Effect.fail(error), | ||
| 731 | ), | 768 | ), |
| 732 | ); | 769 | ); |
| 733 | 770 | ||
| @@ -39,7 +39,19 @@ export class OpenApiSpecOverrideError extends Schema.TaggedErrorClass<OpenApiSpe · 38 unmodified lines | |||
| 39 | export class OpenApiInvocationError extends Data.TaggedError("OpenApiInvocationError")<{ | 39 | export class OpenApiInvocationError extends Data.TaggedError("OpenApiInvocationError")<{ |
| 40 | readonly message: string; | 40 | readonly message: string; |
| 41 | readonly statusCode: Option.Option<number>; | 41 | readonly statusCode: Option.Option<number>; |
| 42 | readonly reason?: "response_headers_timeout" | "response_body_timeout" | "unknown_arguments"; | 42 | readonly reason?: |
| 43 | | "response_headers_timeout" | ||
| 44 | | "response_body_timeout" | ||
| 45 | | "unknown_arguments" | ||
| 46 | | "transport_error"; | ||
| 47 | // `host[:port]` of a request that failed at the transport layer. It is the | ||
| 48 | // integration's configured origin, so it is safe to show; the path, query, | ||
| 49 | // and headers stay on `cause`. | ||
| 50 | readonly upstreamHost?: string | undefined; | ||
| 51 | // Errno-style code behind a transport failure (`ECONNREFUSED`, `ENOTFOUND`, | ||
| 52 | // `UND_ERR_SOCKET`, …) when the runtime exposes one. Tells DNS from refused | ||
| 53 | // from TLS without exposing the request. | ||
| 54 | readonly transportCode?: string | undefined; | ||
| 43 | readonly cause?: unknown; | 55 | readonly cause?: unknown; |
| 44 | }> {} | 56 | }> {} |
| 45 | 57 | ||
| @@ -1,5 +1,10 @@ | |||
| 1 | import { Effect, Exit, Fiber, Layer, Option, Schema, Stream } from "effect"; | 1 | import { Effect, Exit, Fiber, Layer, Option, Predicate, Schema, Stream } from "effect"; |
| 2 | import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http"; | 2 | import { |
| 3 | HttpClient, | ||
| 4 | type HttpClientError, | ||
| 5 | HttpClientRequest, | ||
| 6 | HttpClientResponse, | ||
| 7 | } from "effect/unstable/http"; | ||
| 3 | import { isToolFile, type ToolFileValue } from "@executor-js/sdk/core"; | 8 | import { isToolFile, type ToolFileValue } from "@executor-js/sdk/core"; |
| 4 | 9 | ||
| 5 | import { OpenApiInvocationError } from "./errors"; | 10 | import { OpenApiInvocationError } from "./errors"; |
| @@ -1148,6 +1153,44 @@ export const buildRequest = Effect.fn("OpenApi.buildRequest")(function* ( · 1142 unmodified lines | |||
| 1148 | return request; | 1153 | return request; |
| 1149 | }); | 1154 | }); |
| 1150 | 1155 | ||
| 1156 | // --------------------------------------------------------------------------- | ||
| 1157 | // Transport failure classification | ||
| 1158 | // --------------------------------------------------------------------------- | ||
| 1159 | |||
| 1160 | const urlHost = Option.liftThrowable((url: string) => new URL(url).host); | ||
| 1161 | |||
| 1162 | // `fetch` rejects with a generic `TypeError("fetch failed")`; the errno-style | ||
| 1163 | // code (`ECONNREFUSED`, `ENOTFOUND`, `UND_ERR_SOCKET`, …) sits on the innermost | ||
| 1164 | // link of its `cause` chain. The walk is bounded so a cyclic cause cannot spin. | ||
| 1165 | const TransportCauseLink = Schema.Struct({ | ||
| 1166 | code: Schema.optional(Schema.String), | ||
| 1167 | cause: Schema.optional(Schema.Unknown), | ||
| 1168 | }); | ||
| 1169 | const decodeTransportCauseLink = Schema.decodeUnknownOption(TransportCauseLink); | ||
| 1170 | const TRANSPORT_CAUSE_MAX_DEPTH = 5; | ||
| 1171 | |||
| 1172 | const transportFailureCode = (cause: unknown, depth = 0): string | undefined => | ||
| 1173 | Option.match(decodeTransportCauseLink(cause), { | ||
| 1174 | onNone: () => undefined, | ||
| 1175 | onSome: (link) => | ||
| 1176 | (link.cause !== undefined && depth < TRANSPORT_CAUSE_MAX_DEPTH | ||
| 1177 | ? transportFailureCode(link.cause, depth + 1) | ||
| 1178 | : undefined) ?? link.code, | ||
| 1179 | }); | ||
| 1180 | |||
| 1181 | // A transport failure produced no response: DNS, connection refused, TLS, or a | ||
| 1182 | // socket dropped before headers. The TransportError carries the whole request | ||
| 1183 | // (URL, headers, credentials), so only the origin and the errno-style code are | ||
| 1184 | // lifted onto the invocation error. | ||
| 1185 | const transportFailureFields = (reason: HttpClientError.HttpClientError["reason"]) => | ||
| 1186 | Predicate.isTagged(reason, "TransportError") | ||
| 1187 | ? { | ||
| 1188 | reason: "transport_error" as const, | ||
| 1189 | upstreamHost: Option.getOrUndefined(urlHost(reason.request.url)), | ||
| 1190 | transportCode: transportFailureCode(reason.cause), | ||
| 1191 | } | ||
| 1192 | : {}; | ||
| 1193 | |||
| 1151 | // --------------------------------------------------------------------------- | 1194 | // --------------------------------------------------------------------------- |
| 1152 | // Public API — invoke a single operation | 1195 | // Public API — invoke a single operation |
| 1153 | // --------------------------------------------------------------------------- | 1196 | // --------------------------------------------------------------------------- |
| @@ -1183,6 +1226,7 @@ export const invoke = Effect.fn("OpenApi.invoke")(function* ( · 29 unmodified lines | |||
| 1183 | (err) => | 1226 | (err) => |
| 1184 | new OpenApiInvocationError({ | 1227 | new OpenApiInvocationError({ |
| 1185 | message: "HTTP request failed", | 1228 | message: "HTTP request failed", |
| 1229 | ...transportFailureFields(err.reason), | ||
| 1186 | statusCode: Option.none(), | 1230 | statusCode: Option.none(), |
| 1187 | cause: err, | 1231 | cause: err, |
| 1188 | }), | 1232 | }), |
| @@ -1197,7 +1241,6 @@ export const invoke = Effect.fn("OpenApi.invoke")(function* ( · 8 unmodified lines | |||
| 1197 | }), | 1241 | }), |
| 1198 | ), | 1242 | ), |
| 1199 | ); | 1243 | ); |
| 1200 | const fiber = runFork(responseEffect); | ||
| 1201 | const interrupt = () => { | 1244 | const interrupt = () => { |
| 1202 | runFork(Fiber.interrupt(fiber)); | 1245 | runFork(Fiber.interrupt(fiber)); |
| 1203 | }; | 1246 | }; |
| @@ -1207,6 +1250,7 @@ export const invoke = Effect.fn("OpenApi.invoke")(function* ( · 3 unmodified lines | |||
| 1207 | interrupt(); | 1250 | interrupt(); |
| 1208 | resume(Effect.succeed(Option.none())); | 1251 | resume(Effect.succeed(Option.none())); |
| 1209 | }, responseHeadersTimeoutMs); | 1252 | }, responseHeadersTimeoutMs); |
| 1253 | const fiber = runFork(responseEffect); | ||
| 1210 | signal.addEventListener("abort", interrupt, { once: true }); | 1254 | signal.addEventListener("abort", interrupt, { once: true }); |
| 1211 | return Effect.sync(() => { | 1255 | return Effect.sync(() => { |
| 1212 | clearTimeout(timer); | 1256 | clearTimeout(timer); |
| @@ -1257,7 +1301,6 @@ export const invoke = Effect.fn("OpenApi.invoke")(function* ( · 44 unmodified lines | |||
| 1257 | }), | 1301 | }), |
| 1258 | ), | 1302 | ), |
| 1259 | ); | 1303 | ); |
| 1260 | const fiber = runFork(bodyEffect); | ||
| 1261 | const interrupt = () => { | 1304 | const interrupt = () => { |
| 1262 | runFork(Fiber.interrupt(fiber)); | 1305 | runFork(Fiber.interrupt(fiber)); |
| 1263 | }; | 1306 | }; |
| @@ -1267,6 +1310,7 @@ export const invoke = Effect.fn("OpenApi.invoke")(function* ( · 3 unmodified lines | |||
| 1267 | interrupt(); | 1310 | interrupt(); |
| 1268 | resume(Effect.succeed(Option.none())); | 1311 | resume(Effect.succeed(Option.none())); |
| 1269 | }, responseBodyTimeoutMs); | 1312 | }, responseBodyTimeoutMs); |
| 1313 | const fiber = runFork(bodyEffect); | ||
| 1270 | signal.addEventListener("abort", interrupt, { once: true }); | 1314 | signal.addEventListener("abort", interrupt, { once: true }); |
| 1271 | return Effect.sync(() => { | 1315 | return Effect.sync(() => { |
| 1272 | clearTimeout(timer); | 1316 | clearTimeout(timer); |
| @@ -11,8 +11,14 @@ · 10 unmodified lines | |||
| 11 | // --------------------------------------------------------------------------- | 11 | // --------------------------------------------------------------------------- |
| 12 | 12 | ||
| 13 | import { describe, expect, it } from "@effect/vitest"; | 13 | import { describe, expect, it } from "@effect/vitest"; |
| 14 | import { Effect, Exit, Schema } from "effect"; | 14 | import { Cause, Data, Effect, Exit, Layer, Logger, References, Schema } from "effect"; |
| 15 | import { FetchHttpClient, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; | 15 | import { |
| 16 | FetchHttpClient, | ||
| 17 | HttpClient, | ||
| 18 | HttpClientError, | ||
| 19 | HttpServerRequest, | ||
| 20 | HttpServerResponse, | ||
| 21 | } from "effect/unstable/http"; | ||
| 16 | import { | 22 | import { |
| 17 | HttpApi, | 23 | HttpApi, |
| 18 | HttpApiBuilder, | 24 | HttpApiBuilder, |
| @@ -43,8 +49,10 @@ import { · 24 unmodified lines | |||
| 43 | 49 | ||
| 44 | import { openApiPlugin } from "./plugin"; | 50 | import { openApiPlugin } from "./plugin"; |
| 45 | 51 | ||
| 46 | const testPlugins = () => | 52 | class AdapterDefect extends Data.TaggedError("AdapterDefect") {} |
| 47 | [openApiPlugin({ httpClientLayer: FetchHttpClient.layer }), memoryCredentialsPlugin()] as const; | 53 | |
| 54 | const testPlugins = (httpClientLayer = FetchHttpClient.layer) => | ||
| 55 | [openApiPlugin({ httpClientLayer }), memoryCredentialsPlugin()] as const; | ||
| 48 | 56 | ||
| 49 | // `/things` GET op `listThings` under group "things" → tool path | 57 | // `/things` GET op `listThings` under group "things" → tool path |
| 50 | // `things.listThings`, used verbatim (dots and all) as the address tool segment. | 58 | // `things.listThings`, used verbatim (dots and all) as the address tool segment. |
| @@ -102,6 +110,30 @@ const startDroppingServer = () => · 51 unmodified lines | |||
| 102 | (s) => Effect.sync(() => s.close()), | 110 | (s) => Effect.sync(() => s.close()), |
| 103 | ); | 111 | ); |
| 104 | 112 | ||
| 113 | // Bind an ephemeral port, then release it so nothing listens there and the | ||
| 114 | // kernel refuses the connection (`ECONNREFUSED`). Port 1 is not equivalent: | ||
| 115 | // `fetch` rejects it as a bad port before dialing, with no errno. | ||
| 116 | const refusedBaseUrl = () => | ||
| 117 | Effect.callback<string>((resume) => { | ||
| 118 | const server = createServer(); | ||
| 119 | server.listen(0, "127.0.0.1", () => { | ||
| 120 | const port = (server.address() as AddressInfo).port; | ||
| 121 | server.close(() => resume(Effect.succeed(`http://127.0.0.1:${port}`))); | ||
| 122 | }); | ||
| 123 | }); | ||
| 124 | |||
| 125 | type CapturedLog = { readonly message: string; readonly annotations: Record<string, unknown> }; | ||
| 126 | |||
| 127 | const capturingLogger = (sink: Array<CapturedLog>) => | ||
| 128 | Logger.layer([ | ||
| 129 | Logger.make<unknown, void>((options) => { | ||
| 130 | sink.push({ | ||
| 131 | message: String(options.message), | ||
| 132 | annotations: options.fiber.getRef(References.CurrentLogAnnotations), | ||
| 133 | }); | ||
| 134 | }), | ||
| 135 | ]); | ||
| 136 | |||
| 105 | const ThingsGroup = HttpApiGroup.make("things").add( | 137 | const ThingsGroup = HttpApiGroup.make("things").add( |
| 106 | HttpApiEndpoint.get("listThings", "/things", { | 138 | HttpApiEndpoint.get("listThings", "/things", { |
| 107 | success: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), | 139 | success: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), |
| @@ -114,9 +146,11 @@ const FailureApi = HttpApi.make("failuresTest") · 6 unmodified lines | |||
| 114 | 146 | ||
| 115 | // Build an executor + connection from the FailureApi HttpApi against an | 147 | // Build an executor + connection from the FailureApi HttpApi against an |
| 116 | // arbitrary baseUrl (used for the Node-transport socket-drop / slow cases). | 148 | // arbitrary baseUrl (used for the Node-transport socket-drop / slow cases). |
| 117 | const buildExecutor = (baseUrl: string) => | 149 | const buildExecutor = (baseUrl: string, httpClientLayer = FetchHttpClient.layer) => |
| 118 | Effect.gen(function* () { | 150 | Effect.gen(function* () { |
| 119 | const executor = yield* createExecutor(makeTestConfig({ plugins: testPlugins() })); | 151 | const executor = yield* createExecutor( |
| 152 | makeTestConfig({ plugins: testPlugins(httpClientLayer) }), | ||
| 153 | ); | ||
| 120 | yield* executor.openapi.addSpec( | 154 | yield* executor.openapi.addSpec( |
| 121 | makeOpenApiHttpApiTestIntegrationConfig(FailureApi, { slug: "f", baseUrl }), | 155 | makeOpenApiHttpApiTestIntegrationConfig(FailureApi, { slug: "f", baseUrl }), |
| 122 | ); | 156 | ); |
| @@ -394,9 +428,12 @@ describe("OpenAPI upstream failure modes", () => { · 271 unmodified lines | |||
| 394 | const { baseUrl } = yield* startDroppingServer(); | 428 | const { baseUrl } = yield* startDroppingServer(); |
| 395 | const { executor, address } = yield* buildExecutor(baseUrl); | 429 | const { executor, address } = yield* buildExecutor(baseUrl); |
| 396 | 430 | ||
| 397 | const exit = yield* executor.execute(address, {}).pipe(Effect.exit); | 431 | const result = yield* executor.execute(address, {}); |
| 398 | 432 | ||
| 399 | expect(Exit.isFailure(exit)).toBe(true); | 433 | expect(result).toMatchObject({ |
| 434 | ok: false, | ||
| 435 | error: { code: "upstream_unreachable", details: { code: expect.any(String) } }, | ||
| 436 | }); | ||
| 400 | }), | 437 | }), |
| 401 | ); | 438 | ); |
| 402 | 439 | ||
| @@ -446,4 +483,126 @@ describe("OpenAPI upstream failure modes", () => { · 43 unmodified lines | |||
| 446 | expect(result.data).toEqual([]); | 483 | expect(result.data).toEqual([]); |
| 447 | }), | 484 | }), |
| 448 | ); | 485 | ); |
| 486 | |||
| 487 | it.effect("request encoding failures remain invocation failures", () => | ||
| 488 | Effect.gen(function* () { | ||
| 489 | const httpClientLayer = Layer.succeed( | ||
| 490 | HttpClient.HttpClient, | ||
| 491 | HttpClient.make((request) => | ||
| 492 | Effect.fail( | ||
| 493 | new HttpClientError.HttpClientError({ | ||
| 494 | reason: new HttpClientError.EncodeError({ request, cause: new AdapterDefect() }), | ||
| 495 | }), | ||
| 496 | ), | ||
| 497 | ), | ||
| 498 | ); | ||
| 499 | const { executor, address } = yield* buildExecutor( | ||
| 500 | "https://upstream.example", | ||
| 501 | httpClientLayer, | ||
| 502 | ); | ||
| 503 | const exit = yield* executor.execute(address, {}).pipe(Effect.exit); | ||
| 504 | expect(Exit.isFailure(exit)).toBe(true); | ||
| 505 | }), | ||
| 506 | ); | ||
| 507 | |||
| 508 | it.effect("transport defects remain defects", () => | ||
| 509 | Effect.gen(function* () { | ||
| 510 | const defect = new AdapterDefect(); | ||
| 511 | const httpClientLayer = Layer.succeed( | ||
| 512 | HttpClient.HttpClient, | ||
| 513 | HttpClient.make(() => Effect.die(defect)), | ||
| 514 | ); | ||
| 515 | const { executor, address } = yield* buildExecutor( | ||
| 516 | "https://upstream.example", | ||
| 517 | httpClientLayer, | ||
| 518 | ); | ||
| 519 | const exit = yield* executor.execute(address, {}).pipe(Effect.exit); | ||
| 520 | expect(Exit.isFailure(exit)).toBe(true); | ||
| 521 | expect(Exit.match(exit, { onFailure: Cause.hasDies, onSuccess: () => false })).toBe(true); | ||
| 522 | }), | ||
| 523 | ); | ||
| 524 | |||
| 525 | it.effect("interrupted transport remains interrupted", () => | ||
| 526 | Effect.gen(function* () { | ||
| 527 | const httpClientLayer = Layer.succeed( | ||
| 528 | HttpClient.HttpClient, | ||
| 529 | HttpClient.make(() => Effect.interrupt), | ||
| 530 | ); | ||
| 531 | const { executor, address } = yield* buildExecutor( | ||
| 532 | "https://upstream.example", | ||
| 533 | httpClientLayer, | ||
| 534 | ); | ||
| 535 | const exit = yield* executor.execute(address, {}).pipe(Effect.exit); | ||
| 536 | expect(Exit.isFailure(exit)).toBe(true); | ||
| 537 | expect(Exit.match(exit, { onFailure: Cause.hasInterrupts, onSuccess: () => false })).toBe( | ||
| 538 | true, | ||
| 539 | ); | ||
| 540 | }), | ||
| 541 | ); | ||
| 542 | |||
| 543 | // Port 1 refuses immediately. The same path used to throw `Internal tool | ||
| 544 | // error [hex]` because the raw HttpClientError carries the request URL. | ||
| 545 | // Executor makes the request, so the message names the integration and | ||
| 546 | // origin the user can fix instead of blaming their own network. | ||
| 547 | it.effect("connection refused names the integration and origin without the path", () => | ||
| 548 | Effect.gen(function* () { | ||
| 549 | const { executor, address } = yield* buildExecutor("http://127.0.0.1:1"); | ||
| 550 | |||
| 551 | const result = yield* executor.execute(address, {}); | ||
| 552 | |||
| 553 | expect(result).toMatchObject({ | ||
| 554 | ok: false, | ||
| 555 | error: { | ||
| 556 | code: "upstream_unreachable", | ||
| 557 | message: expect.stringContaining( | ||
| 558 | 'Could not reach the upstream server for "f" at 127.0.0.1:1.', | ||
| 559 | ), | ||
| 560 | }, | ||
| 561 | }); | ||
| 562 | const failure = result as { | ||
| 563 | readonly ok: false; | ||
| 564 | readonly error: { readonly message: string; readonly details?: unknown }; | ||
| 565 | }; | ||
| 566 | // No errno here (`fetch` rejects port 1 before dialing). The result | ||
| 567 | // crosses a JSON boundary, so the missing code must be absent rather | ||
| 568 | // than an `undefined` property. | ||
| 569 | expect(failure.error.details).toStrictEqual({ host: "127.0.0.1:1" }); | ||
| 570 | expect(failure.error.message).toContain("base URL"); | ||
| 571 | expect(failure.error.message).not.toContain("your network"); | ||
| 572 | expect(failure.error.message).not.toContain("Internal tool error"); | ||
| 573 | expect(failure.error.message).not.toContain("/things"); | ||
| 574 | }), | ||
| 575 | ); | ||
| 576 | |||
| 577 | // Classifying the failure took it off the hosts' correlation-id defect log, | ||
| 578 | // so the sanitized cause must reach both the caller (details) and operators | ||
| 579 | // (log) — and never the request, which carries the resolved auth header. | ||
| 580 | it.effect("connection refused reports the errno code to the caller and the log", () => | ||
| 581 | Effect.gen(function* () { | ||
| 582 | const baseUrl = yield* refusedBaseUrl(); | ||
| 583 | const { executor, address } = yield* buildExecutor(baseUrl); | ||
| 584 | const logged: Array<CapturedLog> = []; | ||
| 585 | |||
| 586 | const result = yield* executor | ||
| 587 | .execute(address, {}) | ||
| 588 | .pipe(Effect.provide(capturingLogger(logged))); | ||
| 589 | |||
| 590 | const host = new URL(baseUrl).host; | ||
| 591 | expect(result).toMatchObject({ | ||
| 592 | ok: false, | ||
| 593 | error: { code: "upstream_unreachable", details: { host, code: "ECONNREFUSED" } }, | ||
| 594 | }); | ||
| 595 | const rendered = JSON.stringify(result); | ||
| 596 | expect(rendered).not.toContain("/things"); | ||
| 597 | // The apiKey value `buildExecutor` puts on the connection. | ||
| 598 | expect(rendered).not.toContain("token"); | ||
| 599 | |||
| 600 | const warning = logged.find((entry) => entry.message.includes("upstream unreachable")); | ||
| 601 | expect(warning?.annotations).toMatchObject({ | ||
| 602 | "plugin.openapi.integration": "f", | ||
| 603 | "plugin.openapi.upstream.host": host, | ||
| 604 | "plugin.openapi.upstream.transport_code": "ECONNREFUSED", | ||
| 605 | }); | ||
| 606 | }), | ||
| 607 | ); | ||
| 449 | }); | 608 | }); |