(apiKey, proxy = null)
| 424 | * @returns {Promise<{hasCapacity: boolean, messagesRemaining: number, maxMessages: number}>} |
| 425 | */ |
| 426 | export async function checkMessageRateLimit(apiKey, proxy = null) { |
| 427 | const body = { metadata: buildMetadata(apiKey) }; |
| 428 | |
| 429 | const proxyModes = proxy ? [proxy, null] : [null]; |
| 430 | let lastErr = null; |
| 431 | for (const px of proxyModes) { |
| 432 | for (const host of SERVER_HOSTS) { |
| 433 | try { |
| 434 | const res = await postJson(host, RATE_LIMIT_PATH, body, px); |
| 435 | if (res.status >= 400) { |
| 436 | lastErr = new Error(`CheckRateLimit ${host} → ${res.status}: ${res.raw.slice(0, 160)}`); |
| 437 | continue; |
| 438 | } |
| 439 | return { |
| 440 | hasCapacity: res.data.hasCapacity !== false, |
| 441 | messagesRemaining: res.data.messagesRemaining ?? -1, |
| 442 | maxMessages: res.data.maxMessages ?? -1, |
| 443 | retryAfterMs: Number.isFinite(res.data.retryAfterMs) ? res.data.retryAfterMs : null, |
| 444 | }; |
| 445 | } catch (e) { |
| 446 | lastErr = e; |
| 447 | log.debug(`CheckRateLimit host ${host} failed: ${e.message}`); |
| 448 | if (px && isProxyError(e)) break; |
| 449 | } |
| 450 | } |
| 451 | } |
| 452 | // On failure, assume capacity so we don't block requests. |
| 453 | log.warn(`CheckRateLimit failed: ${lastErr?.message}`); |
| 454 | return { hasCapacity: true, messagesRemaining: -1, maxMessages: -1, retryAfterMs: null }; |
| 455 | } |
no test coverage detected