Skip to content
This repository was archived by the owner on Oct 23, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 39 additions & 4 deletions src/lib/init/init-service-auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { MastraClientError } from "@mastra/client-js";
import { enrich401Detail } from "../api/infrastructure.js";
import { ApiError, HostScopeError } from "../errors.js";
import { isSaaSTrustOrigin, normalizeOrigin } from "../sentry-urls.js";
Expand All @@ -15,6 +16,10 @@ export const WORKFLOW_CREATE_RUN_ENDPOINT = `${WORKFLOW_ENDPOINT}/create-run`;
export const WORKFLOW_RESUME_ASYNC_ENDPOINT = `${WORKFLOW_ENDPOINT}/resume-async`;
export const WORKFLOW_START_ASYNC_ENDPOINT = `${WORKFLOW_ENDPOINT}/start-async`;
const MASTRA_HTTP_401_RE = /HTTP error!\s*status:\s*401\b/i;
const RETRYABLE_AUTH_FAILURE_CODES = new Set([
"AUTH_UPSTREAM_TIMEOUT",
"AUTH_UPSTREAM_UNAVAILABLE",
]);

function classifyInitServiceAuthFailure(
err: unknown,
Expand All @@ -32,14 +37,44 @@ function classifyInitServiceAuthFailure(
);
}

function isRetryableInitServiceAuthFailure(err: unknown): boolean {
if (
!(err instanceof MastraClientError) ||
err.status !== 503 ||
typeof err.body !== "object" ||
err.body === null
) {
return false;
}

const body = err.body as Record<string, unknown>;
return (
body.safeToRetry === true &&
typeof body.code === "string" &&
RETRYABLE_AUTH_FAILURE_CODES.has(body.code)
);
}

export async function withInitServiceAuthClassification<T>(
operation: () => Promise<T>,
endpoint: string
): Promise<T> {
try {
return await operation();
} catch (err) {
throw classifyInitServiceAuthFailure(err, endpoint) ?? err;
let retried = false;

while (true) {
try {
return await operation();
} catch (err) {
const classified = classifyInitServiceAuthFailure(err, endpoint);
if (classified) {
throw classified;
}
if (!retried && isRetryableInitServiceAuthFailure(err)) {
retried = true;
continue;
}
throw err;
}
}
}

Expand Down
83 changes: 83 additions & 0 deletions test/lib/init/init-service-auth.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { MastraClientError } from "@mastra/client-js";
import { describe, expect, test, vi } from "vitest";
import { ApiError } from "../../../src/lib/errors.js";
import { withInitServiceAuthClassification } from "../../../src/lib/init/init-service-auth.js";

const ENDPOINT = "/api/workflows/sentry-wizard/resume-async";

function authFailure(
code: string,
safeToRetry = true,
status = 503
): MastraClientError {
return new MastraClientError(status, "Service Unavailable", "auth failed", {
code,
safeToRetry,
});
}

describe("withInitServiceAuthClassification", () => {
test.each([
"AUTH_UPSTREAM_TIMEOUT",
"AUTH_UPSTREAM_UNAVAILABLE",
])("retries %s once", async (code) => {
const failure = authFailure(code);
const operation = vi
.fn<() => Promise<string>>()
.mockRejectedValueOnce(failure)
.mockResolvedValueOnce("ok");

await expect(
withInitServiceAuthClassification(operation, ENDPOINT)
).resolves.toBe("ok");
expect(operation).toHaveBeenCalledTimes(2);
});

test("stops after one retry when the auth service remains unavailable", async () => {
const failure = authFailure("AUTH_UPSTREAM_TIMEOUT");
const operation = vi.fn<() => Promise<never>>().mockRejectedValue(failure);

await expect(
withInitServiceAuthClassification(operation, ENDPOINT)
).rejects.toBe(failure);
expect(operation).toHaveBeenCalledTimes(2);
});

test("classifies a 401 returned by the second attempt", async () => {
const operation = vi
.fn<() => Promise<never>>()
.mockRejectedValueOnce(authFailure("AUTH_UPSTREAM_TIMEOUT"))
.mockRejectedValueOnce(
new Error(
'HTTP error! status: 401 - {"error":"Unauthorized: invalid token"}'
)
);

const error = await withInitServiceAuthClassification(
operation,
ENDPOINT
).catch((caught) => caught);

expect(error).toBeInstanceOf(ApiError);
expect(error).toMatchObject({ status: 401, endpoint: ENDPOINT });
expect(operation).toHaveBeenCalledTimes(2);
});

test.each([
authFailure("AUTH_UPSTREAM_RATE_LIMITED", false),
authFailure("UNKNOWN_CODE"),
authFailure("AUTH_UPSTREAM_TIMEOUT", true, 502),
new TypeError("fetch failed"),
Object.assign(new Error("auth failed"), {
status: 503,
body: { code: "AUTH_UPSTREAM_TIMEOUT", safeToRetry: true },
}),
])("does not retry an unauthorized failure contract", async (failure) => {
const operation = vi.fn<() => Promise<never>>().mockRejectedValue(failure);

await expect(
withInitServiceAuthClassification(operation, ENDPOINT)
).rejects.toBe(failure);
expect(operation).toHaveBeenCalledTimes(1);
});
});
Loading