@kumori/aurora-backend-handler 1.0.137 → 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
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kumori/aurora-backend-handler",
3
- "version": "1.0.137",
3
+ "version": "1.0.138",
4
4
  "description": "backend handler",
5
5
  "main": "backend-handler.ts",
6
6
  "scripts": {
@@ -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,
@@ -198,7 +202,6 @@ let secretsMap = new Map<string, any>();
198
202
  let tempProviders: Record<string, string> = {};
199
203
  let pendingProjects: Array<{ tenant: string; project: string }> = [];
200
204
  let isLoadingReporting = false;
201
- const REPORTING_ITERATIONS = 5;
202
205
  const REPORTING_INTERVAL = 1000;
203
206
  let hasLoadedReportingOnce = false;
204
207
  let recentlyUpdatedServices = new Map<string, Service>();
@@ -661,6 +664,7 @@ export const closeGlobalWebSocketConnection = () => {
661
664
  platformInfo = null;
662
665
  isPlatformInfoLoaded = false;
663
666
  isPlatformInfoLoading = false;
667
+ resetReporting();
664
668
 
665
669
  pendingRequests.forEach((pending, messageId) => {
666
670
  pending.reject(new Error("WebSocket connection manually closed"));
@@ -2106,55 +2110,16 @@ const updateEnvironmentsCloudProvider = (
2106
2110
  );
2107
2111
  };
2108
2112
 
2109
- const loadReportingForEnvironment = async (environment: Environment) => {
2110
- try {
2111
- const reportingData = await getReporting(environment);
2112
- if (
2113
- reportingData !== undefined &&
2114
- reportingData !== null &&
2115
- Array.isArray(reportingData)
2116
- ) {
2117
- const envReportKey = environment.tenant && environment.account ? `${environment.tenant}/${environment.account}/${environment.id}` : environment.id;
2118
- const updatedEnvironment = environmentsMap.get(envReportKey);
2119
-
2120
- if (!updatedEnvironment) {
2121
- console.warn(`Environment ${environment.id} not found in map`);
2122
- return;
2123
- }
2124
-
2125
- if (!updatedEnvironment.usage.current.cpuConsuption) {
2126
- updatedEnvironment.usage.current.cpuConsuption = [];
2127
- }
2128
- const cpuValues = reportingData.map((dataPoint: any) => {
2129
- const fromTime = Date.parse(dataPoint.From);
2130
- const toTime = Date.parse(dataPoint.To);
2131
- const durationMs = toTime - fromTime;
2132
- const milliCores =
2133
- durationMs > 0 ? dataPoint.VCPUMillisMs / durationMs : 0;
2134
- return milliCores;
2135
- });
2136
-
2137
- updatedEnvironment.usage.current.cpuConsuption.push(...cpuValues);
2138
-
2139
- if (
2140
- updatedEnvironment.usage.current.cpuConsuption.length >
2141
- REPORTING_ITERATIONS
2142
- ) {
2143
- updatedEnvironment.usage.current.cpuConsuption =
2144
- updatedEnvironment.usage.current.cpuConsuption.slice(
2145
- -REPORTING_ITERATIONS,
2146
- );
2147
- }
2113
+ const getReportingContext = () => ({
2114
+ environmentsMap,
2115
+ publish: () => {
2116
+ rebuildHierarchy();
2117
+ updateUserWithPlatformInfo();
2118
+ },
2119
+ });
2148
2120
 
2149
- environmentsMap.set(envReportKey, updatedEnvironment);
2150
- }
2151
- } catch (error) {
2152
- console.error(
2153
- `Error loading reporting for environment ${environment.name}:`,
2154
- error,
2155
- );
2156
- }
2157
- };
2121
+ export const refreshReportingForService = (service: Service) =>
2122
+ refreshServiceReporting(service, getReportingContext());
2158
2123
 
2159
2124
  const loadAllEnvironmentsReporting = async () => {
2160
2125
  if (isLoadingReporting || hasLoadedReportingOnce) {
@@ -2164,7 +2129,9 @@ const loadAllEnvironmentsReporting = async () => {
2164
2129
  try {
2165
2130
  const environments = Array.from(environmentsMap.values());
2166
2131
  await Promise.all(
2167
- environments.map((env) => loadReportingForEnvironment(env)),
2132
+ environments.map((env) =>
2133
+ refreshEnvironmentReporting(env, getReportingContext()),
2134
+ ),
2168
2135
  );
2169
2136
  hasLoadedReportingOnce = true;
2170
2137
  } catch (error) {