All files / web/src/lib metrics.ts

93.1% Statements 689/740
100% Branches 9/9
50% Functions 2/4
93.1% Lines 689/740

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 7411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 6x 6x 9x 6x 6x 9x 6x 6x 9x 6x 6x 9x 1x 1x 1x 1x 1x 1x 1x                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Prometheus Metrics Library
 *
 * Comprehensive application metrics for observability:
 * - HTTP request duration and counts
 * - Socket.IO connection metrics
 * - Database query metrics
 * - Practice and arcade game metrics
 * - Worksheet and flowchart usage
 * - Classroom and user activity
 * - Node.js runtime metrics (default collectors)
 *
 * Usage:
 *   import { metrics } from '@/lib/metrics'
 *
 *   // Track a problem attempt
 *   metrics.practice.problemsTotal.inc({ game: 'addition', correct: 'true', difficulty: '2-digit' })
 *
 *   // Track request timing
 *   const end = metrics.http.requestDuration.startTimer({ method: 'GET', route: '/api/health' })
 *   // ... handle request ...
 *   end({ status_code: '200' })
 */
 
import { Registry, Counter, Histogram, Gauge, Summary, collectDefaultMetrics } from 'prom-client'
 
// Create a custom registry to avoid conflicts
export const metricsRegistry = new Registry()
 
// Set default labels for all metrics
metricsRegistry.setDefaultLabels({
  app: 'abaci-app',
})
 
// Collect default Node.js metrics (memory, CPU, event loop, etc.)
collectDefaultMetrics({
  register: metricsRegistry,
  prefix: 'nodejs_',
})
 
// =============================================================================
// HTTP METRICS
// =============================================================================
 
export const httpRequestDuration = new Histogram({
  name: 'http_request_duration_seconds',
  help: 'Duration of HTTP requests in seconds',
  labelNames: ['method', 'route', 'status_code'],
  buckets: [0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10],
  registers: [metricsRegistry],
})
 
export const httpRequestTotal = new Counter({
  name: 'http_requests_total',
  help: 'Total number of HTTP requests',
  labelNames: ['method', 'route', 'status_code'],
  registers: [metricsRegistry],
})
 
export const httpRequestsInFlight = new Gauge({
  name: 'http_requests_in_flight',
  help: 'Number of HTTP requests currently being processed',
  labelNames: ['method', 'route'],
  registers: [metricsRegistry],
})
 
export const httpRequestSize = new Summary({
  name: 'http_request_size_bytes',
  help: 'Size of HTTP request bodies',
  labelNames: ['method', 'route'],
  registers: [metricsRegistry],
})
 
export const httpResponseSize = new Summary({
  name: 'http_response_size_bytes',
  help: 'Size of HTTP response bodies',
  labelNames: ['method', 'route'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// SOCKET.IO METRICS
// =============================================================================
 
export const socketConnections = new Gauge({
  name: 'socketio_connections_active',
  help: 'Number of active Socket.IO connections',
  registers: [metricsRegistry],
})
 
export const socketConnectionsTotal = new Counter({
  name: 'socketio_connections_total',
  help: 'Total number of Socket.IO connections',
  registers: [metricsRegistry],
})
 
export const socketEventsTotal = new Counter({
  name: 'socketio_events_total',
  help: 'Total Socket.IO events by type',
  labelNames: ['event', 'direction'], // direction: 'in' or 'out'
  registers: [metricsRegistry],
})
 
export const socketRoomsActive = new Gauge({
  name: 'socketio_rooms_active',
  help: 'Number of active Socket.IO rooms',
  labelNames: ['room_type'], // 'practice', 'classroom', 'remote-camera'
  registers: [metricsRegistry],
})
 
// =============================================================================
// DATABASE METRICS
// =============================================================================
 
export const dbQueryDuration = new Histogram({
  name: 'db_query_duration_seconds',
  help: 'Duration of database queries in seconds',
  labelNames: ['operation', 'table'],
  buckets: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1],
  registers: [metricsRegistry],
})
 
export const dbQueryTotal = new Counter({
  name: 'db_queries_total',
  help: 'Total number of database queries',
  labelNames: ['operation', 'table', 'success'],
  registers: [metricsRegistry],
})
 
export const dbConnectionsActive = new Gauge({
  name: 'db_connections_active',
  help: 'Number of active database connections',
  registers: [metricsRegistry],
})
 
// =============================================================================
// PRACTICE & LEARNING METRICS
// =============================================================================
 
export const practiceSessionsActive = new Gauge({
  name: 'practice_sessions_active',
  help: 'Number of active practice sessions',
  labelNames: ['mode'], // 'timed', 'untimed', 'curriculum'
  registers: [metricsRegistry],
})
 
export const practiceSessionsTotal = new Counter({
  name: 'practice_sessions_total',
  help: 'Total practice sessions started',
  labelNames: ['mode'],
  registers: [metricsRegistry],
})
 
export const practiceProblemsTotal = new Counter({
  name: 'practice_problems_total',
  help: 'Total number of practice problems attempted',
  labelNames: ['operation', 'correct', 'digits'],
  registers: [metricsRegistry],
})
 
export const practiceResponseTime = new Histogram({
  name: 'practice_response_time_seconds',
  help: 'Time taken to answer practice problems',
  labelNames: ['operation', 'correct', 'digits'],
  buckets: [1, 2, 5, 10, 15, 30, 60, 120],
  registers: [metricsRegistry],
})
 
export const practiceStreakMax = new Gauge({
  name: 'practice_streak_current_max',
  help: 'Current maximum streak across all active sessions',
  registers: [metricsRegistry],
})
 
// =============================================================================
// ARCADE GAME METRICS
// =============================================================================
 
export const arcadeSessionsActive = new Gauge({
  name: 'arcade_sessions_active',
  help: 'Number of active arcade game sessions',
  labelNames: ['game'],
  registers: [metricsRegistry],
})
 
export const arcadeSessionsTotal = new Counter({
  name: 'arcade_sessions_total',
  help: 'Total arcade game sessions started',
  labelNames: ['game'],
  registers: [metricsRegistry],
})
 
export const arcadeGamesCompleted = new Counter({
  name: 'arcade_games_completed_total',
  help: 'Total arcade games completed',
  labelNames: ['game', 'outcome'], // outcome: 'win', 'lose', 'timeout', 'quit'
  registers: [metricsRegistry],
})
 
export const arcadeScoreHistogram = new Histogram({
  name: 'arcade_score',
  help: 'Distribution of arcade game scores',
  labelNames: ['game'],
  buckets: [0, 100, 500, 1000, 2500, 5000, 10000, 25000, 50000],
  registers: [metricsRegistry],
})
 
export const arcadeHighScore = new Gauge({
  name: 'arcade_high_score',
  help: 'Current high score by game',
  labelNames: ['game'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// WORKSHEET METRICS
// =============================================================================
 
export const worksheetGenerationsTotal = new Counter({
  name: 'worksheet_generations_total',
  help: 'Total worksheets generated',
  labelNames: ['operator', 'digits', 'format'], // format: 'pdf', 'preview'
  registers: [metricsRegistry],
})
 
export const worksheetGenerationDuration = new Histogram({
  name: 'worksheet_generation_duration_seconds',
  help: 'Time to generate worksheets',
  labelNames: ['operator', 'format'],
  buckets: [0.1, 0.5, 1, 2, 5, 10, 30],
  registers: [metricsRegistry],
})
 
export const worksheetProblemsGenerated = new Counter({
  name: 'worksheet_problems_generated_total',
  help: 'Total problems generated in worksheets',
  labelNames: ['operator'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// FLASHCARD METRICS
// =============================================================================
 
export const flashcardGenerationsTotal = new Counter({
  name: 'flashcard_generations_total',
  help: 'Total flashcard sets generated',
  labelNames: ['type'], // 'number-bonds', 'complements', 'custom'
  registers: [metricsRegistry],
})
 
export const flashcardCardsGenerated = new Counter({
  name: 'flashcard_cards_generated_total',
  help: 'Total flashcards generated',
  labelNames: ['type'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// FLOWCHART METRICS
// =============================================================================
 
export const flowchartViewsTotal = new Counter({
  name: 'flowchart_views_total',
  help: 'Total flowchart views',
  labelNames: ['flowchart', 'language'],
  registers: [metricsRegistry],
})
 
export const flowchartWorkshopSessionsActive = new Gauge({
  name: 'flowchart_workshop_sessions_active',
  help: 'Active flowchart workshop sessions',
  registers: [metricsRegistry],
})
 
export const flowchartWorkshopProblemsTotal = new Counter({
  name: 'flowchart_workshop_problems_total',
  help: 'Problems completed in flowchart workshop',
  labelNames: ['flowchart', 'correct'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// VISION / CAMERA METRICS
// =============================================================================
 
export const visionRecordingsActive = new Gauge({
  name: 'vision_recordings_active',
  help: 'Number of active vision recording sessions',
  registers: [metricsRegistry],
})
 
export const visionRecordingsTotal = new Counter({
  name: 'vision_recordings_total',
  help: 'Total vision recordings started',
  registers: [metricsRegistry],
})
 
export const visionFramesProcessed = new Counter({
  name: 'vision_frames_processed_total',
  help: 'Total video frames processed',
  registers: [metricsRegistry],
})
 
export const visionRecognitionsTotal = new Counter({
  name: 'vision_recognitions_total',
  help: 'Total abacus recognitions attempted',
  labelNames: ['success'],
  registers: [metricsRegistry],
})
 
export const remoteCameraSessionsActive = new Gauge({
  name: 'remote_camera_sessions_active',
  help: 'Active remote camera sessions',
  registers: [metricsRegistry],
})
 
// =============================================================================
// CLASSROOM / USER METRICS
// =============================================================================
 
export const classroomsActive = new Gauge({
  name: 'classrooms_active',
  help: 'Number of active classrooms',
  registers: [metricsRegistry],
})
 
export const classroomStudentsTotal = new Gauge({
  name: 'classroom_students_total',
  help: 'Total students across all classrooms',
  registers: [metricsRegistry],
})
 
export const playerLoginsTotal = new Counter({
  name: 'player_logins_total',
  help: 'Total player logins',
  labelNames: ['method'], // 'code', 'returning', 'guest'
  registers: [metricsRegistry],
})
 
export const teacherLoginsTotal = new Counter({
  name: 'teacher_logins_total',
  help: 'Total teacher logins',
  registers: [metricsRegistry],
})
 
// =============================================================================
// CURRICULUM / BKT METRICS
// =============================================================================
 
export const curriculumSkillMastery = new Histogram({
  name: 'curriculum_skill_mastery',
  help: 'Distribution of skill mastery levels',
  labelNames: ['skill_category'],
  buckets: [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0],
  registers: [metricsRegistry],
})
 
export const curriculumSkillsUnlocked = new Counter({
  name: 'curriculum_skills_unlocked_total',
  help: 'Total skills unlocked by students',
  labelNames: ['skill_category'],
  registers: [metricsRegistry],
})
 
export const curriculumSessionsCompleted = new Counter({
  name: 'curriculum_sessions_completed_total',
  help: 'Total curriculum sessions completed',
  labelNames: ['mode'], // 'daily', 'review', 'custom'
  registers: [metricsRegistry],
})
 
// =============================================================================
// LLM / AI METRICS
// =============================================================================
 
export const llmRequestsTotal = new Counter({
  name: 'llm_requests_total',
  help: 'Total LLM API requests',
  labelNames: ['provider', 'model', 'success'],
  registers: [metricsRegistry],
})
 
export const llmRequestDuration = new Histogram({
  name: 'llm_request_duration_seconds',
  help: 'LLM API request duration',
  labelNames: ['provider', 'model'],
  buckets: [0.5, 1, 2, 5, 10, 30, 60],
  registers: [metricsRegistry],
})
 
export const llmTokensUsed = new Counter({
  name: 'llm_tokens_used_total',
  help: 'Total LLM tokens used',
  labelNames: ['provider', 'model', 'type'], // type: 'input', 'output'
  registers: [metricsRegistry],
})
 
// =============================================================================
// SESSION / USAGE METRICS
// =============================================================================
 
export const sessionsActive = new Gauge({
  name: 'sessions_active',
  help: 'Number of active user sessions (heartbeat within last 60s)',
  registers: [metricsRegistry],
})
 
export const sessionDuration = new Histogram({
  name: 'session_duration_seconds',
  help: 'Duration of user sessions',
  buckets: [30, 60, 120, 300, 600, 1200, 1800, 3600, 7200],
  registers: [metricsRegistry],
})
 
export const pageViewsTotal = new Counter({
  name: 'page_views_total',
  help: 'Total page views',
  labelNames: ['path'],
  registers: [metricsRegistry],
})
 
export const uniqueVisitorsDaily = new Gauge({
  name: 'unique_visitors_daily',
  help: 'Approximate unique visitors in the last 24 hours',
  registers: [metricsRegistry],
})
 
// =============================================================================
// E2E SMOKE TEST METRICS
// =============================================================================
 
export const smokeTestLastStatus = new Gauge({
  name: 'smoke_test_last_status',
  help: 'Status of the last smoke test run (1=passed, 0=failed/error)',
  registers: [metricsRegistry],
})
 
export const smokeTestLastRunTimestamp = new Gauge({
  name: 'smoke_test_last_run_timestamp_seconds',
  help: 'Unix timestamp of the last completed smoke test run',
  registers: [metricsRegistry],
})
 
export const smokeTestLastDuration = new Gauge({
  name: 'smoke_test_last_duration_seconds',
  help: 'Duration of the last smoke test run in seconds',
  registers: [metricsRegistry],
})
 
export const smokeTestLastTotal = new Gauge({
  name: 'smoke_test_last_total_count',
  help: 'Total number of tests in the last smoke test run',
  registers: [metricsRegistry],
})
 
export const smokeTestLastPassed = new Gauge({
  name: 'smoke_test_last_passed_count',
  help: 'Number of passed tests in the last smoke test run',
  registers: [metricsRegistry],
})
 
export const smokeTestLastFailed = new Gauge({
  name: 'smoke_test_last_failed_count',
  help: 'Number of failed tests in the last smoke test run',
  registers: [metricsRegistry],
})
 
export const smokeTestRunsTotal = new Counter({
  name: 'smoke_test_runs_total',
  help: 'Total number of completed smoke test runs',
  labelNames: ['status'], // 'passed', 'failed', 'error'
  registers: [metricsRegistry],
})
 
/**
 * Update smoke test gauges from a result object.
 * Used both for DB initialization and when new results arrive via API.
 */
export function updateSmokeTestMetrics(run: {
  status: string
  startedAt: Date
  completedAt: Date | null
  totalTests: number | null
  passedTests: number | null
  failedTests: number | null
  durationMs: number | null
}) {
  smokeTestLastStatus.set(run.status === 'passed' ? 1 : 0)
  smokeTestLastRunTimestamp.set((run.completedAt ?? run.startedAt).getTime() / 1000)
  if (run.durationMs != null) {
    smokeTestLastDuration.set(run.durationMs / 1000)
  }
  if (run.totalTests != null) {
    smokeTestLastTotal.set(run.totalTests)
  }
  if (run.passedTests != null) {
    smokeTestLastPassed.set(run.passedTests)
  }
  if (run.failedTests != null) {
    smokeTestLastFailed.set(run.failedTests)
  }
}
 
/**
 * Initialize smoke test metrics from DB.
 * Called from the /api/metrics handler on first scrape so it runs in a
 * proper request context on every pod. Guarded to only execute once.
 */
let _smokeTestMetricsInitialized = false
export async function initSmokeTestMetrics() {
  if (_smokeTestMetricsInitialized) return
  _smokeTestMetricsInitialized = true

  try {
    const { db } = await import('@/db')
    const { smokeTestRuns } = await import('@/db/schema')
    const { desc, ne } = await import('drizzle-orm')

    const latestRun = await db
      .select()
      .from(smokeTestRuns)
      .where(ne(smokeTestRuns.status, 'running'))
      .orderBy(desc(smokeTestRuns.startedAt))
      .limit(1)
      .get()

    if (latestRun) {
      updateSmokeTestMetrics(latestRun)
    }
  } catch (err) {
    // Allow retry on next scrape if init fails
    _smokeTestMetricsInitialized = false
    console.error('Failed to initialize smoke test metrics from DB:', err)
  }
}
 
// =============================================================================
// UNIT TEST COVERAGE METRICS
// =============================================================================
 
export const coverageLinesPct = new Gauge({
  name: 'coverage_lines_pct',
  help: 'Line coverage percentage from unit tests',
  registers: [metricsRegistry],
})
 
export const coverageBranchesPct = new Gauge({
  name: 'coverage_branches_pct',
  help: 'Branch coverage percentage from unit tests',
  registers: [metricsRegistry],
})
 
export const coverageFunctionsPct = new Gauge({
  name: 'coverage_functions_pct',
  help: 'Function coverage percentage from unit tests',
  registers: [metricsRegistry],
})
 
export const coverageStatementsPct = new Gauge({
  name: 'coverage_statements_pct',
  help: 'Statement coverage percentage from unit tests',
  registers: [metricsRegistry],
})
 
export const coverageLastRunTimestamp = new Gauge({
  name: 'coverage_last_run_timestamp_seconds',
  help: 'Unix timestamp of the last coverage report',
  registers: [metricsRegistry],
})
 
/**
 * Update coverage gauges from a result object.
 * Used both for DB initialization and when new results arrive via API.
 */
export function updateCoverageMetrics(run: {
  linesPct: number
  branchesPct: number
  functionsPct: number
  statementsPct: number
  timestamp: Date
}) {
  coverageLinesPct.set(run.linesPct)
  coverageBranchesPct.set(run.branchesPct)
  coverageFunctionsPct.set(run.functionsPct)
  coverageStatementsPct.set(run.statementsPct)
  coverageLastRunTimestamp.set(run.timestamp.getTime() / 1000)
}
 
/**
 * Initialize coverage metrics from DB.
 * Called from the /api/metrics handler on first scrape so it runs in a
 * proper request context on every pod. Guarded to only execute once.
 */
let _coverageMetricsInitialized = false
export async function initCoverageMetrics() {
  if (_coverageMetricsInitialized) return
  _coverageMetricsInitialized = true

  try {
    const { db } = await import('@/db')
    const { coverageResults } = await import('@/db/schema')
    const { desc } = await import('drizzle-orm')

    const latest = await db
      .select()
      .from(coverageResults)
      .orderBy(desc(coverageResults.timestamp))
      .limit(1)
      .get()

    if (latest) {
      updateCoverageMetrics(latest)
    }
  } catch (err) {
    // Allow retry on next scrape if init fails
    _coverageMetricsInitialized = false
    console.error('Failed to initialize coverage metrics from DB:', err)
  }
}
 
// =============================================================================
// ERROR METRICS
// =============================================================================
 
export const errorsTotal = new Counter({
  name: 'errors_total',
  help: 'Total application errors',
  labelNames: ['type', 'location'], // type: 'api', 'render', 'database', 'external'
  registers: [metricsRegistry],
})
 
export const errorsByCode = new Counter({
  name: 'errors_by_code_total',
  help: 'Errors by HTTP status code',
  labelNames: ['status_code', 'route'],
  registers: [metricsRegistry],
})
 
// =============================================================================
// CONVENIENCE NAMESPACE EXPORT
// =============================================================================
 
export const metrics = {
  http: {
    requestDuration: httpRequestDuration,
    requestTotal: httpRequestTotal,
    requestsInFlight: httpRequestsInFlight,
    requestSize: httpRequestSize,
    responseSize: httpResponseSize,
  },
  socket: {
    connections: socketConnections,
    connectionsTotal: socketConnectionsTotal,
    eventsTotal: socketEventsTotal,
    roomsActive: socketRoomsActive,
  },
  db: {
    queryDuration: dbQueryDuration,
    queryTotal: dbQueryTotal,
    connectionsActive: dbConnectionsActive,
  },
  practice: {
    sessionsActive: practiceSessionsActive,
    sessionsTotal: practiceSessionsTotal,
    problemsTotal: practiceProblemsTotal,
    responseTime: practiceResponseTime,
    streakMax: practiceStreakMax,
  },
  arcade: {
    sessionsActive: arcadeSessionsActive,
    sessionsTotal: arcadeSessionsTotal,
    gamesCompleted: arcadeGamesCompleted,
    scoreHistogram: arcadeScoreHistogram,
    highScore: arcadeHighScore,
  },
  worksheet: {
    generationsTotal: worksheetGenerationsTotal,
    generationDuration: worksheetGenerationDuration,
    problemsGenerated: worksheetProblemsGenerated,
  },
  flashcard: {
    generationsTotal: flashcardGenerationsTotal,
    cardsGenerated: flashcardCardsGenerated,
  },
  flowchart: {
    viewsTotal: flowchartViewsTotal,
    workshopSessionsActive: flowchartWorkshopSessionsActive,
    workshopProblemsTotal: flowchartWorkshopProblemsTotal,
  },
  vision: {
    recordingsActive: visionRecordingsActive,
    recordingsTotal: visionRecordingsTotal,
    framesProcessed: visionFramesProcessed,
    recognitionsTotal: visionRecognitionsTotal,
    remoteCameraSessionsActive: remoteCameraSessionsActive,
  },
  classroom: {
    active: classroomsActive,
    studentsTotal: classroomStudentsTotal,
    playerLogins: playerLoginsTotal,
    teacherLogins: teacherLoginsTotal,
  },
  curriculum: {
    skillMastery: curriculumSkillMastery,
    skillsUnlocked: curriculumSkillsUnlocked,
    sessionsCompleted: curriculumSessionsCompleted,
  },
  llm: {
    requestsTotal: llmRequestsTotal,
    requestDuration: llmRequestDuration,
    tokensUsed: llmTokensUsed,
  },
  smokeTest: {
    lastStatus: smokeTestLastStatus,
    lastRunTimestamp: smokeTestLastRunTimestamp,
    lastDuration: smokeTestLastDuration,
    lastTotal: smokeTestLastTotal,
    lastPassed: smokeTestLastPassed,
    lastFailed: smokeTestLastFailed,
    runsTotal: smokeTestRunsTotal,
  },
  coverage: {
    linesPct: coverageLinesPct,
    branchesPct: coverageBranchesPct,
    functionsPct: coverageFunctionsPct,
    statementsPct: coverageStatementsPct,
    lastRunTimestamp: coverageLastRunTimestamp,
  },
  errors: {
    total: errorsTotal,
    byCode: errorsByCode,
  },
  sessions: {
    active: sessionsActive,
    duration: sessionDuration,
    pageViews: pageViewsTotal,
    uniqueVisitors: uniqueVisitorsDaily,
  },
}