@kumori/aurora-backend-handler 1.0.136 → 1.0.138

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.
@@ -1,7 +1,9 @@
1
1
  import { Environment } from "@kumori/aurora-interfaces";
2
2
  import { makeGlobalWebSocketRequest } from "../websocket-manager";
3
3
 
4
- export const getReporting = async (env: Environment) => {
4
+ export type ReportingTarget = Pick<Environment, "tenant" | "account" | "name">;
5
+
6
+ export const getReporting = async (env: ReportingTarget) => {
5
7
  try {
6
8
  const toDate = new Date();
7
9
  const fromDate = new Date();
@@ -5,6 +5,7 @@ import {
5
5
  initializeGlobalWebSocketClient,
6
6
  getWebSocketStatus,
7
7
  makeGlobalWebSocketRequest,
8
+ refreshReportingForService,
8
9
  } from "../websocket-manager";
9
10
  import { errors, Link, Notification, Service } from "@kumori/aurora-interfaces";
10
11
  import { Revision } from "@kumori/aurora-interfaces/interfaces/revision-interface";
@@ -168,6 +169,7 @@ export const deleteService = async (data: Service, security: string) => {
168
169
  "DELETE",
169
170
  data.name,
170
171
  );
172
+ refreshReportingForService(data);
171
173
  return response;
172
174
  } catch (err) {
173
175
  console.error("Error in service deletion WebSocket request:", err);
@@ -485,6 +487,8 @@ export const updateService = async (
485
487
  code: "TIMEOUT",
486
488
  error: "_timeout_",
487
489
  });
490
+ } else {
491
+ refreshReportingForService(data);
488
492
  }
489
493
  } else {
490
494
  const parameterObject: Record<string, any> = {};
@@ -617,6 +621,7 @@ export const updateService = async (
617
621
  "UPDATE_CONFIG",
618
622
  data.name,
619
623
  );
624
+ refreshReportingForService(data);
620
625
  const updatedService: Service = {
621
626
  ...data,
622
627
  status: {
@@ -0,0 +1,105 @@
1
+ import { Environment, Service } from "@kumori/aurora-interfaces";
2
+ import { getReporting, ReportingTarget } from "../api/reporting-api-service";
3
+
4
+ const REPORTING_ITERATIONS = 5;
5
+ const REPORTING_MAX_AGE_MS = 15 * 60 * 1000;
6
+
7
+ interface ReportingContext {
8
+ environmentsMap: Map<string, Environment>;
9
+ publish: () => void;
10
+ }
11
+
12
+ interface ReportingDataPoint {
13
+ From: string;
14
+ To: string;
15
+ VCPUMillisMs: number;
16
+ }
17
+
18
+ const expiryTimers = new Map<string, ReturnType<typeof setTimeout>>();
19
+ const appliedRequests = new Map<string, number>();
20
+ let requestCount = 0;
21
+
22
+ const toMilliCores = ({ From, To, VCPUMillisMs }: ReportingDataPoint): number => {
23
+ const durationMs = Date.parse(To) - Date.parse(From);
24
+ return durationMs > 0 ? VCPUMillisMs / durationMs : 0;
25
+ };
26
+
27
+ const getNewestSampleTime = (dataPoints: ReportingDataPoint[]): number =>
28
+ dataPoints.reduce((newest, { To }) => Math.max(newest, Date.parse(To) || 0), 0);
29
+
30
+ const setCpuConsumption = (
31
+ key: string,
32
+ cpuConsuption: number[],
33
+ environmentsMap: Map<string, Environment>,
34
+ ): boolean => {
35
+ const environment = environmentsMap.get(key);
36
+ if (!environment) return false;
37
+ environmentsMap.set(key, {
38
+ ...environment,
39
+ usage: {
40
+ ...environment.usage,
41
+ current: { ...environment.usage.current, cpuConsuption },
42
+ },
43
+ });
44
+ return true;
45
+ };
46
+
47
+ const applyReporting = (
48
+ key: string,
49
+ dataPoints: ReportingDataPoint[],
50
+ { environmentsMap, publish }: ReportingContext,
51
+ ): void => {
52
+ clearTimeout(expiryTimers.get(key));
53
+ expiryTimers.delete(key);
54
+
55
+ const values = dataPoints.map(toMilliCores).slice(-REPORTING_ITERATIONS);
56
+ const expiredValues = values.map(() => 0);
57
+ const remainingMs =
58
+ getNewestSampleTime(dataPoints) + REPORTING_MAX_AGE_MS - Date.now();
59
+
60
+ if (remainingMs < 0) {
61
+ setCpuConsumption(key, expiredValues, environmentsMap);
62
+ return;
63
+ }
64
+ if (!setCpuConsumption(key, values, environmentsMap)) return;
65
+
66
+ expiryTimers.set(
67
+ key,
68
+ setTimeout(() => {
69
+ expiryTimers.delete(key);
70
+ if (setCpuConsumption(key, expiredValues, environmentsMap)) publish();
71
+ }, remainingMs),
72
+ );
73
+ };
74
+
75
+ export const refreshEnvironmentReporting = async (
76
+ target: ReportingTarget,
77
+ context: ReportingContext,
78
+ ): Promise<void> => {
79
+ const key = `${target.tenant}/${target.account}/${target.name}`;
80
+ const request = ++requestCount;
81
+ try {
82
+ const dataPoints = await getReporting(target);
83
+ if (!Array.isArray(dataPoints)) return;
84
+ if (request < (appliedRequests.get(key) ?? 0)) return;
85
+ appliedRequests.set(key, request);
86
+ applyReporting(key, dataPoints, context);
87
+ } catch (error) {
88
+ console.error(`Error loading reporting for environment ${target.name}:`, error);
89
+ }
90
+ };
91
+
92
+ export const refreshServiceReporting = (
93
+ service: Service | undefined,
94
+ context: ReportingContext,
95
+ ): void => {
96
+ if (!service?.tenant || !service.account || !service.environment) return;
97
+ const { tenant, account, environment } = service;
98
+ refreshEnvironmentReporting({ tenant, account, name: environment }, context);
99
+ };
100
+
101
+ export const resetReporting = (): void => {
102
+ expiryTimers.forEach((timer) => clearTimeout(timer));
103
+ expiryTimers.clear();
104
+ appliedRequests.clear();
105
+ };
@@ -1,4 +1,4 @@
1
- import { Channel, Resource, Service, Tenant, Usage } from "@kumori/aurora-interfaces";
1
+ import { Channel, errors, Notification, Resource, Service, Tenant, Usage } from "@kumori/aurora-interfaces";
2
2
  import { Revision } from "@kumori/aurora-interfaces/interfaces/revision-interface";
3
3
  import { getTimestamp } from "../utils/utils";
4
4
 
@@ -530,4 +530,56 @@ export const mapChannelsFromApiData = (
530
530
  mapChannels(apiData.duplex, duplexChannels);
531
531
 
532
532
  return { serverChannels, clientChannels, duplexChannels };
533
- };
533
+ };
534
+
535
+ const instancesNotRunningNotifications = new Map<string, Notification>();
536
+ let lastInstancesNotRunningNotificationDate = 0;
537
+
538
+ const hasInstancesNotRunning = (service: Service): boolean =>
539
+ (service.role ?? []).some((role) =>
540
+ (role.instances ?? []).some(
541
+ (instance) => instance.status?.toLowerCase() !== "running",
542
+ ),
543
+ );
544
+
545
+ export const syncInstancesNotRunningNotifications = (
546
+ services: Iterable<Service>,
547
+ eventHelper: any,
548
+ ): void => {
549
+ const pending = new Map<string, Record<string, string>>();
550
+ for (const service of services) {
551
+ if (service.status?.code === "REMOVING_SERVICE") continue;
552
+ if (!hasInstancesNotRunning(service)) continue;
553
+ const { tenant, account, environment, name } = service;
554
+ pending.set(`${tenant}/${account}/${environment}/${name}`, {
555
+ tenant,
556
+ account,
557
+ environment,
558
+ service: name,
559
+ });
560
+ }
561
+
562
+ instancesNotRunningNotifications.forEach((notification, key) => {
563
+ if (pending.has(key)) return;
564
+ instancesNotRunningNotifications.delete(key);
565
+ eventHelper.notification.publish.deletion(notification);
566
+ });
567
+
568
+ pending.forEach((data, key) => {
569
+ if (instancesNotRunningNotifications.has(key)) return;
570
+ lastInstancesNotRunningNotificationDate = Math.max(
571
+ Date.now(),
572
+ lastInstancesNotRunningNotificationDate + 1,
573
+ );
574
+ const notification: Notification = {
575
+ type: "warning",
576
+ subtype: errors.service.instancesNotRunning.subtype,
577
+ date: lastInstancesNotRunningNotificationDate.toString(),
578
+ status: "unread",
579
+ notificationType: "regular",
580
+ data,
581
+ };
582
+ instancesNotRunningNotifications.set(key, notification);
583
+ eventHelper.notification.publish.creation(notification);
584
+ });
585
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumori/aurora-backend-handler",
3
- "version": "1.0.136",
3
+ "version": "1.0.138",
4
4
  "description": "backend handler",
5
5
  "main": "backend-handler.ts",
6
6
  "scripts": {
@@ -11,7 +11,7 @@
11
11
  "glob": "^11.0.0"
12
12
  },
13
13
  "dependencies": {
14
- "@kumori/aurora-interfaces": "^1.0.40",
14
+ "@kumori/aurora-interfaces": "1.0.41",
15
15
  "@kumori/kumori-dsl-generator": "1.0.11",
16
16
  "@kumori/kumori-module-generator": "^1.1.6",
17
17
  "ts-node": "^10.9.2",
@@ -16,6 +16,7 @@ jest.mock("../websocket-manager", () => ({
16
16
  initializeGlobalWebSocketClient: jest.fn().mockResolvedValue(undefined),
17
17
  getWebSocketStatus: jest.fn(),
18
18
  makeGlobalWebSocketRequest: jest.fn(),
19
+ refreshReportingForService: jest.fn(),
19
20
  }));
20
21
 
21
22
  jest.mock("../environment", () => ({ environment: {} }));
@@ -24,7 +24,11 @@ import {
24
24
  UserStatus
25
25
  } from "@kumori/aurora-interfaces";
26
26
  import { loadMarketplaceItemsForTenant } from "./api/marketplace-api-service";
27
- import { getReporting } from "./api/reporting-api-service";
27
+ import {
28
+ refreshEnvironmentReporting,
29
+ refreshServiceReporting,
30
+ resetReporting,
31
+ } from "./helpers/reporting-helper";
28
32
  import { parseKeyPath } from "./utils/utils";
29
33
  import {
30
34
  handleTenantEvent,
@@ -49,6 +53,7 @@ import {
49
53
  handleServiceOperationError,
50
54
  handleServiceOperationSuccess,
51
55
  mapChannelsFromApiData,
56
+ syncInstancesNotRunningNotifications,
52
57
  } from "./helpers/service-helper";
53
58
  import {
54
59
  handleAccountEvent,
@@ -197,7 +202,6 @@ let secretsMap = new Map<string, any>();
197
202
  let tempProviders: Record<string, string> = {};
198
203
  let pendingProjects: Array<{ tenant: string; project: string }> = [];
199
204
  let isLoadingReporting = false;
200
- const REPORTING_ITERATIONS = 5;
201
205
  const REPORTING_INTERVAL = 1000;
202
206
  let hasLoadedReportingOnce = false;
203
207
  let recentlyUpdatedServices = new Map<string, Service>();
@@ -660,6 +664,7 @@ export const closeGlobalWebSocketConnection = () => {
660
664
  platformInfo = null;
661
665
  isPlatformInfoLoaded = false;
662
666
  isPlatformInfoLoading = false;
667
+ resetReporting();
663
668
 
664
669
  pendingRequests.forEach((pending, messageId) => {
665
670
  pending.reject(new Error("WebSocket connection manually closed"));
@@ -685,6 +690,7 @@ const rebuildHierarchy = () => {
685
690
  accountsMap.values(),
686
691
  eventHelper,
687
692
  );
693
+ syncInstancesNotRunningNotifications(servicesMap.values(), eventHelper);
688
694
 
689
695
  tenantsMap.forEach((tenant) => {
690
696
  tenant.accounts = Array.from(accountsMap.values()).filter((account) => {
@@ -2104,55 +2110,16 @@ const updateEnvironmentsCloudProvider = (
2104
2110
  );
2105
2111
  };
2106
2112
 
2107
- const loadReportingForEnvironment = async (environment: Environment) => {
2108
- try {
2109
- const reportingData = await getReporting(environment);
2110
- if (
2111
- reportingData !== undefined &&
2112
- reportingData !== null &&
2113
- Array.isArray(reportingData)
2114
- ) {
2115
- const envReportKey = environment.tenant && environment.account ? `${environment.tenant}/${environment.account}/${environment.id}` : environment.id;
2116
- const updatedEnvironment = environmentsMap.get(envReportKey);
2117
-
2118
- if (!updatedEnvironment) {
2119
- console.warn(`Environment ${environment.id} not found in map`);
2120
- return;
2121
- }
2122
-
2123
- if (!updatedEnvironment.usage.current.cpuConsuption) {
2124
- updatedEnvironment.usage.current.cpuConsuption = [];
2125
- }
2126
- const cpuValues = reportingData.map((dataPoint: any) => {
2127
- const fromTime = Date.parse(dataPoint.From);
2128
- const toTime = Date.parse(dataPoint.To);
2129
- const durationMs = toTime - fromTime;
2130
- const milliCores =
2131
- durationMs > 0 ? dataPoint.VCPUMillisMs / durationMs : 0;
2132
- return milliCores;
2133
- });
2134
-
2135
- updatedEnvironment.usage.current.cpuConsuption.push(...cpuValues);
2136
-
2137
- if (
2138
- updatedEnvironment.usage.current.cpuConsuption.length >
2139
- REPORTING_ITERATIONS
2140
- ) {
2141
- updatedEnvironment.usage.current.cpuConsuption =
2142
- updatedEnvironment.usage.current.cpuConsuption.slice(
2143
- -REPORTING_ITERATIONS,
2144
- );
2145
- }
2113
+ const getReportingContext = () => ({
2114
+ environmentsMap,
2115
+ publish: () => {
2116
+ rebuildHierarchy();
2117
+ updateUserWithPlatformInfo();
2118
+ },
2119
+ });
2146
2120
 
2147
- environmentsMap.set(envReportKey, updatedEnvironment);
2148
- }
2149
- } catch (error) {
2150
- console.error(
2151
- `Error loading reporting for environment ${environment.name}:`,
2152
- error,
2153
- );
2154
- }
2155
- };
2121
+ export const refreshReportingForService = (service: Service) =>
2122
+ refreshServiceReporting(service, getReportingContext());
2156
2123
 
2157
2124
  const loadAllEnvironmentsReporting = async () => {
2158
2125
  if (isLoadingReporting || hasLoadedReportingOnce) {
@@ -2162,7 +2129,9 @@ const loadAllEnvironmentsReporting = async () => {
2162
2129
  try {
2163
2130
  const environments = Array.from(environmentsMap.values());
2164
2131
  await Promise.all(
2165
- environments.map((env) => loadReportingForEnvironment(env)),
2132
+ environments.map((env) =>
2133
+ refreshEnvironmentReporting(env, getReportingContext()),
2134
+ ),
2166
2135
  );
2167
2136
  hasLoadedReportingOnce = true;
2168
2137
  } catch (error) {