From 91979dc0bbbf255bf6a00b57b41034108deab4ef Mon Sep 17 00:00:00 2001 From: Mike Rubino <73962981+mrNLK@users.noreply.github.com> Date: Mon, 19 Oct 2026 15:13:10 -0700 Subject: [PATCH] fix(people-search): per-source timeouts, client timeout, visible errors; Firecrawl opt-in source-candidates had no time limits (~55-65s per search with 4 sources); a slow provider could stall the whole request with only a spinner. Each source now has a 30s budget (reported as a per-source error), post-processing calls 8s each, and per-source ms is returned. The client aborts at 100s with a clear message, shows elapsed seconds, per-source error details and a no-results notice. Firecrawl is no longer auto-checked. --- src/components/PeopleSearchTab.tsx | 17 ++++++--- src/services/candidateSources.ts | 22 +++++++++--- supabase/functions/source-candidates/index.ts | 35 +++++++++++++++---- 3 files changed, 59 insertions(+), 15 deletions(-) diff --git a/src/components/PeopleSearchTab.tsx b/src/components/PeopleSearchTab.tsx index 376a934..69c6686 100644 --- a/src/components/PeopleSearchTab.tsx +++ b/src/components/PeopleSearchTab.tsx @@ -89,11 +89,19 @@ const PeopleSearchTab = () => { if (!alive) return setEnabledSources(e) if (e.parallel) setSources((cur) => new Set([...cur, 'parallel'])) - if (e.firecrawl) setSources((cur) => new Set([...cur, 'firecrawl'])) + // Firecrawl is opt-in (slowest source); it is only enabled for selection, not auto-checked. }).catch(() => { /* keep Parallel disabled if the probe fails */ }) return () => { alive = false } }, []) const [loading, setLoading] = useState(false) + const [elapsed, setElapsed] = useState(0) + useEffect(() => { + if (!loading) return + setElapsed(0) + const t0 = Date.now() + const id = setInterval(() => setElapsed(Math.round((Date.now() - t0) / 1000)), 1000) + return () => clearInterval(id) + }, [loading]) const [results, setResults] = useState([]) const [sourceStats, setSourceStats] = useState>({}) const [selected, setSelected] = useState>(new Set()) @@ -130,8 +138,9 @@ const PeopleSearchTab = () => { setResults(res.candidates) setSourceStats(res.sources) void recordHistory(query.trim() || [titles, companies].filter(Boolean).join(' · '), res.candidates.length, { source: 'people_search', titles, locations, skills, companies, status: res.candidates.length ? 'success' : 'no_results' }) - const failed = Object.entries(res.sources).filter(([, s]) => s.error).map(([k]) => k) - if (failed.length) toast({ title: 'Some sources failed', description: failed.join(', ') }) + const failed = Object.entries(res.sources).filter(([, s]) => s.error) + if (failed.length) toast({ title: 'Some sources failed', description: failed.map(([k, s]) => `${k}: ${s.error}`).join(' · '), variant: res.candidates.length ? undefined : 'destructive' }) + else if (!res.candidates.length) toast({ title: 'No results', description: 'Try a broader query or more sources.' }) } catch (e) { toast({ title: 'Search failed', description: e instanceof Error ? e.message : String(e), variant: 'destructive' }) } finally { @@ -208,7 +217,7 @@ const PeopleSearchTab = () => {
setQuery(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && runSearch()} />
diff --git a/src/services/candidateSources.ts b/src/services/candidateSources.ts index 0cba67c..1341dbe 100644 --- a/src/services/candidateSources.ts +++ b/src/services/candidateSources.ts @@ -42,7 +42,7 @@ export interface CandidateFiltersInput { export interface SourceCandidatesResponse { candidates: SourcedCandidate[] - sources: Record + sources: Record enabled: Record raw_count: number est_cost_usd: number @@ -92,10 +92,18 @@ export function splitList(v: string): string[] { return v.split(/[,\n]/).map((s) => s.trim()).filter(Boolean) } -async function invoke(name: string, body: Record): Promise { +/** Client-side cap for a People Search request (server caps each source at 30s). */ +export const PEOPLE_SEARCH_TIMEOUT_MS = 100_000 + +async function invoke(name: string, body: Record, opts: { timeoutMs?: number } = {}): Promise { const { data: { session } } = await supabase.auth.getSession() if (!session?.access_token) throw new Error('Authentication required – please sign in.') - const res = await fetch(`${SUPABASE_URL}/functions/v1/${name}`, { + const ctrl = opts.timeoutMs ? new AbortController() : null + const timer = ctrl ? setTimeout(() => ctrl.abort(), opts.timeoutMs) : undefined + let res: Response + try { + res = await fetch(`${SUPABASE_URL}/functions/v1/${name}`, { + signal: ctrl?.signal, method: 'POST', headers: { apikey: SUPABASE_KEY, @@ -104,6 +112,12 @@ async function invoke(name: string, body: Record): Promise ({ error: `HTTP ${res.status}` })) if (!res.ok || data?.error) { throw new Error(data?.message || data?.error || `HTTP ${res.status}`) @@ -119,7 +133,7 @@ export function sourceCandidates(input: { person_name?: string harmonic_enrich?: boolean }): Promise { - return invoke('source-candidates', input) + return invoke('source-candidates', input, { timeoutMs: PEOPLE_SEARCH_TIMEOUT_MS }) } export function startDeepSearch(input: { diff --git a/supabase/functions/source-candidates/index.ts b/supabase/functions/source-candidates/index.ts index 0b1f8bc..3268af1 100644 --- a/supabase/functions/source-candidates/index.ts +++ b/supabase/functions/source-candidates/index.ts @@ -55,6 +55,19 @@ async function addTalentFlags(rows: any[]): Promise { }).filter((c) => !c.is_bot && c.gh_type !== "Organization"); // orgs (e.g. README owners) are not people } +/** Per-source wall-clock budget: a slow provider becomes a per-source error instead of hanging the search. */ +const SOURCE_TIMEOUT_MS = 30_000; +/** Budget for each optional post-processing call (enrich, GitHub handle lookup, site scrape). */ +const POST_STEP_TIMEOUT_MS = 8_000; + +function withTimeout(p: Promise, ms: number, message: string): Promise { + let timer: ReturnType | undefined; + return Promise.race([ + p, + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(message)), ms); }), + ]).finally(() => clearTimeout(timer)); +} + serve(async (req) => { if (req.method === "OPTIONS") return new Response(null, { headers: getCorsHeaders(req) }); const headers = { ...getCorsHeaders(req), "Content-Type": "application/json" }; @@ -143,20 +156,28 @@ serve(async (req) => { return new Response(JSON.stringify({ error: "No enabled people sources for this request", enabled }), { status: 422, headers }); } - const settled = await Promise.allSettled(tasks.map((t) => t.run())); - const sources: Record }> = {}; + const timings: Record = {}; + const settled = await Promise.allSettled(tasks.map(async (t) => { + const t0 = Date.now(); + try { + return await withTimeout(t.run(), SOURCE_TIMEOUT_MS, `${t.source} timed out after ${SOURCE_TIMEOUT_MS / 1000}s`); + } finally { + timings[t.source] = Date.now() - t0; + } + })); + const sources: Record }> = {}; // Order = merge priority for field conflicts: structured sources first. const priority: SourceName[] = ["harmonic", "github", "exa", "parallel", "firecrawl"]; const bySource = new Map(); settled.forEach((r, i) => { const s = tasks[i].source; if (r.status === "fulfilled") { - sources[s] = { count: r.value.candidates.length, est_cost_usd: Number(r.value.cost.toFixed(4)), total: r.value.total, ...(r.value.detail ? { detail: r.value.detail } : {}) }; + sources[s] = { count: r.value.candidates.length, est_cost_usd: Number(r.value.cost.toFixed(4)), total: r.value.total, ms: timings[s], ...(r.value.detail ? { detail: r.value.detail } : {}) }; bySource.set(s, r.value.candidates); } else { const msg = r.reason instanceof Error ? r.reason.message : String(r.reason); console.error(`source ${s} failed:`, msg); - sources[s] = { count: 0, est_cost_usd: 0, error: msg.slice(0, 200) }; + sources[s] = { count: 0, est_cost_usd: 0, ms: timings[s], error: msg.slice(0, 200) }; } }); const all = priority.flatMap((s) => bySource.get(s) || []); @@ -164,14 +185,14 @@ serve(async (req) => { // Optional: resolve top LinkedIn candidates to Harmonic people so they dedup by Harmonic URN. if (harmonicCfg && body.harmonic_enrich === true) { const targets = all.filter((c) => c.linkedinUrl && !c.harmonicUrn).slice(0, HARMONIC_ENRICH_TOP); - const enriched = await Promise.allSettled(targets.map((c) => harmonicPersonByLinkedin(harmonicCfg, c.linkedinUrl!))); + const enriched = await Promise.allSettled(targets.map((c) => withTimeout(harmonicPersonByLinkedin(harmonicCfg, c.linkedinUrl!), POST_STEP_TIMEOUT_MS, "harmonic enrich timed out"))); for (const r of enriched) if (r.status === "fulfilled" && r.value) all.push(r.value); } // Free GitHub handle lookup (name + company) for top web-profile results without one. const nameTargets = all.filter((c) => !c.githubLogin && c.currentCompany && c.sources.some((h) => h.provider === "exa")) .sort((a, b) => (a.sources[0]?.rank ?? 99) - (b.sources[0]?.rank ?? 99)).slice(0, GITHUB_NAME_LOOKUPS); - const handles = await Promise.allSettled(nameTargets.map((c) => githubHandleByNameCompany(getEnv("GITHUB_TOKEN"), c.fullName, c.currentCompany!, fetch, c.location))); + const handles = await Promise.allSettled(nameTargets.map((c) => withTimeout(githubHandleByNameCompany(getEnv("GITHUB_TOKEN"), c.fullName, c.currentCompany!, fetch, c.location), POST_STEP_TIMEOUT_MS, "github lookup timed out"))); handles.forEach((r, i) => { if (r.status === "fulfilled" && r.value) { nameTargets[i].githubLogin = r.value.login.toLowerCase(); @@ -197,7 +218,7 @@ serve(async (req) => { if (enabled.firecrawl && requested.has("firecrawl")) { const kw = extractSearchTerms(query, filters).keywords; const targets = (candidates as any[]).filter((c) => isPersonalSiteUrl(c.blog_url)).slice(0, FIRECRAWL_LIMITS.scrapes); - const ev = await Promise.allSettled(targets.map((c) => firecrawlScrapeEvidence(getEnv("FIRECRAWL_API_KEY")!, String(c.blog_url).startsWith("http") ? c.blog_url : `https://${c.blog_url}`))); + const ev = await Promise.allSettled(targets.map((c) => withTimeout(firecrawlScrapeEvidence(getEnv("FIRECRAWL_API_KEY")!, String(c.blog_url).startsWith("http") ? c.blog_url : `https://${c.blog_url}`), POST_STEP_TIMEOUT_MS, "firecrawl scrape timed out"))); let scraped = 0; ev.forEach((r, i) => { const text = r.status === "fulfilled" ? r.value : null;