mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): add per-pool cycle filter and harden weekly reset anchors
- Add a compact inline quota-pool selector on ConsumptionView when Cycle is active, pre-bundling per-pool cycle slices for instant switching and scoping range labels in exports - Classify >6h clientModelConfigs resetTime fallbacks as weekly anchors and advance usageRevision when official reset windows arrive or shift - Deduplicate same-day and same-month date span badges (e.g. Nov 24, Nov 24 ~ 25)
This commit is contained in:
@@ -258,8 +258,10 @@ export async function executeTelemetryAction(data, opts = {}) {
|
||||
rawScope === 'conversation'
|
||||
? rawScope
|
||||
: '';
|
||||
const rawPool = typeof data?.pool === 'string' ? data.pool.trim().slice(0, 48) : '';
|
||||
const filterOpts = {
|
||||
range: data?.range || 'all',
|
||||
...(rawPool ? { pool: rawPool } : {}),
|
||||
startMs: sanitizePositiveFiniteMs(data?.startMs),
|
||||
endMs: sanitizePositiveFiniteMs(data?.endMs),
|
||||
...(scope ? { scope } : {}),
|
||||
|
||||
@@ -370,9 +370,14 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) {
|
||||
}
|
||||
|
||||
const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo, nowForQuotaMs);
|
||||
const cfgResetMs = parseIsoMs(cfgQuota?.resetTime);
|
||||
const isCfgWeekly =
|
||||
targetIdent.poolKey === 'Argon' ||
|
||||
targetIdent.poolKey === 'Carbon' ||
|
||||
cfgResetMs > nowForQuotaMs + 6 * 3600 * 1000;
|
||||
if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) {
|
||||
if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') {
|
||||
builder.bucketWeekly = cfgQuota;
|
||||
if (isCfgWeekly) {
|
||||
builder.bucketWeekly = { ...cfgQuota, window: 'weekly' };
|
||||
} else {
|
||||
builder.fallback5h = cfgQuota;
|
||||
}
|
||||
|
||||
@@ -2382,6 +2382,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
revision: usageRevision,
|
||||
selectedRange: {
|
||||
key: selectedWindow.key,
|
||||
...(selectedWindow.pool ? { pool: selectedWindow.pool } : {}),
|
||||
...(selectedWindow.poolLabel ? { poolLabel: selectedWindow.poolLabel } : {}),
|
||||
...(selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
|
||||
label: selectedWindow.label,
|
||||
startMs: trendStartMs,
|
||||
endMs: trendEndMs,
|
||||
@@ -2802,6 +2805,9 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
|
||||
revision: agg.usageRevision,
|
||||
selectedRange: {
|
||||
key: agg.selectedWindow.key,
|
||||
...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}),
|
||||
...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}),
|
||||
...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
|
||||
label: agg.selectedWindow.label,
|
||||
startMs: agg.trendStartMs,
|
||||
endMs: agg.trendEndMs,
|
||||
@@ -2969,7 +2975,7 @@ export function buildTelemetryPayload(
|
||||
}
|
||||
}
|
||||
}
|
||||
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
|
||||
const rangeSig = `${filterOpts.range || 'all'}:${filterOpts.pool || 'all'}:${filterOpts.startMs || 0}:${filterOpts.endMs || 0}`;
|
||||
const key = `${endpointKey}::${requestedConvId || '__auto__'}::${forceQuotaRefresh ? 'force' : 'normal'}::${rangeSig}`;
|
||||
if (inFlightRequests.has(key)) {
|
||||
return inFlightRequests.get(key);
|
||||
|
||||
@@ -786,13 +786,14 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
|
||||
? Math.min(nowMs, reset5hMs - 5 * 3600 * 1000)
|
||||
: nowMs - 5 * 3600 * 1000;
|
||||
const resetWkMs = parseIsoMs(poolObj?.weeklyResetTime) || 0;
|
||||
const startWkMs =
|
||||
resetWkMs > nowMs
|
||||
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
|
||||
: weekFallbackStartMs;
|
||||
const hasOfficialWk = resetWkMs > nowMs;
|
||||
const startWkMs = hasOfficialWk
|
||||
? Math.min(nowMs, resetWkMs - 7 * 24 * 3600 * 1000)
|
||||
: weekFallbackStartMs;
|
||||
poolCycleBuckets.set(poolKey, {
|
||||
start5hMs,
|
||||
startWkMs,
|
||||
hasOfficialWk,
|
||||
b5h: createUsageBucket(),
|
||||
bWk: createUsageBucket(),
|
||||
pricedTokens5h: 0,
|
||||
@@ -809,7 +810,27 @@ function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
|
||||
return poolCycleBuckets;
|
||||
}
|
||||
|
||||
function resolvePoolBucketForStep(
|
||||
export function normalizeCyclePoolFilter(rawPool, availablePoolKeys = null) {
|
||||
const raw = typeof rawPool === 'string' ? rawPool.trim() : '';
|
||||
if (!raw || raw.toLowerCase() === 'all') return 'all';
|
||||
const lower = raw.toLowerCase();
|
||||
let canonical = raw;
|
||||
if (lower === 'gemini') canonical = 'Gemini';
|
||||
else if (lower === 'argon' || lower === 'gemini 4 argon') canonical = 'Argon';
|
||||
else if (lower === 'carbon' || lower === 'gemini 4 carbon') canonical = 'Carbon';
|
||||
else if (lower === 'claude & gpt' || lower === 'claude' || lower === 'gpt') {
|
||||
canonical = 'Claude & GPT';
|
||||
}
|
||||
if (availablePoolKeys && availablePoolKeys.size > 0 && !availablePoolKeys.has(canonical)) {
|
||||
for (const k of availablePoolKeys.keys()) {
|
||||
if (String(k).toLowerCase() === lower) return k;
|
||||
}
|
||||
return 'all';
|
||||
}
|
||||
return canonical;
|
||||
}
|
||||
|
||||
function resolveStepPoolAssignment(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
@@ -817,7 +838,6 @@ function resolvePoolBucketForStep(
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
) {
|
||||
if (poolCycleBuckets.size === 0) return null;
|
||||
let cachedPool = poolByModel.get(mInfo);
|
||||
if (
|
||||
!cachedPool ||
|
||||
@@ -841,11 +861,68 @@ function resolvePoolBucketForStep(
|
||||
key: st.modelKey,
|
||||
response: st.responseModel,
|
||||
displayName: st.modelDisplayName,
|
||||
bucket: poolCycleBuckets.get(poolKey) || null,
|
||||
poolKey,
|
||||
bucket: poolKey && poolCycleBuckets.size > 0 ? poolCycleBuckets.get(poolKey) || null : null,
|
||||
};
|
||||
poolByModel.set(mInfo, cachedPool);
|
||||
}
|
||||
return cachedPool.bucket;
|
||||
return cachedPool;
|
||||
}
|
||||
|
||||
function resolveEffectiveSelectedCycleWindow({
|
||||
selectedWindow,
|
||||
effectiveCyclePool = 'all',
|
||||
isCustomWeeklyMode = false,
|
||||
cycleAnchors = {},
|
||||
nowMs = Date.now(),
|
||||
poolCycleBuckets,
|
||||
quotaPoolsMap = null,
|
||||
earliestActiveCyclePoolStartMs = Infinity,
|
||||
earliestSelectedStepMs = Infinity,
|
||||
}) {
|
||||
if (!selectedWindow || selectedWindow.key !== 'cycle') return selectedWindow;
|
||||
if (effectiveCyclePool !== 'all') {
|
||||
const poolBucket = poolCycleBuckets?.get?.(effectiveCyclePool) || null;
|
||||
const poolMeta = quotaPoolsMap instanceof Map ? quotaPoolsMap.get(effectiveCyclePool) : null;
|
||||
const poolLabel = poolMeta?.poolLabel || effectiveCyclePool;
|
||||
const baseStartMs =
|
||||
!isCustomWeeklyMode && poolBucket ? poolBucket.startWkMs : selectedWindow.startMs;
|
||||
const startMs =
|
||||
Number.isFinite(earliestSelectedStepMs) && earliestSelectedStepMs < Infinity
|
||||
? Math.min(baseStartMs, earliestSelectedStepMs)
|
||||
: baseStartMs;
|
||||
const isFallbackWeek = !isCustomWeeklyMode && !poolBucket?.hasOfficialWk;
|
||||
return {
|
||||
...selectedWindow,
|
||||
pool: effectiveCyclePool,
|
||||
poolLabel,
|
||||
isFallbackWeek,
|
||||
label: `${isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期'} · ${poolLabel}`,
|
||||
startMs,
|
||||
};
|
||||
}
|
||||
let hasAnyOfficialWk = !isCustomWeeklyMode && (cycleAnchors?.weeklyResetMs || 0) > nowMs;
|
||||
if (!hasAnyOfficialWk && poolCycleBuckets instanceof Map) {
|
||||
for (const b of poolCycleBuckets.values()) {
|
||||
if (b?.hasOfficialWk) {
|
||||
hasAnyOfficialWk = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const isFallbackWeek = !isCustomWeeklyMode && !hasAnyOfficialWk;
|
||||
const startMs =
|
||||
Number.isFinite(earliestActiveCyclePoolStartMs) && earliestActiveCyclePoolStartMs < Infinity
|
||||
? Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs)
|
||||
: selectedWindow.startMs;
|
||||
return {
|
||||
...selectedWindow,
|
||||
pool: 'all',
|
||||
poolLabel: '',
|
||||
isFallbackWeek,
|
||||
label: isCustomWeeklyMode || isFallbackWeek ? '本周' : '当前周期',
|
||||
startMs,
|
||||
};
|
||||
}
|
||||
|
||||
function buildUsageTrendSeries(
|
||||
@@ -1155,6 +1232,7 @@ function computeFamilySessionBuckets({
|
||||
presetKeys = [],
|
||||
presetWindows = {},
|
||||
selectedWindow,
|
||||
effectiveCyclePool = 'all',
|
||||
isCustomWeeklyMode = false,
|
||||
poolCycleBuckets = new Map(),
|
||||
normalizedQuotaAccount = '',
|
||||
@@ -1166,8 +1244,11 @@ function computeFamilySessionBuckets({
|
||||
for (const k of presetKeys) {
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
const isScopedCyclePool = selectedWindow?.key === 'cycle' && effectiveCyclePool !== 'all';
|
||||
const selectedSessionBucket =
|
||||
(selectedWindow?.key && sessionBuckets[selectedWindow.key]) || createUsageBucket();
|
||||
selectedWindow?.key && !isScopedCyclePool && sessionBuckets[selectedWindow.key]
|
||||
? sessionBuckets[selectedWindow.key]
|
||||
: createUsageBucket();
|
||||
if (!(familySet instanceof Set) || familySet.size === 0) {
|
||||
const sessionPresets = {};
|
||||
for (const k of presetKeys) {
|
||||
@@ -1233,17 +1314,15 @@ function computeFamilySessionBuckets({
|
||||
unpriced,
|
||||
};
|
||||
|
||||
const poolBucketEntry =
|
||||
poolCycleBuckets.size > 0
|
||||
? resolvePoolBucketForStep(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
poolByModel,
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
)
|
||||
: null;
|
||||
const stepPool = resolveStepPoolAssignment(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
poolByModel,
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
);
|
||||
const poolBucketEntry = stepPool.bucket;
|
||||
|
||||
let inCurrentCycle = false;
|
||||
if (qMs > 0 && qMs <= nowMs) {
|
||||
@@ -1273,14 +1352,19 @@ function computeFamilySessionBuckets({
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedWindow && (!sessionBuckets[selectedWindow.key] || selectedWindow.key === 'custom')) {
|
||||
if (
|
||||
selectedWindow &&
|
||||
(!sessionBuckets[selectedWindow.key] ||
|
||||
selectedWindow.key === 'custom' ||
|
||||
isScopedCyclePool)
|
||||
) {
|
||||
const selCmpMs =
|
||||
selectedWindow.key === '5h' || selectedWindow.key === 'week' ? qMs : tMs;
|
||||
const inSelectedWindow =
|
||||
selectedWindow.key === 'all'
|
||||
? true
|
||||
: selectedWindow.key === 'cycle'
|
||||
? inCurrentCycle
|
||||
? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
|
||||
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
|
||||
if (inSelectedWindow) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, entry.cascadeId);
|
||||
@@ -1407,16 +1491,30 @@ export function aggregateMultiWindowUsage({
|
||||
sessionBuckets[k] = createUsageBucket();
|
||||
}
|
||||
|
||||
// 为每个配额池建立独立的 5h 与周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
|
||||
// 为每个配额池建立独立的 5h 及周限周期统计桶(按各池自身的 resetTime / weeklyResetTime 截取窗口)
|
||||
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
|
||||
const effectiveCyclePool =
|
||||
selectedWindow.key === 'cycle'
|
||||
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
|
||||
: 'all';
|
||||
const isScopedCyclePool = selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all';
|
||||
const selectedRangeCacheKey = isScopedCyclePool
|
||||
? `cycle:${effectiveCyclePool}`
|
||||
: selectedWindow.key;
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const poolByModel = new Map();
|
||||
const quotaWeekBucket = createUsageBucket();
|
||||
const normalizedQuotaAccount =
|
||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedAccountBucket =
|
||||
!isScopedCyclePool && accountBuckets[selectedWindow.key]
|
||||
? accountBuckets[selectedWindow.key]
|
||||
: createUsageBucket();
|
||||
const selectedSessionBucket =
|
||||
!isScopedCyclePool && sessionBuckets[selectedWindow.key]
|
||||
? sessionBuckets[selectedWindow.key]
|
||||
: createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const perConvStats = new Map();
|
||||
const perWorkspaceStats = new Map();
|
||||
@@ -1463,15 +1561,31 @@ export function aggregateMultiWindowUsage({
|
||||
modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
||||
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
||||
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedRangeCacheKey) : null;
|
||||
if (previous) {
|
||||
// 时钟继续前进,只有实际有步骤跨过窗口边界时才重新聚合。
|
||||
const probeEffectiveWin =
|
||||
selectedWindow.key === 'cycle'
|
||||
? resolveEffectiveSelectedCycleWindow({
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
cycleAnchors,
|
||||
nowMs,
|
||||
poolCycleBuckets,
|
||||
quotaPoolsMap,
|
||||
earliestActiveCyclePoolStartMs: previous.earliestActiveCyclePoolStartMs,
|
||||
earliestSelectedStepMs: previous.earliest,
|
||||
})
|
||||
: selectedWindow;
|
||||
const effectivePrevWin =
|
||||
selectedWindow.key === 'cycle' && previous.effectiveSelectedWindow
|
||||
? { ...previous.effectiveSelectedWindow, endMs: nowMs }
|
||||
? { ...probeEffectiveWin, endMs: nowMs }
|
||||
: selectedWindow;
|
||||
const trend = planUsageTrend(effectivePrevWin, nowMs, previous.earliest, previous.latest);
|
||||
if (
|
||||
Boolean(effectivePrevWin.isFallbackWeek) ===
|
||||
Boolean(previous.effectiveSelectedWindow?.isFallbackWeek) &&
|
||||
trend.hourly === previous.trend.hourly &&
|
||||
trend.stepMs === previous.trend.stepMs &&
|
||||
trend.first === previous.trend.first &&
|
||||
@@ -1483,8 +1597,8 @@ export function aggregateMultiWindowUsage({
|
||||
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
|
||||
)
|
||||
) {
|
||||
snapshot.ranges.delete(selectedWindow.key);
|
||||
snapshot.ranges.set(selectedWindow.key, previous);
|
||||
snapshot.ranges.delete(selectedRangeCacheKey);
|
||||
snapshot.ranges.set(selectedRangeCacheKey, previous);
|
||||
if (previous.familySig === familySig) {
|
||||
return {
|
||||
...previous.result,
|
||||
@@ -1501,6 +1615,7 @@ export function aggregateMultiWindowUsage({
|
||||
presetKeys,
|
||||
presetWindows,
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
@@ -1588,7 +1703,7 @@ export function aggregateMultiWindowUsage({
|
||||
}
|
||||
}
|
||||
|
||||
const poolBucketEntry = resolvePoolBucketForStep(
|
||||
const stepPool = resolveStepPoolAssignment(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
@@ -1596,6 +1711,7 @@ export function aggregateMultiWindowUsage({
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
);
|
||||
const poolBucketEntry = stepPool.bucket;
|
||||
|
||||
if (includeInQuotaPools && poolBucketEntry && qMs > 0 && qMs <= nowMs) {
|
||||
if (qMs > poolBucketEntry.lastActivityMs) {
|
||||
@@ -1691,7 +1807,7 @@ export function aggregateMultiWindowUsage({
|
||||
selectedWindow.key === 'all'
|
||||
? true
|
||||
: selectedWindow.key === 'cycle'
|
||||
? inCurrentCycle
|
||||
? inCurrentCycle && (effectiveCyclePool === 'all' || stepPool.poolKey === effectiveCyclePool)
|
||||
: selCmpMs > 0 && selCmpMs >= selectedWindow.startMs && selCmpMs <= selectedWindow.endMs;
|
||||
|
||||
if (inSelectedWindow) {
|
||||
@@ -1703,7 +1819,7 @@ export function aggregateMultiWindowUsage({
|
||||
) {
|
||||
earliestActiveCyclePoolStartMs = poolBucketEntry.startWkMs;
|
||||
}
|
||||
if (selectedWindow.key === 'custom') {
|
||||
if (selectedWindow.key === 'custom' || isScopedCyclePool) {
|
||||
accumulateStepIntoBucket(selectedAccountBucket, stepUsage, cascadeId);
|
||||
if (isCurrentConv) {
|
||||
accumulateStepIntoBucket(selectedSessionBucket, stepUsage, cascadeId);
|
||||
@@ -1785,15 +1901,17 @@ export function aggregateMultiWindowUsage({
|
||||
);
|
||||
|
||||
// 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries)
|
||||
const effectiveSelectedWindow =
|
||||
selectedWindow.key === 'cycle' &&
|
||||
Number.isFinite(earliestActiveCyclePoolStartMs) &&
|
||||
earliestActiveCyclePoolStartMs < Infinity
|
||||
? {
|
||||
...selectedWindow,
|
||||
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs),
|
||||
}
|
||||
: selectedWindow;
|
||||
const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
cycleAnchors,
|
||||
nowMs,
|
||||
poolCycleBuckets,
|
||||
quotaPoolsMap,
|
||||
earliestActiveCyclePoolStartMs,
|
||||
earliestSelectedStepMs,
|
||||
});
|
||||
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
|
||||
selectedWindow,
|
||||
effectiveSelectedWindow,
|
||||
@@ -1929,6 +2047,11 @@ export function aggregateMultiWindowUsage({
|
||||
if (oldestKey !== undefined) lastUsageSnapshotsByEndpoint.delete(oldestKey);
|
||||
}
|
||||
lastUsageSnapshotsByEndpoint.set(endpointKey, activeSnap);
|
||||
} else if (previous) {
|
||||
resolvedUsageRevision = ++usageSnapshotRevisionSeq;
|
||||
activeSnap.revision = resolvedUsageRevision;
|
||||
activeSnap.ranges.clear();
|
||||
activeSnap.selectedRanges?.clear?.();
|
||||
} else {
|
||||
resolvedUsageRevision = activeSnap.revision;
|
||||
}
|
||||
@@ -1959,19 +2082,20 @@ export function aggregateMultiWindowUsage({
|
||||
};
|
||||
if (modelInputs && activeSnap) {
|
||||
const { ranges } = activeSnap;
|
||||
ranges.delete(selectedWindow.key);
|
||||
ranges.set(selectedWindow.key, {
|
||||
ranges.delete(selectedRangeCacheKey);
|
||||
ranges.set(selectedRangeCacheKey, {
|
||||
familySig,
|
||||
windows,
|
||||
selectedWindow,
|
||||
effectiveSelectedWindow,
|
||||
earliestActiveCyclePoolStartMs,
|
||||
trend,
|
||||
result,
|
||||
earliest: earliestSelectedStepMs,
|
||||
latest: latestSelectedStepMs,
|
||||
});
|
||||
// 缓存各时间窗口的完整多窗口聚合结果,同快照复用时亚毫秒命中。
|
||||
if (ranges.size > 10) ranges.delete(ranges.keys().next().value);
|
||||
if (ranges.size > 16) ranges.delete(ranges.keys().next().value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -2019,6 +2143,14 @@ export function aggregateSelectedWindowUsage({
|
||||
: 0;
|
||||
const poolCycleBuckets =
|
||||
selectedWindow.key === 'cycle' ? buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) : new Map();
|
||||
const effectiveCyclePool =
|
||||
selectedWindow.key === 'cycle'
|
||||
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
|
||||
: 'all';
|
||||
const selectedRangeCacheKey =
|
||||
selectedWindow.key === 'cycle' && effectiveCyclePool !== 'all'
|
||||
? `cycle:${effectiveCyclePool}`
|
||||
: selectedWindow.key;
|
||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||
const poolByModel = new Map();
|
||||
@@ -2032,6 +2164,19 @@ export function aggregateSelectedWindowUsage({
|
||||
const currentYear = new Date(nowMs).getFullYear();
|
||||
const timeZone = modelInputs ? resolveCachedLocalTimeZone() : '';
|
||||
|
||||
const currentCheckWindows =
|
||||
selectedWindow.key === 'cycle'
|
||||
? [
|
||||
selectedWindow,
|
||||
...Array.from(poolCycleBuckets, ([key, { startWkMs }]) => ({
|
||||
key: `${key}:week`,
|
||||
label: `${key}:week`,
|
||||
startMs: startWkMs,
|
||||
endMs: nowMs,
|
||||
})),
|
||||
]
|
||||
: [selectedWindow];
|
||||
|
||||
const snapshot = lastUsageSnapshotsByEndpoint.get(endpointKey) || null;
|
||||
const sameSnapshot = Boolean(
|
||||
modelInputs &&
|
||||
@@ -2047,24 +2192,45 @@ export function aggregateSelectedWindowUsage({
|
||||
|
||||
if (sameSnapshot) {
|
||||
snapshot.selectedRanges ??= new Map();
|
||||
const cachedFull = snapshot.ranges.get(selectedWindow.key);
|
||||
const cachedLite = snapshot.selectedRanges.get(selectedWindow.key);
|
||||
const cachedFull = snapshot.ranges.get(selectedRangeCacheKey);
|
||||
const cachedLite = snapshot.selectedRanges.get(selectedRangeCacheKey);
|
||||
const candidate = cachedFull || cachedLite;
|
||||
if (candidate) {
|
||||
const prevWin = candidate.selectedWindow || candidate.windows?.[0] || selectedWindow;
|
||||
const probeEffectiveWin =
|
||||
selectedWindow.key === 'cycle'
|
||||
? resolveEffectiveSelectedCycleWindow({
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
cycleAnchors,
|
||||
nowMs,
|
||||
poolCycleBuckets,
|
||||
quotaPoolsMap,
|
||||
earliestActiveCyclePoolStartMs: candidate.earliestActiveCyclePoolStartMs,
|
||||
earliestSelectedStepMs: candidate.earliest,
|
||||
})
|
||||
: selectedWindow;
|
||||
const effectivePrevWin =
|
||||
selectedWindow.key === 'cycle' && candidate.effectiveSelectedWindow
|
||||
? { ...candidate.effectiveSelectedWindow, endMs: nowMs }
|
||||
? { ...probeEffectiveWin, endMs: nowMs }
|
||||
: selectedWindow;
|
||||
const trend = planUsageTrend(effectivePrevWin, nowMs, candidate.earliest, candidate.latest);
|
||||
const prevCheckWindows = candidate.checkWindows || [prevWin];
|
||||
const compareNextWindows =
|
||||
prevCheckWindows.length === currentCheckWindows.length
|
||||
? currentCheckWindows
|
||||
: [selectedWindow];
|
||||
if (
|
||||
Boolean(effectivePrevWin.isFallbackWeek) ===
|
||||
Boolean(candidate.effectiveSelectedWindow?.isFallbackWeek) &&
|
||||
trend.hourly === candidate.trend.hourly &&
|
||||
trend.stepMs === candidate.trend.stepMs &&
|
||||
trend.first === candidate.trend.first &&
|
||||
trend.last === candidate.trend.last &&
|
||||
sameUsageWindows(
|
||||
[prevWin],
|
||||
[selectedWindow],
|
||||
prevCheckWindows.length === compareNextWindows.length ? prevCheckWindows : [prevWin],
|
||||
compareNextWindows,
|
||||
(snapshot.dates ??= sortedUsageTimestamps(allEntriesToAggregate)),
|
||||
(snapshot.quotaDates ??= sortedQuotaBillingTimestamps(allEntriesToAggregate, nowMs))
|
||||
)
|
||||
@@ -2079,6 +2245,7 @@ export function aggregateSelectedWindowUsage({
|
||||
presetKeys: [],
|
||||
presetWindows: {},
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
@@ -2100,6 +2267,9 @@ export function aggregateSelectedWindowUsage({
|
||||
topWorkspaces: res.topWorkspaces || [],
|
||||
};
|
||||
}
|
||||
snapshot.revision = ++usageSnapshotRevisionSeq;
|
||||
snapshot.ranges.clear();
|
||||
snapshot.selectedRanges.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2115,6 +2285,11 @@ export function aggregateSelectedWindowUsage({
|
||||
maxCutoffMs = nowMs;
|
||||
if (isCustomWeeklyMode) {
|
||||
minCutoffMs = weekStartMs;
|
||||
} else if (effectiveCyclePool !== 'all' && poolCycleBuckets.has(effectiveCyclePool)) {
|
||||
minCutoffMs = Math.max(
|
||||
0,
|
||||
poolCycleBuckets.get(effectiveCyclePool).startWkMs - maxSettlementSlackMs
|
||||
);
|
||||
} else if (poolCycleBuckets.size > 0) {
|
||||
minCutoffMs = selectedWindow.startMs;
|
||||
for (const entry of poolCycleBuckets.values()) {
|
||||
@@ -2190,20 +2365,24 @@ export function aggregateSelectedWindowUsage({
|
||||
: normalizedQuotaAccount === '' || stepOwner === ''
|
||||
? true
|
||||
: stepOwner === normalizedQuotaAccount;
|
||||
mInfo = resolveStepModel(st);
|
||||
const stepPool = resolveStepPoolAssignment(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
poolByModel,
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
);
|
||||
poolBucketEntry = stepPool.bucket;
|
||||
if (effectiveCyclePool !== 'all' && stepPool.poolKey !== effectiveCyclePool) {
|
||||
continue;
|
||||
}
|
||||
let inCurrentCycle = false;
|
||||
if (isCustomWeeklyMode) {
|
||||
inCurrentCycle = tMs >= weekStartMs;
|
||||
} else if (poolCycleBuckets.size > 0) {
|
||||
if (!includeInQuotaPools) continue;
|
||||
mInfo = resolveStepModel(st);
|
||||
poolBucketEntry = resolvePoolBucketForStep(
|
||||
st,
|
||||
mInfo,
|
||||
poolCycleBuckets,
|
||||
poolByModel,
|
||||
hasDedicatedCarbonPool,
|
||||
hasDedicatedArgonPool
|
||||
);
|
||||
const effCycleStartMs = poolBucketEntry
|
||||
? poolBucketEntry.startWkMs
|
||||
: selectedWindow.startMs;
|
||||
@@ -2320,15 +2499,17 @@ export function aggregateSelectedWindowUsage({
|
||||
}
|
||||
}
|
||||
|
||||
const effectiveSelectedWindow =
|
||||
selectedWindow.key === 'cycle' &&
|
||||
Number.isFinite(earliestActiveCyclePoolStartMs) &&
|
||||
earliestActiveCyclePoolStartMs < Infinity
|
||||
? {
|
||||
...selectedWindow,
|
||||
startMs: Math.min(earliestActiveCyclePoolStartMs, earliestSelectedStepMs),
|
||||
}
|
||||
: selectedWindow;
|
||||
const effectiveSelectedWindow = resolveEffectiveSelectedCycleWindow({
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
cycleAnchors,
|
||||
nowMs,
|
||||
poolCycleBuckets,
|
||||
quotaPoolsMap,
|
||||
earliestActiveCyclePoolStartMs,
|
||||
earliestSelectedStepMs,
|
||||
});
|
||||
|
||||
const { trend, trendStartMs, trendEndMs, trendSeries } = buildUsageTrendSeries(
|
||||
selectedWindow,
|
||||
@@ -2369,17 +2550,19 @@ export function aggregateSelectedWindowUsage({
|
||||
|
||||
if (sameSnapshot) {
|
||||
snapshot.selectedRanges ??= new Map();
|
||||
snapshot.selectedRanges.delete(selectedWindow.key);
|
||||
snapshot.selectedRanges.set(selectedWindow.key, {
|
||||
snapshot.selectedRanges.delete(selectedRangeCacheKey);
|
||||
snapshot.selectedRanges.set(selectedRangeCacheKey, {
|
||||
familySig,
|
||||
checkWindows: currentCheckWindows,
|
||||
selectedWindow,
|
||||
effectiveSelectedWindow,
|
||||
earliestActiveCyclePoolStartMs,
|
||||
trend,
|
||||
result: sliceResult,
|
||||
earliest: earliestSelectedStepMs,
|
||||
latest: latestSelectedStepMs,
|
||||
});
|
||||
if (snapshot.selectedRanges.size > 12) {
|
||||
if (snapshot.selectedRanges.size > 16) {
|
||||
snapshot.selectedRanges.delete(snapshot.selectedRanges.keys().next().value);
|
||||
}
|
||||
}
|
||||
@@ -2426,6 +2609,10 @@ export function aggregateSessionUsageForFamily({
|
||||
presetWindows[k] = resolveTimeWindow(k, 0, 0, nowMs, cycleAnchors, isCustomWeeklyMode);
|
||||
}
|
||||
const poolCycleBuckets = buildQuotaPoolCycleMap(quotaPoolsMap, nowMs);
|
||||
const effectiveCyclePool =
|
||||
selectedWindow.key === 'cycle'
|
||||
? normalizeCyclePoolFilter(filterOpts.pool, poolCycleBuckets)
|
||||
: 'all';
|
||||
const normalizedQuotaAccount =
|
||||
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||
|
||||
@@ -2464,6 +2651,7 @@ export function aggregateSessionUsageForFamily({
|
||||
presetKeys,
|
||||
presetWindows,
|
||||
selectedWindow,
|
||||
effectiveCyclePool,
|
||||
isCustomWeeklyMode,
|
||||
poolCycleBuckets,
|
||||
normalizedQuotaAccount,
|
||||
@@ -2473,7 +2661,7 @@ export function aggregateSessionUsageForFamily({
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量预聚合全部 7 个用量页预设区间(复用同一次条目收集与时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
||||
* 批量预聚合全部 7 个用量页预设区间及各配额池独立周期(复用同一次条目收集和时间剪枝),供前端进入「用量统计」时静默预取实现 0ms 瞬切。
|
||||
*/
|
||||
export function aggregateConsumptionPresetBundle(params) {
|
||||
const { activeCascadeId = null, activeFamilyCascadeIds = null, endpoint = null } = params || {};
|
||||
@@ -2488,6 +2676,25 @@ export function aggregateConsumptionPresetBundle(params) {
|
||||
const ranges = {};
|
||||
let usageRevision = usageSnapshotRevisionSeq;
|
||||
|
||||
const packSlice = (agg) => ({
|
||||
selectedRange: {
|
||||
key: agg.selectedWindow.key,
|
||||
...(agg.selectedWindow.pool ? { pool: agg.selectedWindow.pool } : {}),
|
||||
...(agg.selectedWindow.poolLabel ? { poolLabel: agg.selectedWindow.poolLabel } : {}),
|
||||
...(agg.selectedWindow.isFallbackWeek ? { isFallbackWeek: true } : {}),
|
||||
label: agg.selectedWindow.label,
|
||||
startMs: agg.trendStartMs,
|
||||
endMs: agg.trendEndMs,
|
||||
},
|
||||
session: agg.finalizedSelectedSession,
|
||||
account: agg.finalizedSelectedAccount,
|
||||
trendSeries: agg.trendSeries,
|
||||
sourcesBreakdown: agg.sourcesBreakdown,
|
||||
modelBreakdown: agg.modelBreakdown,
|
||||
topConversations: agg.topConversations || [],
|
||||
topWorkspaces: agg.topWorkspaces || [],
|
||||
});
|
||||
|
||||
for (const rangeKey of CONSUMPTION_PRESET_RANGE_KEYS) {
|
||||
const agg = aggregateSelectedWindowUsage({
|
||||
...params,
|
||||
@@ -2495,21 +2702,20 @@ export function aggregateConsumptionPresetBundle(params) {
|
||||
precollectedEntries,
|
||||
});
|
||||
usageRevision = agg.usageRevision;
|
||||
ranges[rangeKey] = {
|
||||
selectedRange: {
|
||||
key: agg.selectedWindow.key,
|
||||
label: agg.selectedWindow.label,
|
||||
startMs: agg.trendStartMs,
|
||||
endMs: agg.trendEndMs,
|
||||
},
|
||||
session: agg.finalizedSelectedSession,
|
||||
account: agg.finalizedSelectedAccount,
|
||||
trendSeries: agg.trendSeries,
|
||||
sourcesBreakdown: agg.sourcesBreakdown,
|
||||
modelBreakdown: agg.modelBreakdown,
|
||||
topConversations: agg.topConversations || [],
|
||||
topWorkspaces: agg.topWorkspaces || [],
|
||||
};
|
||||
ranges[rangeKey] = packSlice(agg);
|
||||
}
|
||||
|
||||
if (params?.quotaPoolsMap instanceof Map) {
|
||||
for (const poolKey of params.quotaPoolsMap.keys()) {
|
||||
if (!poolKey || poolKey === 'all') continue;
|
||||
const agg = aggregateSelectedWindowUsage({
|
||||
...params,
|
||||
filterOpts: { range: 'cycle', pool: poolKey },
|
||||
precollectedEntries,
|
||||
});
|
||||
usageRevision = agg.usageRevision;
|
||||
ranges[`cycle:${poolKey}`] = packSlice(agg);
|
||||
}
|
||||
}
|
||||
|
||||
return { usageRevision, ranges };
|
||||
|
||||
Reference in New Issue
Block a user