|
| 1 | +/** |
| 2 | + * Cloudflare Workers Analytics Engine integration utility |
| 3 | + */ |
| 4 | + |
| 5 | +export interface AnalyticsEngineDataset { |
| 6 | + writeDataPoint(data: AnalyticsDataPoint): void |
| 7 | +} |
| 8 | + |
| 9 | +export interface AnalyticsDataPoint { |
| 10 | + blobs?: (string | null)[] |
| 11 | + doubles?: number[] |
| 12 | + indexes?: (string | null)[] |
| 13 | +} |
| 14 | + |
| 15 | +export interface WorkerMetrics { |
| 16 | + duration: number |
| 17 | + endpoint: string |
| 18 | + method: string |
| 19 | + status: number |
| 20 | + userAgent?: string |
| 21 | + country?: string |
| 22 | + timestamp: number |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + * Helper class for sending metrics to Cloudflare Analytics Engine |
| 27 | + */ |
| 28 | +export class AnalyticsReporter { |
| 29 | + private analyticsEngine: AnalyticsEngineDataset | null = null |
| 30 | + |
| 31 | + constructor(analyticsEngine?: AnalyticsEngineDataset) { |
| 32 | + this.analyticsEngine = analyticsEngine || null |
| 33 | + } |
| 34 | + |
| 35 | + /** |
| 36 | + * Report worker execution metrics to Analytics Engine |
| 37 | + */ |
| 38 | + reportWorkerMetrics(metrics: WorkerMetrics): void { |
| 39 | + if (!this.analyticsEngine) { |
| 40 | + // In development or when Analytics Engine is not available |
| 41 | + console.log('Worker Metrics:', metrics) |
| 42 | + return |
| 43 | + } |
| 44 | + |
| 45 | + try { |
| 46 | + this.analyticsEngine.writeDataPoint({ |
| 47 | + // Indexed fields (can be queried and filtered) |
| 48 | + indexes: [ |
| 49 | + metrics.endpoint, // index[1]: endpoint path |
| 50 | + metrics.method, // index[2]: HTTP method |
| 51 | + metrics.status.toString(), // index[3]: status code |
| 52 | + metrics.country || null, // index[4]: user country |
| 53 | + ], |
| 54 | + // Blob fields (string data) |
| 55 | + blobs: [ |
| 56 | + metrics.userAgent || null, // blob[1]: user agent |
| 57 | + ], |
| 58 | + // Double fields (numeric data for aggregation) |
| 59 | + doubles: [ |
| 60 | + metrics.duration, // double[1]: duration in milliseconds |
| 61 | + metrics.timestamp, // double[2]: timestamp |
| 62 | + ], |
| 63 | + }) |
| 64 | + } catch (error) { |
| 65 | + console.error('Failed to report analytics:', error) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + /** |
| 70 | + * Report custom metrics to Analytics Engine |
| 71 | + */ |
| 72 | + reportCustomMetric( |
| 73 | + name: string, |
| 74 | + value: number, |
| 75 | + tags: Record<string, string | null> = {}, |
| 76 | + ): void { |
| 77 | + if (!this.analyticsEngine) { |
| 78 | + console.log('Custom Metric:', { name, value, tags }) |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + try { |
| 83 | + const indexes = [name, null, null, null] // Start with metric name |
| 84 | + const tagKeys = Object.keys(tags).slice(0, 3) // Limit to 3 additional tags |
| 85 | + |
| 86 | + tagKeys.forEach((key, index) => { |
| 87 | + indexes[index + 1] = tags[key] |
| 88 | + }) |
| 89 | + |
| 90 | + this.analyticsEngine.writeDataPoint({ |
| 91 | + indexes: indexes as (string | null)[], |
| 92 | + doubles: [value, Date.now()], |
| 93 | + blobs: [null], |
| 94 | + }) |
| 95 | + } catch (error) { |
| 96 | + console.error('Failed to report custom metric:', error) |
| 97 | + } |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +/** |
| 102 | + * Extract country from Cloudflare request headers |
| 103 | + */ |
| 104 | +export function getCountryFromRequest(request: Request): string | undefined { |
| 105 | + return request.headers.get('CF-IPCountry') || undefined |
| 106 | +} |
| 107 | + |
| 108 | +/** |
| 109 | + * Create a performance timing wrapper for functions |
| 110 | + */ |
| 111 | +export function withTiming<T extends unknown[], R>( |
| 112 | + fn: (...args: T) => R | Promise<R>, |
| 113 | + onComplete: (duration: number) => void, |
| 114 | +): (...args: T) => R | Promise<R> { |
| 115 | + return (...args: T) => { |
| 116 | + const startTime = performance.now() |
| 117 | + |
| 118 | + const handleComplete = (result: R) => { |
| 119 | + const duration = performance.now() - startTime |
| 120 | + onComplete(duration) |
| 121 | + return result |
| 122 | + } |
| 123 | + |
| 124 | + try { |
| 125 | + const result = fn(...args) |
| 126 | + if (result instanceof Promise) { |
| 127 | + return result.then(handleComplete).catch(error => { |
| 128 | + const duration = performance.now() - startTime |
| 129 | + onComplete(duration) |
| 130 | + throw error |
| 131 | + }) |
| 132 | + } else { |
| 133 | + return handleComplete(result) |
| 134 | + } |
| 135 | + } catch (error) { |
| 136 | + const duration = performance.now() - startTime |
| 137 | + onComplete(duration) |
| 138 | + throw error |
| 139 | + } |
| 140 | + } |
| 141 | +} |
0 commit comments