-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathcdnService.ts
More file actions
402 lines (347 loc) · 11.1 KB
/
Copy pathcdnService.ts
File metadata and controls
402 lines (347 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
* CDN Service - Manages CDN integration for faster global asset delivery
* Supports multiple CDN providers with automatic fallback
*/
import { createLogger } from '@/utils/logger'
const logger = createLogger('CDNService')
export interface CDNConfig {
enabled: boolean
provider: 'cloudflare' | 'aws' | 'fastly' | 'custom'
primaryUrl: string
fallbackUrl?: string
cacheControl?: string
corsOrigins: string[]
compressionEnabled: boolean
imageOptimization: boolean
imageCDNUrl?: string
}
export interface AssetOptions {
ttl?: number
public?: boolean
format?: string
quality?: number
width?: number
height?: number
}
class CDNService {
private config: CDNConfig
private assetCache: Map<string, string> = new Map()
constructor() {
this.config = this.initializeConfig()
}
/**
* Initialize CDN configuration from environment variables
*/
private initializeConfig(): CDNConfig {
const cdnEnabled = process.env.CDN_ENABLED === 'true'
const provider = (process.env.CDN_PROVIDER || 'custom') as CDNConfig['provider']
const primaryUrl = process.env.CDN_PRIMARY_URL || ''
const fallbackUrl = process.env.CDN_FALLBACK_URL
const corsOrigins = process.env.CDN_CORS_ORIGINS?.split(',') || ['*']
const compressionEnabled = process.env.CDN_COMPRESSION_ENABLED !== 'false'
const imageOptimization = process.env.CDN_IMAGE_OPTIMIZATION === 'true'
const imageCDNUrl = process.env.CDN_IMAGE_URL
if (cdnEnabled && !primaryUrl) {
logger.warn('CDN is enabled but CDN_PRIMARY_URL is not set. CDN features will be limited.')
}
const config: CDNConfig = {
enabled: cdnEnabled,
provider,
primaryUrl,
fallbackUrl,
corsOrigins,
compressionEnabled,
imageOptimization,
imageCDNUrl,
cacheControl: process.env.CDN_CACHE_CONTROL || 'public, max-age=31536000, immutable'
}
logger.info(`CDN Service initialized - Enabled: ${config.enabled}, Provider: ${provider}`)
return config
}
/**
* Get CDN URL for a given asset path
*/
getAssetUrl(assetPath: string, options?: AssetOptions): string {
if (!this.config.enabled || !this.config.primaryUrl) {
return assetPath
}
const cacheKey = `${assetPath}:${JSON.stringify(options || {})}`
// Check cache first
if (this.assetCache.has(cacheKey)) {
return this.assetCache.get(cacheKey)!
}
let cdnUrl = this.buildCDNUrl(assetPath, options)
// Cache the result
this.assetCache.set(cacheKey, cdnUrl)
return cdnUrl
}
/**
* Build CDN URL based on provider and asset options
*/
private buildCDNUrl(assetPath: string, options?: AssetOptions): string {
const cleanPath = assetPath.startsWith('/') ? assetPath : `/${assetPath}`
const baseUrl = this.config.primaryUrl.replace(/\/$/, '')
switch (this.config.provider) {
case 'cloudflare':
return this.buildCloudflareUrl(baseUrl, cleanPath, options)
case 'aws':
return this.buildAwsUrl(baseUrl, cleanPath, options)
case 'fastly':
return this.buildFastlyUrl(baseUrl, cleanPath, options)
case 'custom':
default:
return `${baseUrl}${cleanPath}`
}
}
/**
* Build Cloudflare CDN URL with image optimization
*/
private buildCloudflareUrl(baseUrl: string, assetPath: string, options?: AssetOptions): string {
if (!options || !this.config.imageOptimization) {
return `${baseUrl}${assetPath}`
}
// Cloudflare Image Optimization API
const imageUrl = `${baseUrl}${assetPath}`
const params = new URLSearchParams()
if (options.width) params.append('width', options.width.toString())
if (options.height) params.append('height', options.height.toString())
if (options.quality) params.append('quality', options.quality.toString())
if (options.format) params.append('format', options.format)
return params.size > 0 ? `${imageUrl}?${params.toString()}` : imageUrl
}
/**
* Build AWS CloudFront URL
*/
private buildAwsUrl(baseUrl: string, assetPath: string, options?: AssetOptions): string {
if (!options || !this.config.imageOptimization) {
return `${baseUrl}${assetPath}`
}
// AWS CloudFront with Lambda@Edge can handle image optimization via query params
const params = new URLSearchParams()
if (options.width) params.append('w', options.width.toString())
if (options.height) params.append('h', options.height.toString())
if (options.quality) params.append('q', options.quality.toString())
if (options.format) params.append('f', options.format)
return params.size > 0 ? `${baseUrl}${assetPath}?${params.toString()}` : `${baseUrl}${assetPath}`
}
/**
* Build Fastly CDN URL
*/
private buildFastlyUrl(baseUrl: string, assetPath: string, options?: AssetOptions): string {
if (!options || !this.config.imageOptimization) {
return `${baseUrl}${assetPath}`
}
// Fastly image optimization via query params
const params = new URLSearchParams()
if (options.width) params.append('width', options.width.toString())
if (options.height) params.append('height', options.height.toString())
if (options.quality) params.append('quality', options.quality.toString())
return params.size > 0 ? `${baseUrl}${assetPath}?${params.toString()}` : `${baseUrl}${assetPath}`
}
/**
* Get CDN URL for images with optimization
*/
getImageUrl(
imagePath: string,
options?: {
width?: number
height?: number
quality?: number
format?: 'webp' | 'avif' | 'jpg' | 'png'
}
): string {
if (this.config.imageCDNUrl && this.config.imageOptimization) {
return this.buildCDNUrl(imagePath, options)
}
return imagePath
}
/**
* Get cache control headers for CDN responses
*/
getCacheHeaders(permanent: boolean = true): Record<string, string> {
if (!this.config.enabled) {
return {
'Cache-Control': 'no-cache, no-store, must-revalidate'
}
}
return {
'Cache-Control': permanent
? 'public, max-age=31536000, immutable' // 1 year for versioned assets
: 'public, max-age=3600, must-revalidate', // 1 hour for non-versioned assets
'CDN-Cache-Control': 'max-age=31536000',
'Expires': permanent
? new Date(Date.now() + 31536000000).toUTCString()
: new Date(Date.now() + 3600000).toUTCString()
}
}
/**
* Get CORS headers for CDN responses
*/
getCORSHeaders(): Record<string, string> {
const allowedOrigins = this.config.corsOrigins.includes('*')
? '*'
: this.config.corsOrigins.join(', ')
return {
'Access-Control-Allow-Origin': allowedOrigins,
'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Accept-Encoding',
'Access-Control-Max-Age': '86400'
}
}
/**
* Get compression headers for CDN responses
*/
getCompressionHeaders(): Record<string, string> {
if (!this.config.compressionEnabled) {
return {}
}
return {
'Content-Encoding': 'gzip, deflate, br',
'Vary': 'Accept-Encoding'
}
}
/**
* Health check for CDN availability
*/
async healthCheck(): Promise<{ healthy: boolean; provider: string; primaryUrl: string }> {
if (!this.config.enabled) {
return {
healthy: true,
provider: this.config.provider,
primaryUrl: this.config.primaryUrl || 'disabled'
}
}
try {
const response = await fetch(this.config.primaryUrl, { method: 'HEAD' })
return {
healthy: response.ok || response.status === 403, // 403 is OK, means CDN is responding
provider: this.config.provider,
primaryUrl: this.config.primaryUrl
}
} catch (error) {
logger.error('CDN health check failed:', error)
return {
healthy: false,
provider: this.config.provider,
primaryUrl: this.config.primaryUrl
}
}
}
/**
* Get CDN configuration (safe for client consumption)
*/
getPublicConfig(): Partial<CDNConfig> {
return {
enabled: this.config.enabled,
provider: this.config.provider,
primaryUrl: this.config.primaryUrl,
imageOptimization: this.config.imageOptimization,
compressionEnabled: this.config.compressionEnabled
}
}
/**
* Purge CDN cache for specific path (provider-specific)
*/
async purgeCachePath(path: string): Promise<boolean> {
logger.info(`Cache purge requested for path: ${path}`)
try {
switch (this.config.provider) {
case 'cloudflare':
return await this.purgeCloudflareCache(path)
case 'aws':
return await this.purgeAwsCache(path)
case 'fastly':
return await this.purgeFastlyCache(path)
default:
logger.warn('Cache purge not implemented for custom CDN provider')
return false
}
} catch (error) {
logger.error('Cache purge failed:', error)
return false
}
}
/**
* Purge Cloudflare cache
*/
private async purgeCloudflareCache(path: string): Promise<boolean> {
const token = process.env.CLOUDFLARE_API_TOKEN
const zoneId = process.env.CLOUDFLARE_ZONE_ID
if (!token || !zoneId) {
logger.warn('Cloudflare credentials not configured')
return false
}
try {
const response = await fetch(`https://api.cloudflare.com/client/v4/zones/${zoneId}/purge_cache`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
files: [`${this.config.primaryUrl}${path}`]
})
})
const success = response.ok
if (success) {
logger.info(`Cloudflare cache purged for path: ${path}`)
}
return success
} catch (error) {
logger.error('Cloudflare cache purge failed:', error)
return false
}
}
/**
* Purge AWS CloudFront cache
*/
private async purgeAwsCache(path: string): Promise<boolean> {
logger.info('AWS cache purge requires AWS SDK configuration')
// Implementation would use AWS CloudFront invalidation API
return false
}
/**
* Purge Fastly cache
*/
private async purgeFastlyCache(path: string): Promise<boolean> {
const token = process.env.FASTLY_API_TOKEN
if (!token) {
logger.warn('Fastly API token not configured')
return false
}
try {
const response = await fetch(`${this.config.primaryUrl}${path}`, {
method: 'PURGE',
headers: {
'Fastly-Key': token
}
})
const success = response.ok
if (success) {
logger.info(`Fastly cache purged for path: ${path}`)
}
return success
} catch (error) {
logger.error('Fastly cache purge failed:', error)
return false
}
}
/**
* Clear internal asset URL cache
*/
clearCache(): void {
this.assetCache.clear()
logger.info('CDN asset URL cache cleared')
}
/**
* Get CDN statistics
*/
getStats(): { enabled: boolean; provider: string; cachedUrls: number } {
return {
enabled: this.config.enabled,
provider: this.config.provider,
cachedUrls: this.assetCache.size
}
}
}
export default new CDNService()