@cartanova/qgrid-cli 2.21.0 → 2.22.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +5 -4
- package/README.md +5 -4
- package/bundle/dist/application/monit/monit.frame.js +1 -1
- package/bundle/dist/application/qgrid/expired-token-reminder.js +1 -1
- package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
- package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -3
- package/bundle/dist/application/qgrid/qgrid.frame.js +130 -24
- package/bundle/dist/application/qgrid/qgrid.types.js +205 -2
- package/bundle/dist/application/qgrid/token-death.js +1 -1
- package/bundle/dist/application/qgrid/token-window-keepalive.js +1 -1
- package/bundle/dist/application/request-log/request-log.model.js +2 -2
- package/bundle/dist/application/sonamu.generated.js +5 -3
- package/bundle/dist/i18n/en.js +2 -1
- package/bundle/dist/i18n/ko.js +2 -1
- package/bundle/dist/i18n/sd.generated.js +3 -2
- package/bundle/dist/sonamu.config.js +2 -2
- package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +1 -1
- package/bundle/dist/utils/providers/common/model-cost.js +15 -2
- package/bundle/dist/utils/providers/grok/grok-dispatcher.js +2 -2
- package/bundle/dist/utils/providers/openai/openai-backend-protocol.js +6 -2
- package/bundle/dist/utils/providers/openai/openai-decisions.js +178 -0
- package/bundle/dist/utils/providers/openai/openai-dispatcher.js +61 -677
- package/bundle/dist/utils/providers/openai/openai-image-generation.js +1 -1
- package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +1 -1
- package/bundle/dist/utils/providers/openai/openai-refresh.js +2 -2
- package/bundle/dist/utils/providers/openai/openai-responses-runtime.js +430 -0
- package/bundle/dist/utils/providers/openai/openai-token-pool.js +291 -0
- package/bundle/dist/utils/providers/openai/openai-voice-client.js +2 -6
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
- package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +2 -1
- package/bundle/src/application/qgrid/qgrid.dispatcher.ts +2 -4
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +100 -1
- package/bundle/src/application/qgrid/qgrid.frame.ts +146 -7
- package/bundle/src/application/qgrid/qgrid.types.ts +242 -0
- package/bundle/src/application/request-log/request-log.entity.json +3 -2
- package/bundle/src/application/sonamu.generated.http +31 -0
- package/bundle/src/application/sonamu.generated.ts +2 -1
- package/bundle/src/i18n/en.ts +1 -0
- package/bundle/src/i18n/ko.ts +1 -0
- package/bundle/src/i18n/sd.generated.ts +2 -1
- package/bundle/src/utils/providers/common/model-cost.ts +20 -0
- package/bundle/src/utils/providers/openai/openai-backend-protocol.ts +5 -0
- package/bundle/src/utils/providers/openai/openai-decisions.test.ts +240 -0
- package/bundle/src/utils/providers/openai/openai-decisions.ts +266 -0
- package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +133 -7
- package/bundle/src/utils/providers/openai/openai-dispatcher.ts +90 -1083
- package/bundle/src/utils/providers/openai/openai-responses-runtime.ts +677 -0
- package/bundle/src/utils/providers/openai/openai-token-pool.ts +481 -0
- package/bundle/src/utils/providers/openai/openai-voice-client.ts +0 -5
- package/bundle/web-dist/client/assets/{index-NGqKa5_C.js → index-BSjyOyOc.js} +17 -17
- package/bundle/web-dist/client/assets/{logs-BLhlxqoB.js → logs-CFyeyR7u.js} +1 -1
- package/bundle/web-dist/client/assets/{monit-C3stGFEK.js → monit-N3gBNCXy.js} +1 -1
- package/bundle/web-dist/client/assets/{routes-Dgh-_yS5.js → routes-UbYa5WQL.js} +1 -1
- package/bundle/web-dist/client/assets/{settings-DiOZwvRj.js → settings-CTZGAJjl.js} +1 -1
- package/bundle/web-dist/client/assets/{show-DucEoTrr.js → show-oNGv2jAJ.js} +2 -2
- package/bundle/web-dist/client/assets/{tokens-DvCT1bbk.js → tokens-BrhEjJ3t.js} +1 -1
- package/bundle/web-dist/client/assets/{use-oauth-login-flow-DazQfaBL.js → use-oauth-login-flow-Ca1Sn84P.js} +1 -1
- package/bundle/web-dist/client/assets/{use-update-token-mutation-CfGbUel6.js → use-update-token-mutation-DMy7Pw8U.js} +1 -1
- package/bundle/web-dist/client/assets/{voice-zPre2iO8.js → voice-CVXYbgBN.js} +1 -1
- package/bundle/web-dist/client/index.html +1 -1
- package/bundle/web-dist/server/assets/{TimedPlayer-CcClBzGi.js → TimedPlayer-mpJpP5tQ.js} +1 -1
- package/bundle/web-dist/server/assets/{logs-CxAwuDKc.js → logs-CFa_xamY.js} +6 -3
- package/bundle/web-dist/server/assets/{monit-Bl2kSkSF.js → monit-BF6osfj5.js} +2 -2
- package/bundle/web-dist/server/assets/{plus-CQ8AHpih.js → plus-DwQFfeid.js} +1 -1
- package/bundle/web-dist/server/assets/{refresh-cw-pYSuvt4c.js → refresh-cw-Bj-Jxeb6.js} +1 -1
- package/bundle/web-dist/server/assets/{request-model-ZulJMbGm.js → request-model-D_iYrudl.js} +1 -1
- package/bundle/web-dist/server/assets/{routes-W-pd1Hps.js → routes-B6be8sJP.js} +3 -3
- package/bundle/web-dist/server/assets/{services.generated-C3b31_vt.js → services.generated-D0995hJr.js} +14 -2
- package/bundle/web-dist/server/assets/{settings-CFdTg1_f.js → settings-DAle7AgI.js} +3 -3
- package/bundle/web-dist/server/assets/{show-DVEIHsXh.js → show-BTSdMDoM.js} +4 -4
- package/bundle/web-dist/server/assets/{tokens-BO1hyBuB.js → tokens-Bc9flfLz.js} +4 -4
- package/bundle/web-dist/server/assets/{use-oauth-login-flow-CCc8LEmn.js → use-oauth-login-flow-C7c0gCjf.js} +1 -1
- package/bundle/web-dist/server/assets/{use-update-token-mutation-Ba-sEhq1.js → use-update-token-mutation-DLJDGdxu.js} +1 -1
- package/bundle/web-dist/server/assets/{voice-BCF-Pkzo.js → voice-CEQT57xZ.js} +2 -2
- package/bundle/web-dist/server/entry-server.generated.js +214 -10
- package/package.json +1 -1
- package/skills/qgrid/SKILL.md +2 -2
- package/skills/qgrid/references/ai-sdk-provider-contract.md +10 -0
- package/skills/qgrid/references/cli-env-and-server-boot.md +2 -3
- package/skills/qgrid/references/decision-rationale.md +9 -3
- package/skills/qgrid/references/openai-codex-runtime.md +9 -2
- package/skills/qgrid/references/provider-runtime-differences.md +2 -2
- package/skills/qgrid/references/request-log-run-lifecycle.md +5 -3
- package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
- package/skills/qgrid/references/token-auth-quota-lifecycle.md +5 -3
- package/skills/qgrid/references/verification-and-debugging.md +3 -3
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
|
|
3
|
+
import { getLogger } from "@logtape/logtape";
|
|
4
|
+
|
|
5
|
+
import { QuotaThresholdExceededError } from "../../../application/qgrid/qgrid.types";
|
|
6
|
+
import { TokenModel } from "../../../application/token/token.model";
|
|
7
|
+
import { type OpenAICredentials } from "../../../application/token/token.types";
|
|
8
|
+
import { isOpenAICredentials } from "../common/credentials";
|
|
9
|
+
import { type MediaDispatchResult, type MediaTokenSelection } from "../common/provider-dispatcher";
|
|
10
|
+
import { SmoothWeightedRoundRobin } from "../common/smooth-weighted-round-robin";
|
|
11
|
+
import { isOpenAIUnauthorizedError } from "./openai-backend-protocol";
|
|
12
|
+
import { type OpenAIDirectCredentials } from "./openai-direct-client";
|
|
13
|
+
import { readOpenAIQuotaUsage, type OpenAIRateLimitsWithMeta } from "./openai-quota";
|
|
14
|
+
import { handleChatgptAuthTokensRefresh } from "./openai-refresh";
|
|
15
|
+
|
|
16
|
+
// Same category as before the dispatcher split, so log filters keep matching.
|
|
17
|
+
const logger = getLogger(["qgrid", "openai-dispatcher"]);
|
|
18
|
+
|
|
19
|
+
export type TokenMetadata = {
|
|
20
|
+
name: string;
|
|
21
|
+
credentials: OpenAICredentials;
|
|
22
|
+
quotaThreshold?: number | null;
|
|
23
|
+
weight: number;
|
|
24
|
+
active: boolean;
|
|
25
|
+
generation: number;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type TokenSelection = { tokenId: number; metadata: TokenMetadata };
|
|
29
|
+
|
|
30
|
+
function quotaMessage(entries: Array<{ name: string; threshold: number }>): string {
|
|
31
|
+
const detail = entries.map((e) => `${e.name} (threshold ${e.threshold}%)`).join(", ");
|
|
32
|
+
|
|
33
|
+
return detail
|
|
34
|
+
? `All openai tokens exceeded quota threshold: ${detail}`
|
|
35
|
+
: "All openai tokens exceeded quota threshold";
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The OpenAI subscription tokens every OpenAI API surface shares: weighted selection behind the
|
|
40
|
+
* quota-threshold gate, rate-limit lookups, and OAuth refresh. Listeners registered with
|
|
41
|
+
* `onTokenInvalidated` run when a token's credentials stop being usable (refreshed or removed), so
|
|
42
|
+
* transports can drop clients built from them.
|
|
43
|
+
*/
|
|
44
|
+
export class OpenAITokenPool {
|
|
45
|
+
readonly tokenMetadata = new Map<number, TokenMetadata>();
|
|
46
|
+
readonly rateLimitsCache = new Map<number, OpenAIRateLimitsWithMeta & { generation: number }>();
|
|
47
|
+
readonly pendingRateLimits = new Map<
|
|
48
|
+
number,
|
|
49
|
+
{ token: TokenMetadata; generation: number; promise: Promise<OpenAIRateLimitsWithMeta> }
|
|
50
|
+
>();
|
|
51
|
+
static readonly RATE_LIMITS_CACHE_TTL = 60_000;
|
|
52
|
+
|
|
53
|
+
readonly selector = new SmoothWeightedRoundRobin();
|
|
54
|
+
readonly quotaBlocked = new Set<number>();
|
|
55
|
+
readonly invalidationListeners: Array<(tokenId: number) => void> = [];
|
|
56
|
+
|
|
57
|
+
constructor(readonly fetchImpl: typeof fetch) {}
|
|
58
|
+
|
|
59
|
+
onTokenInvalidated(listener: (tokenId: number) => void): void {
|
|
60
|
+
this.invalidationListeners.push(listener);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
notifyTokenInvalidated(tokenId: number): void {
|
|
64
|
+
for (const listener of this.invalidationListeners) listener(tokenId);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Loads the active OpenAI tokens from the database. */
|
|
68
|
+
async load(): Promise<void> {
|
|
69
|
+
// Not `findMany`: its default page holds 24 rows across every provider.
|
|
70
|
+
const rows = await TokenModel.findActiveByProvider("A", "openai");
|
|
71
|
+
|
|
72
|
+
for (const row of rows) {
|
|
73
|
+
if (!isOpenAICredentials(row.credentials)) {
|
|
74
|
+
logger.warn(`skipping token ${row.name}: credentials are not OpenAI OAuth credentials`);
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
this.setToken(row.id, row.name, row.credentials, row.quota_threshold, row.weight, row.active);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
logger.info(`started direct OpenAI runtime with ${this.tokenMetadata.size} tokens`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Forgets every token. In-flight rate-limit lookups are left to finish, as before. */
|
|
85
|
+
clear(): void {
|
|
86
|
+
this.tokenMetadata.clear();
|
|
87
|
+
this.rateLimitsCache.clear();
|
|
88
|
+
this.quotaBlocked.clear();
|
|
89
|
+
this.selector.resetScores();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Selects a token, runs one non-Responses call (realtime voice, Decisions), and on one 401
|
|
94
|
+
* refreshes that token's credentials and retries once (as the Responses transports do). Any
|
|
95
|
+
* other failure propagates: a failed call may already have consumed tokens.
|
|
96
|
+
*/
|
|
97
|
+
async runWithToken<T>(
|
|
98
|
+
selection: MediaTokenSelection,
|
|
99
|
+
signal: AbortSignal | undefined,
|
|
100
|
+
call: (credentials: OpenAIDirectCredentials) => Promise<T>,
|
|
101
|
+
// Voice sessions re-read quota after each call. Decisions runs at high frequency, so it keeps
|
|
102
|
+
// the cached lookup (60 s TTL) like Responses does.
|
|
103
|
+
options: { refreshQuota: boolean } = { refreshQuota: true },
|
|
104
|
+
): Promise<MediaDispatchResult<T>> {
|
|
105
|
+
const active = signal ?? new AbortController().signal;
|
|
106
|
+
|
|
107
|
+
const selected = await this.selectToken(
|
|
108
|
+
selection.preferredTokenId,
|
|
109
|
+
selection.requirePreferredToken ?? false,
|
|
110
|
+
active,
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
const { tokenId, metadata } = selected;
|
|
114
|
+
|
|
115
|
+
let credentials: OpenAIDirectCredentials = {
|
|
116
|
+
accessToken: metadata.credentials.accessToken,
|
|
117
|
+
accountId: metadata.credentials.accountId,
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
for (let attempt = 0; ; attempt++) {
|
|
121
|
+
try {
|
|
122
|
+
const result = await call(credentials);
|
|
123
|
+
|
|
124
|
+
if (options.refreshQuota) this.invalidateRateLimitsCache(tokenId);
|
|
125
|
+
|
|
126
|
+
return { result, tokenId, tokenName: metadata.name };
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (attempt === 0 && error instanceof Error && isOpenAIUnauthorizedError(error)) {
|
|
129
|
+
credentials = await this.refreshCredentials(tokenId);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async onTokenAdded(
|
|
139
|
+
id: number,
|
|
140
|
+
name: string,
|
|
141
|
+
credentials: OpenAICredentials,
|
|
142
|
+
quotaThreshold?: number | null,
|
|
143
|
+
weight = 1,
|
|
144
|
+
): Promise<void> {
|
|
145
|
+
this.setToken(id, name, credentials, quotaThreshold, weight, true);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async onTokenUpdated(
|
|
149
|
+
id: number,
|
|
150
|
+
name: string,
|
|
151
|
+
credentials: OpenAICredentials,
|
|
152
|
+
quotaThreshold?: number | null,
|
|
153
|
+
weight = 1,
|
|
154
|
+
): Promise<void> {
|
|
155
|
+
const old = this.tokenMetadata.get(id);
|
|
156
|
+
this.setToken(id, name, credentials, quotaThreshold, weight, old?.active ?? true);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async onTokenRemoved(id: number): Promise<void> {
|
|
160
|
+
this.notifyTokenInvalidated(id);
|
|
161
|
+
this.tokenMetadata.delete(id);
|
|
162
|
+
this.selector.removeToken(id);
|
|
163
|
+
this.invalidateRateLimitsCache(id);
|
|
164
|
+
this.quotaBlocked.delete(id);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
onTokenDeactivated(id: number): void {
|
|
168
|
+
const token = this.tokenMetadata.get(id);
|
|
169
|
+
|
|
170
|
+
if (token) token.active = false;
|
|
171
|
+
this.selector.resetScores();
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
onTokenActivated(id: number): void {
|
|
175
|
+
const token = this.tokenMetadata.get(id);
|
|
176
|
+
|
|
177
|
+
if (token) token.active = true;
|
|
178
|
+
this.selector.resetScores();
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async replaceTokens(
|
|
182
|
+
rows: Array<{
|
|
183
|
+
id: number;
|
|
184
|
+
name: string;
|
|
185
|
+
credentials: OpenAICredentials;
|
|
186
|
+
quotaThreshold?: number | null;
|
|
187
|
+
weight: number;
|
|
188
|
+
}>,
|
|
189
|
+
): Promise<void> {
|
|
190
|
+
const ids = new Set(rows.map((r) => r.id));
|
|
191
|
+
|
|
192
|
+
for (const id of this.tokenMetadata.keys()) if (!ids.has(id)) await this.onTokenRemoved(id);
|
|
193
|
+
|
|
194
|
+
// Rows are the active tokens: unlike `onTokenUpdated`, this re-activates a token whose
|
|
195
|
+
// re-activation NOTIFY was missed.
|
|
196
|
+
for (const row of rows) {
|
|
197
|
+
this.setToken(row.id, row.name, row.credentials, row.quotaThreshold, row.weight, true);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 선호 토큰이 quota를 통과하면 다른 토큰 조회와 weighted 상태 변경을 생략한다.
|
|
202
|
+
async selectToken(
|
|
203
|
+
preferredTokenId: number | undefined,
|
|
204
|
+
requirePreferredToken: boolean,
|
|
205
|
+
signal: AbortSignal,
|
|
206
|
+
): Promise<TokenSelection> {
|
|
207
|
+
if (preferredTokenId !== undefined) {
|
|
208
|
+
const preferred = this.tokenMetadata.get(preferredTokenId);
|
|
209
|
+
|
|
210
|
+
if (preferred?.active && (await this.isQuotaEligible(preferredTokenId, preferred, signal))) {
|
|
211
|
+
return { tokenId: preferredTokenId, metadata: preferred };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (requirePreferredToken) {
|
|
215
|
+
if (!preferred?.active) {
|
|
216
|
+
throw new Error(`Preferred openai token ${preferredTokenId} is not available`);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const threshold = preferred.quotaThreshold;
|
|
220
|
+
|
|
221
|
+
if (threshold !== null && threshold !== undefined) {
|
|
222
|
+
throw new QuotaThresholdExceededError(
|
|
223
|
+
quotaMessage([{ name: preferred.name, threshold }]),
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// 콜드 캐시에서 토큰 수만큼 조회 지연이 쌓이지 않도록 병렬 판정한다.
|
|
230
|
+
const activeTokens = [...this.tokenMetadata.entries()].filter(([, token]) => token.active);
|
|
231
|
+
|
|
232
|
+
const checks = await Promise.all(
|
|
233
|
+
activeTokens.map(async ([id, token]) => ({
|
|
234
|
+
id,
|
|
235
|
+
token,
|
|
236
|
+
eligible: await this.isQuotaEligible(id, token, signal),
|
|
237
|
+
})),
|
|
238
|
+
);
|
|
239
|
+
|
|
240
|
+
const eligible = new Set(checks.filter((c) => c.eligible).map((c) => c.id));
|
|
241
|
+
|
|
242
|
+
if (eligible.size === 0) {
|
|
243
|
+
const over = checks.flatMap((c) => {
|
|
244
|
+
const threshold = c.token.quotaThreshold;
|
|
245
|
+
|
|
246
|
+
return c.eligible || threshold === null || threshold === undefined
|
|
247
|
+
? []
|
|
248
|
+
: [{ name: c.token.name, threshold }];
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
if (over.length) {
|
|
252
|
+
logger.warn("quota_threshold gate: all_exceeded", {
|
|
253
|
+
provider: "openai",
|
|
254
|
+
overThresholdTokens: over,
|
|
255
|
+
});
|
|
256
|
+
throw new QuotaThresholdExceededError(quotaMessage(over));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
throw new Error("NO_OPENAI_WORKERS");
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
const selected = this.selector.select(eligible);
|
|
263
|
+
const metadata = selected !== null ? this.tokenMetadata.get(selected) : undefined;
|
|
264
|
+
|
|
265
|
+
if (selected === null || !metadata) throw new Error("NO_OPENAI_WORKERS");
|
|
266
|
+
|
|
267
|
+
return { tokenId: selected, metadata };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
setToken(
|
|
271
|
+
id: number,
|
|
272
|
+
name: string,
|
|
273
|
+
credentials: OpenAICredentials,
|
|
274
|
+
quotaThreshold: number | null | undefined,
|
|
275
|
+
weight: number,
|
|
276
|
+
active: boolean,
|
|
277
|
+
): void {
|
|
278
|
+
const old = this.tokenMetadata.get(id);
|
|
279
|
+
|
|
280
|
+
// The periodic reconcile re-sends every token. An unchanged one keeps its generation, so its
|
|
281
|
+
// Responses client, quota cache, and over-threshold state survive.
|
|
282
|
+
if (
|
|
283
|
+
old &&
|
|
284
|
+
old.name === name &&
|
|
285
|
+
old.weight === weight &&
|
|
286
|
+
old.active === active &&
|
|
287
|
+
(old.quotaThreshold ?? null) === (quotaThreshold ?? null) &&
|
|
288
|
+
isDeepStrictEqual(old.credentials, credentials)
|
|
289
|
+
) {
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (old) {
|
|
294
|
+
Object.assign(old, {
|
|
295
|
+
name,
|
|
296
|
+
credentials,
|
|
297
|
+
quotaThreshold,
|
|
298
|
+
weight,
|
|
299
|
+
active,
|
|
300
|
+
generation: old.generation + 1,
|
|
301
|
+
});
|
|
302
|
+
} else {
|
|
303
|
+
this.tokenMetadata.set(id, {
|
|
304
|
+
name,
|
|
305
|
+
credentials,
|
|
306
|
+
quotaThreshold,
|
|
307
|
+
weight,
|
|
308
|
+
active,
|
|
309
|
+
generation: 1,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
this.selector.setToken(id, weight);
|
|
314
|
+
this.invalidateRateLimitsCache(id);
|
|
315
|
+
this.quotaBlocked.delete(id);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async getRateLimitsByTokenId(
|
|
319
|
+
tokenId: number,
|
|
320
|
+
signal?: AbortSignal,
|
|
321
|
+
): Promise<OpenAIRateLimitsWithMeta> {
|
|
322
|
+
const token = this.tokenMetadata.get(tokenId);
|
|
323
|
+
|
|
324
|
+
if (!token) throw new Error(`openai token ${tokenId} not found`);
|
|
325
|
+
const generation = token.generation;
|
|
326
|
+
const cached = this.rateLimitsCache.get(tokenId);
|
|
327
|
+
|
|
328
|
+
if (
|
|
329
|
+
cached &&
|
|
330
|
+
cached.generation === token.generation &&
|
|
331
|
+
Date.now() - cached.cachedAt < OpenAITokenPool.RATE_LIMITS_CACHE_TTL
|
|
332
|
+
)
|
|
333
|
+
return cached;
|
|
334
|
+
|
|
335
|
+
// TTL 만료 시 조회를 공유한다. 최초 호출자의 abort로 실패해도 isQuotaEligible은 fail-open한다.
|
|
336
|
+
const pending = this.pendingRateLimits.get(tokenId);
|
|
337
|
+
|
|
338
|
+
if (pending?.token === token && pending.generation === generation) return pending.promise;
|
|
339
|
+
|
|
340
|
+
const fetchPromise = (async () => {
|
|
341
|
+
const result = await readOpenAIQuotaUsage({
|
|
342
|
+
credentials: token.credentials,
|
|
343
|
+
refreshCredentials: () => this.refreshCredentials(tokenId),
|
|
344
|
+
fetch: this.fetchImpl,
|
|
345
|
+
signal,
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
if (result.kind === "lookup_failed") throw new Error(result.reason);
|
|
349
|
+
|
|
350
|
+
if (!result.raw) throw new Error("OpenAI quota response missing raw rate limits");
|
|
351
|
+
const entry = { data: result.raw, cachedAt: Date.now(), generation };
|
|
352
|
+
|
|
353
|
+
if (this.tokenMetadata.get(tokenId) === token && token.generation === generation) {
|
|
354
|
+
this.rateLimitsCache.set(tokenId, entry);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
return entry;
|
|
358
|
+
})().finally(() => {
|
|
359
|
+
if (this.pendingRateLimits.get(tokenId)?.promise === fetchPromise) {
|
|
360
|
+
this.pendingRateLimits.delete(tokenId);
|
|
361
|
+
}
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
this.pendingRateLimits.set(tokenId, { token, generation, promise: fetchPromise });
|
|
365
|
+
|
|
366
|
+
return fetchPromise;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async refreshCredentials(tokenId: number) {
|
|
370
|
+
const previous = this.tokenMetadata.get(tokenId);
|
|
371
|
+
const generation = previous?.generation;
|
|
372
|
+
const refreshed = await handleChatgptAuthTokensRefresh(tokenId);
|
|
373
|
+
|
|
374
|
+
const credentials = {
|
|
375
|
+
accessToken: refreshed.accessToken,
|
|
376
|
+
accountId: refreshed.chatgptAccountId,
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
const current = this.tokenMetadata.get(tokenId);
|
|
380
|
+
|
|
381
|
+
if (!current?.active) throw new Error(`openai token ${tokenId} is no longer active`);
|
|
382
|
+
|
|
383
|
+
// A subscriber update may already contain newer credentials. Never overwrite it
|
|
384
|
+
// with the result of a refresh that started against an older generation.
|
|
385
|
+
if (current === previous && current.generation === generation) {
|
|
386
|
+
current.credentials = { ...current.credentials, ...credentials };
|
|
387
|
+
this.notifyTokenInvalidated(tokenId);
|
|
388
|
+
this.invalidateRateLimitsCache(tokenId);
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return {
|
|
392
|
+
accessToken: current.credentials.accessToken,
|
|
393
|
+
accountId: current.credentials.accountId,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async isQuotaEligible(id: number, token: TokenMetadata, signal?: AbortSignal): Promise<boolean> {
|
|
398
|
+
if (token.quotaThreshold === null || token.quotaThreshold === undefined) return true;
|
|
399
|
+
const generation = token.generation;
|
|
400
|
+
const result = await readOpenAIQuotaUsage(async () => this.getRateLimitsByTokenId(id, signal));
|
|
401
|
+
const current = this.tokenMetadata.get(id);
|
|
402
|
+
|
|
403
|
+
// A token update (credential refresh, sync) landed mid-lookup: judge the updated token
|
|
404
|
+
// instead of reporting it over quota.
|
|
405
|
+
if (current !== token || token.generation !== generation) {
|
|
406
|
+
return current?.active ? this.isQuotaEligible(id, current, signal) : false;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (result.kind === "lookup_failed") {
|
|
410
|
+
this.quotaBlocked.delete(id);
|
|
411
|
+
logger.warn("quota_threshold gate: lookup_fail_open", {
|
|
412
|
+
tokenId: id,
|
|
413
|
+
tokenName: token.name,
|
|
414
|
+
lookupReason: result.reason,
|
|
415
|
+
});
|
|
416
|
+
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
if (result.utilizationPct >= token.quotaThreshold) {
|
|
421
|
+
if (!this.quotaBlocked.has(id))
|
|
422
|
+
logger.info(
|
|
423
|
+
`quota_threshold gate: over_threshold ${token.name}[${id}] (${result.utilizationPct}% >= ${token.quotaThreshold}%)`,
|
|
424
|
+
);
|
|
425
|
+
this.quotaBlocked.add(id);
|
|
426
|
+
|
|
427
|
+
return false;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (this.quotaBlocked.delete(id))
|
|
431
|
+
logger.info(
|
|
432
|
+
`quota_threshold gate: recovered ${token.name}[${id}] (${result.utilizationPct}% < ${token.quotaThreshold}%)`,
|
|
433
|
+
);
|
|
434
|
+
|
|
435
|
+
return true;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
invalidateRateLimitsCache(id: number): void {
|
|
439
|
+
this.rateLimitsCache.delete(id);
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
countActiveTokens(): number {
|
|
443
|
+
return [...this.tokenMetadata.values()].filter((t) => t.active).length;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// 모니터링 폴링은 TTL 내 캐시만 읽고 fetch하지 않는다. 미조회 토큰은 usedPercent가 null이다.
|
|
447
|
+
getQuotaSnapshot(): Array<{
|
|
448
|
+
name: string;
|
|
449
|
+
usedPercent: number | null;
|
|
450
|
+
threshold: number | null;
|
|
451
|
+
blocked: boolean;
|
|
452
|
+
resetsAt: number | null;
|
|
453
|
+
}> {
|
|
454
|
+
const now = Date.now();
|
|
455
|
+
|
|
456
|
+
return [...this.tokenMetadata.entries()]
|
|
457
|
+
.map(([id, t]) => {
|
|
458
|
+
const cached = this.rateLimitsCache.get(id);
|
|
459
|
+
|
|
460
|
+
const fresh =
|
|
461
|
+
cached !== undefined &&
|
|
462
|
+
cached.generation === t.generation &&
|
|
463
|
+
now - cached.cachedAt < OpenAITokenPool.RATE_LIMITS_CACHE_TTL;
|
|
464
|
+
|
|
465
|
+
const primary = fresh ? cached.data.rateLimits?.primary : undefined;
|
|
466
|
+
|
|
467
|
+
return {
|
|
468
|
+
name: t.name,
|
|
469
|
+
usedPercent: primary?.usedPercent ?? null,
|
|
470
|
+
threshold: t.quotaThreshold ?? null,
|
|
471
|
+
blocked: this.quotaBlocked.has(id),
|
|
472
|
+
// wham의 Unix 초를 epoch ms로 변환한다.
|
|
473
|
+
resetsAt:
|
|
474
|
+
primary?.resetsAt !== null && primary?.resetsAt !== undefined
|
|
475
|
+
? primary.resetsAt * 1000
|
|
476
|
+
: null,
|
|
477
|
+
};
|
|
478
|
+
})
|
|
479
|
+
.toSorted((a, b) => a.name.localeCompare(b.name));
|
|
480
|
+
}
|
|
481
|
+
}
|
|
@@ -1014,10 +1014,5 @@ export function isSidebandTeardownError(error: Error): boolean {
|
|
|
1014
1014
|
);
|
|
1015
1015
|
}
|
|
1016
1016
|
|
|
1017
|
-
/** Used by the dispatcher's single 401 → refresh → retry step. */
|
|
1018
|
-
export function isUnauthorizedRealtimeError(error: Error): boolean {
|
|
1019
|
-
return error instanceof OpenAIProtocolError && error.status === 401;
|
|
1020
|
-
}
|
|
1021
|
-
|
|
1022
1017
|
/** Event schema export for tests that replay captured server traffic. */
|
|
1023
1018
|
export { realtimeServerEvent };
|