From 379bcb03251e1d71bad1f7dbd156df2ea5b185ab Mon Sep 17 00:00:00 2001 From: Casey Vega Date: Thu, 3 Dec 2026 01:03:54 -0800 Subject: [PATCH 1/5] fix(github): quieter, cheaper GitHub profiling probes Refs: gh-migrate-dashboard-0rtz --- .../adapters/namespace-discovery.test.ts | 14 +- .../adapters/namespace-discovery.ts | 40 ++++-- src/lib/server/core/github-profile-probes.ts | 105 ++++++++++++++ .../server/core/github-profile-retry.test.ts | 130 +++++++++++++++++- src/lib/server/core/github.ts | 15 +- 5 files changed, 290 insertions(+), 14 deletions(-) create mode 100644 src/lib/server/core/github-profile-probes.ts diff --git a/src/lib/server/application/adapters/namespace-discovery.test.ts b/src/lib/server/application/adapters/namespace-discovery.test.ts index 3aa48878..9d0b06a4 100644 --- a/src/lib/server/application/adapters/namespace-discovery.test.ts +++ b/src/lib/server/application/adapters/namespace-discovery.test.ts @@ -447,9 +447,16 @@ test.each([true, false])( calls.push(url.pathname + url.search); if (url.pathname.endsWith("/user")) return Response.json({ site_admin: siteAdmin }); return calls.length === 2 - ? Response.json([{ login: "first", id: 71 }], { - headers: { link: '; rel="next"' }, - }) + ? Response.json( + [ + { login: "actions", id: 3 }, + { login: "github", id: 5 }, + { login: "first", id: 71 }, + ], + { + headers: { link: '; rel="next"' }, + }, + ) : Response.json([{ login: "second", id: 93 }]); }) as typeof fetch); try { @@ -463,6 +470,7 @@ test.each([true, false])( ); expect(result).toEqual({ keys: ["second"], + systemNotice: "Skipped GitHub Enterprise Server system organizations: actions, github", found: 2, outOfScope: 1, scopeVariable: "GITHUB_SOURCE_ORGS", diff --git a/src/lib/server/application/adapters/namespace-discovery.ts b/src/lib/server/application/adapters/namespace-discovery.ts index 2304e6d1..55346de8 100644 --- a/src/lib/server/application/adapters/namespace-discovery.ts +++ b/src/lib/server/application/adapters/namespace-discovery.ts @@ -93,6 +93,7 @@ interface EnterpriseWalk { signal: AbortSignal; read: PageReader; add(key: string): void; + skipped: Set; } /** Page through every namespace the source credentials can see. */ @@ -109,8 +110,18 @@ async function walkVisibleNamespaces({ provider, signal, read, add, hosting }: E } } -async function walkGitHubSite(walk: EnterpriseWalk) { - const { rest, sourceApiUrl } = getSourceClients(undefined, walk.hosting); +const GHES_SYSTEM_ORGS = new Set(["actions", "github"]); + +async function walkGitHubSite(input: EnterpriseWalk) { + const { rest, sourceApiUrl } = getSourceClients(undefined, input.hosting); + const walk: EnterpriseWalk = { + ...input, + add(key) { + const login = key.toLowerCase(); + if (GHES_SYSTEM_ORGS.has(login)) input.skipped.add(login); + else input.add(key); + }, + }; if (isSourceAppConfigured(walk.hosting)) return walkVisibleNamespaces(walk); const user = await rest.users.getAuthenticated({ request: { signal: walk.signal } }); if (!user.data.site_admin) return walkVisibleNamespaces(walk); @@ -289,6 +300,7 @@ export interface EnterpriseDiscovery { found: number; outOfScope: number; scopeVariable: string; + systemNotice?: string; } /** Drop namespaces whose ancestor is also queued, since its profile covers them. */ @@ -321,9 +333,13 @@ export async function enterpriseNamespaces( throw new Error("Invalid namespace in discovery"); keys.add(key); } - await discovery.walkEnterprise({ provider, enterprise, signal, read, add, hosting }); + const skipped = new Set(); + await discovery.walkEnterprise({ provider, enterprise, signal, read, add, hosting, skipped }); return { keys: discovery.profilesIncludeDescendants ? withoutCoveredDescendants(keys) : [...keys], + ...(skipped.size && { + systemNotice: `Skipped GitHub Enterprise Server system organizations: ${[...skipped].sort().join(", ")}`, + }), found: found.size, outOfScope: found.size - keys.size, scopeVariable: discovery.scopeVariable(hosting), @@ -332,15 +348,23 @@ export async function enterpriseNamespaces( export function describeEmptyDiscovery(provider: SourceProvider, result: EnterpriseDiscovery) { const noun = getSourceProviderAdapter(provider).presentation.discoveredNamespaces; - return result.found > 0 && result.outOfScope === result.found - ? `Discovery found ${result.found} ${noun}, but all are outside the configured scope (${result.scopeVariable}). No profiles queued.` - : `Discovery found no ${noun} visible to the source credentials. No profiles queued.`; + if (result.systemNotice && !result.found) return `${result.systemNotice}. No profiles queued.`; + const message = + result.found > 0 && result.outOfScope === result.found + ? `Discovery found ${result.found} ${noun}, but all are outside the configured scope (${result.scopeVariable}). No profiles queued.` + : `Discovery found no ${noun} visible to the source credentials. No profiles queued.`; + return [result.systemNotice, message].filter(Boolean).join(" "); } export function describeScopeNotice(provider: SourceProvider, result: EnterpriseDiscovery) { - if (result.outOfScope === 0) return undefined; + if (result.outOfScope === 0) return result.systemNotice; const noun = getSourceProviderAdapter(provider).presentation.discoveredNamespaces; - return `${result.outOfScope} of ${result.found} ${noun} found are outside the configured scope (${result.scopeVariable}).`; + return [ + result.systemNotice, + `${result.outOfScope} of ${result.found} ${noun} found are outside the configured scope (${result.scopeVariable}).`, + ] + .filter(Boolean) + .join(" "); } export type DiscoveryFailureReason = diff --git a/src/lib/server/core/github-profile-probes.ts b/src/lib/server/core/github-profile-probes.ts new file mode 100644 index 00000000..41ad45a7 --- /dev/null +++ b/src/lib/server/core/github-profile-probes.ts @@ -0,0 +1,105 @@ +const repo = "/repos/{owner}/{repo}/"; +const org = "/orgs/{org}/"; +const signals = new Map([ + [`${repo}code-scanning/alerts`, "code scanning"], + [`${repo}tags/protection`, "tag protection"], + [`${org}codespaces/secrets`, "Codespaces secrets"], + [`${org}installations`, "app installations"], + [`${org}properties/schema`, "custom properties"], + [`${org}dependabot/secrets`, "Dependabot secrets"], +]); +const optional = new Set([ + ...signals.keys(), + ...["actions/secrets", "actions/variables", "actions/runners", "teams", "rulesets"].map( + (p) => org + p, + ), + `${repo}hooks`, + `${repo}collaborators`, +]); +const unavailable = new Map(); +const pending = new Map>(); + +function applianceUnavailable(path: string, status: number, message: string) { + if (path.endsWith("/code-scanning/alerts")) + return ( + status === 403 && + /advanced security (?:is |must be |has been )?(?:not enabled|disabled|enabled for this repository to use code scanning)/i.test( + message, + ) + ); + if (path.endsWith("/dependabot/secrets")) return status >= 500; + return status === 404; +} + +function failureDetails(error: unknown) { + const e = error as Error & { + status?: number; + response?: { headers: Record }; + }; + const status = e.status; + const headers = e.response?.headers; + const limited = + status === 403 && + (headers?.["x-ratelimit-remaining"] === "0" || + headers?.["retry-after"] || + /rate limit/i.test(e.message)); + return { status, headers, limited, message: e.message }; +} + +export function profileProbes(baseUrl: string, appliance: boolean, now = Date.now) { + const { host, origin } = new URL(baseUrl); + const summary = new Map(); + + async function attempt(path: string, send: () => Promise, key?: string) { + try { + return await send(); + } catch (error) { + const { status, headers, limited, message } = failureDetails(error); + if (status && headers && !limited && optional.has(path)) { + const expected = signals.has(path) && applianceUnavailable(path, status, message); + if (key && expected) { + unavailable.set(key, { status, expires: now() + 3_600_000 }); + if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); + } + if (expected || status === 404 || status >= 500) + throw new Error("Optional GitHub probe unavailable"); + } + console.warn( + `[profile] request failed on ${host} (${headers && typeof status === "number" ? status : "network"})`, + ); + throw error; + } + } + + return { + async request(path: string, send: () => Promise) { + if (!appliance || !signals.has(path)) return attempt(path, send); + const key = origin + path; + // Concurrent repositories must observe the previous probe's verdict before dispatch. + while (pending.has(key)) await pending.get(key); + const cached = unavailable.get(key); + if (cached && cached.expires > now()) { + const entry = summary.get(path) ?? { status: cached.status, skipped: 0 }; + entry.skipped++; + summary.set(path, entry); + throw new Error("Optional GitHub probe unavailable"); + } + unavailable.delete(key); + const operation = attempt(path, send, key); + const release = () => { + pending.delete(key); + }; + pending.set(key, operation.then(release, release)); + return operation; + }, + report() { + for (const [path, { status, skipped }] of summary) { + const unit = path.startsWith(repo) ? "repositories" : "organizations"; + console.info( + `[profile] ${signals.get(path)} unavailable on ${host} (${status}); skipped for ${skipped} ${unit} in this run`, + ); + } + summary.clear(); + }, + }; +} diff --git a/src/lib/server/core/github-profile-retry.test.ts b/src/lib/server/core/github-profile-retry.test.ts index 7963c31e..c2b3094e 100644 --- a/src/lib/server/core/github-profile-retry.test.ts +++ b/src/lib/server/core/github-profile-retry.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, setSystemTime, spyOn, test } from "bun:test"; import { createProfileClient } from "./github"; // The profile client owns its retry timers so shutdown can cancel them: retry @@ -229,3 +229,131 @@ describe("profile client cancellation", () => { await client.drainProfileRequests(); }); }); + +const scanning = "GET /repos/{owner}/{repo}/code-scanning/alerts"; +const disabled = { + message: "Advanced Security must be enabled for this repository to use code scanning.", +}; + +function appliance(host: string, fetch: () => Response, now?: () => number) { + let calls = 0; + const client = createProfileClient( + { token: "fixture" }, + `https://${host}/api/v3`, + new AbortController().signal, + { + now, + fetch: async () => { + calls++; + return fetch(); + }, + wait: async () => {}, + }, + ); + return { + client, + calls: () => calls, + scan: (repo: string) => client.request(scanning, { owner: "private-owner", repo }), + }; +} + +test("concurrent probes share an unavailable answer across runs for an hour on one appliance", async () => { + const host = "scan.example"; + let clock = Date.now(); + const make = (origin = host) => + appliance( + origin, + () => Response.json(disabled, { status: 403 }), + () => clock, + ); + const info = spyOn(console, "info").mockImplementation(() => {}); + const error = spyOn(console, "error").mockImplementation(() => {}); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + const first = make(); + const results = await Promise.allSettled(["a", "b", "c"].map((repo) => first.scan(repo))); + expect(results.map((r) => r.status)).toEqual(["rejected", "rejected", "rejected"]); + expect(first.calls()).toBe(1); + await first.client.drainProfileRequests(); + const second = make(); + await expect(second.scan("d")).rejects.toThrow(); + await second.client.drainProfileRequests(); + expect(second.calls()).toBe(0); + expect(info.mock.calls).toEqual( + [2, 1].map((n) => [ + `[profile] code scanning unavailable on scan.example (403); skipped for ${n} repositories in this run`, + ]), + ); + const other = make("other-scan.example"); + await expect(other.scan("e")).rejects.toThrow(); + expect(other.calls()).toBe(1); + clock += 3_601_000; + await expect(second.scan("f")).rejects.toThrow(); + expect(second.calls()).toBe(1); + expect(error).not.toHaveBeenCalled(); + expect(warn).not.toHaveBeenCalled(); + } finally { + info.mockRestore(); + error.mockRestore(); + warn.mockRestore(); + } +}); + +test.each([ + ["GET /repos/{owner}/{repo}/tags/protection", 404], + ["GET /orgs/{org}/codespaces/secrets", 404], + ["GET /orgs/{org}/installations", 404], + ["GET /orgs/{org}/properties/schema", 404], + ["GET /orgs/{org}/dependabot/secrets", 500], +] as const)("appliance caches %s after one HTTP %i", async (route, status) => { + const run = appliance("features.example", () => Response.json({}, { status })); + for (const org of ["first", "second"]) + await expect(run.client.request(route, { org, owner: org, repo: "project" })).rejects.toThrow(); + expect(run.calls()).toBe(1); +}); + +test.each([401, 403, 429])( + "authentication and throttling failures stay visible and do not suppress scanning (%i)", + async (status) => { + let first = true; + const run = appliance("permissions.example", () => { + if (!first) return Response.json([]); + first = false; + return Response.json({ message: "private diagnostic" }, { status }); + }); + const warn = spyOn(console, "warn").mockImplementation(() => {}); + try { + if (status === 429) await run.scan("a"); + else await expect(run.scan("a")).rejects.toMatchObject({ status }); + await run.scan("b"); + expect(run.calls()).toBe(status === 429 ? 3 : 2); + expect(warn.mock.calls).toEqual([ + [`[profile] request failed on permissions.example (${status})`], + ]); + } finally { + warn.mockRestore(); + } + }, +); + +test("Retry-After on an optional 503 does not cause a retry", async () => { + const run = appliance("maintenance.example", () => + Response.json({}, { status: 503, headers: { "retry-after": "1" } }), + ); + await expect( + run.client.request("GET /orgs/{org}/actions/secrets", { org: "one" }), + ).rejects.toThrow(); + expect(run.calls()).toBe(1); +}); + +test("rate-limited scanning retries even when the response mentions Advanced Security", async () => { + let limited = true; + const run = appliance("limit.example", () => { + if (!limited) return Response.json([]); + limited = false; + return Response.json(disabled, { status: 403, headers: { "retry-after": "1" } }); + }); + await run.scan("first"); + await run.scan("second"); + expect(run.calls()).toBe(3); +}); diff --git a/src/lib/server/core/github.ts b/src/lib/server/core/github.ts index 3062a35f..df9b08f8 100644 --- a/src/lib/server/core/github.ts +++ b/src/lib/server/core/github.ts @@ -12,6 +12,7 @@ import type { AuthInput, Counts } from "$lib/migrate/types"; import { normalizeEditionApiUrl } from "$lib/source/editions"; import { getGitHubSourcePlatform } from "$lib/source-provider"; import { config } from "./config"; +import { profileProbes } from "./github-profile-probes"; import { parseLinkRelations } from "./http/link-header"; import { MAX_TIMER_DELAY_MS } from "./http/options"; import { sleep } from "./polling"; @@ -293,6 +294,7 @@ export function createProfileClient( deadline?: () => AbortSignal; fetch?: GitHubFetch; wait?: typeof sleep; + now?: () => number; } = {}, ): GitHubClient & { drainProfileRequests(): Promise } { const active = new AsyncLocalStorage(); @@ -306,6 +308,9 @@ export function createProfileClient( false, ).client; + const probes = profileProbes(normalizeGitHubApiUrl(baseUrl), !isGhecSource(baseUrl), options.now); + // Octokit's default request log includes paths and query strings. Log safe metadata at the probe. + client.log.warn = client.log.error = () => {}; client.hook.wrap("request", async (request, params) => { const signal = AbortSignal.any([ runSignal, @@ -317,7 +322,9 @@ export function createProfileClient( const operation = active.run(signal, () => sendWithProfileRetries( async (attemptSignal) => - request({ ...params, request: { ...params.request, signal: attemptSignal } }), + probes.request(params.url, async () => + request({ ...params, request: { ...params.request, signal: attemptSignal } }), + ), signal, options.wait ?? sleep, ), @@ -334,6 +341,7 @@ export function createProfileClient( return Object.assign(client, { async drainProfileRequests() { while (pending.size > 0) await Promise.allSettled(pending); + probes.report(); }, }); } @@ -348,7 +356,10 @@ function profileRetryDelay(error: unknown, attempt: number): number | null { const reset = Number(headers?.["x-ratelimit-reset"]); if (headers?.["x-ratelimit-remaining"] === "0" || error.message === "GraphQL Rate Limit Exceeded") return reset > 0 ? Math.max(0, reset * 1000 - Date.now() + 1000) : 60_000; - if (status === 429 || (status === 403 && /secondary rate/i.test(error.message))) + if ( + status === 429 || + (status === 403 && (headers?.["retry-after"] || /secondary rate/i.test(error.message))) + ) return (Number(headers?.["retry-after"]) || 60) * 1000; return status !== undefined && status >= 500 ? attempt ** 2 * 1000 : null; } From 59f96e9fcf44485c65c0f71350167b78334d1097 Mon Sep 17 00:00:00 2001 From: Casey Vega Date: Thu, 3 Dec 2026 22:01:54 -0800 Subject: [PATCH 2/5] fix(github): filter system organizations and cache optional probe failures Refs: gh-migrate-dashboard-0rtz --- .../adapters/namespace-discovery.test.ts | 52 +++++++++++++++++-- .../adapters/namespace-discovery.ts | 51 ++++++------------ src/lib/server/core/github-profile-probes.ts | 34 +++++++----- .../server/core/github-profile-retry.test.ts | 38 ++++++++++++++ src/lib/server/core/github.ts | 8 +-- .../server/core/target-organizations.test.ts | 13 +++-- src/lib/server/core/target-organizations.ts | 13 +++-- src/lib/server/profile/request.test.ts | 8 +++ src/lib/server/profile/request.ts | 6 +++ src/lib/source-provider.ts | 6 +++ src/routes/setup/targets.test.ts | 2 + 11 files changed, 169 insertions(+), 62 deletions(-) diff --git a/src/lib/server/application/adapters/namespace-discovery.test.ts b/src/lib/server/application/adapters/namespace-discovery.test.ts index 9d0b06a4..8d0d4f00 100644 --- a/src/lib/server/application/adapters/namespace-discovery.test.ts +++ b/src/lib/server/application/adapters/namespace-discovery.test.ts @@ -367,7 +367,12 @@ test("GitHub discovers credential-visible organizations and filters an explicit { GITHUB_CLOUD_SOURCE_TOKEN: "fixture", GITHUB_CLOUD_SOURCE_ORGS: undefined }, async () => { const network = spyOn(globalThis, "fetch").mockImplementation((async () => - Response.json([{ login: "one" }, { login: "two" }])) as unknown as typeof fetch); + Response.json([ + { login: "one" }, + { login: "AcTions" }, + { login: "GitHUB" }, + { login: "two" }, + ])) as unknown as typeof fetch); try { const discover = async () => (await discoverNamespacePage("github", 0, new AbortController().signal)).entries.map( @@ -449,8 +454,8 @@ test.each([true, false])( return calls.length === 2 ? Response.json( [ - { login: "actions", id: 3 }, - { login: "github", id: 5 }, + { login: "AcTIONS", id: 3 }, + { login: "GItHub", id: 5 }, { login: "first", id: 71 }, ], { @@ -470,7 +475,6 @@ test.each([true, false])( ); expect(result).toEqual({ keys: ["second"], - systemNotice: "Skipped GitHub Enterprise Server system organizations: actions, github", found: 2, outOfScope: 1, scopeVariable: "GITHUB_SOURCE_ORGS", @@ -527,3 +531,43 @@ test.each([ } }), ); + +test.each(["https://api.github.com", "https://api.acme.ghe.com"])( + "Every organization excludes GitHub-owned logins on %s", + (url) => + withEnv( + { + GITHUB_CLOUD_SOURCE_URL: url === "https://api.github.com" ? undefined : url, + GITHUB_CLOUD_SOURCE_TOKEN: "fixture", + GITHUB_CLOUD_SOURCE_ORGS: undefined, + }, + async () => { + using network = spyOn(globalThis, "fetch").mockImplementation((async () => + Response.json({ + data: { + enterprise: { + organizations: { + nodes: ["GitHub", "ActioNs", "engineering"].map((login) => ({ login })), + pageInfo: { hasNextPage: false, endCursor: null }, + }, + }, + }, + })) as unknown as typeof fetch); + expect( + await enterpriseNamespaces( + "github", + new AbortController().signal, + "acme", + undefined, + "cloud", + ), + ).toEqual({ + keys: ["engineering"], + found: 1, + outOfScope: 0, + scopeVariable: "GITHUB_CLOUD_SOURCE_ORGS", + }); + expect(network).toHaveBeenCalledTimes(1); + }, + ), +); diff --git a/src/lib/server/application/adapters/namespace-discovery.ts b/src/lib/server/application/adapters/namespace-discovery.ts index 55346de8..1d141cd0 100644 --- a/src/lib/server/application/adapters/namespace-discovery.ts +++ b/src/lib/server/application/adapters/namespace-discovery.ts @@ -6,7 +6,11 @@ import { organizationPage, siteOrganizationPage } from "$lib/server/core/github- import { cloudWorkspacePage } from "$lib/server/source/bitbucket/cloud-inventory"; import { getBitbucketServerSourceClient } from "$lib/server/source/bitbucket/config"; import { getGitLabSourceClient, getGitLabSourceConfig } from "$lib/server/source/gitlab/config"; -import { getSourceProviderAdapter, type SourceProvider } from "$lib/source-provider"; +import { + getSourceProviderAdapter, + isGitHubSystemOrganization, + type SourceProvider, +} from "$lib/source-provider"; const limit = 50; @@ -93,7 +97,6 @@ interface EnterpriseWalk { signal: AbortSignal; read: PageReader; add(key: string): void; - skipped: Set; } /** Page through every namespace the source credentials can see. */ @@ -110,18 +113,8 @@ async function walkVisibleNamespaces({ provider, signal, read, add, hosting }: E } } -const GHES_SYSTEM_ORGS = new Set(["actions", "github"]); - -async function walkGitHubSite(input: EnterpriseWalk) { - const { rest, sourceApiUrl } = getSourceClients(undefined, input.hosting); - const walk: EnterpriseWalk = { - ...input, - add(key) { - const login = key.toLowerCase(); - if (GHES_SYSTEM_ORGS.has(login)) input.skipped.add(login); - else input.add(key); - }, - }; +async function walkGitHubSite(walk: EnterpriseWalk) { + const { rest, sourceApiUrl } = getSourceClients(undefined, walk.hosting); if (isSourceAppConfigured(walk.hosting)) return walkVisibleNamespaces(walk); const user = await rest.users.getAuthenticated({ request: { signal: walk.signal } }); if (!user.data.site_admin) return walkVisibleNamespaces(walk); @@ -289,7 +282,9 @@ export async function discoverNamespacePage( ) { const page = await readPage(provider, cursor, signal, hosting); const entries = page.entries.filter( - (item) => !validateProfileCredentialScope(provider, item.key, hosting), + (item) => + !isGitHubSystemOrganization(item.key, provider) && + !validateProfileCredentialScope(provider, item.key, hosting), ); return { ...page, entries, observedAt: new Date().toISOString() }; } @@ -300,7 +295,6 @@ export interface EnterpriseDiscovery { found: number; outOfScope: number; scopeVariable: string; - systemNotice?: string; } /** Drop namespaces whose ancestor is also queued, since its profile covers them. */ @@ -326,6 +320,7 @@ export async function enterpriseNamespaces( const keys = new Set(); const found = new Set(); function add(key: string) { + if (isGitHubSystemOrganization(key, provider)) return; found.add(key); // Out-of-scope entries are only counted; admission rules apply to what may be queued. if (validateProfileCredentialScope(provider, key, hosting)) return; @@ -333,13 +328,9 @@ export async function enterpriseNamespaces( throw new Error("Invalid namespace in discovery"); keys.add(key); } - const skipped = new Set(); - await discovery.walkEnterprise({ provider, enterprise, signal, read, add, hosting, skipped }); + await discovery.walkEnterprise({ provider, enterprise, signal, read, add, hosting }); return { keys: discovery.profilesIncludeDescendants ? withoutCoveredDescendants(keys) : [...keys], - ...(skipped.size && { - systemNotice: `Skipped GitHub Enterprise Server system organizations: ${[...skipped].sort().join(", ")}`, - }), found: found.size, outOfScope: found.size - keys.size, scopeVariable: discovery.scopeVariable(hosting), @@ -348,23 +339,15 @@ export async function enterpriseNamespaces( export function describeEmptyDiscovery(provider: SourceProvider, result: EnterpriseDiscovery) { const noun = getSourceProviderAdapter(provider).presentation.discoveredNamespaces; - if (result.systemNotice && !result.found) return `${result.systemNotice}. No profiles queued.`; - const message = - result.found > 0 && result.outOfScope === result.found - ? `Discovery found ${result.found} ${noun}, but all are outside the configured scope (${result.scopeVariable}). No profiles queued.` - : `Discovery found no ${noun} visible to the source credentials. No profiles queued.`; - return [result.systemNotice, message].filter(Boolean).join(" "); + return result.found > 0 && result.outOfScope === result.found + ? `Discovery found ${result.found} ${noun}, but all are outside the configured scope (${result.scopeVariable}). No profiles queued.` + : `Discovery found no ${noun} visible to the source credentials. No profiles queued.`; } export function describeScopeNotice(provider: SourceProvider, result: EnterpriseDiscovery) { - if (result.outOfScope === 0) return result.systemNotice; + if (result.outOfScope === 0) return undefined; const noun = getSourceProviderAdapter(provider).presentation.discoveredNamespaces; - return [ - result.systemNotice, - `${result.outOfScope} of ${result.found} ${noun} found are outside the configured scope (${result.scopeVariable}).`, - ] - .filter(Boolean) - .join(" "); + return `${result.outOfScope} of ${result.found} ${noun} found are outside the configured scope (${result.scopeVariable}).`; } export type DiscoveryFailureReason = diff --git a/src/lib/server/core/github-profile-probes.ts b/src/lib/server/core/github-profile-probes.ts index 41ad45a7..2930a9fc 100644 --- a/src/lib/server/core/github-profile-probes.ts +++ b/src/lib/server/core/github-profile-probes.ts @@ -7,19 +7,19 @@ const signals = new Map([ [`${org}installations`, "app installations"], [`${org}properties/schema`, "custom properties"], [`${org}dependabot/secrets`, "Dependabot secrets"], -]); -const optional = new Set([ - ...signals.keys(), - ...["actions/secrets", "actions/variables", "actions/runners", "teams", "rulesets"].map( - (p) => org + p, - ), - `${repo}hooks`, - `${repo}collaborators`, + [`${org}actions/secrets`, "Actions secrets"], + [`${org}actions/variables`, "Actions variables"], + [`${org}actions/runners`, "Actions runners"], + [`${org}teams`, "teams"], + [`${org}rulesets`, "rulesets"], + [`${repo}hooks`, "webhooks"], + [`${repo}collaborators`, "collaborators"], ]); const unavailable = new Map(); const pending = new Map>(); function applianceUnavailable(path: string, status: number, message: string) { + if (status >= 500) return true; if (path.endsWith("/code-scanning/alerts")) return ( status === 403 && @@ -27,8 +27,15 @@ function applianceUnavailable(path: string, status: number, message: string) { message, ) ); - if (path.endsWith("/dependabot/secrets")) return status >= 500; - return status === 404; + return ( + status === 404 && + [ + `${repo}tags/protection`, + `${org}codespaces/secrets`, + `${org}installations`, + `${org}properties/schema`, + ].includes(path) + ); } function failureDetails(error: unknown) { @@ -55,14 +62,13 @@ export function profileProbes(baseUrl: string, appliance: boolean, now = Date.no return await send(); } catch (error) { const { status, headers, limited, message } = failureDetails(error); - if (status && headers && !limited && optional.has(path)) { - const expected = signals.has(path) && applianceUnavailable(path, status, message); + if (status && headers && !limited && signals.has(path)) { + const expected = applianceUnavailable(path, status, message); if (key && expected) { unavailable.set(key, { status, expires: now() + 3_600_000 }); if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); } - if (expected || status === 404 || status >= 500) - throw new Error("Optional GitHub probe unavailable"); + if (expected || status === 404) throw new Error("Optional GitHub probe unavailable"); } console.warn( `[profile] request failed on ${host} (${headers && typeof status === "number" ? status : "network"})`, diff --git a/src/lib/server/core/github-profile-retry.test.ts b/src/lib/server/core/github-profile-retry.test.ts index c2b3094e..3f405736 100644 --- a/src/lib/server/core/github-profile-retry.test.ts +++ b/src/lib/server/core/github-profile-retry.test.ts @@ -357,3 +357,41 @@ test("rate-limited scanning retries even when the response mentions Advanced Sec await run.scan("second"); expect(run.calls()).toBe(3); }); + +test.each([ + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/rulesets", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/collaborators", + scanning, +] as const)("concurrent runs share an optional HTTP 502 for %s", async (route) => { + const make = () => appliance("optional.example", () => Response.json({}, { status: 502 })); + const first = make(); + const second = make(); + const request = (run: typeof first) => + run.client.request(route, { org: "org", owner: "org", repo: "repo" }); + const results = await Promise.allSettled([request(first), request(second)]); + expect(results.map((r) => r.status)).toEqual(["rejected", "rejected"]); + expect(first.calls() + second.calls()).toBe(1); +}); + +test("optional transport failures log safe metadata and leave the signal available", async () => { + using warn = spyOn(console, "warn").mockImplementation(() => {}); + let failing = true; + const run = appliance("transport.example", () => { + if (failing) { + failing = false; + throw new Error("private network diagnostic"); + } + return Response.json([]); + }); + await run.scan("private-repo"); + await run.scan("another"); + expect(run.calls()).toBe(3); + expect(warn.mock.calls).toHaveLength(1); + for (const call of warn.mock.calls) + expect(call).toEqual(["[profile] request failed on transport.example (network)"]); +}); diff --git a/src/lib/server/core/github.ts b/src/lib/server/core/github.ts index df9b08f8..45ce6f52 100644 --- a/src/lib/server/core/github.ts +++ b/src/lib/server/core/github.ts @@ -321,10 +321,10 @@ export function createProfileClient( // The caller can time out before the underlying request or response body settles. const operation = active.run(signal, () => sendWithProfileRetries( - async (attemptSignal) => - probes.request(params.url, async () => - request({ ...params, request: { ...params.request, signal: attemptSignal } }), - ), + (attemptSignal) => { + const options = { ...params.request, log: client.log, signal: attemptSignal }; + return probes.request(params.url, async () => request({ ...params, request: options })); + }, signal, options.wait ?? sleep, ), diff --git a/src/lib/server/core/target-organizations.test.ts b/src/lib/server/core/target-organizations.test.ts index 8e5c000f..73c8b0de 100644 --- a/src/lib/server/core/target-organizations.test.ts +++ b/src/lib/server/core/target-organizations.test.ts @@ -43,9 +43,16 @@ test("picker pages active owner memberships on the selected GHE.com API", async link: '; rel="next"', }, }) - : Response.json([{ state: "active", role: "admin", organization: { login: "owned" } }], { - headers: { "x-oauth-scopes": "repo, admin:org" }, - }); + : Response.json( + ["owned", "GitHub", "ACTIONS"].map((login) => ({ + state: "active", + role: "admin", + organization: { login }, + })), + { + headers: { "x-oauth-scopes": "repo, admin:org" }, + }, + ); }) as typeof fetch); try { expect((await pickerTarget(requireMigrationTargetProfile())).organizations).toEqual(["owned"]); diff --git a/src/lib/server/core/target-organizations.ts b/src/lib/server/core/target-organizations.ts index 6ac62e76..9b61ba88 100644 --- a/src/lib/server/core/target-organizations.ts +++ b/src/lib/server/core/target-organizations.ts @@ -1,5 +1,6 @@ import type { CreateMigrationRequest } from "$lib/migrate/types"; import type { MigrationTargetProfile } from "$lib/migration-target"; +import { isGitHubSystemOrganization } from "$lib/source-provider"; import { createSingleClient } from "./github"; import { siteOrganizationPage } from "./github-organizations"; import { targetListError } from "./target-list"; @@ -58,14 +59,18 @@ async function administeredOrganizations( }; } -export function targetOrganizationPage( +export async function targetOrganizationPage( target: MigrationTargetProfile, cursor: number, signal: AbortSignal, ) { - return target.organizations.length + const page = target.organizations.length ? { organizations: target.organizations, next: null } - : administeredOrganizations(target, cursor, signal); + : await administeredOrganizations(target, cursor, signal); + return { + ...page, + organizations: page.organizations.filter((org) => !isGitHubSystemOrganization(org)), + }; } export async function pickerTarget(target: T): Promise { @@ -92,6 +97,8 @@ export async function targetAdministrationError(destination: Destination) { } export async function credentialAdministrationError(target: MigrationTargetProfile, org: string) { + if (isGitHubSystemOrganization(org)) + return "Choose a target organization other than actions or github."; const matches = (login: string) => login.toLowerCase() === org.toLowerCase(); try { const signal = AbortSignal.timeout(12000); diff --git a/src/lib/server/profile/request.test.ts b/src/lib/server/profile/request.test.ts index 458f5f50..f1068921 100644 --- a/src/lib/server/profile/request.test.ts +++ b/src/lib/server/profile/request.test.ts @@ -20,3 +20,11 @@ test("rejects unknown providers and malformed namespaces", () => { ok: false, }); }); + +test.each(["ActIons", "GitHUB"])("refuses the GitHub system organization %s", (org) => { + expect(validateStartProfileRequest({ org })).toEqual({ + ok: false, + error: "actions and github are GitHub's own organizations and can't be profiled.", + }); + expect(validateStartProfileRequest({ sourceProvider: "gitlab", org }).ok).toBe(true); +}); diff --git a/src/lib/server/profile/request.ts b/src/lib/server/profile/request.ts index 115b6659..2ba2127b 100644 --- a/src/lib/server/profile/request.ts +++ b/src/lib/server/profile/request.ts @@ -1,5 +1,6 @@ import { getSourceProviderAdapter, + isGitHubSystemOrganization, isSourceProvider, SOURCE_PROVIDERS, type SourceProvider, @@ -18,6 +19,11 @@ export function validateStartProfileRequest( return { ok: false, error: `sourceProvider must be one of: ${SOURCE_PROVIDERS.join(", ")}` }; } const org = typeof data.org === "string" ? data.org.trim() : ""; + if (isGitHubSystemOrganization(org, sourceProvider)) + return { + ok: false, + error: "actions and github are GitHub's own organizations and can't be profiled.", + }; const adapter = getSourceProviderAdapter(sourceProvider); if (!adapter.isValidNamespace(org)) { return { ok: false, error: `A valid ${adapter.namespaceLabel} ('org') is required` }; diff --git a/src/lib/source-provider.ts b/src/lib/source-provider.ts index dcef40ea..93b82e37 100644 --- a/src/lib/source-provider.ts +++ b/src/lib/source-provider.ts @@ -172,6 +172,12 @@ function githubSourcePlatform(apiUrl: string | null | undefined): { : { label: "GHES", displayName: "GitHub Enterprise Server", icon: "mark-github" }; } +const GITHUB_SYSTEM_ORGS = new Set(["actions", "github"]); + +export function isGitHubSystemOrganization(login: string, provider: SourceProvider = "github") { + return provider === "github" && GITHUB_SYSTEM_ORGS.has(login.toLowerCase()); +} + export function getGitHubSourcePlatform(apiUrl: string | null | undefined): TargetPlatform { return matchSourceEdition("github", apiUrl ?? "")?.hosting === "cloud" ? "ghec" : "ghes"; } diff --git a/src/routes/setup/targets.test.ts b/src/routes/setup/targets.test.ts index de26627f..5b5808ae 100644 --- a/src/routes/setup/targets.test.ts +++ b/src/routes/setup/targets.test.ts @@ -111,6 +111,8 @@ test("only admins manage targets; stale connections and malformed values never c expect(await actions.add(event("admin", { org: "test", connection: "stale" }))).toMatchObject({ status: 400, }); + for (const org of ["GitHUB", "AcTiOns"]) + expect(await actions.add(event("admin", { connection, org }))).toMatchObject({ status: 400 }); expect(remote).not.toHaveBeenCalled(); } finally { remote.mockRestore(); From 3f4a7902433a83de4988b6e2b55be28e3c156a3c Mon Sep 17 00:00:00 2001 From: Casey Vega Date: Thu, 3 Dec 2026 22:09:53 -0800 Subject: [PATCH 3/5] fix(github): release concurrent probes after the first success Refs: gh-migrate-dashboard-0rtz --- .../server/core/github-profile-probes.test.ts | 77 +++++++++++++++++++ src/lib/server/core/github-profile-probes.ts | 36 ++++++--- src/lib/server/core/github.ts | 3 +- 3 files changed, 103 insertions(+), 13 deletions(-) create mode 100644 src/lib/server/core/github-profile-probes.test.ts diff --git a/src/lib/server/core/github-profile-probes.test.ts b/src/lib/server/core/github-profile-probes.test.ts new file mode 100644 index 00000000..53248cd7 --- /dev/null +++ b/src/lib/server/core/github-profile-probes.test.ts @@ -0,0 +1,77 @@ +import { expect, mock, test } from "bun:test"; +import { profileProbes } from "./github-profile-probes"; + +const active = new Promise(() => {}); +const path = "/repos/{owner}/{repo}/hooks"; + +test("healthy first verdict releases concurrent probes across runs", async () => { + const make = () => profileProbes("https://fanout.example", true); + const first = Promise.withResolvers(); + const followers = Promise.withResolvers(); + const send = mock(() => followers.promise); + const calls = [ + make().request(path, () => first.promise, active), + make().request(path, send, active), + make().request(path, send, active), + make().request(path, send, active), + ]; + try { + expect(send).toHaveBeenCalledTimes(0); + first.resolve(); + // Flush every continuation of the initial verdict while followers remain in flight. + await new Promise((resolve) => setImmediate(resolve)); + expect(send).toHaveBeenCalledTimes(3); + } finally { + followers.resolve(); + await Promise.all(calls); + } +}); + +test("a later HTTP failure suppresses new probes even after an in-flight success", async () => { + let clock = 0; + const make = () => profileProbes("https://outage.example", true, () => clock); + const ok = mock(async () => "ok"); + const run = make(); + await run.request(path, ok, active); + const held = Promise.withResolvers(); + const prior = run.request(path, () => held.promise, active); + const unavailable = () => + Promise.reject(Object.assign(new Error(), { status: 503, response: { headers: {} } })); + try { + await expect(make().request(path, unavailable, active)).rejects.toThrow("unavailable"); + } finally { + held.resolve("ok"); + await prior; + } + await expect(run.request(path, ok, active)).rejects.toThrow("unavailable"); + expect(ok).toHaveBeenCalledTimes(1); + clock += 3_600_000; + const recovery = Promise.withResolvers(); + const probe = run.request(path, () => recovery.promise, active); + const waiter = make().request(path, ok, active); + expect(ok).toHaveBeenCalledTimes(1); + recovery.resolve("recovered"); + expect(await Promise.all([probe, waiter])).toEqual(["recovered", "ok"]); +}); + +test("an expired waiter drains independently and an expired leader releases its live waiters", async () => { + const probes = profileProbes("https://deadline.example", true); + const transport = Promise.withResolvers(); + const leaderDeadline = Promise.withResolvers(); + const waiterDeadline = Promise.withResolvers(); + const send = mock(async () => "available"); + const leader = probes.request(path, () => transport.promise, leaderDeadline.promise); + const expired = probes.request(path, send, waiterDeadline.promise); + const live = probes.request(path, send, active); + try { + waiterDeadline.reject(new Error("waiter deadline")); + await expect(expired).rejects.toThrow("waiter deadline"); + expect(send).not.toHaveBeenCalled(); + leaderDeadline.reject(new Error("leader deadline")); + expect(await live).toBe("available"); + expect(send).toHaveBeenCalledTimes(1); + } finally { + transport.resolve(); + await leader; + } +}); diff --git a/src/lib/server/core/github-profile-probes.ts b/src/lib/server/core/github-profile-probes.ts index 2930a9fc..09fcd900 100644 --- a/src/lib/server/core/github-profile-probes.ts +++ b/src/lib/server/core/github-profile-probes.ts @@ -15,8 +15,21 @@ const signals = new Map([ [`${repo}hooks`, "webhooks"], [`${repo}collaborators`, "collaborators"], ]); -const unavailable = new Map(); -const pending = new Map>(); +type Verdict = Promise | "supported" | { expires: number; status: number }; +const verdicts = new Map(); + +function trackFirstProbe(key: string, operation: Promise, interrupted: Promise) { + // A timed-out request can still be draining. Only the current probe owns this verdict. + const pending = Promise.race([operation, interrupted]).then( + () => { + if (verdicts.get(key) === pending) verdicts.set(key, "supported"); + }, + () => { + if (verdicts.get(key) === pending) verdicts.delete(key); + }, + ); + verdicts.set(key, pending); +} function applianceUnavailable(path: string, status: number, message: string) { if (status >= 500) return true; @@ -65,7 +78,7 @@ export function profileProbes(baseUrl: string, appliance: boolean, now = Date.no if (status && headers && !limited && signals.has(path)) { const expected = applianceUnavailable(path, status, message); if (key && expected) { - unavailable.set(key, { status, expires: now() + 3_600_000 }); + verdicts.set(key, { status, expires: now() + 3_600_000 }); if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); } if (expected || status === 404) throw new Error("Optional GitHub probe unavailable"); @@ -78,24 +91,23 @@ export function profileProbes(baseUrl: string, appliance: boolean, now = Date.no } return { - async request(path: string, send: () => Promise) { + async request(path: string, send: () => Promise, interrupted: Promise) { if (!appliance || !signals.has(path)) return attempt(path, send); const key = origin + path; - // Concurrent repositories must observe the previous probe's verdict before dispatch. - while (pending.has(key)) await pending.get(key); - const cached = unavailable.get(key); + let cached = verdicts.get(key); + while (cached instanceof Promise) { + await Promise.race([cached, interrupted]); + cached = verdicts.get(key); + } + if (cached === "supported") return attempt(path, send, key); if (cached && cached.expires > now()) { const entry = summary.get(path) ?? { status: cached.status, skipped: 0 }; entry.skipped++; summary.set(path, entry); throw new Error("Optional GitHub probe unavailable"); } - unavailable.delete(key); const operation = attempt(path, send, key); - const release = () => { - pending.delete(key); - }; - pending.set(key, operation.then(release, release)); + trackFirstProbe(key, operation, interrupted); return operation; }, report() { diff --git a/src/lib/server/core/github.ts b/src/lib/server/core/github.ts index 45ce6f52..78d43de6 100644 --- a/src/lib/server/core/github.ts +++ b/src/lib/server/core/github.ts @@ -323,7 +323,8 @@ export function createProfileClient( sendWithProfileRetries( (attemptSignal) => { const options = { ...params.request, log: client.log, signal: attemptSignal }; - return probes.request(params.url, async () => request({ ...params, request: options })); + const send = async () => request({ ...params, request: options }); + return probes.request(params.url, send, interrupted); }, signal, options.wait ?? sleep, From 66dccfe342a2f0f423eb752d85f807ea1bb62ce5 Mon Sep 17 00:00:00 2001 From: Casey Vega Date: Thu, 3 Dec 2026 22:17:08 -0800 Subject: [PATCH 4/5] fix(github): release waiting probes on repository-local responses Refs: gh-migrate-dashboard-0rtz --- .../server/core/github-profile-probes.test.ts | 47 ++++++++++++++++ src/lib/server/core/github-profile-probes.ts | 53 ++++++++++++------- 2 files changed, 81 insertions(+), 19 deletions(-) diff --git a/src/lib/server/core/github-profile-probes.test.ts b/src/lib/server/core/github-profile-probes.test.ts index 53248cd7..56f66843 100644 --- a/src/lib/server/core/github-profile-probes.test.ts +++ b/src/lib/server/core/github-profile-probes.test.ts @@ -75,3 +75,50 @@ test("an expired waiter drains independently and an expired leader releases its await leader; } }); + +test.each([ + ["code-scanning/alerts", 404], + ["collaborators", 403], + ["hooks", 403], +] as const)( + "batched %s probes fan out after a repository-local HTTP %i", + async (resource, status) => { + const route = `/repos/{owner}/{repo}/${resource}`; + const make = () => profileProbes(`https://${resource.split("/")[0]}.batch.example`, true); + const failure = (http: number) => + Object.assign(new Error("private diagnostic"), { status: http, response: { headers: {} } }); + const initial = Promise.withResolvers(); + const leader = make().request(route, () => initial.promise, active); + const outage = Promise.withResolvers(); + const local = Promise.withResolvers(); + const measured = Promise.withResolvers(); + const repos = [outage, local, measured]; + const send = mock((repo: typeof measured) => repo.promise); + const results = Promise.allSettled( + repos.map((repo) => make().request(route, () => send(repo), active)), + ); + try { + expect(send).not.toHaveBeenCalled(); + initial.reject(failure(status)); + await expect(leader).rejects.toThrow(); + await new Promise((resolve) => setImmediate(resolve)); + expect(send).toHaveBeenCalledTimes(3); + outage.reject(failure(503)); + await new Promise((resolve) => setImmediate(resolve)); + local.reject(failure(status)); + measured.resolve(7); + expect(await results).toMatchObject([ + { status: "rejected" }, + { status: "rejected" }, + { status: "fulfilled", value: 7 }, + ]); + await expect(make().request(route, () => send(measured), active)).rejects.toThrow( + "unavailable", + ); + expect(send).toHaveBeenCalledTimes(3); + } finally { + for (const repo of repos) repo.resolve(0); + await results; + } + }, +); diff --git a/src/lib/server/core/github-profile-probes.ts b/src/lib/server/core/github-profile-probes.ts index 09fcd900..72a5a3b6 100644 --- a/src/lib/server/core/github-profile-probes.ts +++ b/src/lib/server/core/github-profile-probes.ts @@ -15,20 +15,28 @@ const signals = new Map([ [`${repo}hooks`, "webhooks"], [`${repo}collaborators`, "collaborators"], ]); -type Verdict = Promise | "supported" | { expires: number; status: number }; +type Verdict = Promise | "independent" | { expires: number; status: number }; const verdicts = new Map(); -function trackFirstProbe(key: string, operation: Promise, interrupted: Promise) { +function firstProbe( + key: string, + send: (onLocalResponse: () => void) => Promise, + interrupted: Promise, +) { + // A repository-local response releases the batch while its own observation still fails. + const local = Promise.withResolvers(); + const operation = send(local.resolve); // A timed-out request can still be draining. Only the current probe owns this verdict. - const pending = Promise.race([operation, interrupted]).then( + const pending = Promise.race([operation, local.promise, interrupted]).then( () => { - if (verdicts.get(key) === pending) verdicts.set(key, "supported"); + if (verdicts.get(key) === pending) verdicts.set(key, "independent"); }, () => { if (verdicts.get(key) === pending) verdicts.delete(key); }, ); verdicts.set(key, pending); + return operation; } function applianceUnavailable(path: string, status: number, message: string) { @@ -51,7 +59,7 @@ function applianceUnavailable(path: string, status: number, message: string) { ); } -function failureDetails(error: unknown) { +function failureDetails(path: string, error: unknown) { const e = error as Error & { status?: number; response?: { headers: Record }; @@ -63,26 +71,35 @@ function failureDetails(error: unknown) { (headers?.["x-ratelimit-remaining"] === "0" || headers?.["retry-after"] || /rate limit/i.test(e.message)); - return { status, headers, limited, message: e.message }; + if (!headers || !status || limited || !signals.has(path)) return { status, headers }; + if (applianceUnavailable(path, status, e.message)) + return { status, headers, scope: "appliance" } as const; + if (status >= 400 && status < 500 && status !== 401 && status !== 429) + return { status, headers, scope: "local" } as const; + return { status, headers }; } export function profileProbes(baseUrl: string, appliance: boolean, now = Date.now) { const { host, origin } = new URL(baseUrl); const summary = new Map(); - async function attempt(path: string, send: () => Promise, key?: string) { + async function attempt( + path: string, + send: () => Promise, + key?: string, + onLocalResponse?: () => void, + ) { try { return await send(); } catch (error) { - const { status, headers, limited, message } = failureDetails(error); - if (status && headers && !limited && signals.has(path)) { - const expected = applianceUnavailable(path, status, message); - if (key && expected) { - verdicts.set(key, { status, expires: now() + 3_600_000 }); - if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); - } - if (expected || status === 404) throw new Error("Optional GitHub probe unavailable"); + const { status, headers, scope } = failureDetails(path, error); + if (key && scope === "appliance") { + verdicts.set(key, { status, expires: now() + 3_600_000 }); + if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); } + if (scope === "local") onLocalResponse?.(); + if (scope === "appliance" || (scope === "local" && status === 404)) + throw new Error("Optional GitHub probe unavailable"); console.warn( `[profile] request failed on ${host} (${headers && typeof status === "number" ? status : "network"})`, ); @@ -99,16 +116,14 @@ export function profileProbes(baseUrl: string, appliance: boolean, now = Date.no await Promise.race([cached, interrupted]); cached = verdicts.get(key); } - if (cached === "supported") return attempt(path, send, key); + if (cached === "independent") return attempt(path, send, key); if (cached && cached.expires > now()) { const entry = summary.get(path) ?? { status: cached.status, skipped: 0 }; entry.skipped++; summary.set(path, entry); throw new Error("Optional GitHub probe unavailable"); } - const operation = attempt(path, send, key); - trackFirstProbe(key, operation, interrupted); - return operation; + return firstProbe(key, (release) => attempt(path, send, key, release), interrupted); }, report() { for (const [path, { status, skipped }] of summary) { From 3130c5423ddd75a02d6a905b11e2b3b06af346e2 Mon Sep 17 00:00:00 2001 From: Casey Vega Date: Thu, 3 Dec 2026 23:54:20 -0800 Subject: [PATCH 5/5] fix(github): cache only completed unavailable probes Refs: gh-migrate-dashboard-0rtz --- .../server/core/github-profile-probes.test.ts | 124 ------------------ src/lib/server/core/github-profile-probes.ts | 67 +++------- .../server/core/github-profile-retry.test.ts | 20 +-- src/lib/server/core/github.ts | 3 +- 4 files changed, 29 insertions(+), 185 deletions(-) delete mode 100644 src/lib/server/core/github-profile-probes.test.ts diff --git a/src/lib/server/core/github-profile-probes.test.ts b/src/lib/server/core/github-profile-probes.test.ts deleted file mode 100644 index 56f66843..00000000 --- a/src/lib/server/core/github-profile-probes.test.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { expect, mock, test } from "bun:test"; -import { profileProbes } from "./github-profile-probes"; - -const active = new Promise(() => {}); -const path = "/repos/{owner}/{repo}/hooks"; - -test("healthy first verdict releases concurrent probes across runs", async () => { - const make = () => profileProbes("https://fanout.example", true); - const first = Promise.withResolvers(); - const followers = Promise.withResolvers(); - const send = mock(() => followers.promise); - const calls = [ - make().request(path, () => first.promise, active), - make().request(path, send, active), - make().request(path, send, active), - make().request(path, send, active), - ]; - try { - expect(send).toHaveBeenCalledTimes(0); - first.resolve(); - // Flush every continuation of the initial verdict while followers remain in flight. - await new Promise((resolve) => setImmediate(resolve)); - expect(send).toHaveBeenCalledTimes(3); - } finally { - followers.resolve(); - await Promise.all(calls); - } -}); - -test("a later HTTP failure suppresses new probes even after an in-flight success", async () => { - let clock = 0; - const make = () => profileProbes("https://outage.example", true, () => clock); - const ok = mock(async () => "ok"); - const run = make(); - await run.request(path, ok, active); - const held = Promise.withResolvers(); - const prior = run.request(path, () => held.promise, active); - const unavailable = () => - Promise.reject(Object.assign(new Error(), { status: 503, response: { headers: {} } })); - try { - await expect(make().request(path, unavailable, active)).rejects.toThrow("unavailable"); - } finally { - held.resolve("ok"); - await prior; - } - await expect(run.request(path, ok, active)).rejects.toThrow("unavailable"); - expect(ok).toHaveBeenCalledTimes(1); - clock += 3_600_000; - const recovery = Promise.withResolvers(); - const probe = run.request(path, () => recovery.promise, active); - const waiter = make().request(path, ok, active); - expect(ok).toHaveBeenCalledTimes(1); - recovery.resolve("recovered"); - expect(await Promise.all([probe, waiter])).toEqual(["recovered", "ok"]); -}); - -test("an expired waiter drains independently and an expired leader releases its live waiters", async () => { - const probes = profileProbes("https://deadline.example", true); - const transport = Promise.withResolvers(); - const leaderDeadline = Promise.withResolvers(); - const waiterDeadline = Promise.withResolvers(); - const send = mock(async () => "available"); - const leader = probes.request(path, () => transport.promise, leaderDeadline.promise); - const expired = probes.request(path, send, waiterDeadline.promise); - const live = probes.request(path, send, active); - try { - waiterDeadline.reject(new Error("waiter deadline")); - await expect(expired).rejects.toThrow("waiter deadline"); - expect(send).not.toHaveBeenCalled(); - leaderDeadline.reject(new Error("leader deadline")); - expect(await live).toBe("available"); - expect(send).toHaveBeenCalledTimes(1); - } finally { - transport.resolve(); - await leader; - } -}); - -test.each([ - ["code-scanning/alerts", 404], - ["collaborators", 403], - ["hooks", 403], -] as const)( - "batched %s probes fan out after a repository-local HTTP %i", - async (resource, status) => { - const route = `/repos/{owner}/{repo}/${resource}`; - const make = () => profileProbes(`https://${resource.split("/")[0]}.batch.example`, true); - const failure = (http: number) => - Object.assign(new Error("private diagnostic"), { status: http, response: { headers: {} } }); - const initial = Promise.withResolvers(); - const leader = make().request(route, () => initial.promise, active); - const outage = Promise.withResolvers(); - const local = Promise.withResolvers(); - const measured = Promise.withResolvers(); - const repos = [outage, local, measured]; - const send = mock((repo: typeof measured) => repo.promise); - const results = Promise.allSettled( - repos.map((repo) => make().request(route, () => send(repo), active)), - ); - try { - expect(send).not.toHaveBeenCalled(); - initial.reject(failure(status)); - await expect(leader).rejects.toThrow(); - await new Promise((resolve) => setImmediate(resolve)); - expect(send).toHaveBeenCalledTimes(3); - outage.reject(failure(503)); - await new Promise((resolve) => setImmediate(resolve)); - local.reject(failure(status)); - measured.resolve(7); - expect(await results).toMatchObject([ - { status: "rejected" }, - { status: "rejected" }, - { status: "fulfilled", value: 7 }, - ]); - await expect(make().request(route, () => send(measured), active)).rejects.toThrow( - "unavailable", - ); - expect(send).toHaveBeenCalledTimes(3); - } finally { - for (const repo of repos) repo.resolve(0); - await results; - } - }, -); diff --git a/src/lib/server/core/github-profile-probes.ts b/src/lib/server/core/github-profile-probes.ts index 72a5a3b6..f68ab7c8 100644 --- a/src/lib/server/core/github-profile-probes.ts +++ b/src/lib/server/core/github-profile-probes.ts @@ -15,29 +15,7 @@ const signals = new Map([ [`${repo}hooks`, "webhooks"], [`${repo}collaborators`, "collaborators"], ]); -type Verdict = Promise | "independent" | { expires: number; status: number }; -const verdicts = new Map(); - -function firstProbe( - key: string, - send: (onLocalResponse: () => void) => Promise, - interrupted: Promise, -) { - // A repository-local response releases the batch while its own observation still fails. - const local = Promise.withResolvers(); - const operation = send(local.resolve); - // A timed-out request can still be draining. Only the current probe owns this verdict. - const pending = Promise.race([operation, local.promise, interrupted]).then( - () => { - if (verdicts.get(key) === pending) verdicts.set(key, "independent"); - }, - () => { - if (verdicts.get(key) === pending) verdicts.delete(key); - }, - ); - verdicts.set(key, pending); - return operation; -} +const unavailable = new Map(); function applianceUnavailable(path: string, status: number, message: string) { if (status >= 500) return true; @@ -59,7 +37,7 @@ function applianceUnavailable(path: string, status: number, message: string) { ); } -function failureDetails(path: string, error: unknown) { +function failureDetails(error: unknown) { const e = error as Error & { status?: number; response?: { headers: Record }; @@ -71,35 +49,26 @@ function failureDetails(path: string, error: unknown) { (headers?.["x-ratelimit-remaining"] === "0" || headers?.["retry-after"] || /rate limit/i.test(e.message)); - if (!headers || !status || limited || !signals.has(path)) return { status, headers }; - if (applianceUnavailable(path, status, e.message)) - return { status, headers, scope: "appliance" } as const; - if (status >= 400 && status < 500 && status !== 401 && status !== 429) - return { status, headers, scope: "local" } as const; - return { status, headers }; + return { status, headers, limited, message: e.message }; } export function profileProbes(baseUrl: string, appliance: boolean, now = Date.now) { const { host, origin } = new URL(baseUrl); const summary = new Map(); - async function attempt( - path: string, - send: () => Promise, - key?: string, - onLocalResponse?: () => void, - ) { + async function attempt(path: string, send: () => Promise, key?: string) { try { return await send(); } catch (error) { - const { status, headers, scope } = failureDetails(path, error); - if (key && scope === "appliance") { - verdicts.set(key, { status, expires: now() + 3_600_000 }); - if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); + const { status, headers, limited, message } = failureDetails(error); + if (status && headers && !limited && signals.has(path)) { + const expected = applianceUnavailable(path, status, message); + if (key && expected) { + unavailable.set(key, { status, expires: now() + 3_600_000 }); + if (!summary.has(path)) summary.set(path, { status, skipped: 0 }); + } + if (expected || status === 404) throw new Error("Optional GitHub probe unavailable"); } - if (scope === "local") onLocalResponse?.(); - if (scope === "appliance" || (scope === "local" && status === 404)) - throw new Error("Optional GitHub probe unavailable"); console.warn( `[profile] request failed on ${host} (${headers && typeof status === "number" ? status : "network"})`, ); @@ -108,22 +77,18 @@ export function profileProbes(baseUrl: string, appliance: boolean, now = Date.no } return { - async request(path: string, send: () => Promise, interrupted: Promise) { + async request(path: string, send: () => Promise) { if (!appliance || !signals.has(path)) return attempt(path, send); const key = origin + path; - let cached = verdicts.get(key); - while (cached instanceof Promise) { - await Promise.race([cached, interrupted]); - cached = verdicts.get(key); - } - if (cached === "independent") return attempt(path, send, key); + const cached = unavailable.get(key); if (cached && cached.expires > now()) { const entry = summary.get(path) ?? { status: cached.status, skipped: 0 }; entry.skipped++; summary.set(path, entry); throw new Error("Optional GitHub probe unavailable"); } - return firstProbe(key, (release) => attempt(path, send, key, release), interrupted); + unavailable.delete(key); + return attempt(path, send, key); }, report() { for (const [path, { status, skipped }] of summary) { diff --git a/src/lib/server/core/github-profile-retry.test.ts b/src/lib/server/core/github-profile-retry.test.ts index 3f405736..c883a3a1 100644 --- a/src/lib/server/core/github-profile-retry.test.ts +++ b/src/lib/server/core/github-profile-retry.test.ts @@ -257,7 +257,7 @@ function appliance(host: string, fetch: () => Response, now?: () => number) { }; } -test("concurrent probes share an unavailable answer across runs for an hour on one appliance", async () => { +test("runs reuse a cached unavailable signal for an hour on the same appliance", async () => { const host = "scan.example"; let clock = Date.now(); const make = (origin = host) => @@ -271,8 +271,8 @@ test("concurrent probes share an unavailable answer across runs for an hour on o const warn = spyOn(console, "warn").mockImplementation(() => {}); try { const first = make(); - const results = await Promise.allSettled(["a", "b", "c"].map((repo) => first.scan(repo))); - expect(results.map((r) => r.status)).toEqual(["rejected", "rejected", "rejected"]); + for (const repo of ["a", "b", "c"]) + await expect(first.scan(repo)).rejects.toThrow("Optional GitHub probe unavailable"); expect(first.calls()).toBe(1); await first.client.drainProfileRequests(); const second = make(); @@ -287,7 +287,10 @@ test("concurrent probes share an unavailable answer across runs for an hour on o const other = make("other-scan.example"); await expect(other.scan("e")).rejects.toThrow(); expect(other.calls()).toBe(1); - clock += 3_601_000; + clock += 3_599_999; + await expect(second.scan("before-expiry")).rejects.toThrow(); + expect(second.calls()).toBe(0); + clock++; await expect(second.scan("f")).rejects.toThrow(); expect(second.calls()).toBe(1); expect(error).not.toHaveBeenCalled(); @@ -367,15 +370,16 @@ test.each([ "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/collaborators", scanning, -] as const)("concurrent runs share an optional HTTP 502 for %s", async (route) => { +] as const)("a subsequent run skips %s after a cached HTTP 502", async (route) => { const make = () => appliance("optional.example", () => Response.json({}, { status: 502 })); const first = make(); const second = make(); const request = (run: typeof first) => run.client.request(route, { org: "org", owner: "org", repo: "repo" }); - const results = await Promise.allSettled([request(first), request(second)]); - expect(results.map((r) => r.status)).toEqual(["rejected", "rejected"]); - expect(first.calls() + second.calls()).toBe(1); + await expect(request(first)).rejects.toThrow("Optional GitHub probe unavailable"); + await expect(request(second)).rejects.toThrow("Optional GitHub probe unavailable"); + expect(first.calls()).toBe(1); + expect(second.calls()).toBe(0); }); test("optional transport failures log safe metadata and leave the signal available", async () => { diff --git a/src/lib/server/core/github.ts b/src/lib/server/core/github.ts index 78d43de6..45ce6f52 100644 --- a/src/lib/server/core/github.ts +++ b/src/lib/server/core/github.ts @@ -323,8 +323,7 @@ export function createProfileClient( sendWithProfileRetries( (attemptSignal) => { const options = { ...params.request, log: client.log, signal: attemptSignal }; - const send = async () => request({ ...params, request: options }); - return probes.request(params.url, send, interrupted); + return probes.request(params.url, async () => request({ ...params, request: options })); }, signal, options.wait ?? sleep,