Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): map registry network/5xx failures to a clean RegistryUnavailableError

Jose Ramirezac1652868109
diff --git a/control-api/src/services/registryClient.ts b/control-api/src/services/registryClient.ts
index 2e74f5ea2..64b4b80c9 100644
--- a/control-api/src/services/registryClient.ts
+++ b/control-api/src/services/registryClient.ts
@@ -250,28 +250,58 @@ async function authedFetch(
return attempt(isGet)
}
+/**
+ * Registry origin/gateway is unreachable (network refusal, timeout, or an
+ * upstream HTTP 5xx). A clean, user-safe error the global handler forwards as a
+ * 503 so the marketplace shows a clear message instead of a raw 500.
+ */
+export class RegistryUnavailableError extends Error {
+ readonly status = 503
+ readonly code = 'registry_unavailable'
+ constructor(message = 'The registry is currently unavailable. Check the connection and try again.') {
+ super(message)
+ this.name = 'RegistryUnavailableError'
+ }
+}
+
async function registryFetch<T>(path: string, init?: RequestInit): Promise<T> {
- const res = await authedFetch(path, init)
+ let res: Response
+ try {
+ res = await authedFetch(path, init)
+ } catch (err) {
+ // Remap ONLY genuine network/timeout signals to a clean "unavailable":
+ // undici's "fetch failed" (ECONNREFUSED / DNS) surfaces as a TypeError, and
+ // an Abort/Timeout that survives the single GET retry surfaces via
+ // isTransientFetchError. Everything else is rethrown unchanged — critically,
+ // mintToken's status-less "registry credential rejected" (a wrong-secret
+ // misconfig) must keep its own signal rather than be mislabeled "unavailable".
+ if (err instanceof TypeError || isTransientFetchError(err)) {
+ throw new RegistryUnavailableError()
+ }
+ throw err
+ }
if (!res.ok) {
const body = await res.text()
// A persistent 401 (authedFetch already evict-retried once) is a registry
// machine-token / integration fault — NOT the admin's control-ui session.
- // Remap to 502 so control-ui's global 401 handler doesn't force-logout the
- // admin when the registry rejects control-api (e.g. auth off, or a
- // half-configured/failing connection). Mirrors orgRegistryFetch, which
- // already does this. Every other status is forwarded verbatim so a
- // registry 404 stays a 404 (see the e2e-registry-publish-update-remove
- // failure class below).
+ // Remap to 502 (so control-ui's global 401 handler never force-logs-out the
+ // admin) and carry a machine code + a user-safe message.
if (res.status === 401) {
- throw Object.assign(new Error('Registry 401: registry_integration_error'), {
+ throw Object.assign(new Error('The registry could not be reached.'), {
status: 502,
+ code: 'registry_integration_error',
})
}
- // Attach the upstream status so the global error handler (app.ts) can
- // forward 4xx responses to the API client. Without `.status`, a registry
- // 404 surfaces as a 500 Internal Server Error from control-api — the
- // exact failure class scripts/e2e/e2e-registry-publish-update-remove.sh
- // is designed to catch.
+ // Registry origin/gateway down — an HTTP 5xx (500/502/503/504 and Cloudflare
+ // 520–524) is the dominant real-world "registry unavailable" signal (edge up,
+ // origin down). Map to a clean 503. Retriable GET statuses already retried
+ // once via RETRIABLE_GET_STATUSES in authedFetch before landing here.
+ if (res.status >= 500) {
+ throw new RegistryUnavailableError()
+ }
+ // Attach the upstream status so the global error handler (app.ts) forwards
+ // 4xx verbatim to the API client (a registry 404 stays a 404 — the
+ // e2e-registry-publish-update-remove failure class).
throw Object.assign(new Error(`Registry ${res.status}: ${body}`), {
status: res.status,
})
diff --git a/control-api/test/registryClient.test.ts b/control-api/test/registryClient.test.ts
index bbb670213..86b5b1b1f 100644
--- a/control-api/test/registryClient.test.ts
+++ b/control-api/test/registryClient.test.ts
@@ -296,7 +296,7 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
expect(entryAttempts).toBe(2)
})
- it('only retries ONCE — a second transient surfaces as an error', async () => {
+ it('only retries ONCE — a second transient surfaces as registry_unavailable', async () => {
const fetchMock = entriesQueue([
() => new Response('gw', { status: 503 }),
() => new Response('gw', { status: 503 }),
@@ -304,7 +304,12 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
vi.stubGlobal('fetch', fetchMock)
Object.assign(process.env, ENV_OVERRIDE)
- await expect(searchEntries({ q: 'thing' })).rejects.toThrow(/Registry 503/)
+ const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
+ expect(err.status).toBe(503)
+ expect(err.code).toBe('registry_unavailable')
const entryCalls = fetchMock.mock.calls.filter(
(c: unknown[]) => typeof c[0] === 'string' && (c[0] as string).includes('/entries')
@@ -323,11 +328,14 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
vi.stubGlobal('fetch', fetchMock)
Object.assign(process.env, ENV_OVERRIDE)
- const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & { status?: number }
+ const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
// Load-bearing: status MUST be 502, NOT 401.
expect(err.status).toBe(502)
expect(err.status).not.toBe(401)
- expect(err.message).toMatch(/registry_integration_error/)
+ expect(err.code).toBe('registry_integration_error')
})
it('still forwards a registry 404 verbatim (not remapped)', async () => {
@@ -342,7 +350,7 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
expect(err.message).toMatch(/Registry 404/)
})
- it('does NOT retry a non-GET (POST publish) on 503', async () => {
+ it('does NOT retry a non-GET (POST publish) on 503, and surfaces registry_unavailable', async () => {
const fetchMock = vi.fn().mockImplementation((url: string) => {
if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))
return Promise.resolve(new Response('gw', { status: 503 }))
@@ -350,9 +358,12 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
vi.stubGlobal('fetch', fetchMock)
Object.assign(process.env, ENV_OVERRIDE)
- await expect(publishEntry({ name: '@clerum/x', version: '0.0.1' })).rejects.toThrow(
- /Registry 503/
- )
+ const err = (await publishEntry({ name: '@clerum/x', version: '0.0.1' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
+ expect(err.status).toBe(503)
+ expect(err.code).toBe('registry_unavailable')
const publishCalls = fetchMock.mock.calls.filter(
(c: unknown[]) =>
@@ -364,6 +375,68 @@ describe('registryClient — GET retry-once (transient resilience)', () => {
})
})
+describe('registryClient — registry-unavailable remap (Fix 2)', () => {
+ it('remaps a TypeError ("fetch failed" = ECONNREFUSED / DNS) to 503 registry_unavailable', async () => {
+ // A TypeError is NOT transient (isTransientFetchError is false for it), so
+ // authedFetch does not retry it — it rethrows, and registryFetch remaps it.
+ const fetchMock = vi.fn().mockImplementation((url: string) => {
+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))
+ return Promise.reject(new TypeError('fetch failed'))
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ Object.assign(process.env, ENV_OVERRIDE)
+
+ const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
+ expect(err.status).toBe(503)
+ expect(err.code).toBe('registry_unavailable')
+ })
+
+ it('remaps an upstream HTTP 5xx (origin/gateway down) to 503 registry_unavailable', async () => {
+ // The dominant real-world path: the edge is reachable but the origin returns
+ // a 5xx. A GET retries once (RETRIABLE_GET_STATUSES) then maps to unavailable.
+ const fetchMock = vi.fn().mockImplementation((url: string) => {
+ if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))
+ return Promise.resolve(new Response('origin down', { status: 503 }))
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ Object.assign(process.env, ENV_OVERRIDE)
+
+ const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
+ expect(err.status).toBe(503)
+ expect(err.code).toBe('registry_unavailable')
+ })
+
+ it('does NOT relabel a status-less credential-rejected error as registry_unavailable', async () => {
+ // mintToken throws "registry credential rejected: 401 …" (a wrong-secret
+ // misconfig) — a status-less, non-network Error. It must surface unchanged,
+ // NOT collapsed into the "unavailable" message.
+ const fetchMock = vi.fn().mockImplementation((url: string) => {
+ if (url.endsWith('/oauth/token')) return Promise.resolve(new Response('bad creds', { status: 401 }))
+ return Promise.resolve(
+ new Response(JSON.stringify({ data: [], meta: { total: 0, limit: 0, offset: 0 } }), {
+ status: 200,
+ })
+ )
+ })
+ vi.stubGlobal('fetch', fetchMock)
+ Object.assign(process.env, ENV_OVERRIDE)
+
+ const err = (await searchEntries({ q: 'thing' }).catch(e => e)) as Error & {
+ status?: number
+ code?: string
+ }
+ expect(err.message).toMatch(/registry credential rejected: 401/)
+ expect(err.code).not.toBe('registry_unavailable')
+ expect(err.status).toBeUndefined()
+ })
+})
+
describe('registryClient — resolvePublishScope', () => {
// whoami() mints a token first (POST /oauth/token) and then GETs /api/v1/whoami,
// so the fetch mock must answer BOTH calls. Branch on URL like the other tests.
@@ -482,7 +555,7 @@ describe('registryClient — stale-while-error cache', () => {
expect(second).toEqual({ data: ['ai', 'devtools'] })
})
- it('throws when the registry errors and there is NO cached value', async () => {
+ it('throws registry_unavailable when the registry errors and there is NO cached value', async () => {
const fetchMock = vi.fn().mockImplementation((url: string) => {
if (url.endsWith('/oauth/token')) return Promise.resolve(fakeTokenResponse('tok', 600))
return Promise.resolve(new Response('down', { status: 503 }))
@@ -490,7 +563,9 @@ describe('registryClient — stale-while-error cache', () => {
vi.stubGlobal('fetch', fetchMock)
Object.assign(process.env, ENV_OVERRIDE)
- await expect(getCategories()).rejects.toThrow(/Registry 503/)
+ const err = (await getCategories().catch(e => e)) as Error & { status?: number; code?: string }
+ expect(err.status).toBe(503)
+ expect(err.code).toBe('registry_unavailable')
})
it('serves last-good default catalog search (limit:200) on error', async () => {