11import  {  writeClient  }  from  './telemetry.js' 
22import  {  Point  }  from  '@influxdata/influxdb-client' 
33import  EventEmitter  from  'node:events' 
4+ import  *  as  Sentry  from  '@sentry/node' 
45
56export  class  MetricsEvent  { 
67  /** 
@@ -21,6 +22,7 @@ export class Metrics {
2122    this . mergedMetrics  =  null 
2223    /** @type  {Map<string, MetricsEvent> } */ 
2324    this . moduleMetrics  =  new  Map ( ) 
25+     this . lastErrorReportedAt  =  0 
2426  } 
2527
2628  /** 
@@ -46,15 +48,19 @@ export class Metrics {
4648      typeof  metrics . totalJobsCompleted  ===  'number'  && 
4749      typeof  this . moduleMetrics . get ( moduleName ) ?. totalJobsCompleted  ===  'number' 
4850    )  { 
49-       writeClient . writePoint ( 
50-         new  Point ( 'jobs-completed' ) 
51-           . stringField ( 'module' ,  moduleName ) 
52-           . intField ( 
53-             'value' , 
54-             metrics . totalJobsCompleted  - 
55-               this . moduleMetrics . get ( moduleName ) . totalJobsCompleted 
56-           ) 
57-       ) 
51+       const  diff  =  metrics . totalJobsCompleted  - 
52+         this . moduleMetrics . get ( moduleName ) . totalJobsCompleted 
53+       if  ( diff  <  0 )  { 
54+         this . maybeReportErrorToSentry ( 
55+           new  Error ( `Negative jobs completed for ${ moduleName }  ) 
56+         ) 
57+       }  else  if  ( diff  >  0 )  { 
58+         writeClient . writePoint ( 
59+           new  Point ( 'jobs-completed' ) 
60+             . stringField ( 'module' ,  moduleName ) 
61+             . intField ( 'value' ,  diff ) 
62+         ) 
63+       } 
5864    } 
5965    this . moduleMetrics . set ( moduleName ,  resolvedMetrics ) 
6066    const  mergedMetrics  =  { 
@@ -84,6 +90,18 @@ export class Metrics {
8490  onUpdate  ( fn )  { 
8591    this . #events. on ( 'update' ,  fn ) 
8692  } 
93+ 
94+   /** 
95+    * @param  {unknown } err 
96+    */ 
97+   maybeReportErrorToSentry  ( err )  { 
98+     const  now  =  Date . now ( ) 
99+     if  ( now  -  this . lastErrorReportedAt  <  4  /* HOURS */  *  3600_000 )  return 
100+     this . lastErrorReportedAt  =  now 
101+ 
102+     console . error ( 'Reporting the problem to Sentry for inspection by the Station team.' ) 
103+     Sentry . captureException ( err ) 
104+   } 
87105} 
88106
89107export  const  metrics  =  new  Metrics ( ) 
0 commit comments