Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(errors): enhance client disconnection handling and error classification

Victor Hugo dos Santos1678a83ee509
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index da8c0f6107..e673786918 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -850,9 +850,21 @@ Custom error classes in `src/lib/errors/index.ts`:
- `InternalServerError` (500)
- `RateLimitError`
- `ScimRequestError` — SCIM-specific formatting with schemas and status
+- `ClientClosedRequestError` (499, nginx convention) — the client disconnected before the response was written; see below
Global error handler in `src/server/plugins/error-handler.ts` maps these to HTTP status codes and records OpenTelemetry error metrics.
+#### Stopping work after a client disconnect
+
+Node keeps running a handler after its client has gone, and a disconnected client usually retries, so a CPU-heavy request that outlives its caller does the full cost again on another pod. Routes whose work can run long after the database reads finish (fan-out over folders, references, or imports) should stop when the connection closes. `GET /api/v3/secrets/raw` and `GET /api/v4/secrets` are examples.
+
+- **Route:** pass `abortSignal: getClientDisconnectSignal(reply)` (`src/server/lib/client-disconnect.ts`) into the service. It aborts only when the socket closes before the response was written, so a normal completion never trips it.
+- **Service:** call `throwIfClientDisconnected(abortSignal)` at fan-out points only: before each unit of work that triggers more reads (each reference, each import level, a shared folder load). Don't add one after every `await`; a check that saves a single query for a client that has already left is noise. Checks are cooperative, so an in-flight query or synchronous block still finishes, and a long synchronous block delays noticing the disconnect. Keep the per-item work linear.
+- **`Promise.allSettled` fan-outs:** they swallow the rejection, so scan the results with `throwIfAnySettledClientClosed(results)` instead of rechecking the signal. A disconnect mid-fan-out means the result is partial and must not be cached or returned as reference errors; a result that completed before the client left should still be cached so the retry is a hit.
+- **Catch blocks** that turn failures into an empty result (a folder that failed to load, a skipped cross-project read) must rethrow `ClientClosedRequestError` first, or the partial state gets cached.
+
+The 499 never reaches the caller. It exists for logs (warn, no stack) and the `error.type="client_closed"` label on `infisical.core.http.error.count`. This is disconnect handling, not a request deadline: a slow client that stays connected is still bounded only by Fastify's 100s socket `connectionTimeout` in `src/server/app.ts`.
+
### Logging
Uses Pino via `@app/lib/logger`. Always include key identifiers in the message string using `[key=value]` format for log searchability. You may also pass a structured object as the first argument for programmatic access, but the message must be self-contained:
diff --git a/backend/src/lib/errors/classify.test.ts b/backend/src/lib/errors/classify.test.ts
index ea2a7d062c..8725335056 100644
--- a/backend/src/lib/errors/classify.test.ts
+++ b/backend/src/lib/errors/classify.test.ts
@@ -2,7 +2,14 @@ import { createMongoAbility, ForbiddenError } from "@casl/ability";
import { AxiosError } from "axios";
import { classifyError } from "./classify";
-import { BadRequestError, ForbiddenRequestError, NotFoundError, RateLimitError, UnauthorizedError } from "./index";
+import {
+ BadRequestError,
+ ClientClosedRequestError,
+ ForbiddenRequestError,
+ NotFoundError,
+ RateLimitError,
+ UnauthorizedError
+} from "./index";
describe("classifyError", () => {
test("maps known Infisical error classes to bounded labels", () => {
@@ -11,6 +18,7 @@ describe("classifyError", () => {
expect(classifyError(new RateLimitError({ message: "x" }))).toBe("rate_limit");
expect(classifyError(new NotFoundError({ message: "x" }))).toBe("not_found");
expect(classifyError(new BadRequestError({ message: "x" }))).toBe("validation");
+ expect(classifyError(new ClientClosedRequestError())).toBe("client_closed");
});
test("maps CASL ForbiddenError (thrown by permission checks) to permission, not unknown", () => {
diff --git a/backend/src/lib/errors/classify.ts b/backend/src/lib/errors/classify.ts
index 90bb639214..c9dfd02f9b 100644
--- a/backend/src/lib/errors/classify.ts
+++ b/backend/src/lib/errors/classify.ts
@@ -33,6 +33,7 @@ export const ERROR_TYPES = [
"db",
"timeout",
"network",
+ "client_closed",
"cryptography",
"policy",
"scim",
@@ -78,7 +79,7 @@ export const classifyError = (err: unknown): ErrorType => {
if (err instanceof ScimRequestError) return "scim";
if (err instanceof OidcAuthError) return "oidc";
if (err instanceof InternalServerError) return "internal";
- if (err instanceof ClientClosedRequestError) return "network";
+ if (err instanceof ClientClosedRequestError) return "client_closed";
if (isAwsError(err, "ThrottlingException")) return "rate_limit";
diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdx
index dae7607f3c..8f8f38911c 100644
--- a/docs/self-hosting/guides/monitoring-telemetry.mdx
+++ b/docs/self-hosting/guides/monitoring-telemetry.mdx
@@ -778,7 +778,7 @@ These metrics give per-queue visibility into BullMQ worker health: throughput, l
**Attributes**:
- `queue.name`, `job.name`
- - `error.type` (string): one of `validation`, `auth`, `permission`, `not_found`, `rate_limit`, `db`, `timeout`, `network`, `cryptography`, `policy`, `scim`, `oidc`, `internal`, `unknown`
+ - `error.type` (string): one of `validation`, `auth`, `permission`, `not_found`, `rate_limit`, `db`, `timeout`, `network`, `client_closed`, `cryptography`, `policy`, `scim`, `oidc`, `internal`, `unknown`
- `attempts.exhausted` (string): `"true"` or `"false"`
</Accordion>