|
| 1 | +import { IBaseComponent } from '@well-known-components/interfaces' |
| 2 | +import { AppComponents, ThirdPartyProvider } from '../types' |
| 3 | + |
| 4 | +export type ThirdPartyCollectionsCacheWarmer = IBaseComponent & { |
| 5 | + warmCache(): Promise<void> |
| 6 | + getStatus(): CacheWarmerStatus |
| 7 | +} |
| 8 | + |
| 9 | +export type CacheWarmerStatus = { |
| 10 | + enabled: boolean |
| 11 | + lastWarmupTime?: number |
| 12 | + lastWarmupDuration?: number |
| 13 | + collectionsWarmed: number |
| 14 | + totalCollections: number |
| 15 | + errors: string[] |
| 16 | + isWarming: boolean |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Cache warmer component that pre-loads third-party collections into cache |
| 21 | + * on service boot and periodically refreshes them. |
| 22 | + * |
| 23 | + * This eliminates the cold-start penalty where the first user to request |
| 24 | + * a collection triggers expensive pagination across thousands of entities. |
| 25 | + */ |
| 26 | +export async function createThirdPartyCollectionsCacheWarmer( |
| 27 | + components: Pick<AppComponents, 'config' | 'logs' | 'thirdPartyProvidersStorage' | 'entitiesFetcher'> |
| 28 | +): Promise<ThirdPartyCollectionsCacheWarmer> { |
| 29 | + const { config, logs, thirdPartyProvidersStorage, entitiesFetcher } = components |
| 30 | + const logger = logs.getLogger('third-party-collections-cache-warmer') |
| 31 | + |
| 32 | + // Configuration |
| 33 | + const enabled = (await config.getString('CACHE_WARMER_ENABLED'))?.toLowerCase() === 'true' || false |
| 34 | + const warmupIntervalMs = (await config.getNumber('CACHE_WARMER_INTERVAL_MS')) || 1000 * 60 * 60 * 24 // 24 hours default |
| 35 | + const warmupDelayMs = (await config.getNumber('CACHE_WARMER_DELAY_MS')) || 5000 // 5 seconds delay after boot |
| 36 | + const maxConcurrent = (await config.getNumber('CACHE_WARMER_MAX_CONCURRENT')) || 3 // Warm 3 collections in parallel |
| 37 | + |
| 38 | + // State |
| 39 | + let intervalId: ReturnType<typeof setInterval> | undefined |
| 40 | + let isWarming = false |
| 41 | + const status: CacheWarmerStatus = { |
| 42 | + enabled, |
| 43 | + collectionsWarmed: 0, |
| 44 | + totalCollections: 0, |
| 45 | + errors: [], |
| 46 | + isWarming: false |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Warm a single collection by fetching all its entities |
| 51 | + */ |
| 52 | + async function warmCollection(provider: ThirdPartyProvider): Promise<void> { |
| 53 | + const collectionId = provider.id |
| 54 | + const providerName = provider.metadata?.thirdParty?.name || 'unknown' |
| 55 | + const startTime = Date.now() |
| 56 | + |
| 57 | + try { |
| 58 | + logger.info('[warmCollection] Starting cache warm', { |
| 59 | + collectionId, |
| 60 | + providerName |
| 61 | + }) |
| 62 | + |
| 63 | + // Fetch all entities - this will populate the 48h cache |
| 64 | + const entities = await entitiesFetcher.fetchCollectionEntities(collectionId) |
| 65 | + const duration = Date.now() - startTime |
| 66 | + |
| 67 | + logger.info('[warmCollection] Collection warmed successfully', { |
| 68 | + collectionId, |
| 69 | + providerName, |
| 70 | + entitiesCount: entities.length, |
| 71 | + durationMs: duration |
| 72 | + }) |
| 73 | + |
| 74 | + // Record metric (TODO: Uncomment when metrics are properly configured) |
| 75 | + // metrics.increment('cache_warmer_collections_warmed_total', { collection: providerName }) |
| 76 | + // metrics.observe('cache_warmer_duration_seconds', duration / 1000, { collection: providerName }) |
| 77 | + |
| 78 | + status.collectionsWarmed++ |
| 79 | + } catch (error) { |
| 80 | + const duration = Date.now() - startTime |
| 81 | + const errorMsg = error instanceof Error ? error.message : 'Unknown error' |
| 82 | + |
| 83 | + logger.error('[warmCollection] Failed to warm collection', { |
| 84 | + collectionId, |
| 85 | + providerName, |
| 86 | + error: errorMsg, |
| 87 | + durationMs: duration |
| 88 | + }) |
| 89 | + |
| 90 | + status.errors.push(`${collectionId}: ${errorMsg}`) |
| 91 | + |
| 92 | + // Record error metric (TODO: Uncomment when metrics are properly configured) |
| 93 | + // metrics.increment('cache_warmer_errors_total', { collection: providerName }) |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + /** |
| 98 | + * Warm collections in batches with concurrency control |
| 99 | + */ |
| 100 | + async function warmCollectionsInBatches(providers: ThirdPartyProvider[]): Promise<void> { |
| 101 | + const batches: ThirdPartyProvider[][] = [] |
| 102 | + |
| 103 | + // Split providers into batches |
| 104 | + for (let i = 0; i < providers.length; i += maxConcurrent) { |
| 105 | + batches.push(providers.slice(i, i + maxConcurrent)) |
| 106 | + } |
| 107 | + |
| 108 | + logger.info('[warmCollectionsInBatches] Processing batches', { |
| 109 | + totalProviders: providers.length, |
| 110 | + batchCount: batches.length, |
| 111 | + maxConcurrent |
| 112 | + }) |
| 113 | + |
| 114 | + // Process each batch sequentially, but items within batch in parallel |
| 115 | + for (let i = 0; i < batches.length; i++) { |
| 116 | + const batch = batches[i] |
| 117 | + logger.debug('[warmCollectionsInBatches] Processing batch', { |
| 118 | + batchNumber: i + 1, |
| 119 | + batchSize: batch.length |
| 120 | + }) |
| 121 | + |
| 122 | + await Promise.all(batch.map((provider) => warmCollection(provider))) |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Main cache warming function |
| 128 | + */ |
| 129 | + async function warmCache(): Promise<void> { |
| 130 | + if (!enabled) { |
| 131 | + logger.info('[warmCache] Cache warmer is disabled') |
| 132 | + return |
| 133 | + } |
| 134 | + |
| 135 | + if (isWarming) { |
| 136 | + logger.warn('[warmCache] Cache warming already in progress, skipping') |
| 137 | + return |
| 138 | + } |
| 139 | + |
| 140 | + isWarming = true |
| 141 | + status.isWarming = true |
| 142 | + status.errors = [] |
| 143 | + status.collectionsWarmed = 0 |
| 144 | + |
| 145 | + const overallStart = Date.now() |
| 146 | + |
| 147 | + try { |
| 148 | + logger.info('[warmCache] Starting cache warmup') |
| 149 | + |
| 150 | + // Get all third-party providers |
| 151 | + const allProviders = await thirdPartyProvidersStorage.getAll() |
| 152 | + |
| 153 | + // Filter providers with contracts (same logic as fetch-third-party-wearables) |
| 154 | + const providersWithContracts = allProviders.filter( |
| 155 | + (provider) => (provider.metadata.thirdParty.contracts?.length ?? 0) > 0 |
| 156 | + ) |
| 157 | + |
| 158 | + status.totalCollections = providersWithContracts.length |
| 159 | + |
| 160 | + logger.info('[warmCache] Fetched third-party providers', { |
| 161 | + totalProviders: allProviders.length, |
| 162 | + providersWithContracts: providersWithContracts.length, |
| 163 | + providersWithoutContracts: allProviders.length - providersWithContracts.length |
| 164 | + }) |
| 165 | + |
| 166 | + if (providersWithContracts.length === 0) { |
| 167 | + logger.warn('[warmCache] No providers with contracts found') |
| 168 | + return |
| 169 | + } |
| 170 | + |
| 171 | + // Warm collections in batches |
| 172 | + await warmCollectionsInBatches(providersWithContracts) |
| 173 | + |
| 174 | + const overallDuration = Date.now() - overallStart |
| 175 | + status.lastWarmupTime = overallStart |
| 176 | + status.lastWarmupDuration = overallDuration |
| 177 | + |
| 178 | + logger.info('[warmCache] Cache warmup complete', { |
| 179 | + totalProviders: status.totalCollections, |
| 180 | + warmedSuccessfully: status.collectionsWarmed, |
| 181 | + failed: status.totalCollections - status.collectionsWarmed, |
| 182 | + errorsCount: status.errors.length, |
| 183 | + durationMs: overallDuration, |
| 184 | + avgDurationPerCollection: Math.round(overallDuration / status.totalCollections) |
| 185 | + }) |
| 186 | + |
| 187 | + // Record overall metrics (TODO: Uncomment when metrics are properly configured) |
| 188 | + // metrics.observe('cache_warmer_total_duration_seconds', {}, overallDuration / 1000) |
| 189 | + // metrics.increment('cache_warmer_last_warmup_timestamp', {}, overallStart / 1000) |
| 190 | + } catch (error) { |
| 191 | + const errorMsg = error instanceof Error ? error.message : 'Unknown error' |
| 192 | + logger.error('[warmCache] Fatal error during cache warmup', { |
| 193 | + error: errorMsg |
| 194 | + }) |
| 195 | + |
| 196 | + status.errors.push(`Fatal: ${errorMsg}`) |
| 197 | + // metrics.increment('cache_warmer_fatal_errors_total') // TODO: Uncomment when metrics are properly configured |
| 198 | + } finally { |
| 199 | + isWarming = false |
| 200 | + status.isWarming = false |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + /** |
| 205 | + * Get current cache warmer status |
| 206 | + */ |
| 207 | + function getStatus(): CacheWarmerStatus { |
| 208 | + return { ...status } |
| 209 | + } |
| 210 | + |
| 211 | + /** |
| 212 | + * Start the cache warmer component |
| 213 | + */ |
| 214 | + async function start() { |
| 215 | + if (!enabled) { |
| 216 | + logger.info('[start] Cache warmer is disabled via config') |
| 217 | + return |
| 218 | + } |
| 219 | + |
| 220 | + logger.info('[start] Cache warmer starting', { |
| 221 | + warmupIntervalMs, |
| 222 | + warmupDelayMs, |
| 223 | + maxConcurrent |
| 224 | + }) |
| 225 | + |
| 226 | + // Initial warmup after delay |
| 227 | + setTimeout(() => { |
| 228 | + logger.info('[start] Starting initial cache warmup') |
| 229 | + warmCache().catch((error) => { |
| 230 | + logger.error('[start] Initial warmup failed', { |
| 231 | + error: error instanceof Error ? error.message : 'Unknown error' |
| 232 | + }) |
| 233 | + }) |
| 234 | + }, warmupDelayMs) |
| 235 | + |
| 236 | + // Periodic warmup |
| 237 | + intervalId = setInterval(() => { |
| 238 | + logger.info('[start] Starting periodic cache warmup') |
| 239 | + warmCache().catch((error) => { |
| 240 | + logger.error('[start] Periodic warmup failed', { |
| 241 | + error: error instanceof Error ? error.message : 'Unknown error' |
| 242 | + }) |
| 243 | + }) |
| 244 | + }, warmupIntervalMs) |
| 245 | + |
| 246 | + logger.info('[start] Cache warmer started successfully') |
| 247 | + } |
| 248 | + |
| 249 | + /** |
| 250 | + * Stop the cache warmer component |
| 251 | + */ |
| 252 | + async function stop() { |
| 253 | + logger.info('[stop] Stopping cache warmer') |
| 254 | + |
| 255 | + if (intervalId) { |
| 256 | + clearInterval(intervalId) |
| 257 | + intervalId = undefined |
| 258 | + } |
| 259 | + |
| 260 | + logger.info('[stop] Cache warmer stopped') |
| 261 | + } |
| 262 | + |
| 263 | + return { |
| 264 | + start, |
| 265 | + stop, |
| 266 | + warmCache, |
| 267 | + getStatus |
| 268 | + } |
| 269 | +} |
0 commit comments