@zintrust/workers 0.4.67 → 0.4.70

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.
@@ -52,6 +52,7 @@ let shutdownHandlersRegistered = false;
52
52
  const signalHandlers: {
53
53
  sigterm?: () => Promise<void>;
54
54
  sighup?: () => Promise<void>;
55
+ sigusr2?: () => Promise<void>;
55
56
  uncaughtException?: (error: Error) => Promise<void>;
56
57
  unhandledRejection?: (reason: unknown) => void;
57
58
  } = {};
@@ -153,6 +154,17 @@ function registerShutdownHandlers(): void {
153
154
  };
154
155
  process.on('SIGHUP', signalHandlers.sighup);
155
156
 
157
+ // SIGUSR2 - watcher/hot-reload restart
158
+ signalHandlers.sigusr2 = async (): Promise<void> => {
159
+ Logger.info('📨 Received SIGUSR2 signal');
160
+ try {
161
+ await shutdown({ signal: 'SIGUSR2', timeout: 30000, forceExit: true });
162
+ } catch (error) {
163
+ Logger.error('Error during SIGUSR2 shutdown', error);
164
+ }
165
+ };
166
+ process.on('SIGUSR2', signalHandlers.sigusr2);
167
+
156
168
  // Handle uncaught errors during shutdown
157
169
  signalHandlers.uncaughtException = async (error: Error): Promise<void> => {
158
170
  Logger.error('💥 Uncaught exception during worker operations', error);
@@ -185,6 +197,7 @@ function unregisterShutdownHandlers(): void {
185
197
 
186
198
  if (signalHandlers.sigterm) process.off('SIGTERM', signalHandlers.sigterm);
187
199
  if (signalHandlers.sighup) process.off('SIGHUP', signalHandlers.sighup);
200
+ if (signalHandlers.sigusr2) process.off('SIGUSR2', signalHandlers.sigusr2);
188
201
  if (signalHandlers.uncaughtException)
189
202
  process.off('uncaughtException', signalHandlers.uncaughtException);
190
203
  if (signalHandlers.unhandledRejection)
@@ -192,6 +205,7 @@ function unregisterShutdownHandlers(): void {
192
205
 
193
206
  signalHandlers.sigterm = undefined;
194
207
  signalHandlers.sighup = undefined;
208
+ signalHandlers.sigusr2 = undefined;
195
209
  signalHandlers.uncaughtException = undefined;
196
210
  signalHandlers.unhandledRejection = undefined;
197
211
 
@@ -48,8 +48,11 @@ export interface WorkerData {
48
48
  driver: WorkerDriver;
49
49
  version: string;
50
50
  processed: number;
51
+ failed: number;
51
52
  avgTime: number;
52
53
  memory: number;
54
+ cpu: number;
55
+ uptime: number;
53
56
  autoStart: boolean;
54
57
  activeStatus?: boolean;
55
58
  details?: {
@@ -66,6 +69,7 @@ export interface WorkerData {
66
69
 
67
70
  // Workers List Response Types
68
71
  export interface WorkersListResponse {
72
+ appName: string;
69
73
  workers: WorkerData[];
70
74
  queueData: QueueData;
71
75
  pagination: {
@@ -118,6 +122,9 @@ export type RawWorkerData = {
118
122
  avgTime?: number;
119
123
  memory?: number;
120
124
  processed?: number;
125
+ failed?: number;
126
+ cpu?: number;
127
+ uptime?: number;
121
128
  version?: string;
122
129
  autoStart?: boolean;
123
130
  activeStatus?: boolean;
@@ -1,6 +1,7 @@
1
1
  import { Env, ErrorFactory, Logger } from '@zintrust/core';
2
2
  import { WorkerFactory } from '../WorkerFactory';
3
3
  import { WorkerMetrics as WorkerMetricsManager } from '../WorkerMetrics';
4
+ import { WorkerRegistry } from '../WorkerRegistry';
4
5
  import type { WorkerRecord } from '../storage/WorkerStore';
5
6
  import type {
6
7
  GetWorkersQuery,
@@ -19,6 +20,19 @@ import type {
19
20
  const DEFAULT_PAGE_SIZE = 100;
20
21
  const MAX_PAGE_SIZE = 200;
21
22
 
23
+ type LiveWorkerMetrics = Readonly<{
24
+ processed: number;
25
+ failed: number;
26
+ memory: number;
27
+ cpu: number;
28
+ uptime: number;
29
+ }>;
30
+
31
+ type HistoricalMetric = Readonly<{
32
+ total: number;
33
+ average: number;
34
+ }>;
35
+
22
36
  type PersistenceResult = {
23
37
  workers: WorkerData[];
24
38
  total: number;
@@ -155,6 +169,7 @@ export async function getWorkers(query: GetWorkersQuery): Promise<WorkersListRes
155
169
 
156
170
  // Prepare result
157
171
  const result: WorkersListResponse = {
172
+ appName: resolveAppName(),
158
173
  workers: workersWithMetrics,
159
174
  queueData,
160
175
  pagination: {
@@ -428,8 +443,11 @@ const buildWorkerFromRaw = (workerData: RawWorkerData, driver: WorkerDriver): Wo
428
443
  driver,
429
444
  version: workerData.version || '1.0.0',
430
445
  processed: workerData.processed || 0,
446
+ failed: workerData.failed || 0,
431
447
  avgTime: workerData.avgTime || 0,
432
448
  memory: workerData.memory || 0,
449
+ cpu: workerData.cpu || 0,
450
+ uptime: workerData.uptime || 0,
433
451
  autoStart: workerData.autoStart || false,
434
452
  activeStatus: workerData.activeStatus ?? true,
435
453
  details: workerData.details || {
@@ -708,69 +726,120 @@ async function getMemoryQueueData(): Promise<QueueData> {
708
726
  };
709
727
  }
710
728
 
711
- async function enrichWithMetrics(workers: WorkerData[]): Promise<WorkerData[]> {
712
- const now = Date.now();
713
- const oneHourAgo = new Date(now - 60 * 60 * 1000);
714
- const endDate = new Date(now);
715
-
716
- if (workers.length === 0) return workers;
717
-
718
- const metricRequests = workers.flatMap((worker) => [
729
+ const createWorkerMetricRequests = (
730
+ workers: ReadonlyArray<WorkerData>,
731
+ startDate: Date,
732
+ endDate: Date
733
+ ): Array<{
734
+ workerName: string;
735
+ metricType: 'processed' | 'duration' | 'memory';
736
+ granularity: 'hourly';
737
+ startDate: Date;
738
+ endDate: Date;
739
+ }> => {
740
+ return workers.flatMap((worker) => [
719
741
  {
720
742
  workerName: worker.name,
721
743
  metricType: 'processed' as const,
722
744
  granularity: 'hourly' as const,
723
- startDate: oneHourAgo,
745
+ startDate,
724
746
  endDate,
725
747
  },
726
748
  {
727
749
  workerName: worker.name,
728
750
  metricType: 'duration' as const,
729
751
  granularity: 'hourly' as const,
730
- startDate: oneHourAgo,
752
+ startDate,
731
753
  endDate,
732
754
  },
733
755
  {
734
756
  workerName: worker.name,
735
757
  metricType: 'memory' as const,
736
758
  granularity: 'hourly' as const,
737
- startDate: oneHourAgo,
759
+ startDate,
738
760
  endDate,
739
761
  },
740
762
  ]);
763
+ };
764
+
765
+ const mergeWorkerListMetrics = (
766
+ worker: WorkerData,
767
+ results: ReadonlyArray<{ total: number; average: number }>,
768
+ index: number,
769
+ liveMetricsByName: ReadonlyMap<string, LiveWorkerMetrics>
770
+ ): WorkerData => {
771
+ const baseIdx = index * 3;
772
+ const processedMetric = results[baseIdx];
773
+ const durationMetric = results[baseIdx + 1];
774
+ const memoryMetric = results[baseIdx + 2];
775
+ const liveMetrics = liveMetricsByName.get(worker.name);
776
+
777
+ let processed = worker.processed;
778
+ if (liveMetrics) {
779
+ processed = liveMetrics.processed;
780
+ } else if (Number.isFinite(processedMetric?.total)) {
781
+ processed = Math.round(processedMetric.total);
782
+ }
783
+
784
+ let memory = worker.memory;
785
+ if (liveMetrics) {
786
+ memory = liveMetrics.memory;
787
+ } else if (Number.isFinite(memoryMetric?.average)) {
788
+ memory = Math.round(memoryMetric.average);
789
+ }
790
+
791
+ const avgTime =
792
+ durationMetric && Number.isFinite(durationMetric.average)
793
+ ? Math.round(durationMetric.average)
794
+ : worker.avgTime;
795
+
796
+ return {
797
+ ...worker,
798
+ processed,
799
+ failed: liveMetrics?.failed ?? worker.failed,
800
+ avgTime,
801
+ memory,
802
+ cpu: liveMetrics?.cpu ?? worker.cpu,
803
+ uptime: liveMetrics?.uptime ?? worker.uptime,
804
+ };
805
+ };
806
+
807
+ const applyWorkerLiveMetricsFallback = (
808
+ worker: WorkerData,
809
+ liveMetricsByName: ReadonlyMap<string, LiveWorkerMetrics>
810
+ ): WorkerData => {
811
+ const liveMetrics = liveMetricsByName.get(worker.name);
812
+ if (liveMetrics === undefined) {
813
+ return worker;
814
+ }
815
+
816
+ return {
817
+ ...worker,
818
+ processed: liveMetrics.processed,
819
+ failed: liveMetrics.failed,
820
+ memory: liveMetrics.memory,
821
+ cpu: liveMetrics.cpu,
822
+ uptime: liveMetrics.uptime,
823
+ };
824
+ };
825
+
826
+ async function enrichWithMetrics(workers: WorkerData[]): Promise<WorkerData[]> {
827
+ const now = Date.now();
828
+ const oneHourAgo = new Date(now - 60 * 60 * 1000);
829
+ const endDate = new Date(now);
830
+ const liveMetricsByName = getLiveWorkerMetricsByName();
831
+
832
+ if (workers.length === 0) return workers;
833
+ const metricRequests = createWorkerMetricRequests(workers, oneHourAgo, endDate);
741
834
 
742
835
  try {
743
836
  const results = await WorkerMetricsManager.aggregateBatch(metricRequests);
744
-
745
- return workers.map((worker, index) => {
746
- const baseIdx = index * 3;
747
- const processedMetric = results[baseIdx];
748
- const durationMetric = results[baseIdx + 1];
749
- const memoryMetric = results[baseIdx + 2];
750
-
751
- const processed =
752
- processedMetric && Number.isFinite(processedMetric.total)
753
- ? Math.round(processedMetric.total)
754
- : worker.processed;
755
- const avgTime =
756
- durationMetric && Number.isFinite(durationMetric.average)
757
- ? Math.round(durationMetric.average)
758
- : worker.avgTime;
759
- const memory =
760
- memoryMetric && Number.isFinite(memoryMetric.average)
761
- ? Math.round(memoryMetric.average)
762
- : worker.memory;
763
-
764
- return {
765
- ...worker,
766
- processed,
767
- avgTime,
768
- memory,
769
- };
770
- });
837
+ return workers.map((worker, index) =>
838
+ mergeWorkerListMetrics(worker, results, index, liveMetricsByName)
839
+ );
771
840
  } catch (error) {
772
841
  Logger.debug('Batch metrics unavailable', error);
773
- return workers;
842
+ return workers.map((worker) => applyWorkerLiveMetricsFallback(worker, liveMetricsByName));
774
843
  }
775
844
  }
776
845
 
@@ -791,8 +860,11 @@ async function buildWorkerDetails(worker: WorkerData): Promise<WorkerData> {
791
860
  return {
792
861
  ...worker,
793
862
  processed: metrics.processed,
863
+ failed: metrics.failed,
794
864
  avgTime: metrics.avgTime,
795
865
  memory: metrics.memory,
866
+ cpu: metrics.cpu,
867
+ uptime: metrics.uptime,
796
868
  details: {
797
869
  configuration,
798
870
  health,
@@ -865,59 +937,169 @@ const getWorkerMetricsSnapshot = async (
865
937
  const now = Date.now();
866
938
  const oneHourAgo = new Date(now - 60 * 60 * 1000);
867
939
  const endDate = new Date(now);
940
+ const liveMetrics = getLiveWorkerMetrics(name);
868
941
 
869
942
  try {
870
- const [processedMetric, durationMetric, memoryMetric] = await Promise.all([
871
- WorkerMetricsManager.aggregate({
872
- workerName: name,
873
- metricType: 'processed',
874
- granularity: 'hourly',
875
- startDate: oneHourAgo,
876
- endDate,
877
- }),
878
- WorkerMetricsManager.aggregate({
879
- workerName: name,
880
- metricType: 'duration',
881
- granularity: 'hourly',
882
- startDate: oneHourAgo,
883
- endDate,
884
- }),
885
- WorkerMetricsManager.aggregate({
886
- workerName: name,
887
- metricType: 'memory',
888
- granularity: 'hourly',
889
- startDate: oneHourAgo,
890
- endDate,
891
- }),
892
- ]);
893
-
894
- return {
895
- processed: Number.isFinite(processedMetric.total)
896
- ? Math.round(processedMetric.total)
897
- : fallback.processed,
898
- failed: 0,
899
- avgTime: Number.isFinite(durationMetric.average)
900
- ? Math.round(durationMetric.average)
901
- : fallback.avgTime,
902
- memory: Number.isFinite(memoryMetric.average)
903
- ? Math.round(memoryMetric.average)
904
- : fallback.memory,
905
- cpu: 0,
906
- uptime: 0,
907
- };
943
+ const historicalMetrics = await loadHistoricalWorkerMetrics(name, oneHourAgo, endDate);
944
+ return buildWorkerMetricsSnapshot(fallback, liveMetrics, historicalMetrics);
908
945
  } catch (error) {
909
946
  Logger.debug(`Metrics snapshot unavailable for worker ${name}`, error);
910
- return {
911
- processed: fallback.processed,
912
- failed: 0,
913
- avgTime: fallback.avgTime,
914
- memory: fallback.memory,
915
- cpu: 0,
916
- uptime: 0,
917
- };
947
+ return buildWorkerMetricsSnapshot(fallback, liveMetrics);
918
948
  }
919
949
  };
920
950
 
951
+ const loadHistoricalWorkerMetrics = async (
952
+ name: string,
953
+ startDate: Date,
954
+ endDate: Date
955
+ ): Promise<ReadonlyArray<HistoricalMetric>> => {
956
+ return Promise.all([
957
+ WorkerMetricsManager.aggregate({
958
+ workerName: name,
959
+ metricType: 'processed',
960
+ granularity: 'hourly',
961
+ startDate,
962
+ endDate,
963
+ }),
964
+ WorkerMetricsManager.aggregate({
965
+ workerName: name,
966
+ metricType: 'errors',
967
+ granularity: 'hourly',
968
+ startDate,
969
+ endDate,
970
+ }),
971
+ WorkerMetricsManager.aggregate({
972
+ workerName: name,
973
+ metricType: 'duration',
974
+ granularity: 'hourly',
975
+ startDate,
976
+ endDate,
977
+ }),
978
+ WorkerMetricsManager.aggregate({
979
+ workerName: name,
980
+ metricType: 'memory',
981
+ granularity: 'hourly',
982
+ startDate,
983
+ endDate,
984
+ }),
985
+ WorkerMetricsManager.aggregate({
986
+ workerName: name,
987
+ metricType: 'cpu',
988
+ granularity: 'hourly',
989
+ startDate,
990
+ endDate,
991
+ }),
992
+ ]);
993
+ };
994
+
995
+ const resolveHistoricalTotal = (
996
+ liveValue: number | undefined,
997
+ metric: HistoricalMetric | undefined,
998
+ fallback: number
999
+ ): number => {
1000
+ if (typeof liveValue === 'number') {
1001
+ return liveValue;
1002
+ }
1003
+
1004
+ if (Number.isFinite(metric?.total)) {
1005
+ const total = metric?.total ?? fallback;
1006
+ return Math.round(total);
1007
+ }
1008
+
1009
+ return fallback;
1010
+ };
1011
+
1012
+ const resolveHistoricalAverage = (
1013
+ liveValue: number | undefined,
1014
+ metric: HistoricalMetric | undefined,
1015
+ fallback: number
1016
+ ): number => {
1017
+ if (typeof liveValue === 'number') {
1018
+ return liveValue;
1019
+ }
1020
+
1021
+ if (Number.isFinite(metric?.average)) {
1022
+ const average = metric?.average ?? fallback;
1023
+ return Math.round(average);
1024
+ }
1025
+
1026
+ return fallback;
1027
+ };
1028
+
1029
+ const buildWorkerMetricsSnapshot = (
1030
+ fallback: WorkerData,
1031
+ liveMetrics?: LiveWorkerMetrics,
1032
+ historicalMetrics?: ReadonlyArray<HistoricalMetric>
1033
+ ): WorkerMetrics => {
1034
+ const [processedMetric, errorMetric, durationMetric, memoryMetric, cpuMetric] =
1035
+ historicalMetrics ?? [];
1036
+
1037
+ return {
1038
+ processed: resolveHistoricalTotal(liveMetrics?.processed, processedMetric, fallback.processed),
1039
+ failed: resolveHistoricalTotal(liveMetrics?.failed, errorMetric, fallback.failed),
1040
+ avgTime: resolveHistoricalAverage(undefined, durationMetric, fallback.avgTime),
1041
+ memory: resolveHistoricalAverage(liveMetrics?.memory, memoryMetric, fallback.memory),
1042
+ cpu: resolveHistoricalAverage(liveMetrics?.cpu, cpuMetric, fallback.cpu),
1043
+ uptime: liveMetrics?.uptime ?? fallback.uptime,
1044
+ };
1045
+ };
1046
+
1047
+ const resolveAppName = (): string => {
1048
+ return Env.get('APP_NAME', 'ZinTrust').trim() || 'ZinTrust';
1049
+ };
1050
+
1051
+ const getLiveWorkerMetrics = (name: string): LiveWorkerMetrics | undefined => {
1052
+ const metrics = WorkerRegistry.getMetrics(name);
1053
+ const uptime = WorkerRegistry.getSnapshot().workers.find(
1054
+ (worker) => worker.name === name
1055
+ )?.uptime;
1056
+
1057
+ if (metrics === null && uptime === undefined) {
1058
+ return undefined;
1059
+ }
1060
+
1061
+ return Object.freeze({
1062
+ processed: metrics?.processedCount ?? 0,
1063
+ failed: metrics?.errorCount ?? 0,
1064
+ memory: metrics?.memoryUsage ?? 0,
1065
+ cpu: metrics?.cpuUsage ?? 0,
1066
+ uptime:
1067
+ typeof uptime === 'number' && Number.isFinite(uptime) ? Math.max(0, Math.round(uptime)) : 0,
1068
+ });
1069
+ };
1070
+
1071
+ const getLiveWorkerMetricsByName = (): ReadonlyMap<string, LiveWorkerMetrics> => {
1072
+ const snapshot = WorkerRegistry.getSnapshot();
1073
+ const uptimeByName = new Map(
1074
+ snapshot.workers.map((worker) => [worker.name, worker.uptime ?? 0] as const)
1075
+ );
1076
+ const liveMetrics = new Map<string, LiveWorkerMetrics>();
1077
+
1078
+ for (const workerName of WorkerRegistry.list()) {
1079
+ const metrics = WorkerRegistry.getMetrics(workerName);
1080
+ const uptime = uptimeByName.get(workerName);
1081
+ if (metrics === null && uptime === undefined) {
1082
+ continue;
1083
+ }
1084
+
1085
+ liveMetrics.set(
1086
+ workerName,
1087
+ Object.freeze({
1088
+ processed: metrics?.processedCount ?? 0,
1089
+ failed: metrics?.errorCount ?? 0,
1090
+ memory: metrics?.memoryUsage ?? 0,
1091
+ cpu: metrics?.cpuUsage ?? 0,
1092
+ uptime:
1093
+ typeof uptime === 'number' && Number.isFinite(uptime)
1094
+ ? Math.max(0, Math.round(uptime))
1095
+ : 0,
1096
+ })
1097
+ );
1098
+ }
1099
+
1100
+ return liveMetrics;
1101
+ };
1102
+
921
1103
  export async function toggleAutoStart(name: string, enabled: boolean): Promise<void> {
922
1104
  await WorkerFactory.setAutoStart(name, enabled);
923
1105
  }
@@ -1,5 +1,5 @@
1
1
  import type { IRequest, IResponse, IRouter, RouteOptions } from '@zintrust/core';
2
- import { Router } from '@zintrust/core';
2
+ import { Env, Router } from '@zintrust/core';
3
3
  import type { TelemetrySettings } from './api/TelemetryAPI';
4
4
  import { createSnapshotBuilder } from './api/TelemetryAPI';
5
5
  import { teleStream } from './api/TelemetryMonitoringService';
@@ -78,6 +78,7 @@ function registerDashboardRoute(
78
78
  basePath: settings.basePath,
79
79
  autoRefresh: settings.autoRefresh,
80
80
  refreshIntervalMs: settings.refreshIntervalMs,
81
+ appName: Env.get('APP_NAME', 'ZinTrust'),
81
82
  })
82
83
  );
83
84
  },
@@ -7,6 +7,11 @@ export type DashboardUiOptions = {
7
7
  basePath: string;
8
8
  autoRefresh: boolean;
9
9
  refreshIntervalMs: number;
10
+ appName?: string;
11
+ };
12
+
13
+ const resolveAppName = (appName?: string): string => {
14
+ return typeof appName === 'string' && appName.trim() !== '' ? appName.trim() : 'ZinTrust';
10
15
  };
11
16
 
12
17
  const getDashboardColorStyles = (): string => `
@@ -148,24 +153,24 @@ const getLogo = (): string => `
148
153
  <path d="M44 50H56" stroke="rgba(255,255,255,0.22)" stroke-width="6" stroke-linecap="round" />
149
154
  </svg>`;
150
155
 
151
- const getDashboardHead = (): string => `
156
+ const getDashboardHead = (appName: string): string => `
152
157
  <head>
153
158
  <meta charset="UTF-8" />
154
159
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
155
- <title>ZinTrust Telemetry Dashboard</title>
160
+ <title>${appName} Telemetry Dashboard</title>
156
161
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
157
162
  ${getDashboardStyles()}
158
163
  </head>`;
159
164
 
160
- const getDashboardHeader = (): string => `
165
+ const getDashboardHeader = (appName: string): string => `
161
166
  <header class="zt-header">
162
167
  <div class="zt-brand">
163
168
  <div class="zt-brand-icon">
164
169
  ${getLogo()}
165
170
  </div>
166
171
  <div>
167
- <p class="zt-kicker">ZinTrust</p>
168
- <h1 class="zt-title">Telemetry Dashboard</h1>
172
+ <p class="zt-kicker">${appName}</p>
173
+ <h1 class="zt-title">${appName} Telemetry Dashboard</h1>
169
174
  <p class="zt-subtitle">Unified view of worker health and performance</p>
170
175
  </div>
171
176
  </div>
@@ -212,10 +217,10 @@ const getDashboardCharts = (): string => `
212
217
 
213
218
  ${renderAlertPanel()}`;
214
219
 
215
- const getDashboardBody = (): string => `
220
+ const getDashboardBody = (appName: string): string => `
216
221
  <div class="zt-page">
217
222
  <div class="zt-container">
218
- ${getDashboardHeader()}
223
+ ${getDashboardHeader(appName)}
219
224
 
220
225
  <section id="error" class="hidden zt-alert"></section>
221
226
 
@@ -628,11 +633,15 @@ ${getDashboardScriptControls()}
628
633
  ${getDashboardScriptBootstrap()}
629
634
  </script>`;
630
635
 
631
- export const getDashboardHtml = (options: DashboardUiOptions): string => `<!DOCTYPE html>
636
+ export const getDashboardHtml = (options: DashboardUiOptions): string => {
637
+ const appName = resolveAppName(options.appName);
638
+
639
+ return `<!DOCTYPE html>
632
640
  <html lang="en">
633
- ${getDashboardHead()}
641
+ ${getDashboardHead(appName)}
634
642
  <body>
635
- ${getDashboardBody()}
643
+ ${getDashboardBody(appName)}
636
644
  ${getDashboardScript(options)}
637
645
  </body>
638
646
  </html>`;
647
+ };