Files
karaoke-gen/frontend/lib/api/autoCorrect.ts
T
Andrew Beveridge ☄️andClaude Opus 4.8 c65a920a59 feat: graceful backend-outage handling + soften uptime alert noise (#921)
## Why

A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06
UTC on 2026-08-22 and auto-recovered ~1m41s later. Investigation showed
it was a **routine Cloud Run instance recycle** on `--min-instances 1`:
the single warm instance (up ~9.6h) was reaped at 06:01:53, leaving a
~80s gap with no origin, so Cloudflare failed the health check from all
6 checker regions at once. No crash/OOM — a self-healing platform
recycle. (Full write-up:
`docs/archive/2026-08-22-health-check-alert-noise-and-graceful-degradation.md`.)

We're deliberately keeping `--min-instances 1` for cost, so this
addresses the two things we *can* control: alert noise, and how the UI
behaves during such a blip.

## What

**1. Soften the uptime alert** (`infrastructure/modules/monitoring.py`)
- Condition `duration` 60s → **300s**: a sub-5-min self-healing recycle
no longer pages; a sustained hard-down still fires (~5–6 min). Incident
documented in-code.

**2. Graceful frontend degradation**
- `lib/api.ts` — new **`apiFetch`** wrapping every backend call:
non-aborting 2.5s "reconnecting" hint, hard-timeout backstop, **safe
retries (GET only — never replays a mutation)**, transient-status
detection (502/503/504 + Cloudflare 52x), GCS/third-party passthrough.
Throws a typed `BackendUnavailableError`.
- `lib/backend-status.ts` — framework-agnostic connectivity store
(`online | reconnecting | unavailable`); escalates to `unavailable` on a
10s clock, clears to `online` on any success.
- `components/backend-status-banner.tsx` — one reassuring app-wide
banner (mounted under `[locale]`, covers landing + logged-in dashboard +
review screens), **i18n across all 33 locales**. `/admin/*`
intentionally excluded. Copy reassures that in-flight renders are
unaffected.

During a real recycle the dashboard's own polling drives the banner and
it self-heals when the backend returns — no refresh needed.

## Testing
- New unit tests: `__tests__/backend-status.test.ts`,
`__tests__/api-fetch.test.ts` (GET retry→10s escalation, transient 503,
transparent recovery, non-GET never retried, `Request`-input
method/signal, GCS passthrough, caller-abort passthrough). Updated
`completeJobUpload` assertion.
- Full suite green: **1130 passing**.
- Banner verified visually locally (reconnecting + unavailable, en +
es).
- Local CodeRabbit review: 5 findings (1 major, 4 minor) all addressed;
cycle 2 clean.

## Deploy notes
- Infra change: `pulumi up` run locally before merge to avoid IaC drift
(Pulumi CI re-runs as no-op).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:11:58 -04:00

150 lines
4.2 KiB
TypeScript

/**
* Client for the AI auto-correct suggestions endpoint.
*
* POST /api/review/{job_id}/auto-correct
*
* Stateless: posts the client's current working segments + reference lyrics
* and returns word-id-keyed suggestions. Nothing is applied server-side —
* the reviewer accepts/rejects each suggestion in the UI and persistence
* flows through the existing corrections/complete paths.
*/
import type { LyricsSegment, ReferenceSource } from '@/lib/lyrics-review/types'
import { apiFetch } from '@/lib/api'
const API_BASE =
process.env.NEXT_PUBLIC_API_BASE ?? 'https://api.nomadkaraoke.com'
export type AiSuggestionOp = 'replace' | 'delete' | 'insert_after'
export type AiSuggestionCategory =
| 'mishearing'
| 'grammar'
| 'adlib_removal'
| 'repeated_chorus_fix'
| 'formatting'
| 'other'
export interface AutoCorrectSettings {
suggest_adlib_removal: boolean
allow_insertions: boolean
min_confidence: number
/** Query all configured models in parallel and report consensus. */
compare_models: boolean
}
export const DEFAULT_AUTO_CORRECT_SETTINGS: AutoCorrectSettings = {
suggest_adlib_removal: true,
allow_insertions: true,
min_confidence: 0,
// Always multi-model. Kept in sync with the backend proactive run
// (AutoCorrectSettings(compare_models=True)) so the on-load request is a
// cache hit. Not user-configurable.
compare_models: true,
}
export interface AiSuggestion {
id: string
op: AiSuggestionOp
word_ids: string[]
segment_ids: string[]
original_text: string
new_text: string
reason: string
category: AiSuggestionCategory
confidence: number
/** Models that proposed this exact suggestion. */
models: string[]
/** How many of total_models agreed on this exact suggestion. */
consensus: number
total_models: number
/** Suggestions sharing a conflict_group target overlapping words with
* different outcomes — accept at most one per group. */
conflict_group: string | null
}
export interface AutoCorrectResponse {
suggestions: AiSuggestion[]
model: string
elapsed_seconds: number
settings_applied: AutoCorrectSettings
warnings: string[]
/** Served from the per-job cache — no AI cost was incurred. */
cached: boolean
}
export class AutoCorrectApiError extends Error {
readonly status: number
constructor(status: number, message: string) {
super(message)
this.name = 'AutoCorrectApiError'
this.status = status
}
}
export interface AutoCorrectParams {
segments: LyricsSegment[]
referenceLyrics: Record<string, ReferenceSource>
artist?: string
title?: string
settings: AutoCorrectSettings
}
export async function fetchAutoCorrectSuggestions(
jobId: string,
params: AutoCorrectParams,
signal?: AbortSignal,
token?: string,
): Promise<AutoCorrectResponse> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
}
if (token) headers.Authorization = `Bearer ${token}`
const response = await apiFetch(
`${API_BASE}/api/review/${encodeURIComponent(jobId)}/auto-correct`,
{
method: 'POST',
headers,
signal,
body: JSON.stringify({
segments: params.segments,
reference_lyrics: params.referenceLyrics,
artist: params.artist,
title: params.title,
settings: params.settings,
}),
},
)
if (!response.ok) {
let detail = `Request failed (${response.status})`
try {
const body = await response.json()
if (body && typeof body.detail === 'string') detail = body.detail
} catch {
/* swallow JSON parse errors and use generic message */
}
throw new AutoCorrectApiError(response.status, detail)
}
const data = await response.json()
const rawSuggestions: AiSuggestion[] = Array.isArray(data.suggestions)
? data.suggestions
: []
return {
suggestions: rawSuggestions.map((s: AiSuggestion) => ({
...s,
models: s.models ?? [],
consensus: s.consensus ?? 1,
total_models: s.total_models ?? 1,
conflict_group: s.conflict_group ?? null,
})),
model: data.model,
elapsed_seconds: data.elapsed_seconds,
settings_applied: data.settings_applied,
warnings: data.warnings ?? [],
cached: data.cached ?? false,
}
}