@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.
- package/CHANGELOG.md +90 -0
- package/LICENSE +21 -0
- package/README.md +1293 -2
- package/dist/apiServer/APIService.d.ts +125 -0
- package/dist/apiServer/APIService.js +769 -0
- package/dist/apiServer/BaseEndpoint.d.ts +90 -0
- package/dist/apiServer/BaseEndpoint.js +314 -0
- package/dist/apiServer/BaseService.d.ts +17 -0
- package/dist/apiServer/BaseService.js +39 -0
- package/dist/apiServer/DBService.d.ts +131 -0
- package/dist/apiServer/DBService.js +290 -0
- package/dist/apiServer/DocumentService.d.ts +9 -0
- package/dist/apiServer/DocumentService.js +65 -0
- package/dist/apiServer/LocalRequest.d.ts +3 -0
- package/dist/apiServer/LocalRequest.js +6 -0
- package/dist/apiServer/LogService.d.ts +78 -0
- package/dist/apiServer/LogService.js +349 -0
- package/dist/apiServer/MonitorService.d.ts +102 -0
- package/dist/apiServer/MonitorService.js +615 -0
- package/dist/apiServer/StatService.d.ts +4 -0
- package/dist/apiServer/StatService.js +10 -0
- package/dist/apiServer/TimeframeService.d.ts +28 -0
- package/dist/apiServer/TimeframeService.js +97 -0
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
- package/dist/apiServer/db/IDBAdapter.js +2 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
- package/dist/apiServer/db/MysqlAdapter.js +869 -0
- package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
- package/dist/apiServer/db/PostgresAdapter.js +73 -0
- package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
- package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
- package/dist/apiServer/deployment/Activate.d.ts +4 -0
- package/dist/apiServer/deployment/Activate.js +124 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +44 -0
- package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
- package/dist/apiServer/deployment/BlueGreenState.js +150 -0
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
- package/dist/apiServer/deployment/ConfigService.js +195 -0
- package/dist/apiServer/deployment/Deploy.d.ts +4 -0
- package/dist/apiServer/deployment/Deploy.js +404 -0
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +13 -0
- package/dist/apiServer/deployment/Deployer.js +96 -0
- package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
- package/dist/apiServer/deployment/DeployerInit.js +214 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
- package/dist/apiServer/deployment/DeployerService.js +1553 -0
- package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
- package/dist/apiServer/deployment/HashPassword.js +126 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
- package/dist/apiServer/deployment/MigrateProject.js +335 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
- package/dist/apiServer/deployment/NginxHelper.js +111 -0
- package/dist/apiServer/deployment/Notifier.d.ts +30 -0
- package/dist/apiServer/deployment/Notifier.js +82 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +89 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +189 -0
- package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
- package/dist/apiServer/deployment/Status.d.ts +2 -0
- package/dist/apiServer/deployment/Status.js +83 -0
- package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
- package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
- package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
- package/dist/apiServer/deployment/Watchdog.js +65 -0
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +83 -0
- package/dist/apiServer/deployment/cli.d.ts +2 -0
- package/dist/apiServer/deployment/cli.js +224 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
- package/dist/apiServer/deployment/cliCommon.js +110 -0
- package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
- package/dist/apiServer/deployment/cliPrompt.js +38 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
- package/dist/apiServer/deployment/resolveConfig.js +139 -0
- package/dist/apiServer/documentation/Documentation.d.ts +18 -0
- package/dist/apiServer/documentation/Documentation.js +143 -0
- package/dist/apiServer/documentation/index.html +460 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
- package/dist/apiServer/external/MicroserviceClient.js +144 -0
- package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
- package/dist/apiServer/external/MicroserviceHost.js +183 -0
- package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
- package/dist/apiServer/external/MicroserviceHostController.js +65 -0
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +3 -0
- package/dist/apiServer/helper/ClientIp.js +33 -0
- package/dist/apiServer/helper/DataProvider.d.ts +18 -0
- package/dist/apiServer/helper/DataProvider.js +57 -0
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
- package/dist/apiServer/helper/JSONStableStringify.js +15 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/helper/Sleep.d.ts +1 -0
- package/dist/apiServer/helper/Sleep.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/UID.d.ts +16 -0
- package/dist/apiServer/helper/UID.js +98 -0
- package/dist/apiServer/helper/Validator.d.ts +86 -0
- package/dist/apiServer/helper/Validator.js +560 -0
- package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
- package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
- package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
- package/dist/apiServer/helper/ZipUtils.js +28 -0
- package/dist/apiServer/http/Http.d.ts +183 -0
- package/dist/apiServer/http/Http.js +627 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
- package/dist/apiServer/monitor/AccessStore.js +163 -0
- package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
- package/dist/apiServer/monitor/LogFiles.js +109 -0
- package/dist/apiServer/monitor/Monitor.d.ts +54 -0
- package/dist/apiServer/monitor/Monitor.js +447 -0
- package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
- package/dist/apiServer/monitor/MonitorAuth.js +474 -0
- package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
- package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
- package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
- package/dist/apiServer/monitor/SystemInfo.js +217 -0
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
- package/dist/apiServer/monitor/index.html +591 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/dist/apiServer/routes/Liveness.d.ts +7 -0
- package/dist/apiServer/routes/Liveness.js +27 -0
- package/dist/apiServer/routes/Readiness.d.ts +13 -0
- package/dist/apiServer/routes/Readiness.js +20 -0
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +185 -0
- package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
- package/dist/apiServer/structures/DefaultErrors.js +52 -0
- package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
- package/dist/apiServer/structures/HTTPStatus.js +11 -0
- package/dist/apiServer/structures/Interfaces.d.ts +55 -0
- package/dist/apiServer/structures/Interfaces.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +110 -0
- package/dist/signal/Signal.d.ts +23 -0
- package/dist/signal/Signal.js +85 -0
- package/package.json +88 -4
|
@@ -0,0 +1,627 @@
|
|
|
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.Http = void 0;
|
|
7
|
+
const undici_1 = require("undici");
|
|
8
|
+
const node_diagnostics_channel_1 = __importDefault(require("node:diagnostics_channel"));
|
|
9
|
+
const Trace_1 = require("../helper/Trace");
|
|
10
|
+
const MonitorService_1 = require("../MonitorService");
|
|
11
|
+
const LogService_1 = require("../LogService");
|
|
12
|
+
function sleep(ms) {
|
|
13
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
14
|
+
}
|
|
15
|
+
function clamp(n, min, max) {
|
|
16
|
+
return Math.max(min, Math.min(max, n));
|
|
17
|
+
}
|
|
18
|
+
function buildQuery(query) {
|
|
19
|
+
if (!query)
|
|
20
|
+
return "";
|
|
21
|
+
const params = new URLSearchParams();
|
|
22
|
+
for (const [k, v] of Object.entries(query)) {
|
|
23
|
+
if (v === null || v === undefined)
|
|
24
|
+
continue;
|
|
25
|
+
params.set(k, String(v));
|
|
26
|
+
}
|
|
27
|
+
const s = params.toString();
|
|
28
|
+
return s ? `?${s}` : "";
|
|
29
|
+
}
|
|
30
|
+
function mergeHeaders(a, b) {
|
|
31
|
+
return { ...(a || {}), ...(b || {}) };
|
|
32
|
+
}
|
|
33
|
+
function normalizeHeaders(headers) {
|
|
34
|
+
const out = {};
|
|
35
|
+
if (!headers || typeof headers !== "object")
|
|
36
|
+
return out;
|
|
37
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
38
|
+
if (Array.isArray(v))
|
|
39
|
+
out[k.toLowerCase()] = v.join(", ");
|
|
40
|
+
else if (v !== undefined && v !== null)
|
|
41
|
+
out[k.toLowerCase()] = String(v);
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
function isRetryableStatus(status, retryOnStatuses) {
|
|
46
|
+
return retryOnStatuses.includes(status);
|
|
47
|
+
}
|
|
48
|
+
function isFormDataLike(value) {
|
|
49
|
+
return (value !== null &&
|
|
50
|
+
typeof value === "object" &&
|
|
51
|
+
Object.prototype.toString.call(value) === "[object FormData]" &&
|
|
52
|
+
typeof value.entries === "function");
|
|
53
|
+
}
|
|
54
|
+
function normalizeFormData(source) {
|
|
55
|
+
if (source instanceof undici_1.FormData)
|
|
56
|
+
return source;
|
|
57
|
+
const target = new undici_1.FormData();
|
|
58
|
+
for (const [name, value] of source.entries()) {
|
|
59
|
+
if (typeof value === "string") {
|
|
60
|
+
target.append(name, value);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
target.append(name, value, value.name);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return target;
|
|
67
|
+
}
|
|
68
|
+
function removeContentTypeHeader(headers) {
|
|
69
|
+
for (const key of Object.keys(headers)) {
|
|
70
|
+
if (key.toLowerCase() === "content-type")
|
|
71
|
+
delete headers[key];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function isLikelyNetworkError(err) {
|
|
75
|
+
if (!err || typeof err !== "object")
|
|
76
|
+
return false;
|
|
77
|
+
const anyErr = err;
|
|
78
|
+
if (anyErr?.name === "AbortError")
|
|
79
|
+
return true;
|
|
80
|
+
const code = anyErr?.code;
|
|
81
|
+
const networkCodes = new Set(["ECONNRESET", "ETIMEDOUT", "ECONNREFUSED", "EAI_AGAIN", "ENOTFOUND", "EPIPE"]);
|
|
82
|
+
if (code && networkCodes.has(code))
|
|
83
|
+
return true;
|
|
84
|
+
if (err instanceof undici_1.errors.ConnectTimeoutError)
|
|
85
|
+
return true;
|
|
86
|
+
if (err instanceof undici_1.errors.HeadersTimeoutError)
|
|
87
|
+
return true;
|
|
88
|
+
if (err instanceof undici_1.errors.BodyTimeoutError)
|
|
89
|
+
return true;
|
|
90
|
+
if (err instanceof undici_1.errors.SocketError)
|
|
91
|
+
return true;
|
|
92
|
+
return false;
|
|
93
|
+
}
|
|
94
|
+
class Http {
|
|
95
|
+
static _inited = false;
|
|
96
|
+
static config = {
|
|
97
|
+
baseUrl: "",
|
|
98
|
+
timeoutMs: 5000,
|
|
99
|
+
headers: {
|
|
100
|
+
accept: "application/json",
|
|
101
|
+
},
|
|
102
|
+
retry: {
|
|
103
|
+
enabled: false,
|
|
104
|
+
maxAttempts: 2,
|
|
105
|
+
baseDelayMs: 200,
|
|
106
|
+
maxDelayMs: 1500,
|
|
107
|
+
retryOnStatuses: [429, 502, 503, 504],
|
|
108
|
+
retryOnNetworkErrors: true,
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
static _sharedAgent = null;
|
|
112
|
+
static _dcEnabled = false;
|
|
113
|
+
static _dcConnectedChannel = null;
|
|
114
|
+
static _dcListener = null;
|
|
115
|
+
static _activeConnectionsTotal = 0;
|
|
116
|
+
static _activeConnectionsByHost = new Map();
|
|
117
|
+
static _countedSockets = new WeakSet();
|
|
118
|
+
static _socketHostKey = new WeakMap();
|
|
119
|
+
static _outgoingLog = [];
|
|
120
|
+
static _nextOutgoingLogID = 0;
|
|
121
|
+
static _outgoingLogLimit = 500;
|
|
122
|
+
static _truncate(v) {
|
|
123
|
+
if (Buffer.isBuffer(v))
|
|
124
|
+
return `[Buffer ${v.length} bytes]`;
|
|
125
|
+
return LogService_1.LogService.snapshot(v);
|
|
126
|
+
}
|
|
127
|
+
static _origin(url) {
|
|
128
|
+
try {
|
|
129
|
+
return new URL(url).origin;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return "[url not logged]";
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
static _pushOutgoingLog(item) {
|
|
136
|
+
const entry = {
|
|
137
|
+
id: this._nextOutgoingLogID++,
|
|
138
|
+
...item,
|
|
139
|
+
url: typeof item.url === "string" ? LogService_1.LogService.sanitize(item.url) : item.url,
|
|
140
|
+
request: typeof item.request === "string" ? LogService_1.LogService.sanitize(item.request) : LogService_1.LogService.sanitizeDeep(item.request),
|
|
141
|
+
response: typeof item.response === "string" ? LogService_1.LogService.sanitize(item.response) : LogService_1.LogService.sanitizeDeep(item.response),
|
|
142
|
+
error: typeof item.error === "string" ? LogService_1.LogService.sanitize(item.error) : item.error,
|
|
143
|
+
};
|
|
144
|
+
this._outgoingLog.push(entry);
|
|
145
|
+
if (this._outgoingLog.length > this._outgoingLogLimit)
|
|
146
|
+
this._outgoingLog.shift();
|
|
147
|
+
if (this._nextOutgoingLogID > Number.MAX_SAFE_INTEGER - 1000)
|
|
148
|
+
this._nextOutgoingLogID = 0;
|
|
149
|
+
return entry;
|
|
150
|
+
}
|
|
151
|
+
static getOutgoingLogSnapshot() {
|
|
152
|
+
return this._outgoingLog.slice();
|
|
153
|
+
}
|
|
154
|
+
static _totalRequests = 0;
|
|
155
|
+
static _inFlight = 0;
|
|
156
|
+
static _peakInFlight = 0;
|
|
157
|
+
static _inFlightByHost = new Map();
|
|
158
|
+
static _statusDist = {
|
|
159
|
+
s2xx: 0, s3xx: 0, s4xx: 0, s5xx: 0, other: 0, networkErrors: 0, timeouts: 0,
|
|
160
|
+
};
|
|
161
|
+
static _perHost = new Map();
|
|
162
|
+
static _topSlow = [];
|
|
163
|
+
static _topSlowLimit = 20;
|
|
164
|
+
static _hostFromUrl(url) {
|
|
165
|
+
try {
|
|
166
|
+
return new URL(url).host || "unknown";
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return "unknown";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
static _isTimeoutError(err) {
|
|
173
|
+
if (!err || typeof err !== "object")
|
|
174
|
+
return false;
|
|
175
|
+
const e = err;
|
|
176
|
+
if (e.name === "AbortError")
|
|
177
|
+
return true;
|
|
178
|
+
if (typeof e.code === "string" && e.code.includes("TIMEOUT"))
|
|
179
|
+
return true;
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
static _incInFlight(host) {
|
|
183
|
+
this._inFlight++;
|
|
184
|
+
if (this._inFlight > this._peakInFlight)
|
|
185
|
+
this._peakInFlight = this._inFlight;
|
|
186
|
+
this._inFlightByHost.set(host, (this._inFlightByHost.get(host) ?? 0) + 1);
|
|
187
|
+
}
|
|
188
|
+
static _decInFlight(host) {
|
|
189
|
+
this._inFlight = Math.max(0, this._inFlight - 1);
|
|
190
|
+
const prev = this._inFlightByHost.get(host) ?? 0;
|
|
191
|
+
const next = Math.max(0, prev - 1);
|
|
192
|
+
if (next === 0)
|
|
193
|
+
this._inFlightByHost.delete(host);
|
|
194
|
+
else
|
|
195
|
+
this._inFlightByHost.set(host, next);
|
|
196
|
+
}
|
|
197
|
+
static _updateStats(host, entry, isTimeout) {
|
|
198
|
+
this._totalRequests++;
|
|
199
|
+
if (typeof entry.status === "number") {
|
|
200
|
+
const s = entry.status;
|
|
201
|
+
if (s >= 200 && s < 300)
|
|
202
|
+
this._statusDist.s2xx++;
|
|
203
|
+
else if (s >= 300 && s < 400)
|
|
204
|
+
this._statusDist.s3xx++;
|
|
205
|
+
else if (s >= 400 && s < 500)
|
|
206
|
+
this._statusDist.s4xx++;
|
|
207
|
+
else if (s >= 500 && s < 600)
|
|
208
|
+
this._statusDist.s5xx++;
|
|
209
|
+
else
|
|
210
|
+
this._statusDist.other++;
|
|
211
|
+
}
|
|
212
|
+
else if (entry.error) {
|
|
213
|
+
this._statusDist.networkErrors++;
|
|
214
|
+
if (isTimeout)
|
|
215
|
+
this._statusDist.timeouts++;
|
|
216
|
+
}
|
|
217
|
+
let h = this._perHost.get(host);
|
|
218
|
+
if (!h) {
|
|
219
|
+
h = {
|
|
220
|
+
host,
|
|
221
|
+
count: 0, errors: 0, timeouts: 0, retries: 0,
|
|
222
|
+
avgMs: 0, minMs: Infinity, maxMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0, totalTimeMs: 0,
|
|
223
|
+
inFlight: 0,
|
|
224
|
+
byStatus: { s2xx: 0, s3xx: 0, s4xx: 0, s5xx: 0, other: 0, networkErrors: 0 },
|
|
225
|
+
lastRequestAt: 0,
|
|
226
|
+
};
|
|
227
|
+
this._perHost.set(host, h);
|
|
228
|
+
}
|
|
229
|
+
h.count++;
|
|
230
|
+
h.totalTimeMs += entry.time;
|
|
231
|
+
h.avgMs = Math.round((h.totalTimeMs / h.count) * 10) / 10;
|
|
232
|
+
if (entry.time < h.minMs)
|
|
233
|
+
h.minMs = entry.time;
|
|
234
|
+
if (entry.time > h.maxMs)
|
|
235
|
+
h.maxMs = entry.time;
|
|
236
|
+
this._recordLatency(host, entry.time);
|
|
237
|
+
if (!entry.ok)
|
|
238
|
+
h.errors++;
|
|
239
|
+
if (isTimeout)
|
|
240
|
+
h.timeouts++;
|
|
241
|
+
h.retries += Math.max(0, entry.attempts - 1);
|
|
242
|
+
h.lastRequestAt = Date.now();
|
|
243
|
+
if (typeof entry.status === "number") {
|
|
244
|
+
const s = entry.status;
|
|
245
|
+
if (s >= 200 && s < 300)
|
|
246
|
+
h.byStatus.s2xx++;
|
|
247
|
+
else if (s >= 300 && s < 400)
|
|
248
|
+
h.byStatus.s3xx++;
|
|
249
|
+
else if (s >= 400 && s < 500)
|
|
250
|
+
h.byStatus.s4xx++;
|
|
251
|
+
else if (s >= 500 && s < 600)
|
|
252
|
+
h.byStatus.s5xx++;
|
|
253
|
+
else
|
|
254
|
+
h.byStatus.other++;
|
|
255
|
+
}
|
|
256
|
+
else if (entry.error) {
|
|
257
|
+
h.byStatus.networkErrors++;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
static _LAT_CAP = 1024;
|
|
261
|
+
static _latency = new Map();
|
|
262
|
+
static _recordLatency(host, ms) {
|
|
263
|
+
let r = this._latency.get(host);
|
|
264
|
+
if (!r) {
|
|
265
|
+
r = { s: new Array(this._LAT_CAP), pos: 0, n: 0 };
|
|
266
|
+
this._latency.set(host, r);
|
|
267
|
+
}
|
|
268
|
+
r.s[r.pos] = ms;
|
|
269
|
+
r.pos = (r.pos + 1) % this._LAT_CAP;
|
|
270
|
+
if (r.n < this._LAT_CAP)
|
|
271
|
+
r.n++;
|
|
272
|
+
}
|
|
273
|
+
static _percentiles(host) {
|
|
274
|
+
const r = this._latency.get(host);
|
|
275
|
+
if (!r || r.n === 0)
|
|
276
|
+
return { p50: 0, p95: 0, p99: 0 };
|
|
277
|
+
const arr = r.s.slice(0, r.n).sort((a, b) => a - b);
|
|
278
|
+
const pick = (p) => arr[Math.min(arr.length - 1, Math.max(0, Math.ceil((p / 100) * arr.length) - 1))];
|
|
279
|
+
return { p50: pick(50), p95: pick(95), p99: pick(99) };
|
|
280
|
+
}
|
|
281
|
+
static _pushToTopSlow(entry) {
|
|
282
|
+
if (this._topSlow.length < this._topSlowLimit) {
|
|
283
|
+
this._topSlow.push(entry);
|
|
284
|
+
this._topSlow.sort((a, b) => b.time - a.time);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
const slowest_of_top = this._topSlow[this._topSlow.length - 1];
|
|
288
|
+
if (entry.time > slowest_of_top.time) {
|
|
289
|
+
this._topSlow.push(entry);
|
|
290
|
+
this._topSlow.sort((a, b) => b.time - a.time);
|
|
291
|
+
this._topSlow.pop();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
static getHttpStats() {
|
|
295
|
+
const perHost = Array.from(this._perHost.values())
|
|
296
|
+
.map(h => {
|
|
297
|
+
const p = this._percentiles(h.host);
|
|
298
|
+
return {
|
|
299
|
+
...h,
|
|
300
|
+
minMs: Number.isFinite(h.minMs) ? h.minMs : 0,
|
|
301
|
+
p50Ms: p.p50, p95Ms: p.p95, p99Ms: p.p99,
|
|
302
|
+
inFlight: this._inFlightByHost.get(h.host) ?? 0,
|
|
303
|
+
};
|
|
304
|
+
})
|
|
305
|
+
.sort((a, b) => b.count - a.count);
|
|
306
|
+
return {
|
|
307
|
+
totalRequests: this._totalRequests,
|
|
308
|
+
inFlight: {
|
|
309
|
+
current: this._inFlight,
|
|
310
|
+
peak: this._peakInFlight,
|
|
311
|
+
byHost: Object.fromEntries(this._inFlightByHost),
|
|
312
|
+
},
|
|
313
|
+
statusDistribution: { ...this._statusDist },
|
|
314
|
+
perHost,
|
|
315
|
+
topSlow: this._topSlow.slice(),
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
static ensureInit() {
|
|
319
|
+
if (this._inited)
|
|
320
|
+
return;
|
|
321
|
+
this._inited = true;
|
|
322
|
+
this.enableConnectionCounterByHost();
|
|
323
|
+
if (!this.config.dispatcher) {
|
|
324
|
+
this._sharedAgent = this.createAgent({
|
|
325
|
+
connections: 100,
|
|
326
|
+
keepAliveTimeout: 60_000,
|
|
327
|
+
keepAliveMaxTimeout: 60_000,
|
|
328
|
+
});
|
|
329
|
+
this.config.dispatcher = this._sharedAgent;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
static configure(partial) {
|
|
333
|
+
this.config = {
|
|
334
|
+
...this.config,
|
|
335
|
+
...partial,
|
|
336
|
+
headers: mergeHeaders(this.config.headers, partial.headers),
|
|
337
|
+
retry: { ...(this.config.retry || {}), ...(partial.retry || {}) },
|
|
338
|
+
};
|
|
339
|
+
if (partial.dispatcher && this._sharedAgent) {
|
|
340
|
+
try {
|
|
341
|
+
this._sharedAgent.close();
|
|
342
|
+
}
|
|
343
|
+
catch { }
|
|
344
|
+
this._sharedAgent = null;
|
|
345
|
+
}
|
|
346
|
+
this.ensureInit();
|
|
347
|
+
}
|
|
348
|
+
static createAgent(opts) {
|
|
349
|
+
return new undici_1.Agent({
|
|
350
|
+
keepAliveTimeout: 60_000,
|
|
351
|
+
keepAliveMaxTimeout: 60_000,
|
|
352
|
+
...opts,
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
static closeSharedAgent() {
|
|
356
|
+
if (!this._sharedAgent)
|
|
357
|
+
return;
|
|
358
|
+
try {
|
|
359
|
+
this._sharedAgent.close();
|
|
360
|
+
}
|
|
361
|
+
catch { }
|
|
362
|
+
this._sharedAgent = null;
|
|
363
|
+
if (this.config.dispatcher === this._sharedAgent) {
|
|
364
|
+
this.config.dispatcher = undefined;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
static basicAuth(username, password) {
|
|
368
|
+
const token = Buffer.from(`${username}:${password}`).toString("base64");
|
|
369
|
+
return `Basic ${token}`;
|
|
370
|
+
}
|
|
371
|
+
static bearer(token) {
|
|
372
|
+
return `Bearer ${token}`;
|
|
373
|
+
}
|
|
374
|
+
static enableConnectionCounterByHost() {
|
|
375
|
+
if (this._dcEnabled)
|
|
376
|
+
return;
|
|
377
|
+
this._dcEnabled = true;
|
|
378
|
+
const ch = node_diagnostics_channel_1.default.channel("undici:client:connected");
|
|
379
|
+
const listener = (message) => {
|
|
380
|
+
const msg = message;
|
|
381
|
+
const socket = msg?.socket;
|
|
382
|
+
if (!socket)
|
|
383
|
+
return;
|
|
384
|
+
if (this._countedSockets.has(socket))
|
|
385
|
+
return;
|
|
386
|
+
this._countedSockets.add(socket);
|
|
387
|
+
const key = this._makeHostKey(msg?.connectParams, socket);
|
|
388
|
+
this._socketHostKey.set(socket, key);
|
|
389
|
+
this._activeConnectionsTotal += 1;
|
|
390
|
+
this._activeConnectionsByHost.set(key, (this._activeConnectionsByHost.get(key) ?? 0) + 1);
|
|
391
|
+
const onClose = () => {
|
|
392
|
+
this._activeConnectionsTotal = Math.max(0, this._activeConnectionsTotal - 1);
|
|
393
|
+
const k = this._socketHostKey.get(socket) ?? "unknown://unknown:0";
|
|
394
|
+
const prev = this._activeConnectionsByHost.get(k) ?? 0;
|
|
395
|
+
const next = Math.max(0, prev - 1);
|
|
396
|
+
if (next === 0)
|
|
397
|
+
this._activeConnectionsByHost.delete(k);
|
|
398
|
+
else
|
|
399
|
+
this._activeConnectionsByHost.set(k, next);
|
|
400
|
+
socket.off("close", onClose);
|
|
401
|
+
};
|
|
402
|
+
socket.on("close", onClose);
|
|
403
|
+
};
|
|
404
|
+
ch.subscribe(listener);
|
|
405
|
+
this._dcConnectedChannel = ch;
|
|
406
|
+
this._dcListener = listener;
|
|
407
|
+
}
|
|
408
|
+
static disableConnectionCounterByHost(options) {
|
|
409
|
+
if (!this._dcEnabled)
|
|
410
|
+
return;
|
|
411
|
+
const ch = this._dcConnectedChannel;
|
|
412
|
+
const listener = this._dcListener;
|
|
413
|
+
if (ch && listener) {
|
|
414
|
+
ch.unsubscribe(listener);
|
|
415
|
+
}
|
|
416
|
+
this._dcConnectedChannel = null;
|
|
417
|
+
this._dcListener = null;
|
|
418
|
+
this._dcEnabled = false;
|
|
419
|
+
if (options?.reset) {
|
|
420
|
+
this._activeConnectionsTotal = 0;
|
|
421
|
+
this._activeConnectionsByHost.clear();
|
|
422
|
+
this._countedSockets = new WeakSet();
|
|
423
|
+
this._socketHostKey = new WeakMap();
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
static _makeHostKey(connectParams, socket) {
|
|
427
|
+
const protocolRaw = connectParams?.protocol || "unknown:";
|
|
428
|
+
const protocol = protocolRaw.replace(/\/+$/g, "");
|
|
429
|
+
const hostname = connectParams?.hostname || connectParams?.host;
|
|
430
|
+
let port = connectParams?.port !== undefined && connectParams?.port !== null ? String(connectParams.port) : undefined;
|
|
431
|
+
if (!port) {
|
|
432
|
+
if (protocol === "https:")
|
|
433
|
+
port = "443";
|
|
434
|
+
else if (protocol === "http:")
|
|
435
|
+
port = "80";
|
|
436
|
+
else
|
|
437
|
+
port = "?";
|
|
438
|
+
}
|
|
439
|
+
if (hostname)
|
|
440
|
+
return `${protocol}//${hostname}:${port}`;
|
|
441
|
+
const addr = socket?.remoteAddress ?? "unknown";
|
|
442
|
+
const p = socket?.remotePort ?? "?";
|
|
443
|
+
return `${protocol}//${addr}:${p}`;
|
|
444
|
+
}
|
|
445
|
+
static getActiveConnectionsTotal() {
|
|
446
|
+
return this._activeConnectionsTotal;
|
|
447
|
+
}
|
|
448
|
+
static getActiveConnectionsByHost() {
|
|
449
|
+
return new Map(this._activeConnectionsByHost);
|
|
450
|
+
}
|
|
451
|
+
static getActiveConnectionsSnapshot() {
|
|
452
|
+
return {
|
|
453
|
+
total: this._activeConnectionsTotal,
|
|
454
|
+
byHost: Object.fromEntries(this._activeConnectionsByHost.entries()),
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
static async request(opts) {
|
|
458
|
+
MonitorService_1.S_STAT_REGISTRATE_HTTP_REQUEST.invoke({ url: opts.skipLogging ? Http._origin(opts.url) : opts.url });
|
|
459
|
+
this.ensureInit();
|
|
460
|
+
const overallStarted = Date.now();
|
|
461
|
+
const cfg = this.config;
|
|
462
|
+
const retryCfg = {
|
|
463
|
+
enabled: opts.retry?.enabled ?? cfg.retry?.enabled ?? false,
|
|
464
|
+
maxAttempts: opts.retry?.maxAttempts ?? cfg.retry?.maxAttempts ?? 2,
|
|
465
|
+
baseDelayMs: opts.retry?.baseDelayMs ?? cfg.retry?.baseDelayMs ?? 200,
|
|
466
|
+
maxDelayMs: opts.retry?.maxDelayMs ?? cfg.retry?.maxDelayMs ?? 1500,
|
|
467
|
+
retryOnStatuses: opts.retry?.retryOnStatuses ?? cfg.retry?.retryOnStatuses ?? [429, 502, 503, 504],
|
|
468
|
+
retryOnNetworkErrors: opts.retry?.retryOnNetworkErrors ?? cfg.retry?.retryOnNetworkErrors ?? true,
|
|
469
|
+
};
|
|
470
|
+
const timeoutMs = opts.timeoutMs ?? cfg.timeoutMs ?? 5000;
|
|
471
|
+
const dispatcher = opts.dispatcher ?? cfg.dispatcher;
|
|
472
|
+
const baseUrl = cfg.baseUrl || "";
|
|
473
|
+
const isAbsolute = /^https?:\/\//i.test(opts.url);
|
|
474
|
+
const query = buildQuery(opts.query);
|
|
475
|
+
const url = (isAbsolute ? opts.url : baseUrl + opts.url) + query;
|
|
476
|
+
const headers = mergeHeaders(cfg.headers, opts.headers);
|
|
477
|
+
let body = undefined;
|
|
478
|
+
const hasBody = opts.body !== undefined && opts.body !== null;
|
|
479
|
+
const allowBody = opts.allowBody ?? (opts.method !== "GET" && opts.method !== "DELETE");
|
|
480
|
+
let isMultipart = false;
|
|
481
|
+
if (hasBody && allowBody) {
|
|
482
|
+
if (isFormDataLike(opts.body)) {
|
|
483
|
+
isMultipart = true;
|
|
484
|
+
body = normalizeFormData(opts.body);
|
|
485
|
+
removeContentTypeHeader(headers);
|
|
486
|
+
}
|
|
487
|
+
else {
|
|
488
|
+
const ct = (headers["content-type"] || headers["Content-Type"] || "").toLowerCase();
|
|
489
|
+
if (!ct)
|
|
490
|
+
headers["content-type"] = "application/json";
|
|
491
|
+
const ct2 = (headers["content-type"] || headers["Content-Type"] || "").toLowerCase();
|
|
492
|
+
if (ct2.includes("application/json") && typeof opts.body !== "string" && !(opts.body instanceof Buffer)) {
|
|
493
|
+
body = JSON.stringify(opts.body);
|
|
494
|
+
}
|
|
495
|
+
else {
|
|
496
|
+
body = opts.body;
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
if (isMultipart && retryCfg.maxAttempts !== 1) {
|
|
501
|
+
retryCfg.maxAttempts = 1;
|
|
502
|
+
}
|
|
503
|
+
const responseType = opts.responseType ?? "json";
|
|
504
|
+
const throwOnJsonParseError = opts.throwOnJsonParseError ?? false;
|
|
505
|
+
let attemptsMade = 0;
|
|
506
|
+
const host = Http._hostFromUrl(url);
|
|
507
|
+
const traceId = Trace_1.Trace.current() ?? undefined;
|
|
508
|
+
Http._incInFlight(host);
|
|
509
|
+
const finish = (result, networkErr) => {
|
|
510
|
+
Http._decInFlight(host);
|
|
511
|
+
const item = {
|
|
512
|
+
traceId,
|
|
513
|
+
created: overallStarted,
|
|
514
|
+
time: Date.now() - overallStarted,
|
|
515
|
+
method: opts.method,
|
|
516
|
+
url,
|
|
517
|
+
status: result.status,
|
|
518
|
+
ok: result.ok,
|
|
519
|
+
attempts: attemptsMade,
|
|
520
|
+
request: Http._truncate(opts.body),
|
|
521
|
+
response: Http._truncate(result.ok ? result.data : result.error),
|
|
522
|
+
error: networkErr ? String(networkErr?.message ?? networkErr) : undefined,
|
|
523
|
+
};
|
|
524
|
+
const entry = Http._pushOutgoingLog(opts.skipLogging
|
|
525
|
+
? { ...item, url: Http._origin(url), request: "[not logged]", response: "[not logged]",
|
|
526
|
+
error: networkErr ? (Http._isTimeoutError(networkErr) ? "timeout" : "network error") : undefined, skipLogging: true }
|
|
527
|
+
: item);
|
|
528
|
+
const isTimeout = Http._isTimeoutError(networkErr);
|
|
529
|
+
Http._updateStats(host, entry, isTimeout);
|
|
530
|
+
Http._pushToTopSlow(entry);
|
|
531
|
+
MonitorService_1.S_STAT_REGISTRATE_HTTP_RESULT.invoke({ host, ok: result.ok, ms: entry.time });
|
|
532
|
+
return result;
|
|
533
|
+
};
|
|
534
|
+
for (let attempt = 1; attempt <= retryCfg.maxAttempts; attempt++) {
|
|
535
|
+
attemptsMade = attempt;
|
|
536
|
+
const started = Date.now();
|
|
537
|
+
cfg.onRequest?.({ method: opts.method, url, attempt });
|
|
538
|
+
const controller = new AbortController();
|
|
539
|
+
const t = setTimeout(() => controller.abort(), timeoutMs);
|
|
540
|
+
try {
|
|
541
|
+
const res = await (0, undici_1.request)(url, {
|
|
542
|
+
method: opts.method,
|
|
543
|
+
headers,
|
|
544
|
+
body,
|
|
545
|
+
signal: controller.signal,
|
|
546
|
+
dispatcher,
|
|
547
|
+
});
|
|
548
|
+
const ms = Date.now() - started;
|
|
549
|
+
const status = res.statusCode;
|
|
550
|
+
cfg.onResponse?.({ method: opts.method, url, attempt, status, ms });
|
|
551
|
+
const hdrs = normalizeHeaders(res.headers);
|
|
552
|
+
let parsed = undefined;
|
|
553
|
+
let rawText;
|
|
554
|
+
if (responseType === "raw") {
|
|
555
|
+
await res.body.dump();
|
|
556
|
+
parsed = undefined;
|
|
557
|
+
}
|
|
558
|
+
else if (responseType === "text") {
|
|
559
|
+
rawText = await res.body.text();
|
|
560
|
+
parsed = rawText;
|
|
561
|
+
}
|
|
562
|
+
else {
|
|
563
|
+
rawText = await res.body.text();
|
|
564
|
+
if (rawText.length === 0) {
|
|
565
|
+
parsed = null;
|
|
566
|
+
}
|
|
567
|
+
else {
|
|
568
|
+
try {
|
|
569
|
+
parsed = JSON.parse(rawText);
|
|
570
|
+
}
|
|
571
|
+
catch (e) {
|
|
572
|
+
if (throwOnJsonParseError)
|
|
573
|
+
throw e;
|
|
574
|
+
parsed = rawText;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
if (status >= 200 && status < 300) {
|
|
579
|
+
return finish({ ok: true, status, data: parsed, headers: hdrs });
|
|
580
|
+
}
|
|
581
|
+
const retryable = retryCfg.enabled &&
|
|
582
|
+
isRetryableStatus(status, retryCfg.retryOnStatuses) &&
|
|
583
|
+
attempt < retryCfg.maxAttempts;
|
|
584
|
+
if (retryable) {
|
|
585
|
+
const backoff = clamp(retryCfg.baseDelayMs * Math.pow(2, attempt - 1), retryCfg.baseDelayMs, retryCfg.maxDelayMs);
|
|
586
|
+
await sleep(backoff);
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
return finish({ ok: false, status, error: parsed, details: { headers: hdrs } });
|
|
590
|
+
}
|
|
591
|
+
catch (err) {
|
|
592
|
+
const ms = Date.now() - started;
|
|
593
|
+
cfg.onError?.({ method: opts.method, url, attempt, ms, err });
|
|
594
|
+
const retryable = retryCfg.enabled &&
|
|
595
|
+
retryCfg.retryOnNetworkErrors &&
|
|
596
|
+
isLikelyNetworkError(err) &&
|
|
597
|
+
attempt < retryCfg.maxAttempts;
|
|
598
|
+
if (retryable) {
|
|
599
|
+
const backoff = clamp(retryCfg.baseDelayMs * Math.pow(2, attempt - 1), retryCfg.baseDelayMs, retryCfg.maxDelayMs);
|
|
600
|
+
await sleep(backoff);
|
|
601
|
+
continue;
|
|
602
|
+
}
|
|
603
|
+
return finish({ ok: false, error: err, details: { network: true } }, err);
|
|
604
|
+
}
|
|
605
|
+
finally {
|
|
606
|
+
clearTimeout(t);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return finish({ ok: false, error: "UNKNOWN" });
|
|
610
|
+
}
|
|
611
|
+
static get(url, opts) {
|
|
612
|
+
return this.request({ ...(opts || {}), method: "GET", url });
|
|
613
|
+
}
|
|
614
|
+
static post(url, body, opts) {
|
|
615
|
+
return this.request({ ...(opts || {}), method: "POST", url, body });
|
|
616
|
+
}
|
|
617
|
+
static put(url, body, opts) {
|
|
618
|
+
return this.request({ ...(opts || {}), method: "PUT", url, body });
|
|
619
|
+
}
|
|
620
|
+
static patch(url, body, opts) {
|
|
621
|
+
return this.request({ ...(opts || {}), method: "PATCH", url, body });
|
|
622
|
+
}
|
|
623
|
+
static delete(url, opts) {
|
|
624
|
+
return this.request({ ...(opts || {}), method: "DELETE", url });
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
exports.Http = Http;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { IInterceptor } from "../APIService";
|
|
2
|
+
import { IRequest } from "../structures/Interfaces";
|
|
3
|
+
export declare class InterceptorPayAuth implements IInterceptor<any> {
|
|
4
|
+
private static readonly TS_PAST_SEC;
|
|
5
|
+
private static readonly TS_FUTURE_SEC;
|
|
6
|
+
private static readonly NONCE_TTL_MS;
|
|
7
|
+
private static readonly NONCE_MAX;
|
|
8
|
+
private nonceSeen;
|
|
9
|
+
private authorizationsPreset;
|
|
10
|
+
constructor(authorizations?: {
|
|
11
|
+
key: string;
|
|
12
|
+
kid: string;
|
|
13
|
+
}[]);
|
|
14
|
+
private purgeNonces;
|
|
15
|
+
intercept(req: IRequest, authorizations?: {
|
|
16
|
+
key: string;
|
|
17
|
+
kid: string;
|
|
18
|
+
}[]): Promise<any>;
|
|
19
|
+
}
|