@stacksjs/bun-router 0.0.17 → 0.0.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/dist/cli.js +1 -1
  2. package/dist/container/service-provider.d.ts +3 -3
  3. package/dist/development/performance-profiler.d.ts +3 -3
  4. package/dist/development/route-debugger.d.ts +1 -1
  5. package/dist/development/route-inspector.d.ts +2 -2
  6. package/dist/observability/integration.d.ts +1 -1
  7. package/dist/response/macros.d.ts +1 -1
  8. package/dist/router/index.d.ts +7 -7
  9. package/dist/router/router.d.ts +0 -32
  10. package/dist/testing/performance-testing.d.ts +2 -2
  11. package/dist/testing/test-client.d.ts +1 -1
  12. package/dist/testing/websocket-testing.d.ts +1 -1
  13. package/package.json +2 -3
  14. package/src/auth.ts +0 -489
  15. package/src/cache/lru-cache.ts +0 -457
  16. package/src/cache/middleware-memoization.ts +0 -531
  17. package/src/cache/route-cache-warmer.ts +0 -486
  18. package/src/cache/sqlite-cache.ts +0 -783
  19. package/src/cache/streaming-cache.ts +0 -572
  20. package/src/cli/colors.ts +0 -29
  21. package/src/cli/index.ts +0 -287
  22. package/src/cli/middleware.ts +0 -291
  23. package/src/cli/openapi.ts +0 -407
  24. package/src/cli/router.ts +0 -188
  25. package/src/cli/routes.ts +0 -265
  26. package/src/cli/utils.ts +0 -531
  27. package/src/cli.ts +0 -5
  28. package/src/config.ts +0 -322
  29. package/src/container/container.ts +0 -786
  30. package/src/container/contextual-binding.ts +0 -606
  31. package/src/container/decorators.ts +0 -368
  32. package/src/container/index.ts +0 -49
  33. package/src/container/service-provider.ts +0 -596
  34. package/src/development/hot-reload.ts +0 -673
  35. package/src/development/index.ts +0 -499
  36. package/src/development/performance-profiler.ts +0 -717
  37. package/src/development/route-debugger.ts +0 -527
  38. package/src/development/route-inspector.ts +0 -749
  39. package/src/development/typescript-utilities.ts +0 -682
  40. package/src/docs.ts +0 -397
  41. package/src/errors/circuit-breaker.ts +0 -733
  42. package/src/errors/error-handler.ts +0 -569
  43. package/src/errors/error-reporting.ts +0 -672
  44. package/src/errors/exceptions.ts +0 -536
  45. package/src/errors/graceful-degradation.ts +0 -623
  46. package/src/errors/index.ts +0 -21
  47. package/src/errors/router-errors.ts +0 -632
  48. package/src/file-serving/static-files.ts +0 -718
  49. package/src/index.ts +0 -66
  50. package/src/middleware/auth.ts +0 -220
  51. package/src/middleware/content_security_policy.ts +0 -215
  52. package/src/middleware/cors.ts +0 -142
  53. package/src/middleware/csrf.ts +0 -166
  54. package/src/middleware/ddos_protection.ts +0 -279
  55. package/src/middleware/file_security.ts +0 -191
  56. package/src/middleware/file_upload.ts +0 -275
  57. package/src/middleware/helmet.ts +0 -268
  58. package/src/middleware/index.ts +0 -117
  59. package/src/middleware/input_validation.ts +0 -453
  60. package/src/middleware/json_body.ts +0 -37
  61. package/src/middleware/performance_alerting.ts +0 -540
  62. package/src/middleware/performance_dashboard.ts +0 -661
  63. package/src/middleware/performance_monitor.ts +0 -945
  64. package/src/middleware/pipeline.ts +0 -489
  65. package/src/middleware/rate_limit.ts +0 -251
  66. package/src/middleware/request_id.ts +0 -36
  67. package/src/middleware/request_signing.ts +0 -638
  68. package/src/middleware/request_tracer.ts +0 -653
  69. package/src/middleware/response_cache.ts +0 -778
  70. package/src/middleware/security.ts +0 -482
  71. package/src/middleware/security_suite.ts +0 -257
  72. package/src/middleware/session.ts +0 -91
  73. package/src/model-binding/index.ts +0 -18
  74. package/src/model-binding/model-middleware.ts +0 -425
  75. package/src/model-binding/model-registry.ts +0 -550
  76. package/src/model-binding.ts +0 -370
  77. package/src/model-resolver-factory.ts +0 -106
  78. package/src/observability/correlation.ts +0 -691
  79. package/src/observability/health-checks.ts +0 -729
  80. package/src/observability/index.ts +0 -184
  81. package/src/observability/integration.ts +0 -548
  82. package/src/observability/metrics.ts +0 -753
  83. package/src/observability/tracing.ts +0 -638
  84. package/src/optimization/bun-utilities.ts +0 -778
  85. package/src/query-builder-integration.ts +0 -137
  86. package/src/request/context.ts +0 -109
  87. package/src/request/enhanced-request.ts +0 -876
  88. package/src/request/macros.ts +0 -822
  89. package/src/response/macros.ts +0 -665
  90. package/src/response/response-factory.ts +0 -596
  91. package/src/router/api-routes.ts +0 -243
  92. package/src/router/file-based-routing.ts +0 -697
  93. package/src/router/file-streaming.ts +0 -383
  94. package/src/router/fluent-routing.ts +0 -866
  95. package/src/router/group-organization.ts +0 -229
  96. package/src/router/handler-resolver.ts +0 -327
  97. package/src/router/http-methods.ts +0 -407
  98. package/src/router/index.ts +0 -193
  99. package/src/router/middleware-groups.ts +0 -222
  100. package/src/router/middleware-integration.ts +0 -399
  101. package/src/router/middleware.ts +0 -234
  102. package/src/router/model-binding.ts +0 -215
  103. package/src/router/optimized-route-matching.ts +0 -302
  104. package/src/router/route-building.ts +0 -221
  105. package/src/router/route-compiler.ts +0 -691
  106. package/src/router/route-matching.ts +0 -368
  107. package/src/router/route-trie.ts +0 -450
  108. package/src/router/router.ts +0 -1616
  109. package/src/router/server.ts +0 -684
  110. package/src/router/validation-integration.ts +0 -449
  111. package/src/router/view-rendering.ts +0 -233
  112. package/src/router/websocket.ts +0 -100
  113. package/src/routing/route-caching.ts +0 -402
  114. package/src/routing/route-throttling.ts +0 -469
  115. package/src/routing/subdomain-routing.ts +0 -492
  116. package/src/session/database-store.ts +0 -109
  117. package/src/session/file-store.ts +0 -148
  118. package/src/session/index.ts +0 -244
  119. package/src/session/memory-store.ts +0 -88
  120. package/src/session/redis-store.ts +0 -93
  121. package/src/streaming/index.ts +0 -17
  122. package/src/streaming/sse-handler.ts +0 -482
  123. package/src/streaming/stream-handler.ts +0 -552
  124. package/src/testing/auth-testing.ts +0 -448
  125. package/src/testing/file-upload-testing.ts +0 -543
  126. package/src/testing/index.ts +0 -10
  127. package/src/testing/middleware-testing.ts +0 -322
  128. package/src/testing/model-binding-testing.ts +0 -645
  129. package/src/testing/performance-testing.ts +0 -738
  130. package/src/testing/test-client.ts +0 -310
  131. package/src/testing/test-request.ts +0 -315
  132. package/src/testing/test-response.ts +0 -332
  133. package/src/testing/types.ts +0 -224
  134. package/src/testing/websocket-testing.ts +0 -590
  135. package/src/types/controller-types.ts +0 -385
  136. package/src/types/core.ts +0 -683
  137. package/src/types/middleware-types.ts +0 -422
  138. package/src/types/request-response-augmentation.ts +0 -489
  139. package/src/types/route-inference.ts +0 -372
  140. package/src/types.ts +0 -2123
  141. package/src/url.ts +0 -131
  142. package/src/utils/index.ts +0 -1
  143. package/src/utils/query-preservation.ts +0 -201
  144. package/src/utils.ts +0 -395
  145. package/src/validation/validator.ts +0 -688
  146. package/src/websocket/clustering.ts +0 -769
@@ -1,729 +0,0 @@
1
- /**
2
- * Observability & Monitoring - Health Check Endpoints with Dependency Checks
3
- *
4
- * Enterprise-grade health monitoring with dependency validation and detailed reporting
5
- */
6
-
7
- import type { EnhancedRequest } from '../types'
8
-
9
- export interface HealthCheckConfig {
10
- timeout?: number
11
- retries?: number
12
- interval?: number
13
- gracePeriod?: number
14
- dependencies?: DependencyConfig[]
15
- customChecks?: CustomHealthCheck[]
16
- }
17
-
18
- export interface DependencyConfig {
19
- name: string
20
- type: 'http' | 'database' | 'redis' | 'queue' | 'file' | 'custom'
21
- url?: string
22
- timeout?: number
23
- retries?: number
24
- critical?: boolean
25
- metadata?: Record<string, any>
26
- check?: () => Promise<HealthCheckResult>
27
- }
28
-
29
- export interface CustomHealthCheck {
30
- name: string
31
- check: () => Promise<HealthCheckResult>
32
- critical?: boolean
33
- timeout?: number
34
- }
35
-
36
- export interface HealthCheckResult {
37
- status: 'healthy' | 'unhealthy' | 'degraded'
38
- message?: string
39
- duration?: number
40
- metadata?: Record<string, any>
41
- error?: string
42
- timestamp: number
43
- }
44
-
45
- export interface HealthStatus {
46
- status: 'healthy' | 'unhealthy' | 'degraded'
47
- timestamp: number
48
- uptime: number
49
- version?: string
50
- environment?: string
51
- checks: Record<string, HealthCheckResult>
52
- dependencies: Record<string, HealthCheckResult>
53
- summary: {
54
- total: number
55
- healthy: number
56
- unhealthy: number
57
- degraded: number
58
- }
59
- }
60
-
61
- /**
62
- * Health check manager
63
- */
64
- export class HealthCheckManager {
65
- private config: HealthCheckConfig
66
- private dependencies: Map<string, DependencyConfig> = new Map()
67
- private customChecks: Map<string, CustomHealthCheck> = new Map()
68
- private lastResults: Map<string, HealthCheckResult> = new Map()
69
- private startTime: number = Date.now()
70
-
71
- constructor(config: HealthCheckConfig = {}) {
72
- this.config = {
73
- timeout: 5000,
74
- retries: 3,
75
- interval: 30000,
76
- gracePeriod: 60000,
77
- ...config,
78
- }
79
-
80
- // Register dependencies
81
- if (this.config.dependencies) {
82
- for (const dep of this.config.dependencies) {
83
- this.addDependency(dep)
84
- }
85
- }
86
-
87
- // Register custom checks
88
- if (this.config.customChecks) {
89
- for (const check of this.config.customChecks) {
90
- this.addCustomCheck(check)
91
- }
92
- }
93
- }
94
-
95
- /**
96
- * Add a dependency check
97
- */
98
- addDependency(config: DependencyConfig): void {
99
- this.dependencies.set(config.name, {
100
- timeout: this.config.timeout,
101
- retries: this.config.retries,
102
- critical: true,
103
- ...config,
104
- })
105
- }
106
-
107
- /**
108
- * Add a custom health check
109
- */
110
- addCustomCheck(check: CustomHealthCheck): void {
111
- this.customChecks.set(check.name, {
112
- critical: true,
113
- timeout: this.config.timeout,
114
- ...check,
115
- })
116
- }
117
-
118
- /**
119
- * Remove a dependency check
120
- */
121
- removeDependency(name: string): boolean {
122
- return this.dependencies.delete(name)
123
- }
124
-
125
- /**
126
- * Remove a custom check
127
- */
128
- removeCustomCheck(name: string): boolean {
129
- return this.customChecks.delete(name)
130
- }
131
-
132
- /**
133
- * Perform all health checks
134
- */
135
- async checkHealth(): Promise<HealthStatus> {
136
- const checks: Record<string, HealthCheckResult> = {}
137
- const dependencies: Record<string, HealthCheckResult> = {}
138
-
139
- // Run dependency checks
140
- const dependencyPromises = Array.from(this.dependencies.entries()).map(
141
- async ([name, config]) => {
142
- const result = await this.checkDependency(config)
143
- dependencies[name] = result
144
- this.lastResults.set(`dep_${name}`, result)
145
- return result
146
- },
147
- )
148
-
149
- // Run custom checks
150
- const customPromises = Array.from(this.customChecks.entries()).map(
151
- async ([name, config]) => {
152
- const result = await this.runCustomCheck(config)
153
- checks[name] = result
154
- this.lastResults.set(`check_${name}`, result)
155
- return result
156
- },
157
- )
158
-
159
- // Wait for all checks to complete
160
- await Promise.all([
161
- Promise.allSettled(dependencyPromises),
162
- Promise.allSettled(customPromises),
163
- ])
164
-
165
- // Calculate overall status
166
- const allResults = [...Object.values(dependencies), ...Object.values(checks)]
167
- const summary = {
168
- total: allResults.length,
169
- healthy: allResults.filter(r => r.status === 'healthy').length,
170
- unhealthy: allResults.filter(r => r.status === 'unhealthy').length,
171
- degraded: allResults.filter(r => r.status === 'degraded').length,
172
- }
173
-
174
- // Determine overall status
175
- let overallStatus: 'healthy' | 'unhealthy' | 'degraded' = 'healthy'
176
-
177
- // Check for critical failures
178
- const criticalFailures = allResults.some((result) => {
179
- const isCritical = this.isCriticalCheck(result)
180
- return isCritical && result.status === 'unhealthy'
181
- })
182
-
183
- if (criticalFailures) {
184
- overallStatus = 'unhealthy'
185
- }
186
- else if (summary.unhealthy > 0 || summary.degraded > 0) {
187
- overallStatus = 'degraded'
188
- }
189
-
190
- return {
191
- status: overallStatus,
192
- timestamp: Date.now(),
193
- uptime: Math.floor((Date.now() - this.startTime) / 1000),
194
- checks,
195
- dependencies,
196
- summary,
197
- }
198
- }
199
-
200
- /**
201
- * Check a specific dependency
202
- */
203
- private async checkDependency(config: DependencyConfig): Promise<HealthCheckResult> {
204
- const startTime = Date.now()
205
-
206
- try {
207
- // Use custom check if provided
208
- if (config.check) {
209
- return await this.executeWithTimeout(config.check(), config.timeout || this.config.timeout!)
210
- }
211
-
212
- // Built-in dependency checks
213
- switch (config.type) {
214
- case 'http':
215
- return await this.checkHttpDependency(config)
216
- case 'database':
217
- return await this.checkDatabaseDependency(config)
218
- case 'redis':
219
- return await this.checkRedisDependency(config)
220
- case 'queue':
221
- return await this.checkQueueDependency(config)
222
- case 'file':
223
- return await this.checkFileDependency(config)
224
- default:
225
- return {
226
- status: 'unhealthy',
227
- message: `Unknown dependency type: ${config.type}`,
228
- duration: Date.now() - startTime,
229
- timestamp: Date.now(),
230
- }
231
- }
232
- }
233
- catch (error) {
234
- return {
235
- status: 'unhealthy',
236
- message: 'Dependency check failed',
237
- error: error instanceof Error ? error.message : String(error),
238
- duration: Date.now() - startTime,
239
- timestamp: Date.now(),
240
- }
241
- }
242
- }
243
-
244
- /**
245
- * Check HTTP dependency
246
- */
247
- private async checkHttpDependency(config: DependencyConfig): Promise<HealthCheckResult> {
248
- const startTime = Date.now()
249
-
250
- if (!config.url) {
251
- return {
252
- status: 'unhealthy',
253
- message: 'HTTP dependency URL not configured',
254
- duration: 0,
255
- timestamp: Date.now(),
256
- }
257
- }
258
-
259
- try {
260
- const controller = new AbortController()
261
- const timeoutId = setTimeout(() => controller.abort(), config.timeout || this.config.timeout!)
262
-
263
- const response = await fetch(config.url, {
264
- method: 'GET',
265
- signal: controller.signal,
266
- headers: {
267
- 'User-Agent': 'bun-router-health-check/1.0',
268
- },
269
- })
270
-
271
- clearTimeout(timeoutId)
272
- const duration = Date.now() - startTime
273
-
274
- if (response.ok) {
275
- return {
276
- status: 'healthy',
277
- message: `HTTP ${response.status} ${response.statusText}`,
278
- duration,
279
- metadata: {
280
- status: response.status,
281
- statusText: response.statusText,
282
- url: config.url,
283
- },
284
- timestamp: Date.now(),
285
- }
286
- }
287
- else {
288
- return {
289
- status: response.status >= 500 ? 'unhealthy' : 'degraded',
290
- message: `HTTP ${response.status} ${response.statusText}`,
291
- duration,
292
- metadata: {
293
- status: response.status,
294
- statusText: response.statusText,
295
- url: config.url,
296
- },
297
- timestamp: Date.now(),
298
- }
299
- }
300
- }
301
- catch (error) {
302
- return {
303
- status: 'unhealthy',
304
- message: 'HTTP request failed',
305
- error: error instanceof Error ? error.message : String(error),
306
- duration: Date.now() - startTime,
307
- metadata: { url: config.url },
308
- timestamp: Date.now(),
309
- }
310
- }
311
- }
312
-
313
- /**
314
- * Check database dependency
315
- */
316
- private async checkDatabaseDependency(config: DependencyConfig): Promise<HealthCheckResult> {
317
- const startTime = Date.now()
318
-
319
- try {
320
- // This is a placeholder - in real implementation, you'd use actual database clients
321
- // For now, we'll simulate a database check
322
- await new Promise(resolve => setTimeout(resolve, 10))
323
-
324
- return {
325
- status: 'healthy',
326
- message: 'Database connection successful',
327
- duration: Date.now() - startTime,
328
- metadata: {
329
- type: 'database',
330
- ...config.metadata,
331
- },
332
- timestamp: Date.now(),
333
- }
334
- }
335
- catch (error) {
336
- return {
337
- status: 'unhealthy',
338
- message: 'Database connection failed',
339
- error: error instanceof Error ? error.message : String(error),
340
- duration: Date.now() - startTime,
341
- timestamp: Date.now(),
342
- }
343
- }
344
- }
345
-
346
- /**
347
- * Check Redis dependency
348
- */
349
- private async checkRedisDependency(config: DependencyConfig): Promise<HealthCheckResult> {
350
- const startTime = Date.now()
351
-
352
- try {
353
- // Placeholder for Redis check
354
- await new Promise(resolve => setTimeout(resolve, 5))
355
-
356
- return {
357
- status: 'healthy',
358
- message: 'Redis connection successful',
359
- duration: Date.now() - startTime,
360
- metadata: {
361
- type: 'redis',
362
- ...config.metadata,
363
- },
364
- timestamp: Date.now(),
365
- }
366
- }
367
- catch (error) {
368
- return {
369
- status: 'unhealthy',
370
- message: 'Redis connection failed',
371
- error: error instanceof Error ? error.message : String(error),
372
- duration: Date.now() - startTime,
373
- timestamp: Date.now(),
374
- }
375
- }
376
- }
377
-
378
- /**
379
- * Check queue dependency
380
- */
381
- private async checkQueueDependency(config: DependencyConfig): Promise<HealthCheckResult> {
382
- const startTime = Date.now()
383
-
384
- try {
385
- // Placeholder for queue check
386
- await new Promise(resolve => setTimeout(resolve, 8))
387
-
388
- return {
389
- status: 'healthy',
390
- message: 'Queue connection successful',
391
- duration: Date.now() - startTime,
392
- metadata: {
393
- type: 'queue',
394
- ...config.metadata,
395
- },
396
- timestamp: Date.now(),
397
- }
398
- }
399
- catch (error) {
400
- return {
401
- status: 'unhealthy',
402
- message: 'Queue connection failed',
403
- error: error instanceof Error ? error.message : String(error),
404
- duration: Date.now() - startTime,
405
- timestamp: Date.now(),
406
- }
407
- }
408
- }
409
-
410
- /**
411
- * Check file system dependency
412
- */
413
- private async checkFileDependency(config: DependencyConfig): Promise<HealthCheckResult> {
414
- const startTime = Date.now()
415
-
416
- try {
417
- if (!config.url) {
418
- throw new Error('File path not specified')
419
- }
420
-
421
- // Check if file/directory exists and is accessible
422
- const file = Bun.file(config.url)
423
- const exists = await file.exists()
424
-
425
- if (!exists) {
426
- return {
427
- status: 'unhealthy',
428
- message: `File not found: ${config.url}`,
429
- duration: Date.now() - startTime,
430
- timestamp: Date.now(),
431
- }
432
- }
433
-
434
- return {
435
- status: 'healthy',
436
- message: 'File system check successful',
437
- duration: Date.now() - startTime,
438
- metadata: {
439
- type: 'file',
440
- path: config.url,
441
- size: file.size,
442
- },
443
- timestamp: Date.now(),
444
- }
445
- }
446
- catch (error) {
447
- return {
448
- status: 'unhealthy',
449
- message: 'File system check failed',
450
- error: error instanceof Error ? error.message : String(error),
451
- duration: Date.now() - startTime,
452
- timestamp: Date.now(),
453
- }
454
- }
455
- }
456
-
457
- /**
458
- * Run custom health check
459
- */
460
- private async runCustomCheck(config: CustomHealthCheck): Promise<HealthCheckResult> {
461
- const startTime = Date.now()
462
-
463
- try {
464
- const result = await this.executeWithTimeout(config.check(), config.timeout || this.config.timeout!)
465
- return {
466
- ...result,
467
- duration: result.duration || (Date.now() - startTime),
468
- }
469
- }
470
- catch (error) {
471
- return {
472
- status: 'unhealthy',
473
- message: 'Custom check failed',
474
- error: error instanceof Error ? error.message : String(error),
475
- duration: Date.now() - startTime,
476
- timestamp: Date.now(),
477
- }
478
- }
479
- }
480
-
481
- /**
482
- * Execute a promise with timeout
483
- */
484
- private async executeWithTimeout<T>(promise: Promise<T>, timeout: number): Promise<T> {
485
- return new Promise((resolve, reject) => {
486
- const timeoutId = setTimeout(() => {
487
- reject(new Error(`Operation timed out after ${timeout}ms`))
488
- }, timeout)
489
-
490
- promise
491
- .then((result) => {
492
- clearTimeout(timeoutId)
493
- resolve(result)
494
- })
495
- .catch((error) => {
496
- clearTimeout(timeoutId)
497
- reject(error)
498
- })
499
- })
500
- }
501
-
502
- /**
503
- * Check if a result is from a critical check
504
- */
505
- private isCriticalCheck(result: HealthCheckResult): boolean {
506
- // Find the check configuration to determine if it's critical
507
- for (const [name, config] of this.dependencies.entries()) {
508
- const depResult = this.lastResults.get(`dep_${name}`)
509
- if (depResult === result) {
510
- return config.critical !== false
511
- }
512
- }
513
-
514
- for (const [name, config] of this.customChecks.entries()) {
515
- const checkResult = this.lastResults.get(`check_${name}`)
516
- if (checkResult === result) {
517
- return config.critical !== false
518
- }
519
- }
520
-
521
- return true // Default to critical if not found
522
- }
523
-
524
- /**
525
- * Get the last health check results
526
- */
527
- getLastResults(): Map<string, HealthCheckResult> {
528
- return new Map(this.lastResults)
529
- }
530
-
531
- /**
532
- * Get uptime in seconds
533
- */
534
- getUptime(): number {
535
- return Math.floor((Date.now() - this.startTime) / 1000)
536
- }
537
-
538
- /**
539
- * Reset start time (for testing)
540
- */
541
- resetStartTime(): void {
542
- this.startTime = Date.now()
543
- }
544
- }
545
-
546
- /**
547
- * Global health check manager
548
- */
549
- let globalHealthManager: HealthCheckManager | null = null
550
-
551
- /**
552
- * Initialize global health check manager
553
- */
554
- export function initializeHealthChecks(config?: HealthCheckConfig): HealthCheckManager {
555
- globalHealthManager = new HealthCheckManager(config)
556
- return globalHealthManager
557
- }
558
-
559
- /**
560
- * Get global health check manager
561
- */
562
- export function getHealthManager(): HealthCheckManager | null {
563
- return globalHealthManager
564
- }
565
-
566
- /**
567
- * Health check endpoint handlers
568
- */
569
- export const HealthEndpoints = {
570
- /**
571
- * Basic health check endpoint
572
- */
573
- health: async (_req: EnhancedRequest): Promise<Response> => {
574
- const manager = getHealthManager()
575
- if (!manager) {
576
- return new Response(JSON.stringify({
577
- status: 'unhealthy',
578
- message: 'Health checks not initialized',
579
- }), {
580
- status: 503,
581
- headers: { 'Content-Type': 'application/json' },
582
- })
583
- }
584
-
585
- try {
586
- const health = await manager.checkHealth()
587
- const status = health.status === 'healthy' ? 200 : health.status === 'degraded' ? 200 : 503
588
-
589
- return new Response(JSON.stringify(health, null, 2), {
590
- status,
591
- headers: {
592
- 'Content-Type': 'application/json',
593
- 'Cache-Control': 'no-cache',
594
- },
595
- })
596
- }
597
- catch (error) {
598
- return new Response(JSON.stringify({
599
- status: 'unhealthy',
600
- message: 'Health check failed',
601
- error: error instanceof Error ? error.message : String(error),
602
- timestamp: Date.now(),
603
- }), {
604
- status: 503,
605
- headers: { 'Content-Type': 'application/json' },
606
- })
607
- }
608
- },
609
-
610
- /**
611
- * Readiness probe endpoint
612
- */
613
- ready: async (_req: EnhancedRequest): Promise<Response> => {
614
- const manager = getHealthManager()
615
- if (!manager) {
616
- return new Response('Service not ready', { status: 503 })
617
- }
618
-
619
- try {
620
- const health = await manager.checkHealth()
621
-
622
- // Ready if all critical dependencies are healthy
623
- const criticalFailures = Object.values(health.dependencies).some(dep =>
624
- dep.status === 'unhealthy',
625
- )
626
-
627
- if (criticalFailures) {
628
- return new Response('Service not ready', { status: 503 })
629
- }
630
-
631
- return new Response('OK', { status: 200 })
632
- }
633
- catch (error) {
634
- console.error(error)
635
- return new Response('Service not ready', { status: 503 })
636
- }
637
- },
638
-
639
- /**
640
- * Liveness probe endpoint
641
- */
642
- live: async (_req: EnhancedRequest): Promise<Response> => {
643
- // Simple liveness check - just return OK if the service is running
644
- return new Response('OK', { status: 200 })
645
- },
646
-
647
- /**
648
- * Startup probe endpoint
649
- */
650
- startup: async (_req: EnhancedRequest): Promise<Response> => {
651
- const manager = getHealthManager()
652
- if (!manager) {
653
- return new Response('Service not started', { status: 503 })
654
- }
655
-
656
- // Check if service has been running for at least the grace period
657
- const uptime = manager.getUptime()
658
- const gracePeriod = 60 // 60 seconds default grace period
659
-
660
- if (uptime < gracePeriod) {
661
- return new Response('Service starting up', { status: 503 })
662
- }
663
-
664
- return new Response('OK', { status: 200 })
665
- },
666
- }
667
-
668
- /**
669
- * Built-in dependency check factories
670
- */
671
- export const DependencyChecks = {
672
- /**
673
- * HTTP service dependency
674
- */
675
- httpService: (name: string, url: string, options: Partial<DependencyConfig> = {}): DependencyConfig => ({
676
- name,
677
- type: 'http',
678
- url,
679
- timeout: 5000,
680
- critical: true,
681
- ...options,
682
- }),
683
-
684
- /**
685
- * Database dependency
686
- */
687
- database: (name: string, options: Partial<DependencyConfig> = {}): DependencyConfig => ({
688
- name,
689
- type: 'database',
690
- timeout: 3000,
691
- critical: true,
692
- ...options,
693
- }),
694
-
695
- /**
696
- * Redis dependency
697
- */
698
- redis: (name: string, options: Partial<DependencyConfig> = {}): DependencyConfig => ({
699
- name,
700
- type: 'redis',
701
- timeout: 2000,
702
- critical: false,
703
- ...options,
704
- }),
705
-
706
- /**
707
- * File system dependency
708
- */
709
- fileSystem: (name: string, path: string, options: Partial<DependencyConfig> = {}): DependencyConfig => ({
710
- name,
711
- type: 'file',
712
- url: path,
713
- timeout: 1000,
714
- critical: true,
715
- ...options,
716
- }),
717
-
718
- /**
719
- * Custom dependency with function
720
- */
721
- custom: (name: string, checkFn: () => Promise<HealthCheckResult>, options: Partial<DependencyConfig> = {}): DependencyConfig => ({
722
- name,
723
- type: 'custom',
724
- check: checkFn,
725
- timeout: 5000,
726
- critical: true,
727
- ...options,
728
- }),
729
- }