| 80 | * @returns 警告信息,如果不需要警告则返回 null |
| 81 | */ |
| 82 | export function shouldShowCacheWarning( |
| 83 | usage: Usage | null | undefined, |
| 84 | querySource: string, |
| 85 | threshold: number, |
| 86 | ): CacheHitRateInfo | null { |
| 87 | const hitRate = calculateCacheHitRate(usage) |
| 88 | |
| 89 | // 无缓存数据 |
| 90 | if (hitRate === null) { |
| 91 | return null |
| 92 | } |
| 93 | |
| 94 | // 获取或初始化该 querySource 的状态 |
| 95 | let state = cacheWarningStateBySource.get(querySource) |
| 96 | if (!state) { |
| 97 | state = { lastHitRate: null, lastTimestamp: null } |
| 98 | // Evict oldest entry when at capacity so the Map stays bounded |
| 99 | if (cacheWarningStateBySource.size >= MAX_SOURCE_ENTRIES) { |
| 100 | const oldestKey = cacheWarningStateBySource.keys().next().value |
| 101 | if (oldestKey !== undefined) { |
| 102 | cacheWarningStateBySource.delete(oldestKey) |
| 103 | } |
| 104 | } |
| 105 | cacheWarningStateBySource.set(querySource, state) |
| 106 | } |
| 107 | |
| 108 | // 首次请求不显示警告 |
| 109 | if (state.lastHitRate === null) { |
| 110 | state.lastHitRate = hitRate |
| 111 | state.lastTimestamp = Date.now() |
| 112 | return null |
| 113 | } |
| 114 | |
| 115 | // 计算趋势 |
| 116 | const trend = hitRate - state.lastHitRate |
| 117 | |
| 118 | // 更新状态 |
| 119 | state.lastHitRate = hitRate |
| 120 | state.lastTimestamp = Date.now() |
| 121 | |
| 122 | // 检查是否需要警告 |
| 123 | if (hitRate < threshold) { |
| 124 | return { hitRate, threshold, trend, shouldWarn: true } |
| 125 | } |
| 126 | |
| 127 | return null |
| 128 | } |
| 129 | |
| 130 | /** |
| 131 | * 生成缓存警告消息 |