refactor(chatCore): extrai núcleo puro de persistCodexQuotaState (#3501) - #4492
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Code Review
This pull request refactors open-sse/handlers/chatCore.ts by extracting the pure logic of persistCodexQuotaState into a new helper function buildCodexQuotaPersistence in open-sse/handlers/chatCore/codexQuota.ts, accompanied by unit tests in tests/unit/chatcore-codex-quota.test.ts. The review feedback highlights two key areas for improvement: first, protecting against a potential TypeError when assigning credentials.providerSpecificData if credentials is undefined; second, enhancing the purity and determinism of buildCodexQuotaPersistence by deriving the absolute reset time directly from the quota headers instead of recalculating it using Date.now() and cooldownMs.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| }); | ||
|
|
||
| credentials.providerSpecificData = nextProviderData; | ||
| credentials.providerSpecificData = built.nextProviderData; |
There was a problem hiding this comment.
Se credentials for nulo ou indefinido, a atribuição direta a credentials.providerSpecificData lançará um TypeError e quebrará o handler da requisição. Como credentials é acessado defensivamente com encadeamento opcional (optional chaining) na linha 771, devemos também proteger esta atribuição para evitar possíveis falhas em tempo de execução.
if (credentials) {
credentials.providerSpecificData = built.nextProviderData;
}| if (status === 429) { | ||
| const { cooldownMs, window: exhaustedWindow } = getCodexDualWindowCooldownMs(quota); | ||
| if (cooldownMs > 0) { | ||
| const scopeUntil = new Date(Date.now() + cooldownMs).toISOString(); |
There was a problem hiding this comment.
Reconstruir scopeUntil adicionando Date.now() a cooldownMs introduz um pequeno desvio de relógio (clock drift) e não-determinismo, pois cooldownMs foi originalmente computado como resetTime - Date.now(). Como buildCodexQuotaPersistence deve ser uma função pura, podemos determinar o tempo de reset absoluto diretamente de quota.resetAt7d ou quota.resetAt5h com base em exhaustedWindow, recorrendo ao cálculo relativo apenas se necessário.
| const scopeUntil = new Date(Date.now() + cooldownMs).toISOString(); | |
| const resetAt = exhaustedWindow === "7d" ? quota.resetAt7d : quota.resetAt5h; | |
| const scopeUntil = resetAt ? new Date(resetAt).toISOString() : new Date(Date.now() + cooldownMs).toISOString(); |
8d357a4 to
368b433
Compare
Move a construção do payload de persistCodexQuotaState para o novo leaf puro open-sse/handlers/chatCore/codexQuota.ts (buildCodexQuotaPersistence): parseia os headers de quota do Codex no snapshot codexQuotaState, faz passthrough do providerSpecificData existente e, num 429 cuja janela (dual-window) passou do threshold de exaustão, registra o cooldown por escopo (codexScopeRateLimitedUntil) + codexExhaustedWindow, retornando a mensagem de debug-log. O handler mantém as partes impuras byte-idênticas e na mesma ordem: emitir o exhaustionLog retornado, invalidateCodexQuotaCache em todo 429 (connectionId é garantido pelo early-return), depois updateProviderConnection + mutação de credentials. Imports órfãos (parseCodexQuotaHeaders/getCodexModelScope/ getCodexDualWindowCooldownMs) migram para o leaf; isCompactResponsesEndpoint permanece (usado no site de passthrough). chatCore.ts 5055->5019 (shrink -36); baseline file-size ratchetado. complexity 1905=1905 (neutro). Coberto por tests/unit/chatcore-codex-quota.test.ts (5 casos: sem-headers null, snapshot+passthrough, 429 cooldown+janela+log, merge do scope-map, 429 abaixo-do-threshold no-op).
368b433 to
b12c80f
Compare
…uzapw#4492, diegosouzapw#3501) Rebuilt onto release/v3.8.33. Extracts persistCodexQuotaState into a pure leaf (chatCore/codexQuota.ts). Integrated into release/v3.8.33.
O quê
Próximo incremento da decomposição do god-file
chatCore.ts(QG v2 Fase 9 T5, #3501). Extrai o núcleo puro depersistCodexQuotaStatepara o novo leafopen-sse/handlers/chatCore/codexQuota.ts(buildCodexQuotaPersistence).Como (preservação de comportamento)
buildCodexQuotaPersistenceparseia os headers de quota → snapshotcodexQuotaState, faz passthrough doproviderSpecificDataexistente e, num429cuja janela (dual-window) passou do threshold de exaustão, registracodexScopeRateLimitedUntil[scope]+codexExhaustedWindow, retornando a mensagem de debug-log (em vez de emiti-la).exhaustionLogretornado →invalidateCodexQuotaCacheem todo 429 (connectionIdé garantido pelo early-return) →updateProviderConnection→ mutação decredentials.providerSpecificData.parseCodexQuotaHeaders/getCodexModelScope/getCodexDualWindowCooldownMs) migram para o leaf;isCompactResponsesEndpointpermanece (usado no site de passthrough).Gates
chatCore.ts5055→5019 (shrink −36); baseline ratchetado.tests/unit/chatcore-codex-quota.test.ts— 5 casos (sem-headers→null, snapshot+passthrough do existing data, 429 com cooldown+janela+log, merge docodexScopeRateLimitedUntilpreservando outros escopos, 429 abaixo do threshold = no-op).chatcore-imports-cleanly✓ + integração codex (executor-codex+sse-auth) 107/107 + 139/139 na suíte chatcore (excluído só otranslation-pathsflaky pré-existente).Extração de god-file sem mudança de comportamento em runtime.