@bmfk/api 0.0.0-stage → 1.0.1

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.
Files changed (169) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1293 -2
  4. package/dist/apiServer/APIService.d.ts +125 -0
  5. package/dist/apiServer/APIService.js +769 -0
  6. package/dist/apiServer/BaseEndpoint.d.ts +90 -0
  7. package/dist/apiServer/BaseEndpoint.js +314 -0
  8. package/dist/apiServer/BaseService.d.ts +17 -0
  9. package/dist/apiServer/BaseService.js +39 -0
  10. package/dist/apiServer/DBService.d.ts +131 -0
  11. package/dist/apiServer/DBService.js +290 -0
  12. package/dist/apiServer/DocumentService.d.ts +9 -0
  13. package/dist/apiServer/DocumentService.js +65 -0
  14. package/dist/apiServer/LocalRequest.d.ts +3 -0
  15. package/dist/apiServer/LocalRequest.js +6 -0
  16. package/dist/apiServer/LogService.d.ts +78 -0
  17. package/dist/apiServer/LogService.js +349 -0
  18. package/dist/apiServer/MonitorService.d.ts +102 -0
  19. package/dist/apiServer/MonitorService.js +615 -0
  20. package/dist/apiServer/StatService.d.ts +4 -0
  21. package/dist/apiServer/StatService.js +10 -0
  22. package/dist/apiServer/TimeframeService.d.ts +28 -0
  23. package/dist/apiServer/TimeframeService.js +97 -0
  24. package/dist/apiServer/WebSocketServer.d.ts +39 -0
  25. package/dist/apiServer/WebSocketServer.js +173 -0
  26. package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
  27. package/dist/apiServer/db/IDBAdapter.js +2 -0
  28. package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
  29. package/dist/apiServer/db/MysqlAdapter.js +869 -0
  30. package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
  31. package/dist/apiServer/db/PostgresAdapter.js +73 -0
  32. package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
  33. package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
  34. package/dist/apiServer/deployment/Activate.d.ts +4 -0
  35. package/dist/apiServer/deployment/Activate.js +124 -0
  36. package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
  37. package/dist/apiServer/deployment/BackupManager.js +174 -0
  38. package/dist/apiServer/deployment/Backups.d.ts +2 -0
  39. package/dist/apiServer/deployment/Backups.js +44 -0
  40. package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
  41. package/dist/apiServer/deployment/BlueGreenState.js +150 -0
  42. package/dist/apiServer/deployment/Bundler.d.ts +12 -0
  43. package/dist/apiServer/deployment/Bundler.js +178 -0
  44. package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
  45. package/dist/apiServer/deployment/ConfigService.js +195 -0
  46. package/dist/apiServer/deployment/Deploy.d.ts +4 -0
  47. package/dist/apiServer/deployment/Deploy.js +404 -0
  48. package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
  49. package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
  50. package/dist/apiServer/deployment/Deployer.d.ts +13 -0
  51. package/dist/apiServer/deployment/Deployer.js +96 -0
  52. package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
  53. package/dist/apiServer/deployment/DeployerInit.js +214 -0
  54. package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
  55. package/dist/apiServer/deployment/DeployerService.js +1553 -0
  56. package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
  57. package/dist/apiServer/deployment/HashPassword.js +126 -0
  58. package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
  59. package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
  60. package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
  61. package/dist/apiServer/deployment/MigrateProject.js +335 -0
  62. package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
  63. package/dist/apiServer/deployment/NginxHelper.js +111 -0
  64. package/dist/apiServer/deployment/Notifier.d.ts +30 -0
  65. package/dist/apiServer/deployment/Notifier.js +82 -0
  66. package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
  67. package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
  68. package/dist/apiServer/deployment/Restore.d.ts +2 -0
  69. package/dist/apiServer/deployment/Restore.js +89 -0
  70. package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
  71. package/dist/apiServer/deployment/ReviewStore.js +186 -0
  72. package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
  73. package/dist/apiServer/deployment/SecretsInjector.js +189 -0
  74. package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
  75. package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
  76. package/dist/apiServer/deployment/Status.d.ts +2 -0
  77. package/dist/apiServer/deployment/Status.js +83 -0
  78. package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
  79. package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
  80. package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
  81. package/dist/apiServer/deployment/Watchdog.js +65 -0
  82. package/dist/apiServer/deployment/Wizards.d.ts +1 -0
  83. package/dist/apiServer/deployment/Wizards.js +83 -0
  84. package/dist/apiServer/deployment/cli.d.ts +2 -0
  85. package/dist/apiServer/deployment/cli.js +224 -0
  86. package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
  87. package/dist/apiServer/deployment/cliCommon.js +110 -0
  88. package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
  89. package/dist/apiServer/deployment/cliPrompt.js +38 -0
  90. package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
  91. package/dist/apiServer/deployment/resolveConfig.js +139 -0
  92. package/dist/apiServer/documentation/Documentation.d.ts +18 -0
  93. package/dist/apiServer/documentation/Documentation.js +143 -0
  94. package/dist/apiServer/documentation/index.html +460 -0
  95. package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
  96. package/dist/apiServer/external/MicroserviceClient.js +144 -0
  97. package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
  98. package/dist/apiServer/external/MicroserviceHost.js +183 -0
  99. package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
  100. package/dist/apiServer/external/MicroserviceHostController.js +65 -0
  101. package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
  102. package/dist/apiServer/helper/AppDataPath.js +81 -0
  103. package/dist/apiServer/helper/ClientIp.d.ts +3 -0
  104. package/dist/apiServer/helper/ClientIp.js +33 -0
  105. package/dist/apiServer/helper/DataProvider.d.ts +18 -0
  106. package/dist/apiServer/helper/DataProvider.js +57 -0
  107. package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
  108. package/dist/apiServer/helper/IpAllowList.js +40 -0
  109. package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
  110. package/dist/apiServer/helper/JSONStableStringify.js +15 -0
  111. package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
  112. package/dist/apiServer/helper/PasswordHash.js +52 -0
  113. package/dist/apiServer/helper/Sleep.d.ts +1 -0
  114. package/dist/apiServer/helper/Sleep.js +5 -0
  115. package/dist/apiServer/helper/Trace.d.ts +8 -0
  116. package/dist/apiServer/helper/Trace.js +30 -0
  117. package/dist/apiServer/helper/UID.d.ts +16 -0
  118. package/dist/apiServer/helper/UID.js +98 -0
  119. package/dist/apiServer/helper/Validator.d.ts +86 -0
  120. package/dist/apiServer/helper/Validator.js +560 -0
  121. package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
  122. package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
  123. package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
  124. package/dist/apiServer/helper/ZipUtils.js +28 -0
  125. package/dist/apiServer/http/Http.d.ts +183 -0
  126. package/dist/apiServer/http/Http.js +627 -0
  127. package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
  128. package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
  129. package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
  130. package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
  131. package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
  132. package/dist/apiServer/monitor/AccessStore.js +163 -0
  133. package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
  134. package/dist/apiServer/monitor/LogFiles.js +109 -0
  135. package/dist/apiServer/monitor/Monitor.d.ts +54 -0
  136. package/dist/apiServer/monitor/Monitor.js +447 -0
  137. package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
  138. package/dist/apiServer/monitor/MonitorAuth.js +474 -0
  139. package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
  140. package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
  141. package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
  142. package/dist/apiServer/monitor/SystemInfo.js +217 -0
  143. package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
  144. package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
  145. package/dist/apiServer/monitor/index.html +591 -0
  146. package/dist/apiServer/review/Review.d.ts +23 -0
  147. package/dist/apiServer/review/Review.js +149 -0
  148. package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
  149. package/dist/apiServer/review/ReviewAuth.js +147 -0
  150. package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
  151. package/dist/apiServer/review/ReviewDiff.js +175 -0
  152. package/dist/apiServer/review/index.html +501 -0
  153. package/dist/apiServer/routes/Liveness.d.ts +7 -0
  154. package/dist/apiServer/routes/Liveness.js +27 -0
  155. package/dist/apiServer/routes/Readiness.d.ts +13 -0
  156. package/dist/apiServer/routes/Readiness.js +20 -0
  157. package/dist/apiServer/security/BlockedIps.d.ts +46 -0
  158. package/dist/apiServer/security/BlockedIps.js +185 -0
  159. package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
  160. package/dist/apiServer/structures/DefaultErrors.js +52 -0
  161. package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
  162. package/dist/apiServer/structures/HTTPStatus.js +11 -0
  163. package/dist/apiServer/structures/Interfaces.d.ts +55 -0
  164. package/dist/apiServer/structures/Interfaces.js +2 -0
  165. package/dist/index.d.ts +45 -0
  166. package/dist/index.js +110 -0
  167. package/dist/signal/Signal.d.ts +23 -0
  168. package/dist/signal/Signal.js +85 -0
  169. package/package.json +88 -4
@@ -0,0 +1,90 @@
1
+ import { IRequest, IResponse } from "./structures/Interfaces";
2
+ export interface IBaseEndpoint {
3
+ endpoints?: IEndpointHandler[];
4
+ __execute: (req: IRequest) => Promise<IResponse<any>>;
5
+ __precheck: (req: IRequest) => Promise<IResponse<any> | null>;
6
+ init: () => Promise<void>;
7
+ ignoreHttpLogging: boolean;
8
+ }
9
+ declare const httpMethods: string[];
10
+ type HTTPMethod = typeof httpMethods[number];
11
+ export type IHandler = Record<HTTPMethod, ((req: IRequest) => Promise<IResponse<any>>) | {
12
+ controller: (req: IRequest) => Promise<IResponse<any>>;
13
+ ignoreInterceptor?: boolean;
14
+ internalCallParams?: any;
15
+ allowInterceptorError?: boolean;
16
+ validationModel?: any;
17
+ resultModel?: any;
18
+ asStream?: boolean;
19
+ ignoreInDocumentation?: boolean;
20
+ ignoreHttpLogging?: boolean;
21
+ description?: string;
22
+ title?: string;
23
+ }>;
24
+ export interface IEndpointHandler {
25
+ endpoint: string;
26
+ handler?: ((req: IRequest) => Promise<IResponse<any>>) | IHandler;
27
+ ignoreInterceptor?: boolean;
28
+ internalCallParams?: any;
29
+ ignoreInDocumentation?: boolean;
30
+ ignoreHttpLogging?: boolean;
31
+ independed?: boolean;
32
+ allowInterceptorError?: boolean;
33
+ asStream?: boolean;
34
+ description?: string;
35
+ title?: string;
36
+ validationModel?: any;
37
+ resultModel?: any;
38
+ }
39
+ export declare class BaseEndpoint implements IBaseEndpoint {
40
+ static allInstances: BaseEndpoint[];
41
+ private inializedEndpointNames;
42
+ description: string;
43
+ endpoints?: IEndpointHandler[];
44
+ ignoreHttpLogging: boolean;
45
+ ignoreInDocumentation: boolean;
46
+ private static entrypoint;
47
+ endpoint: string;
48
+ createdAt: number;
49
+ initializedAt: number | null;
50
+ protected streamOptions: Record<string, any>;
51
+ static setEntryPoint: (ep: string) => void;
52
+ static getEntryPoint: () => string;
53
+ constructor(endpoint: string);
54
+ registerEndpoints(endpoints: IEndpointHandler[]): void;
55
+ init(): Promise<void>;
56
+ getInitalizedEndpointNames(): String[];
57
+ getInventory(): {
58
+ className: string;
59
+ basePath: string;
60
+ ignoreHttpLogging: boolean;
61
+ ignoreInDocumentation: boolean;
62
+ description: string;
63
+ createdAt: number;
64
+ initializedAt: number | null;
65
+ handlerCount: number;
66
+ handlers: {
67
+ path: string;
68
+ methods: string[];
69
+ ignoreInterceptor: boolean;
70
+ ignoreInDocumentation: boolean;
71
+ ignoreHttpLogging: boolean;
72
+ independed: boolean;
73
+ asStream: boolean;
74
+ hasValidationModel: boolean;
75
+ hasResultModel: boolean;
76
+ description?: string;
77
+ title?: string;
78
+ }[];
79
+ };
80
+ __precheck(req: IRequest): Promise<IResponse<any> | null>;
81
+ __execute(req: IRequest): Promise<IResponse<any>>;
82
+ protected validateStructure(structure: any, req: IRequest): Promise<void>;
83
+ protected createStream(req: IRequest, opts: {
84
+ contentType?: string;
85
+ headers?: {
86
+ [key: string]: string;
87
+ };
88
+ }): IRequest;
89
+ }
90
+ export {};
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.BaseEndpoint = void 0;
7
+ const Validator_1 = require("./helper/Validator");
8
+ const LogService_1 = require("./LogService");
9
+ const DefaultErrors_1 = __importDefault(require("./structures/DefaultErrors"));
10
+ const stream_1 = require("stream");
11
+ const httpMethods = ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD", "TRACE", "CONNECT"];
12
+ class BaseEndpoint {
13
+ static allInstances = [];
14
+ inializedEndpointNames = [];
15
+ description = "no description";
16
+ endpoints;
17
+ ignoreHttpLogging = false;
18
+ ignoreInDocumentation = false;
19
+ static entrypoint = "/";
20
+ endpoint = "";
21
+ createdAt = Date.now();
22
+ initializedAt = null;
23
+ streamOptions = {};
24
+ static setEntryPoint = (ep) => {
25
+ this.entrypoint = ep;
26
+ if (!this.entrypoint.endsWith("/")) {
27
+ this.entrypoint += "/";
28
+ }
29
+ if (!ep.startsWith("/"))
30
+ this.entrypoint = "/" + ep;
31
+ };
32
+ static getEntryPoint = () => {
33
+ return this.entrypoint;
34
+ };
35
+ constructor(endpoint) {
36
+ if (endpoint.startsWith("/"))
37
+ endpoint = endpoint.substring(1);
38
+ if (!endpoint.endsWith("/"))
39
+ endpoint = endpoint + "/";
40
+ this.endpoint = endpoint;
41
+ BaseEndpoint.allInstances.push(this);
42
+ }
43
+ registerEndpoints(endpoints) {
44
+ for (let i of endpoints) {
45
+ if (i.endpoint === "" || i.endpoint === "/") {
46
+ let empty = i.endpoint === "";
47
+ i.endpoint = this.endpoint;
48
+ if (i.endpoint.endsWith("/") && empty)
49
+ i.endpoint = i.endpoint.substring(0, i.endpoint.length - 1);
50
+ continue;
51
+ }
52
+ if (i.endpoint.startsWith("/"))
53
+ i.endpoint = i.endpoint.substring(1);
54
+ if (i.endpoint.endsWith("/"))
55
+ i.endpoint = i.endpoint.substring(0, i.endpoint.length - 1);
56
+ if (!i.independed)
57
+ i.endpoint = this.endpoint + i.endpoint;
58
+ }
59
+ this.endpoints = endpoints;
60
+ }
61
+ async init() {
62
+ if (!this.endpoints) {
63
+ (0, LogService_1.logCrit)("${BaseEndpoint.js}", "No endpoints registered for " + this.endpoint);
64
+ return;
65
+ }
66
+ for (let i of this.endpoints) {
67
+ const models = [i.validationModel, ...Object.values(i.handler && typeof i.handler === "object" ? i.handler : {}).map((h) => h?.validationModel)];
68
+ const samples = models.flatMap(m => Validator_1.Validator.numericSamples(m));
69
+ if (samples.length)
70
+ (0, LogService_1.logWarn)(`${i.endpoint}: number sample(s) without min/max — ${samples.join(", ")}. A sample is only the type now, not a limit; write 0, or add $__<field>_max / $__<field>_min if it was meant as one`);
71
+ (0, LogService_1.logInfo)("${BaseEndpoint.js}", "endpoint: " + i.endpoint + " initalized, ignoreInterceptor: " + (i.ignoreInterceptor ?? "false"));
72
+ this.inializedEndpointNames.push(i.endpoint + " ignore interceptor: " + (i.ignoreInterceptor ?? "false"));
73
+ }
74
+ this.initializedAt = Date.now();
75
+ }
76
+ ;
77
+ getInitalizedEndpointNames() {
78
+ return this.inializedEndpointNames;
79
+ }
80
+ getInventory() {
81
+ const handlers = [];
82
+ for (const i of this.endpoints ?? []) {
83
+ let methods = [];
84
+ let asStream = i.asStream === true;
85
+ let hasVm = i.validationModel !== undefined;
86
+ let hasRm = i.resultModel !== undefined;
87
+ if (typeof i.handler === "function") {
88
+ methods = ["ANY"];
89
+ }
90
+ else if (i.handler && typeof i.handler === "object") {
91
+ for (const key of Object.keys(i.handler)) {
92
+ const h = i.handler[key];
93
+ if (typeof h === "function") {
94
+ methods.push(key);
95
+ }
96
+ else if (h && typeof h === "object" && typeof h.controller === "function") {
97
+ methods.push(key);
98
+ if (h.asStream)
99
+ asStream = true;
100
+ if (h.validationModel !== undefined)
101
+ hasVm = true;
102
+ if (h.resultModel !== undefined)
103
+ hasRm = true;
104
+ }
105
+ }
106
+ }
107
+ handlers.push({
108
+ path: (BaseEndpoint.entrypoint + i.endpoint).replaceAll("//", "/"),
109
+ methods,
110
+ ignoreInterceptor: i.ignoreInterceptor === true,
111
+ ignoreInDocumentation: i.ignoreInDocumentation === true,
112
+ ignoreHttpLogging: i.ignoreHttpLogging === true,
113
+ independed: i.independed === true,
114
+ asStream,
115
+ hasValidationModel: hasVm,
116
+ hasResultModel: hasRm,
117
+ description: i.description,
118
+ title: i.title,
119
+ });
120
+ }
121
+ return {
122
+ className: this.constructor.name,
123
+ basePath: this.endpoint,
124
+ ignoreHttpLogging: this.ignoreHttpLogging,
125
+ ignoreInDocumentation: this.ignoreInDocumentation,
126
+ description: this.description,
127
+ createdAt: this.createdAt,
128
+ initializedAt: this.initializedAt,
129
+ handlerCount: handlers.length,
130
+ handlers,
131
+ };
132
+ }
133
+ async __precheck(req) { return null; }
134
+ async __execute(req) {
135
+ if (this.endpoints && this.endpoints.length > 0) {
136
+ for (let i of this.endpoints) {
137
+ let targetEP = BaseEndpoint.entrypoint + i.endpoint;
138
+ targetEP = targetEP.replaceAll("//", "/");
139
+ if (targetEP !== req.endpoint)
140
+ continue;
141
+ const httpMethod = req.method.toUpperCase();
142
+ const resolveAsStream = () => {
143
+ if (i.asStream)
144
+ return true;
145
+ if (i.handler && typeof i.handler === "object") {
146
+ const h = i.handler[httpMethod];
147
+ if (h && typeof h === "object" && "asStream" in h && h.asStream)
148
+ return true;
149
+ }
150
+ return false;
151
+ };
152
+ const asStream = resolveAsStream();
153
+ if (i.handler && typeof i.handler === "function") {
154
+ if (req.data && req.data.validationModel && req.data.validationModel === "1")
155
+ return { data: i.validationModel };
156
+ if (i.validationModel)
157
+ await this.validateStructure(i.validationModel, req);
158
+ if (asStream)
159
+ req = this.createStream(req, this.streamOptions[i.endpoint] ?? {});
160
+ const result = await i.handler.call(this, req);
161
+ if (asStream)
162
+ return { blockResponse: true, data: null };
163
+ return result;
164
+ }
165
+ if (i.handler && i.handler[httpMethod] && typeof i.handler[httpMethod] === "function") {
166
+ if (req.data && req.data.validationModel && req.data.validationModel === "1")
167
+ return { data: i.validationModel };
168
+ if (i.validationModel)
169
+ await this.validateStructure(i.validationModel, req);
170
+ if (asStream)
171
+ req = this.createStream(req, this.streamOptions[i.endpoint] ?? {});
172
+ const result = await i.handler[httpMethod].call(this, req);
173
+ if (asStream)
174
+ return { blockResponse: true, data: null };
175
+ return result;
176
+ }
177
+ if (i.handler
178
+ && i.handler[httpMethod]
179
+ && typeof i.handler[httpMethod] === "object"
180
+ && "controller" in i.handler[httpMethod]
181
+ && typeof i.handler[httpMethod].controller === "function") {
182
+ const vmodel = i.handler[httpMethod].validationModel;
183
+ if (req.data && req.data.validationModel && req.data.validationModel === "1")
184
+ return { data: vmodel };
185
+ if (vmodel)
186
+ await this.validateStructure(vmodel, req);
187
+ if (asStream)
188
+ req = this.createStream(req, this.streamOptions[i.endpoint] ?? {});
189
+ const result = await i.handler[httpMethod].controller.call(this, req);
190
+ if (asStream)
191
+ return { blockResponse: true, data: null };
192
+ return result;
193
+ }
194
+ return {
195
+ error: { ...DefaultErrors_1.default.METHOD_NOT_ALLOWED, details: "No handler for " + httpMethod },
196
+ data: null
197
+ };
198
+ }
199
+ }
200
+ (0, LogService_1.logWarn)("${BaseEndpoint.js}", "Unhandled entrypoint: " + this.endpoint);
201
+ return {
202
+ error: DefaultErrors_1.default.NOT_IMPLEMENTED,
203
+ data: null
204
+ };
205
+ }
206
+ async validateStructure(structure, req) {
207
+ if (!structure)
208
+ return;
209
+ if (typeof structure === "object" && (!req.data || typeof req.data !== "object"))
210
+ throw { ...DefaultErrors_1.default.WRONG_PARAMS, details: "empty or invalid request" };
211
+ const report = await Validator_1.Validator.validateStructure(structure, req.data);
212
+ if (report)
213
+ throw { ...DefaultErrors_1.default.WRONG_PARAMS, details: report };
214
+ Validator_1.Validator.filterStructure(structure, req.data);
215
+ }
216
+ createStream(req, opts) {
217
+ const res = req.response;
218
+ if (res.headersSent)
219
+ throw { ...DefaultErrors_1.default.INTERNAL_SERVER_ERROR, details: "Headers already sent, can't create stream" };
220
+ res.statusCode = 200;
221
+ res.setHeader("Content-Type", opts?.contentType ?? "application/octet-stream");
222
+ res.setHeader("Transfer-Encoding", "chunked");
223
+ res.setHeader("Cache-Control", "no-cache");
224
+ if (opts?.headers) {
225
+ for (let h in opts.headers) {
226
+ res.setHeader(h, opts.headers[h]);
227
+ }
228
+ }
229
+ const stream = new stream_1.Readable({
230
+ read() {
231
+ }
232
+ });
233
+ let finished = false;
234
+ let timer;
235
+ const cleanup = () => {
236
+ if (finished)
237
+ return;
238
+ finished = true;
239
+ if (timer)
240
+ clearTimeout(timer);
241
+ try {
242
+ if (!stream.destroyed) {
243
+ stream.destroy();
244
+ }
245
+ }
246
+ catch (e) {
247
+ (0, LogService_1.logError)("Error during stream cleanup:", e);
248
+ }
249
+ try {
250
+ if (!res.writableEnded)
251
+ res.end();
252
+ }
253
+ catch { }
254
+ };
255
+ const endOk = () => {
256
+ if (finished)
257
+ return;
258
+ finished = true;
259
+ if (timer)
260
+ clearTimeout(timer);
261
+ try {
262
+ if (!stream.destroyed)
263
+ stream.push(null);
264
+ }
265
+ catch (e) {
266
+ cleanup();
267
+ }
268
+ };
269
+ res.on('close', () => {
270
+ cleanup();
271
+ });
272
+ const setupTimer = () => {
273
+ if (finished)
274
+ return;
275
+ if (timer)
276
+ clearTimeout(timer);
277
+ timer = setTimeout(() => cleanup(), 60_000);
278
+ };
279
+ setupTimer();
280
+ const origPush = stream.push.bind(stream);
281
+ stream.push = (chunk, encoding) => {
282
+ if (chunk === null)
283
+ return origPush(null);
284
+ if (finished)
285
+ return false;
286
+ setupTimer();
287
+ return origPush(chunk, encoding);
288
+ };
289
+ req.raw?.on?.("aborted", () => {
290
+ cleanup();
291
+ try {
292
+ res.destroy?.();
293
+ }
294
+ catch { }
295
+ });
296
+ req.raw?.on?.("close", cleanup);
297
+ stream.on('error', (err) => {
298
+ (0, LogService_1.logError)("Stream error:", err);
299
+ cleanup();
300
+ try {
301
+ res.destroy?.(err);
302
+ }
303
+ catch {
304
+ res.end();
305
+ }
306
+ });
307
+ res.on("finish", cleanup);
308
+ stream.pipe(res);
309
+ req.stream = stream;
310
+ req.endStream = (force) => force ? cleanup() : endOk();
311
+ return req;
312
+ }
313
+ }
314
+ exports.BaseEndpoint = BaseEndpoint;
@@ -0,0 +1,17 @@
1
+ export interface IBaseService {
2
+ init: () => Promise<void>;
3
+ applicationReady: () => void;
4
+ getName: () => string;
5
+ }
6
+ export declare class BaseService implements IBaseService {
7
+ static allInstances: BaseService[];
8
+ protected name: string;
9
+ createdAt: number;
10
+ initializedAt: number | null;
11
+ applicationReadyAt: number | null;
12
+ constructor(name: string);
13
+ init(): Promise<void>;
14
+ finishService(): Promise<void>;
15
+ getName(): string;
16
+ applicationReady(): void;
17
+ }
@@ -0,0 +1,39 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseService = void 0;
4
+ const finalize = [];
5
+ process.on('SIGINT', async () => {
6
+ await Promise.all(finalize.map(f => f()));
7
+ process.exit(0);
8
+ });
9
+ process.on('SIGTERM', async () => {
10
+ await Promise.all(finalize.map(f => f()));
11
+ process.exit(0);
12
+ });
13
+ class BaseService {
14
+ static allInstances = [];
15
+ name = "BaseService";
16
+ createdAt = Date.now();
17
+ initializedAt = null;
18
+ applicationReadyAt = null;
19
+ constructor(name) {
20
+ this.name = name;
21
+ this.finishService = this.finishService.bind(this);
22
+ BaseService.allInstances.push(this);
23
+ }
24
+ async init() {
25
+ console.log("Service: " + this.name + " initialized");
26
+ finalize.push(this.finishService);
27
+ this.initializedAt = Date.now();
28
+ }
29
+ async finishService() {
30
+ console.log("finishService -> " + (this.name ?? "no-name"));
31
+ }
32
+ getName() {
33
+ return this.name;
34
+ }
35
+ applicationReady() {
36
+ this.applicationReadyAt = Date.now();
37
+ }
38
+ }
39
+ exports.BaseService = BaseService;
@@ -0,0 +1,131 @@
1
+ import { Req } from "../signal/Signal";
2
+ import { BaseService } from "./BaseService";
3
+ import { IDBAdapter } from "./db/IDBAdapter";
4
+ export interface IDBQueryField {
5
+ name?: string | null;
6
+ value: string | number | boolean | Date | null | undefined;
7
+ system?: boolean;
8
+ ignoreInInsert?: boolean;
9
+ ignoreInUpdate?: boolean;
10
+ useInReplace?: boolean;
11
+ __parsedValue?: string | number | boolean | null | undefined;
12
+ fields?: Record<string, number | boolean | string | null>;
13
+ }
14
+ export interface IDBQueryFields {
15
+ [key: string]: string | number | boolean | Date | IDBQueryField | null | undefined;
16
+ }
17
+ export interface IDBQuery {
18
+ dbid?: string;
19
+ query: string;
20
+ fields?: IDBQueryFields;
21
+ throwable?: boolean;
22
+ onDuplicateErrorText?: string;
23
+ onErrorText?: string;
24
+ transactionID?: number;
25
+ rollbackOnFail?: boolean;
26
+ calculateCount?: boolean;
27
+ parseQueryOnly?: boolean;
28
+ debug?: boolean;
29
+ }
30
+ export interface IDBBulkQueryItem {
31
+ query: string;
32
+ fields: IDBQueryFields;
33
+ throwable?: boolean;
34
+ calculateCount?: boolean;
35
+ }
36
+ export interface IDBBulkQuery {
37
+ dbid?: string;
38
+ bulk: IDBBulkQueryItem[];
39
+ queued?: boolean;
40
+ }
41
+ export interface IDBError {
42
+ code: string;
43
+ errno: number;
44
+ fatal: boolean;
45
+ sql: string;
46
+ name: string;
47
+ message: string;
48
+ isDuplicateError: boolean;
49
+ }
50
+ export interface IDBResult {
51
+ data?: any | null;
52
+ error?: IDBError | null;
53
+ total?: number;
54
+ execution: {
55
+ started_at: number;
56
+ finished_at: number;
57
+ };
58
+ }
59
+ export interface IDBSericeOptions {
60
+ id: string;
61
+ type: "mysql" | "postgres";
62
+ connection: DBAdapterOptions;
63
+ }
64
+ export interface DBAdapterOptions {
65
+ connectionLimit: number;
66
+ host: string;
67
+ user: string;
68
+ password: string;
69
+ port: number;
70
+ database: string;
71
+ connectionParamers?: string;
72
+ idleTimeoutMillis?: number;
73
+ connectionTimeoutMillis?: number;
74
+ queueLimit?: number;
75
+ transactionFailReport?: (trx: any, message: string) => void;
76
+ transactionFailReportDir?: string;
77
+ maxTransactionWaitTime?: number;
78
+ maxQueryTimeout?: number;
79
+ debug?: boolean;
80
+ }
81
+ export interface IPoolStatus {
82
+ lastSuccessQueryTime: string;
83
+ poolConnections: number;
84
+ acquiredPoolConnections: number;
85
+ }
86
+ export interface IDBStatFrame {
87
+ transactionsCount: number;
88
+ averageQueryTime: number;
89
+ totalQueries: number;
90
+ maxQueryTime: number;
91
+ minQueryTime: number;
92
+ failedQueries: number;
93
+ longestQueries: {
94
+ query: string;
95
+ execution: number;
96
+ }[];
97
+ }
98
+ export declare const REQ_DB: Req<IDBQuery, IDBResult>;
99
+ export declare const REQ_DBX: Req<IDBBulkQuery, IDBResult[]>;
100
+ export declare const REQ_DB_TBEGIN: Req<{
101
+ dbid: string;
102
+ }, IDBResult>;
103
+ export declare const REQ_DB_TCOMMIT: Req<{
104
+ dbid: string;
105
+ trxid: number;
106
+ }, IDBResult>;
107
+ export declare const REQ_DB_TROLLBACK: Req<{
108
+ dbid: string;
109
+ trxid: number;
110
+ }, IDBResult>;
111
+ export declare class DBService extends BaseService {
112
+ static allInstances: DBService[];
113
+ options: IDBSericeOptions;
114
+ adapter: IDBAdapter | null;
115
+ constructor(options: IDBSericeOptions);
116
+ init(): Promise<void>;
117
+ static escape(id: string, value: any): string;
118
+ getAdapter(dbid?: string | null): IDBAdapter | IDBError;
119
+ static healthcheck(range?: "hour" | "day" | "week"): {
120
+ id: string;
121
+ host: string;
122
+ port: number;
123
+ poolStatus: IPoolStatus | null;
124
+ stat: (IDBStatFrame & {
125
+ slot: number;
126
+ })[] | null;
127
+ }[];
128
+ private static aggregateStat;
129
+ finishService(): Promise<void>;
130
+ createMysqlDatabase(): Promise<void>;
131
+ }