Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(trpc): surface upstream storage failures as 502/504 instead of 500 (#20260)

Arvin Xu81c1e378e309
diff --git a/packages/trpc/src/lambda/index.ts b/packages/trpc/src/lambda/index.ts
index 4ecb07afea1..62030326caf 100644
--- a/packages/trpc/src/lambda/index.ts
+++ b/packages/trpc/src/lambda/index.ts
@@ -9,6 +9,7 @@
*/
import { openTelemetry } from '../middleware/openTelemetry';
+import { upstreamError } from '../middleware/upstreamError';
import { userAuth } from '../middleware/userAuth';
import { trpc } from './init';
import { apiKeyScopeGuard } from './middleware/apiKeyScope';
@@ -25,7 +26,7 @@ export const router = trpc.router;
* Create an unprotected procedure
* @link https://trpc.io/docs/v11/procedures
**/
-const baseProcedure = trpc.procedure.use(openTelemetry);
+const baseProcedure = trpc.procedure.use(openTelemetry).use(upstreamError);
// `apiKeyScopeGuard` also covers public procedures: `createLambdaContext`
// authenticates an `X-API-Key` before procedure selection, and several public
diff --git a/packages/trpc/src/middleware/upstreamError.test.ts b/packages/trpc/src/middleware/upstreamError.test.ts
new file mode 100644
index 00000000000..a164edbf81e
--- /dev/null
+++ b/packages/trpc/src/middleware/upstreamError.test.ts
@@ -0,0 +1,110 @@
+import { TRPCError } from '@trpc/server';
+import { describe, expect, it } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { createContextInner } from '@/libs/trpc/lambda/context';
+
+import { trpc } from '../lambda/init';
+import { toUpstreamTRPCError, upstreamError } from './upstreamError';
+
+const sdkError = (props: Record<string, unknown>, metadata: Record<string, unknown> = {}) =>
+ Object.assign(new Error(String(props.name ?? 'UnknownError')), props, {
+ $metadata: { attempts: 3, totalRetryDelay: 195, ...metadata },
+ });
+
+const createRouter = (thrown: unknown) => {
+ const appRouter = trpc.router({
+ run: trpc.procedure.use(upstreamError).mutation(() => {
+ throw thrown;
+ }),
+ });
+
+ return createCallerFactory(appRouter);
+};
+
+const callWith = async (thrown: unknown) => {
+ const caller = createRouter(thrown)(await createContextInner());
+ return caller.run().catch((error: TRPCError) => error);
+};
+
+describe('upstreamError middleware', () => {
+ it('maps an upstream 5xx (R2 HeadObject 500) to BAD_GATEWAY', async () => {
+ const cause = sdkError({ $fault: 'server', name: 'UnknownError' }, { httpStatusCode: 500 });
+
+ const error = await callWith(cause);
+
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error.code).toBe('BAD_GATEWAY');
+ expect(error.message).toBe('Upstream service error (HTTP 500): UnknownError');
+ expect(error.cause).toBe(cause);
+ });
+
+ it('maps an upstream 503 to BAD_GATEWAY', async () => {
+ const error = await callWith(
+ sdkError({ $fault: 'server', name: 'ServiceUnavailable' }, { httpStatusCode: 503 }),
+ );
+
+ expect(error.code).toBe('BAD_GATEWAY');
+ });
+
+ it('maps an SDK timeout to GATEWAY_TIMEOUT', async () => {
+ const error = await callWith(sdkError({ code: 'ETIMEDOUT', name: 'TimeoutError' }));
+
+ expect(error.code).toBe('GATEWAY_TIMEOUT');
+ expect(error.message).toBe('Upstream service error: TimeoutError');
+ });
+
+ it('maps a socket failure to BAD_GATEWAY', async () => {
+ const error = await callWith(sdkError({ code: 'ECONNRESET', name: 'Error' }));
+
+ expect(error.code).toBe('BAD_GATEWAY');
+ });
+
+ it('finds the SDK error deeper in the cause chain', async () => {
+ const root = sdkError({ $fault: 'server', name: 'InternalError' }, { httpStatusCode: 500 });
+ const wrapped = new Error('reserve failed', { cause: root });
+
+ const error = await callWith(wrapped);
+
+ expect(error.code).toBe('BAD_GATEWAY');
+ expect(error.cause).toBe(root);
+ });
+
+ it('keeps upstream 4xx as INTERNAL_SERVER_ERROR (misconfiguration is our bug)', async () => {
+ const error = await callWith(
+ sdkError({ $fault: 'client', name: 'AccessDenied' }, { httpStatusCode: 403 }),
+ );
+
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ });
+
+ it('keeps SDK errors without a response or network code as INTERNAL_SERVER_ERROR', async () => {
+ const error = await callWith(sdkError({ name: 'CredentialsProviderError' }));
+
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ });
+
+ it('leaves plain errors untouched', async () => {
+ const error = await callWith(new Error('boom'));
+
+ expect(error.code).toBe('INTERNAL_SERVER_ERROR');
+ expect(error.message).toBe('boom');
+ });
+
+ it('does not override codes routers chose deliberately', async () => {
+ const error = await callWith(
+ new TRPCError({
+ cause: sdkError({ $fault: 'server' }, { httpStatusCode: 500 }),
+ code: 'CONFLICT',
+ }),
+ );
+
+ expect(error.code).toBe('CONFLICT');
+ });
+});
+
+describe('toUpstreamTRPCError', () => {
+ it('returns undefined when there is no cause', () => {
+ expect(toUpstreamTRPCError(new TRPCError({ code: 'INTERNAL_SERVER_ERROR' }))).toBeUndefined();
+ });
+});
diff --git a/packages/trpc/src/middleware/upstreamError.ts b/packages/trpc/src/middleware/upstreamError.ts
new file mode 100644
index 00000000000..b521e6d1453
--- /dev/null
+++ b/packages/trpc/src/middleware/upstreamError.ts
@@ -0,0 +1,92 @@
+import { TRPCError } from '@trpc/server';
+
+import { trpc } from '../lambda/init';
+
+type UpstreamErrorCode = 'BAD_GATEWAY' | 'GATEWAY_TIMEOUT';
+
+interface SdkErrorLike {
+ $fault?: string;
+ $metadata?: { attempts?: number; httpStatusCode?: number };
+ code?: string;
+ name?: string;
+}
+
+// Socket-level failures: the request never got an HTTP response from upstream.
+const NETWORK_ERROR_CODES = new Set([
+ 'EAI_AGAIN',
+ 'ECONNREFUSED',
+ 'ECONNRESET',
+ 'ENOTFOUND',
+ 'EPIPE',
+]);
+
+const MAX_CAUSE_DEPTH = 5;
+
+/**
+ * AWS SDK v3 errors (S3 / R2, ...) all carry `$metadata` once they leave the
+ * retry middleware, whether they are service errors or network failures.
+ */
+const isSdkError = (error: unknown): error is SdkErrorLike =>
+ !!error &&
+ typeof error === 'object' &&
+ '$metadata' in error &&
+ !!(error as SdkErrorLike).$metadata &&
+ typeof (error as SdkErrorLike).$metadata === 'object';
+
+const classifySdkError = (error: SdkErrorLike): UpstreamErrorCode | undefined => {
+ const status = error.$metadata?.httpStatusCode;
+
+ if (typeof status === 'number') return status >= 500 ? 'BAD_GATEWAY' : undefined;
+ if (error.$fault === 'server') return 'BAD_GATEWAY';
+
+ if (error.name === 'TimeoutError' || error.code === 'ETIMEDOUT') return 'GATEWAY_TIMEOUT';
+ if (error.code && NETWORK_ERROR_CODES.has(error.code)) return 'BAD_GATEWAY';
+
+ // Anything else without a response (credentials, serialization, ...) is ours.
+ return undefined;
+};
+
+/**
+ * Map an error raised by an upstream dependency to the HTTP semantics it deserves:
+ * upstream returned 5xx / connection failed β†’ 502, upstream timed out β†’ 504.
+ * Returns `undefined` for anything that is not clearly an upstream failure, so
+ * our own bugs keep surfacing as 500.
+ */
+export const toUpstreamTRPCError = (error: TRPCError): TRPCError | undefined => {
+ // Respect codes routers chose deliberately; only reclassify the generic 500.
+ if (error.code !== 'INTERNAL_SERVER_ERROR') return;
+
+ let current: unknown = error.cause;
+ for (let depth = 0; current && depth < MAX_CAUSE_DEPTH; depth++) {
+ if (isSdkError(current)) {
+ const code = classifySdkError(current);
+ if (!code) return;
+
+ const status = current.$metadata?.httpStatusCode;
+ const reason = current.name || current.code || 'UnknownError';
+
+ return new TRPCError({
+ cause: current as Error,
+ code,
+ message: `Upstream service error${status ? ` (HTTP ${status})` : ''}: ${reason}`,
+ });
+ }
+
+ current = (current as { cause?: unknown }).cause;
+ }
+};
+
+/**
+ * Reclassify upstream failures that bubbled up as INTERNAL_SERVER_ERROR, so an
+ * R2 / S3 outage shows up as 502/504 instead of being indistinguishable from
+ * our own 500s in monitoring and on the client.
+ */
+export const upstreamError = trpc.middleware(async ({ next }) => {
+ const result = await next();
+ if (result.ok) return result;
+
+ const mapped = toUpstreamTRPCError(result.error);
+ if (mapped) throw mapped;
+
+ return result;
+});