Repository navigation
feat: domain layer, error codes, request ID, fetch timeout (Batch A) #24
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| // @ts-check | ||
| /** | ||
| * Combo Resolver — FASE-09 Domain Extraction (T-46) | ||
| * | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| /** | ||
| * Cost Rules — Domain Layer (T-19) | ||
| * | ||
| * Business rules for cost management: budget thresholds, | ||
| * quota checking, and cost summaries per API key. | ||
| * | ||
| * @module domain/costRules | ||
| */ | ||
|
|
||
| // @ts-check | ||
|
|
||
| /** | ||
| * @typedef {Object} BudgetConfig | ||
| * @property {number} dailyLimitUsd - Max daily spend in USD | ||
| * @property {number} [monthlyLimitUsd] - Max monthly spend in USD | ||
| * @property {number} [warningThreshold=0.8] - Alert when usage reaches this fraction | ||
| */ | ||
|
|
||
| /** | ||
| * @typedef {Object} CostEntry | ||
| * @property {number} cost - Cost in USD | ||
| * @property {number} timestamp - Unix timestamp | ||
| */ | ||
|
|
||
| /** @type {Map<string, BudgetConfig>} API key ID → budget config */ | ||
| const budgets = new Map(); | ||
|
|
||
| /** @type {Map<string, CostEntry[]>} API key ID → cost entries */ | ||
| const costHistory = new Map(); | ||
|
|
||
| /** | ||
| * Set budget for an API key. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @param {BudgetConfig} config | ||
| */ | ||
| export function setBudget(apiKeyId, config) { | ||
| budgets.set(apiKeyId, { | ||
| dailyLimitUsd: config.dailyLimitUsd, | ||
| monthlyLimitUsd: config.monthlyLimitUsd || 0, | ||
| warningThreshold: config.warningThreshold ?? 0.8, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Get budget config for an API key. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @returns {BudgetConfig | null} | ||
| */ | ||
| export function getBudget(apiKeyId) { | ||
| return budgets.get(apiKeyId) || null; | ||
| } | ||
|
|
||
| /** | ||
| * Record a cost for an API key. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @param {number} cost - Cost in USD | ||
| */ | ||
| export function recordCost(apiKeyId, cost) { | ||
| if (!costHistory.has(apiKeyId)) { | ||
| costHistory.set(apiKeyId, []); | ||
| } | ||
| costHistory.get(apiKeyId).push({ cost, timestamp: Date.now() }); | ||
| } | ||
|
Comment on lines
+61
to
+66
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The export function recordCost(apiKeyId, cost) {
if (!costHistory.has(apiKeyId)) {
costHistory.set(apiKeyId, []);
}
const entries = costHistory.get(apiKeyId);
entries.push({ cost, timestamp: Date.now() });
// Prune entries older than 31 days to prevent memory exhaustion
const thirtyOneDaysAgo = Date.now() - 31 * 24 * 60 * 60 * 1000;
while (entries.length > 0 && entries[0].timestamp < thirtyOneDaysAgo) {
entries.shift();
}
} |
||
|
|
||
| /** | ||
| * Check if an API key has remaining budget. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @param {number} [additionalCost=0] - Projected cost to check | ||
| * @returns {{ allowed: boolean, reason?: string, dailyUsed: number, dailyLimit: number, warningReached: boolean }} | ||
| */ | ||
| export function checkBudget(apiKeyId, additionalCost = 0) { | ||
| const budget = budgets.get(apiKeyId); | ||
| if (!budget) { | ||
| return { allowed: true, dailyUsed: 0, dailyLimit: 0, warningReached: false }; | ||
| } | ||
|
|
||
| const dailyUsed = getDailyTotal(apiKeyId); | ||
| const projectedTotal = dailyUsed + additionalCost; | ||
| const warningReached = projectedTotal >= budget.dailyLimitUsd * budget.warningThreshold; | ||
|
|
||
| if (projectedTotal > budget.dailyLimitUsd) { | ||
| return { | ||
| allowed: false, | ||
| reason: `Daily budget exceeded: $${projectedTotal.toFixed(4)} / $${budget.dailyLimitUsd.toFixed(2)}`, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A mensagem de motivo para um orçamento excedido formata o reason: `Daily budget exceeded: $${projectedTotal.toFixed(4)} / $${budget.dailyLimitUsd.toFixed(4)}`, |
||
| dailyUsed, | ||
| dailyLimit: budget.dailyLimitUsd, | ||
| warningReached: true, | ||
| }; | ||
| } | ||
|
|
||
| return { | ||
| allowed: true, | ||
| dailyUsed, | ||
| dailyLimit: budget.dailyLimitUsd, | ||
| warningReached, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Get daily total cost for an API key. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @returns {number} Total cost today in USD | ||
| */ | ||
| export function getDailyTotal(apiKeyId) { | ||
| const entries = costHistory.get(apiKeyId) || []; | ||
| const todayStart = new Date(); | ||
| todayStart.setHours(0, 0, 0, 0); | ||
| const startMs = todayStart.getTime(); | ||
|
Comment on lines
+111
to
+113
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. O cálculo para o início do dia ( const today = new Date();
const todayStart = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()));
const startMs = todayStart.getTime(); |
||
|
|
||
| return entries | ||
| .filter((e) => e.timestamp >= startMs) | ||
| .reduce((sum, e) => sum + e.cost, 0); | ||
| } | ||
|
Comment on lines
+109
to
+118
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A função |
||
|
|
||
| /** | ||
| * Get cost summary for an API key. | ||
| * | ||
| * @param {string} apiKeyId | ||
| * @returns {{ dailyTotal: number, monthlyTotal: number, totalEntries: number, budget: BudgetConfig | null }} | ||
| */ | ||
| export function getCostSummary(apiKeyId) { | ||
| const entries = costHistory.get(apiKeyId) || []; | ||
| const now = new Date(); | ||
|
|
||
| const todayStart = new Date(now); | ||
| todayStart.setHours(0, 0, 0, 0); | ||
|
|
||
| const monthStart = new Date(now.getFullYear(), now.getMonth(), 1); | ||
|
Comment on lines
+130
to
+133
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. O cálculo para o início do dia ( const todayStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
const monthStart = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); |
||
|
|
||
| const dailyTotal = entries | ||
| .filter((e) => e.timestamp >= todayStart.getTime()) | ||
| .reduce((sum, e) => sum + e.cost, 0); | ||
|
|
||
| const monthlyTotal = entries | ||
| .filter((e) => e.timestamp >= monthStart.getTime()) | ||
| .reduce((sum, e) => sum + e.cost, 0); | ||
|
|
||
| return { | ||
| dailyTotal, | ||
| monthlyTotal, | ||
| totalEntries: entries.length, | ||
| budget: budgets.get(apiKeyId) || null, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Clear all cost data (for testing). | ||
| */ | ||
| export function resetCostData() { | ||
| budgets.clear(); | ||
| costHistory.clear(); | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| /** | ||
| * Fallback Policy — Domain Layer (T-19) | ||
| * | ||
| * Declarative fallback chain for model routing. | ||
| * When a primary provider is unavailable, the policy engine | ||
| * resolves to alternative providers in priority order. | ||
| * | ||
| * @module domain/fallbackPolicy | ||
| */ | ||
|
|
||
| // @ts-check | ||
|
|
||
| /** | ||
| * @typedef {Object} FallbackEntry | ||
| * @property {string} provider - Provider ID | ||
| * @property {number} [priority=0] - Lower = higher priority | ||
| * @property {boolean} [enabled=true] - Whether this fallback is active | ||
| */ | ||
|
|
||
| /** @type {Map<string, FallbackEntry[]>} model → fallback chain */ | ||
| const fallbackChains = new Map(); | ||
|
|
||
| /** | ||
| * Register a fallback chain for a model. | ||
| * | ||
| * @param {string} model - Model identifier (e.g. "gpt-4o") | ||
| * @param {FallbackEntry[]} chain - Ordered list of fallback providers | ||
| */ | ||
| export function registerFallback(model, chain) { | ||
| const sorted = [...chain] | ||
| .map((e) => ({ | ||
| provider: e.provider, | ||
| priority: e.priority ?? 0, | ||
| enabled: e.enabled ?? true, | ||
| })) | ||
| .sort((a, b) => a.priority - b.priority); | ||
|
|
||
| fallbackChains.set(model, sorted); | ||
| } | ||
|
|
||
| /** | ||
| * Resolve the fallback chain for a model. | ||
| * Returns only enabled providers, sorted by priority. | ||
| * | ||
| * @param {string} model | ||
| * @param {string[]} [excludeProviders=[]] - Providers to skip (e.g. already tried) | ||
| * @returns {FallbackEntry[]} Ordered list of fallback providers | ||
| */ | ||
| export function resolveFallbackChain(model, excludeProviders = []) { | ||
| const chain = fallbackChains.get(model); | ||
| if (!chain) return []; | ||
|
|
||
| const excludeSet = new Set(excludeProviders); | ||
| return chain.filter((e) => e.enabled && !excludeSet.has(e.provider)); | ||
| } | ||
|
|
||
| /** | ||
| * Get the next provider in the fallback chain. | ||
| * | ||
| * @param {string} model | ||
| * @param {string[]} [excludeProviders=[]] | ||
| * @returns {string | null} Next provider ID or null if chain exhausted | ||
| */ | ||
| export function getNextFallback(model, excludeProviders = []) { | ||
| const chain = resolveFallbackChain(model, excludeProviders); | ||
| return chain.length > 0 ? chain[0].provider : null; | ||
| } | ||
|
|
||
| /** | ||
| * Check if a model has any fallback providers configured. | ||
| * | ||
| * @param {string} model | ||
| * @returns {boolean} | ||
| */ | ||
| export function hasFallback(model) { | ||
| const chain = fallbackChains.get(model); | ||
| return !!chain && chain.some((e) => e.enabled); | ||
| } | ||
|
|
||
| /** | ||
| * Remove a fallback chain for a model. | ||
| * | ||
| * @param {string} model | ||
| * @returns {boolean} true if removed | ||
| */ | ||
| export function removeFallback(model) { | ||
| return fallbackChains.delete(model); | ||
| } | ||
|
|
||
| /** | ||
| * Get all registered fallback chains (for dashboard). | ||
| * | ||
| * @returns {Record<string, FallbackEntry[]>} | ||
| */ | ||
| export function getAllFallbackChains() { | ||
| const result = {}; | ||
| for (const [model, chain] of fallbackChains.entries()) { | ||
| result[model] = chain; | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Reset all fallback chains (for testing). | ||
| */ | ||
| export function resetAllFallbacks() { | ||
| fallbackChains.clear(); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| // @ts-check | ||
| /** | ||
| * Lockout Policy — FASE-09 Domain Extraction (T-46) | ||
| * | ||
|
|
||
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
costHistoryMap accumulates cost entries indefinitely without any cleanup mechanism. In a long-running application, this could lead to unbounded memory growth. Consider implementing periodic cleanup of old entries (e.g., entries older than 30 days) or a maximum size limit with eviction of oldest entries. ThegetDailyTotalandgetCostSummaryfunctions only need recent data, so older entries could be safely removed.