Repository navigation
refactor(chatCore): extrai recordKeyHealthStatus para leaf dedicado (#3501) #4491
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
diegosouzapw
wants to merge
1
commit into
refactor/qg-chatcore-svctier
from
refactor/qg-chatcore-keyhealth
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| /** | ||
| * chatCore per-request API-key health updater (Quality Gate v2 / Fase 9 — chatCore god-file | ||
| * decomposition, #3501). | ||
| * | ||
| * Byte-identical extraction of the `recordKeyHealthStatus` closure that lived at the top of | ||
| * handleChatCore. Translates an upstream HTTP status into the in-memory key-health state | ||
| * (apiKeyRotator) for the connection's currently-selected key, and persists the change to the | ||
| * provider connection so it survives process restarts: | ||
| * - 401 → record a failure (warning, then invalid at the threshold), always persisted. | ||
| * - 2xx → record a success, persisted only when recovering from a warning/invalid state. | ||
| * Any other status only refreshes the tracked extra-key set. The handler binds its `log` once and | ||
| * delegates here, keeping the existing call sites unchanged. | ||
| */ | ||
|
|
||
| import { | ||
| recordKeyFailure, | ||
| recordKeySuccess, | ||
| trackConnectionExtraKeys, | ||
| type KeyHealth, | ||
| } from "../../services/apiKeyRotator.ts"; | ||
| import { updateProviderConnection } from "@/lib/db/providers"; | ||
|
|
||
| type KeyHealthLog = { | ||
| warn?: (tag: string, message: string) => void; | ||
| error?: (tag: string, message: string) => void; | ||
| } | null; | ||
|
|
||
| export function recordKeyHealthStatus( | ||
| status: number, | ||
| creds: Record<string, unknown> | null | undefined, | ||
| log?: KeyHealthLog | ||
| ): void { | ||
| const connId = creds?.connectionId as string | undefined; | ||
| if (!connId) return; | ||
|
|
||
| const psd = creds.providerSpecificData as Record<string, unknown> | undefined; | ||
| const extraKeys = (psd?.extraApiKeys as string[] | undefined) ?? []; | ||
| const health = psd?.apiKeyHealth as Record<string, KeyHealth> | undefined; | ||
| const currentKeyId = (psd?.selectedKeyId as string | undefined) ?? "primary"; | ||
|
|
||
| trackConnectionExtraKeys(connId, extraKeys); | ||
|
|
||
| if (status === 401) { | ||
| const updatedHealth = recordKeyFailure(connId, currentKeyId); | ||
| log?.warn?.( | ||
| "AUTH", | ||
| `401 on connection ${connId.slice(0, 8)} - key marked as failed (failure #${updatedHealth.failures})` | ||
| ); | ||
|
|
||
| // Persist health status to DB on every failure (not just invalid transitions) | ||
| // This ensures in-memory state survives process restarts | ||
| const prevStatus = health?.[currentKeyId]?.status; | ||
| const prevFailures = health?.[currentKeyId]?.failures ?? 0; | ||
| if (updatedHealth.status !== prevStatus || updatedHealth.failures !== prevFailures) { | ||
| updateProviderConnection(connId, { | ||
| providerSpecificData: { | ||
| ...psd, | ||
| apiKeyHealth: { ...health, [currentKeyId]: updatedHealth }, | ||
| }, | ||
| }).catch((err: unknown) => { | ||
| log?.error?.( | ||
| "DB", | ||
| `Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}` | ||
| ); | ||
| }); | ||
| } | ||
| } else if (status >= 200 && status < 300) { | ||
| const updatedHealth = recordKeySuccess(connId, currentKeyId); | ||
| const prevStatus = health?.[currentKeyId]?.status; | ||
| if (prevStatus === "warning" || prevStatus === "invalid") { | ||
| updateProviderConnection(connId, { | ||
| providerSpecificData: { | ||
| ...psd, | ||
| apiKeyHealth: { ...health, [currentKeyId]: updatedHealth }, | ||
| }, | ||
| }).catch((err: unknown) => { | ||
| log?.error?.( | ||
| "DB", | ||
| `Failed to persist apiKeyHealth: ${err instanceof Error ? err.message : String(err)}` | ||
| ); | ||
| }); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| // tests/unit/chatcore-key-health.test.ts | ||
| // Characterization of recordKeyHealthStatus — the per-request API-key health updater extracted | ||
| // from handleChatCore (chatCore god-file decomposition, #3501). Locks the observable in-memory | ||
| // transitions driven through apiKeyRotator: 401 → failure (warning, then invalid at the threshold), | ||
| // 2xx → success/recovery, selectedKeyId scoping, and the no-op paths (missing connectionId, and | ||
| // non-401/non-2xx statuses). The DB persistence side effect (updateProviderConnection) is moved | ||
| // byte-identically and is fire-and-forget; these tests assert the synchronous health mutations. | ||
| import { test, afterEach } from "node:test"; | ||
| import assert from "node:assert/strict"; | ||
| import { recordKeyHealthStatus } from "../../open-sse/handlers/chatCore/keyHealth.ts"; | ||
| import { getAllKeyHealth, removeConnectionHealth } from "../../open-sse/services/apiKeyRotator.ts"; | ||
|
|
||
| const noopLog = { warn: () => {}, error: () => {} }; | ||
| const touched: string[] = []; | ||
|
|
||
| function creds(connectionId: string, psd: Record<string, unknown> = {}) { | ||
| touched.push(connectionId); | ||
| return { connectionId, providerSpecificData: psd }; | ||
| } | ||
|
|
||
| afterEach(() => { | ||
| for (const c of touched.splice(0)) removeConnectionHealth(c); | ||
| }); | ||
|
|
||
| test("missing connectionId is a no-op (no health entry created)", () => { | ||
| const before = Object.keys(getAllKeyHealth()).length; | ||
| const r = recordKeyHealthStatus(200, { providerSpecificData: {} }, noopLog); | ||
| assert.equal(r, undefined); | ||
| assert.equal(Object.keys(getAllKeyHealth()).length, before); | ||
| }); | ||
|
|
||
| test("401 marks the selected key as failed → warning after the first failure", () => { | ||
| const conn = "kh-401-warning"; | ||
| recordKeyHealthStatus(401, creds(conn), noopLog); | ||
| const h = getAllKeyHealth()[`${conn}:primary`]; | ||
| assert.equal(h?.failures, 1); | ||
| assert.equal(h?.status, "warning"); | ||
| }); | ||
|
|
||
| test("401 reaches invalid at the failure threshold (2 consecutive)", () => { | ||
| const conn = "kh-401-invalid"; | ||
| recordKeyHealthStatus(401, creds(conn), noopLog); | ||
| recordKeyHealthStatus(401, creds(conn), noopLog); | ||
| const h = getAllKeyHealth()[`${conn}:primary`]; | ||
| assert.equal(h?.failures, 2); | ||
| assert.equal(h?.status, "invalid"); | ||
| }); | ||
|
|
||
| test("2xx after a failure resets the key to active with 0 failures", () => { | ||
| const conn = "kh-2xx-recover"; | ||
| recordKeyHealthStatus(401, creds(conn), noopLog); | ||
| recordKeyHealthStatus(204, creds(conn), noopLog); | ||
| const h = getAllKeyHealth()[`${conn}:primary`]; | ||
| assert.equal(h?.failures, 0); | ||
| assert.equal(h?.status, "active"); | ||
| }); | ||
|
|
||
| test("honors selectedKeyId — scopes the update to the active extra key, not primary", () => { | ||
| const conn = "kh-selected-key"; | ||
| recordKeyHealthStatus(401, creds(conn, { selectedKeyId: "extra_1" }), noopLog); | ||
| const all = getAllKeyHealth(); | ||
| assert.equal(all[`${conn}:extra_1`]?.status, "warning"); | ||
| assert.equal(all[`${conn}:primary`], undefined); | ||
| }); | ||
|
|
||
| test("non-401 / non-2xx status does not touch key health", () => { | ||
| const conn = "kh-5xx-noop"; | ||
| recordKeyHealthStatus(500, creds(conn), noopLog); | ||
| assert.equal(getAllKeyHealth()[`${conn}:primary`], undefined); | ||
| }); |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The current implementation updates the database with the new
apiKeyHealthbut does not mutate the in-memorycreds.providerSpecificDataobject in-place. This can lead to stale health status reads during retries or subsequent executions within the same request lifecycle if they share the same credentials reference. Mutatingpsd.apiKeyHealthin-place before callingupdateProviderConnectionensures in-memory consistency.