apitally 0.8.3 → 0.9.0
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/README.md +19 -0
- package/dist/common/types.cjs.map +1 -1
- package/dist/common/types.d.cts +2 -2
- package/dist/common/types.d.ts +2 -2
- package/dist/hono/index.cjs +783 -0
- package/dist/hono/index.cjs.map +1 -0
- package/dist/hono/index.d.cts +5 -0
- package/dist/hono/index.d.ts +5 -0
- package/dist/hono/index.js +747 -0
- package/dist/hono/index.js.map +1 -0
- package/dist/hono/middleware.cjs +781 -0
- package/dist/hono/middleware.cjs.map +1 -0
- package/dist/hono/middleware.d.cts +13 -0
- package/dist/hono/middleware.d.ts +13 -0
- package/dist/hono/middleware.js +747 -0
- package/dist/hono/middleware.js.map +1 -0
- package/package.json +24 -3
|
@@ -0,0 +1,783 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
9
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
+
mod
|
|
29
|
+
));
|
|
30
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
31
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
32
|
+
|
|
33
|
+
// src/hono/index.ts
|
|
34
|
+
var hono_exports = {};
|
|
35
|
+
__export(hono_exports, {
|
|
36
|
+
useApitally: () => useApitally
|
|
37
|
+
});
|
|
38
|
+
module.exports = __toCommonJS(hono_exports);
|
|
39
|
+
|
|
40
|
+
// src/hono/middleware.ts
|
|
41
|
+
var import_handler = require("hono/utils/handler");
|
|
42
|
+
var import_perf_hooks = require("perf_hooks");
|
|
43
|
+
|
|
44
|
+
// src/common/client.ts
|
|
45
|
+
var import_crypto3 = require("crypto");
|
|
46
|
+
var import_fetch_retry = __toESM(require("fetch-retry"), 1);
|
|
47
|
+
|
|
48
|
+
// src/common/consumerRegistry.ts
|
|
49
|
+
var consumerFromStringOrObject = /* @__PURE__ */ __name((consumer) => {
|
|
50
|
+
var _a2, _b;
|
|
51
|
+
if (typeof consumer === "string") {
|
|
52
|
+
consumer = String(consumer).trim().substring(0, 128);
|
|
53
|
+
return consumer ? {
|
|
54
|
+
identifier: consumer
|
|
55
|
+
} : null;
|
|
56
|
+
} else {
|
|
57
|
+
consumer.identifier = String(consumer.identifier).trim().substring(0, 128);
|
|
58
|
+
consumer.name = (_a2 = consumer.name) == null ? void 0 : _a2.trim().substring(0, 64);
|
|
59
|
+
consumer.group = (_b = consumer.group) == null ? void 0 : _b.trim().substring(0, 64);
|
|
60
|
+
return consumer.identifier ? consumer : null;
|
|
61
|
+
}
|
|
62
|
+
}, "consumerFromStringOrObject");
|
|
63
|
+
var _ConsumerRegistry = class _ConsumerRegistry {
|
|
64
|
+
consumers;
|
|
65
|
+
updated;
|
|
66
|
+
constructor() {
|
|
67
|
+
this.consumers = /* @__PURE__ */ new Map();
|
|
68
|
+
this.updated = /* @__PURE__ */ new Set();
|
|
69
|
+
}
|
|
70
|
+
addOrUpdateConsumer(consumer) {
|
|
71
|
+
if (!consumer || !consumer.name && !consumer.group) {
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
const existing = this.consumers.get(consumer.identifier);
|
|
75
|
+
if (!existing) {
|
|
76
|
+
this.consumers.set(consumer.identifier, consumer);
|
|
77
|
+
this.updated.add(consumer.identifier);
|
|
78
|
+
} else {
|
|
79
|
+
if (consumer.name && consumer.name !== existing.name) {
|
|
80
|
+
existing.name = consumer.name;
|
|
81
|
+
this.updated.add(consumer.identifier);
|
|
82
|
+
}
|
|
83
|
+
if (consumer.group && consumer.group !== existing.group) {
|
|
84
|
+
existing.group = consumer.group;
|
|
85
|
+
this.updated.add(consumer.identifier);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
getAndResetUpdatedConsumers() {
|
|
90
|
+
const data = [];
|
|
91
|
+
this.updated.forEach((identifier) => {
|
|
92
|
+
const consumer = this.consumers.get(identifier);
|
|
93
|
+
if (consumer) {
|
|
94
|
+
data.push(consumer);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
this.updated.clear();
|
|
98
|
+
return data;
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
__name(_ConsumerRegistry, "ConsumerRegistry");
|
|
102
|
+
var ConsumerRegistry = _ConsumerRegistry;
|
|
103
|
+
|
|
104
|
+
// src/common/logging.ts
|
|
105
|
+
var import_winston = require("winston");
|
|
106
|
+
var getLogger = /* @__PURE__ */ __name(() => {
|
|
107
|
+
return (0, import_winston.createLogger)({
|
|
108
|
+
level: process.env.APITALLY_DEBUG ? "debug" : "warn",
|
|
109
|
+
format: import_winston.format.combine(import_winston.format.colorize(), import_winston.format.timestamp(), import_winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`)),
|
|
110
|
+
transports: [
|
|
111
|
+
new import_winston.transports.Console()
|
|
112
|
+
]
|
|
113
|
+
});
|
|
114
|
+
}, "getLogger");
|
|
115
|
+
|
|
116
|
+
// src/common/paramValidation.ts
|
|
117
|
+
function isValidClientId(clientId) {
|
|
118
|
+
const regexExp = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
119
|
+
return regexExp.test(clientId);
|
|
120
|
+
}
|
|
121
|
+
__name(isValidClientId, "isValidClientId");
|
|
122
|
+
function isValidEnv(env) {
|
|
123
|
+
const regexExp = /^[\w-]{1,32}$/;
|
|
124
|
+
return regexExp.test(env);
|
|
125
|
+
}
|
|
126
|
+
__name(isValidEnv, "isValidEnv");
|
|
127
|
+
|
|
128
|
+
// src/common/requestCounter.ts
|
|
129
|
+
var _RequestCounter = class _RequestCounter {
|
|
130
|
+
requestCounts;
|
|
131
|
+
requestSizeSums;
|
|
132
|
+
responseSizeSums;
|
|
133
|
+
responseTimes;
|
|
134
|
+
requestSizes;
|
|
135
|
+
responseSizes;
|
|
136
|
+
constructor() {
|
|
137
|
+
this.requestCounts = /* @__PURE__ */ new Map();
|
|
138
|
+
this.requestSizeSums = /* @__PURE__ */ new Map();
|
|
139
|
+
this.responseSizeSums = /* @__PURE__ */ new Map();
|
|
140
|
+
this.responseTimes = /* @__PURE__ */ new Map();
|
|
141
|
+
this.requestSizes = /* @__PURE__ */ new Map();
|
|
142
|
+
this.responseSizes = /* @__PURE__ */ new Map();
|
|
143
|
+
}
|
|
144
|
+
getKey(requestInfo) {
|
|
145
|
+
return [
|
|
146
|
+
requestInfo.consumer || "",
|
|
147
|
+
requestInfo.method.toUpperCase(),
|
|
148
|
+
requestInfo.path,
|
|
149
|
+
requestInfo.statusCode
|
|
150
|
+
].join("|");
|
|
151
|
+
}
|
|
152
|
+
addRequest(requestInfo) {
|
|
153
|
+
const key = this.getKey(requestInfo);
|
|
154
|
+
this.requestCounts.set(key, (this.requestCounts.get(key) || 0) + 1);
|
|
155
|
+
if (!this.responseTimes.has(key)) {
|
|
156
|
+
this.responseTimes.set(key, /* @__PURE__ */ new Map());
|
|
157
|
+
}
|
|
158
|
+
const responseTimeMap = this.responseTimes.get(key);
|
|
159
|
+
const responseTimeMsBin = Math.floor(requestInfo.responseTime / 10) * 10;
|
|
160
|
+
responseTimeMap.set(responseTimeMsBin, (responseTimeMap.get(responseTimeMsBin) || 0) + 1);
|
|
161
|
+
if (requestInfo.requestSize !== void 0) {
|
|
162
|
+
requestInfo.requestSize = Number(requestInfo.requestSize);
|
|
163
|
+
this.requestSizeSums.set(key, (this.requestSizeSums.get(key) || 0) + requestInfo.requestSize);
|
|
164
|
+
if (!this.requestSizes.has(key)) {
|
|
165
|
+
this.requestSizes.set(key, /* @__PURE__ */ new Map());
|
|
166
|
+
}
|
|
167
|
+
const requestSizeMap = this.requestSizes.get(key);
|
|
168
|
+
const requestSizeKbBin = Math.floor(requestInfo.requestSize / 1e3);
|
|
169
|
+
requestSizeMap.set(requestSizeKbBin, (requestSizeMap.get(requestSizeKbBin) || 0) + 1);
|
|
170
|
+
}
|
|
171
|
+
if (requestInfo.responseSize !== void 0) {
|
|
172
|
+
requestInfo.responseSize = Number(requestInfo.responseSize);
|
|
173
|
+
this.responseSizeSums.set(key, (this.responseSizeSums.get(key) || 0) + requestInfo.responseSize);
|
|
174
|
+
if (!this.responseSizes.has(key)) {
|
|
175
|
+
this.responseSizes.set(key, /* @__PURE__ */ new Map());
|
|
176
|
+
}
|
|
177
|
+
const responseSizeMap = this.responseSizes.get(key);
|
|
178
|
+
const responseSizeKbBin = Math.floor(requestInfo.responseSize / 1e3);
|
|
179
|
+
responseSizeMap.set(responseSizeKbBin, (responseSizeMap.get(responseSizeKbBin) || 0) + 1);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
getAndResetRequests() {
|
|
183
|
+
const data = [];
|
|
184
|
+
this.requestCounts.forEach((count, key) => {
|
|
185
|
+
const [consumer, method, path, statusCodeStr] = key.split("|");
|
|
186
|
+
const responseTimes = this.responseTimes.get(key) || /* @__PURE__ */ new Map();
|
|
187
|
+
const requestSizes = this.requestSizes.get(key) || /* @__PURE__ */ new Map();
|
|
188
|
+
const responseSizes = this.responseSizes.get(key) || /* @__PURE__ */ new Map();
|
|
189
|
+
data.push({
|
|
190
|
+
consumer: consumer || null,
|
|
191
|
+
method,
|
|
192
|
+
path,
|
|
193
|
+
status_code: parseInt(statusCodeStr),
|
|
194
|
+
request_count: count,
|
|
195
|
+
request_size_sum: this.requestSizeSums.get(key) || 0,
|
|
196
|
+
response_size_sum: this.responseSizeSums.get(key) || 0,
|
|
197
|
+
response_times: Object.fromEntries(responseTimes),
|
|
198
|
+
request_sizes: Object.fromEntries(requestSizes),
|
|
199
|
+
response_sizes: Object.fromEntries(responseSizes)
|
|
200
|
+
});
|
|
201
|
+
});
|
|
202
|
+
this.requestCounts.clear();
|
|
203
|
+
this.requestSizeSums.clear();
|
|
204
|
+
this.responseSizeSums.clear();
|
|
205
|
+
this.responseTimes.clear();
|
|
206
|
+
this.requestSizes.clear();
|
|
207
|
+
this.responseSizes.clear();
|
|
208
|
+
return data;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
__name(_RequestCounter, "RequestCounter");
|
|
212
|
+
var RequestCounter = _RequestCounter;
|
|
213
|
+
|
|
214
|
+
// src/common/serverErrorCounter.ts
|
|
215
|
+
var import_crypto = require("crypto");
|
|
216
|
+
var MAX_MSG_LENGTH = 2048;
|
|
217
|
+
var MAX_STACKTRACE_LENGTH = 65536;
|
|
218
|
+
var _ServerErrorCounter = class _ServerErrorCounter {
|
|
219
|
+
errorCounts;
|
|
220
|
+
errorDetails;
|
|
221
|
+
sentryEventIds;
|
|
222
|
+
sentry;
|
|
223
|
+
constructor() {
|
|
224
|
+
this.errorCounts = /* @__PURE__ */ new Map();
|
|
225
|
+
this.errorDetails = /* @__PURE__ */ new Map();
|
|
226
|
+
this.sentryEventIds = /* @__PURE__ */ new Map();
|
|
227
|
+
this.tryImportSentry();
|
|
228
|
+
}
|
|
229
|
+
addServerError(serverError) {
|
|
230
|
+
const key = this.getKey(serverError);
|
|
231
|
+
if (!this.errorDetails.has(key)) {
|
|
232
|
+
this.errorDetails.set(key, serverError);
|
|
233
|
+
}
|
|
234
|
+
this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
|
|
235
|
+
this.captureSentryEventId(key);
|
|
236
|
+
}
|
|
237
|
+
getAndResetServerErrors() {
|
|
238
|
+
const data = [];
|
|
239
|
+
this.errorCounts.forEach((count, key) => {
|
|
240
|
+
const serverError = this.errorDetails.get(key);
|
|
241
|
+
if (serverError) {
|
|
242
|
+
data.push({
|
|
243
|
+
consumer: serverError.consumer || null,
|
|
244
|
+
method: serverError.method,
|
|
245
|
+
path: serverError.path,
|
|
246
|
+
type: serverError.type,
|
|
247
|
+
msg: this.getTruncatedMessage(serverError.msg),
|
|
248
|
+
traceback: this.getTruncatedStack(serverError.traceback),
|
|
249
|
+
sentry_event_id: this.sentryEventIds.get(key) || null,
|
|
250
|
+
error_count: count
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
this.errorCounts.clear();
|
|
255
|
+
this.errorDetails.clear();
|
|
256
|
+
return data;
|
|
257
|
+
}
|
|
258
|
+
getKey(serverError) {
|
|
259
|
+
const hashInput = [
|
|
260
|
+
serverError.consumer || "",
|
|
261
|
+
serverError.method.toUpperCase(),
|
|
262
|
+
serverError.path,
|
|
263
|
+
serverError.type,
|
|
264
|
+
serverError.msg.trim(),
|
|
265
|
+
serverError.traceback.trim()
|
|
266
|
+
].join("|");
|
|
267
|
+
return (0, import_crypto.createHash)("md5").update(hashInput).digest("hex");
|
|
268
|
+
}
|
|
269
|
+
getTruncatedMessage(msg) {
|
|
270
|
+
msg = msg.trim();
|
|
271
|
+
if (msg.length <= MAX_MSG_LENGTH) {
|
|
272
|
+
return msg;
|
|
273
|
+
}
|
|
274
|
+
const suffix = "... (truncated)";
|
|
275
|
+
const cutoff = MAX_MSG_LENGTH - suffix.length;
|
|
276
|
+
return msg.substring(0, cutoff) + suffix;
|
|
277
|
+
}
|
|
278
|
+
getTruncatedStack(stack) {
|
|
279
|
+
const suffix = "... (truncated) ...";
|
|
280
|
+
const cutoff = MAX_STACKTRACE_LENGTH - suffix.length;
|
|
281
|
+
const lines = stack.trim().split("\n");
|
|
282
|
+
const truncatedLines = [];
|
|
283
|
+
let length = 0;
|
|
284
|
+
for (const line of lines) {
|
|
285
|
+
if (length + line.length + 1 > cutoff) {
|
|
286
|
+
truncatedLines.push(suffix);
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
truncatedLines.push(line);
|
|
290
|
+
length += line.length + 1;
|
|
291
|
+
}
|
|
292
|
+
return truncatedLines.join("\n");
|
|
293
|
+
}
|
|
294
|
+
captureSentryEventId(serverErrorKey) {
|
|
295
|
+
if (this.sentry && this.sentry.lastEventId) {
|
|
296
|
+
const eventId = this.sentry.lastEventId();
|
|
297
|
+
if (eventId) {
|
|
298
|
+
this.sentryEventIds.set(serverErrorKey, eventId);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
async tryImportSentry() {
|
|
303
|
+
try {
|
|
304
|
+
this.sentry = await import("@sentry/node");
|
|
305
|
+
} catch (e) {
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
__name(_ServerErrorCounter, "ServerErrorCounter");
|
|
310
|
+
var ServerErrorCounter = _ServerErrorCounter;
|
|
311
|
+
|
|
312
|
+
// src/common/validationErrorCounter.ts
|
|
313
|
+
var import_crypto2 = require("crypto");
|
|
314
|
+
var _ValidationErrorCounter = class _ValidationErrorCounter {
|
|
315
|
+
errorCounts;
|
|
316
|
+
errorDetails;
|
|
317
|
+
constructor() {
|
|
318
|
+
this.errorCounts = /* @__PURE__ */ new Map();
|
|
319
|
+
this.errorDetails = /* @__PURE__ */ new Map();
|
|
320
|
+
}
|
|
321
|
+
addValidationError(validationError) {
|
|
322
|
+
const key = this.getKey(validationError);
|
|
323
|
+
if (!this.errorDetails.has(key)) {
|
|
324
|
+
this.errorDetails.set(key, validationError);
|
|
325
|
+
}
|
|
326
|
+
this.errorCounts.set(key, (this.errorCounts.get(key) || 0) + 1);
|
|
327
|
+
}
|
|
328
|
+
getAndResetValidationErrors() {
|
|
329
|
+
const data = [];
|
|
330
|
+
this.errorCounts.forEach((count, key) => {
|
|
331
|
+
const validationError = this.errorDetails.get(key);
|
|
332
|
+
if (validationError) {
|
|
333
|
+
data.push({
|
|
334
|
+
consumer: validationError.consumer || null,
|
|
335
|
+
method: validationError.method,
|
|
336
|
+
path: validationError.path,
|
|
337
|
+
loc: validationError.loc.split("."),
|
|
338
|
+
msg: validationError.msg,
|
|
339
|
+
type: validationError.type,
|
|
340
|
+
error_count: count
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
this.errorCounts.clear();
|
|
345
|
+
this.errorDetails.clear();
|
|
346
|
+
return data;
|
|
347
|
+
}
|
|
348
|
+
getKey(validationError) {
|
|
349
|
+
const hashInput = [
|
|
350
|
+
validationError.consumer || "",
|
|
351
|
+
validationError.method.toUpperCase(),
|
|
352
|
+
validationError.path,
|
|
353
|
+
validationError.loc,
|
|
354
|
+
validationError.msg.trim(),
|
|
355
|
+
validationError.type
|
|
356
|
+
].join("|");
|
|
357
|
+
return (0, import_crypto2.createHash)("md5").update(hashInput).digest("hex");
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
__name(_ValidationErrorCounter, "ValidationErrorCounter");
|
|
361
|
+
var ValidationErrorCounter = _ValidationErrorCounter;
|
|
362
|
+
|
|
363
|
+
// src/common/client.ts
|
|
364
|
+
var SYNC_INTERVAL = 6e4;
|
|
365
|
+
var INITIAL_SYNC_INTERVAL = 1e4;
|
|
366
|
+
var INITIAL_SYNC_INTERVAL_DURATION = 36e5;
|
|
367
|
+
var MAX_QUEUE_TIME = 36e5;
|
|
368
|
+
var _a;
|
|
369
|
+
var HTTPError = (_a = class extends Error {
|
|
370
|
+
response;
|
|
371
|
+
constructor(response) {
|
|
372
|
+
const reason = response.status ? `status code ${response.status}` : "an unknown error";
|
|
373
|
+
super(`Request failed with ${reason}`);
|
|
374
|
+
this.response = response;
|
|
375
|
+
}
|
|
376
|
+
}, __name(_a, "HTTPError"), _a);
|
|
377
|
+
var _ApitallyClient = class _ApitallyClient {
|
|
378
|
+
clientId;
|
|
379
|
+
env;
|
|
380
|
+
instanceUuid;
|
|
381
|
+
syncDataQueue;
|
|
382
|
+
syncIntervalId;
|
|
383
|
+
startupData;
|
|
384
|
+
startupDataSent = false;
|
|
385
|
+
requestCounter;
|
|
386
|
+
validationErrorCounter;
|
|
387
|
+
serverErrorCounter;
|
|
388
|
+
consumerRegistry;
|
|
389
|
+
logger;
|
|
390
|
+
constructor({ clientId, env = "dev", logger }) {
|
|
391
|
+
if (_ApitallyClient.instance) {
|
|
392
|
+
throw new Error("Apitally client is already initialized");
|
|
393
|
+
}
|
|
394
|
+
if (!isValidClientId(clientId)) {
|
|
395
|
+
throw new Error(`Invalid client ID '${clientId}' (expecting hexadeciaml UUID format)`);
|
|
396
|
+
}
|
|
397
|
+
if (!isValidEnv(env)) {
|
|
398
|
+
throw new Error(`Invalid env '${env}' (expecting 1-32 alphanumeric lowercase characters and hyphens only)`);
|
|
399
|
+
}
|
|
400
|
+
_ApitallyClient.instance = this;
|
|
401
|
+
this.clientId = clientId;
|
|
402
|
+
this.env = env;
|
|
403
|
+
this.instanceUuid = (0, import_crypto3.randomUUID)();
|
|
404
|
+
this.syncDataQueue = [];
|
|
405
|
+
this.requestCounter = new RequestCounter();
|
|
406
|
+
this.validationErrorCounter = new ValidationErrorCounter();
|
|
407
|
+
this.serverErrorCounter = new ServerErrorCounter();
|
|
408
|
+
this.consumerRegistry = new ConsumerRegistry();
|
|
409
|
+
this.logger = logger || getLogger();
|
|
410
|
+
this.startSync();
|
|
411
|
+
this.handleShutdown = this.handleShutdown.bind(this);
|
|
412
|
+
}
|
|
413
|
+
static getInstance() {
|
|
414
|
+
if (!_ApitallyClient.instance) {
|
|
415
|
+
throw new Error("Apitally client is not initialized");
|
|
416
|
+
}
|
|
417
|
+
return _ApitallyClient.instance;
|
|
418
|
+
}
|
|
419
|
+
static async shutdown() {
|
|
420
|
+
if (_ApitallyClient.instance) {
|
|
421
|
+
await _ApitallyClient.instance.handleShutdown();
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
async handleShutdown() {
|
|
425
|
+
this.stopSync();
|
|
426
|
+
await this.sendSyncData();
|
|
427
|
+
_ApitallyClient.instance = void 0;
|
|
428
|
+
}
|
|
429
|
+
getHubUrlPrefix() {
|
|
430
|
+
const baseURL = process.env.APITALLY_HUB_BASE_URL || "https://hub.apitally.io";
|
|
431
|
+
const version = "v2";
|
|
432
|
+
return `${baseURL}/${version}/${this.clientId}/${this.env}/`;
|
|
433
|
+
}
|
|
434
|
+
async sendData(url, payload) {
|
|
435
|
+
const fetchWithRetry = (0, import_fetch_retry.default)(fetch, {
|
|
436
|
+
retries: 3,
|
|
437
|
+
retryDelay: 1e3,
|
|
438
|
+
retryOn: [
|
|
439
|
+
408,
|
|
440
|
+
429,
|
|
441
|
+
500,
|
|
442
|
+
502,
|
|
443
|
+
503,
|
|
444
|
+
504
|
|
445
|
+
]
|
|
446
|
+
});
|
|
447
|
+
const response = await fetchWithRetry(this.getHubUrlPrefix() + url, {
|
|
448
|
+
method: "POST",
|
|
449
|
+
body: JSON.stringify(payload),
|
|
450
|
+
headers: {
|
|
451
|
+
"Content-Type": "application/json"
|
|
452
|
+
}
|
|
453
|
+
});
|
|
454
|
+
if (!response.ok) {
|
|
455
|
+
throw new HTTPError(response);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
startSync() {
|
|
459
|
+
this.sync();
|
|
460
|
+
this.syncIntervalId = setInterval(() => {
|
|
461
|
+
this.sync();
|
|
462
|
+
}, INITIAL_SYNC_INTERVAL);
|
|
463
|
+
setTimeout(() => {
|
|
464
|
+
clearInterval(this.syncIntervalId);
|
|
465
|
+
this.syncIntervalId = setInterval(() => {
|
|
466
|
+
this.sync();
|
|
467
|
+
}, SYNC_INTERVAL);
|
|
468
|
+
}, INITIAL_SYNC_INTERVAL_DURATION);
|
|
469
|
+
}
|
|
470
|
+
async sync() {
|
|
471
|
+
try {
|
|
472
|
+
const promises = [
|
|
473
|
+
this.sendSyncData()
|
|
474
|
+
];
|
|
475
|
+
if (!this.startupDataSent) {
|
|
476
|
+
promises.push(this.sendStartupData());
|
|
477
|
+
}
|
|
478
|
+
await Promise.all(promises);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
this.logger.error("Error while syncing with Apitally Hub", {
|
|
481
|
+
error
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
stopSync() {
|
|
486
|
+
if (this.syncIntervalId) {
|
|
487
|
+
clearInterval(this.syncIntervalId);
|
|
488
|
+
this.syncIntervalId = void 0;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
setStartupData(data) {
|
|
492
|
+
this.startupData = data;
|
|
493
|
+
this.startupDataSent = false;
|
|
494
|
+
this.sendStartupData();
|
|
495
|
+
}
|
|
496
|
+
async sendStartupData() {
|
|
497
|
+
if (this.startupData) {
|
|
498
|
+
this.logger.debug("Sending startup data to Apitally Hub");
|
|
499
|
+
const payload = {
|
|
500
|
+
instance_uuid: this.instanceUuid,
|
|
501
|
+
message_uuid: (0, import_crypto3.randomUUID)(),
|
|
502
|
+
...this.startupData
|
|
503
|
+
};
|
|
504
|
+
try {
|
|
505
|
+
await this.sendData("startup", payload);
|
|
506
|
+
this.startupDataSent = true;
|
|
507
|
+
} catch (error) {
|
|
508
|
+
const handled = this.handleHubError(error);
|
|
509
|
+
if (!handled) {
|
|
510
|
+
this.logger.error(error.message);
|
|
511
|
+
this.logger.debug("Error while sending startup data to Apitally Hub (will retry)", {
|
|
512
|
+
error
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
async sendSyncData() {
|
|
519
|
+
this.logger.debug("Synchronizing data with Apitally Hub");
|
|
520
|
+
const newPayload = {
|
|
521
|
+
time_offset: 0,
|
|
522
|
+
instance_uuid: this.instanceUuid,
|
|
523
|
+
message_uuid: (0, import_crypto3.randomUUID)(),
|
|
524
|
+
requests: this.requestCounter.getAndResetRequests(),
|
|
525
|
+
validation_errors: this.validationErrorCounter.getAndResetValidationErrors(),
|
|
526
|
+
server_errors: this.serverErrorCounter.getAndResetServerErrors(),
|
|
527
|
+
consumers: this.consumerRegistry.getAndResetUpdatedConsumers()
|
|
528
|
+
};
|
|
529
|
+
this.syncDataQueue.push([
|
|
530
|
+
Date.now(),
|
|
531
|
+
newPayload
|
|
532
|
+
]);
|
|
533
|
+
let i = 0;
|
|
534
|
+
while (this.syncDataQueue.length > 0) {
|
|
535
|
+
const queueItem = this.syncDataQueue.shift();
|
|
536
|
+
if (queueItem) {
|
|
537
|
+
const [time, payload] = queueItem;
|
|
538
|
+
try {
|
|
539
|
+
const timeOffset = Date.now() - time;
|
|
540
|
+
if (timeOffset <= MAX_QUEUE_TIME) {
|
|
541
|
+
if (i > 0) {
|
|
542
|
+
const waitMs = 100 + Math.random() * 200;
|
|
543
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
544
|
+
}
|
|
545
|
+
payload.time_offset = timeOffset / 1e3;
|
|
546
|
+
await this.sendData("sync", payload);
|
|
547
|
+
i += 1;
|
|
548
|
+
}
|
|
549
|
+
} catch (error) {
|
|
550
|
+
const handled = this.handleHubError(error);
|
|
551
|
+
if (!handled) {
|
|
552
|
+
this.logger.debug("Error while synchronizing data with Apitally Hub (will retry)", {
|
|
553
|
+
error
|
|
554
|
+
});
|
|
555
|
+
this.syncDataQueue.push(queueItem);
|
|
556
|
+
break;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
handleHubError(error) {
|
|
563
|
+
if (error instanceof HTTPError) {
|
|
564
|
+
if (error.response.status === 404) {
|
|
565
|
+
this.logger.error(`Invalid Apitally client ID: '${this.clientId}'`);
|
|
566
|
+
this.stopSync();
|
|
567
|
+
return true;
|
|
568
|
+
}
|
|
569
|
+
if (error.response.status === 422) {
|
|
570
|
+
this.logger.error("Received validation error from Apitally Hub");
|
|
571
|
+
return true;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
return false;
|
|
575
|
+
}
|
|
576
|
+
};
|
|
577
|
+
__name(_ApitallyClient, "ApitallyClient");
|
|
578
|
+
__publicField(_ApitallyClient, "instance");
|
|
579
|
+
var ApitallyClient = _ApitallyClient;
|
|
580
|
+
|
|
581
|
+
// src/common/packageVersions.ts
|
|
582
|
+
var import_module = require("module");
|
|
583
|
+
var import_meta = {};
|
|
584
|
+
function getPackageVersion(name) {
|
|
585
|
+
try {
|
|
586
|
+
const _require = (0, import_module.createRequire)(import_meta.url);
|
|
587
|
+
return _require(`${name}/package.json`).version || null;
|
|
588
|
+
} catch (error) {
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
__name(getPackageVersion, "getPackageVersion");
|
|
593
|
+
|
|
594
|
+
// src/hono/middleware.ts
|
|
595
|
+
var useApitally = /* @__PURE__ */ __name((app, config) => {
|
|
596
|
+
const client = new ApitallyClient(config);
|
|
597
|
+
const middleware = getMiddleware(client);
|
|
598
|
+
app.use(middleware);
|
|
599
|
+
setTimeout(() => {
|
|
600
|
+
client.setStartupData(getAppInfo(app, config.appVersion));
|
|
601
|
+
}, 1e3);
|
|
602
|
+
}, "useApitally");
|
|
603
|
+
var getMiddleware = /* @__PURE__ */ __name((client) => {
|
|
604
|
+
const zodInstalled = getPackageVersion("zod") !== null;
|
|
605
|
+
return async (c, next) => {
|
|
606
|
+
const startTime = import_perf_hooks.performance.now();
|
|
607
|
+
await next();
|
|
608
|
+
let response;
|
|
609
|
+
const responseTime = import_perf_hooks.performance.now() - startTime;
|
|
610
|
+
const [responseSize, newResponse] = await measureResponseSize(c.res);
|
|
611
|
+
const consumer = getConsumer(c);
|
|
612
|
+
client.consumerRegistry.addOrUpdateConsumer(consumer);
|
|
613
|
+
client.requestCounter.addRequest({
|
|
614
|
+
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
615
|
+
method: c.req.method,
|
|
616
|
+
path: c.req.routePath,
|
|
617
|
+
statusCode: c.res.status,
|
|
618
|
+
responseTime,
|
|
619
|
+
requestSize: c.req.header("Content-Length"),
|
|
620
|
+
responseSize
|
|
621
|
+
});
|
|
622
|
+
response = newResponse;
|
|
623
|
+
if (c.res.status === 400 && zodInstalled) {
|
|
624
|
+
const [responseJson, newResponse2] = await getResponseJson(response);
|
|
625
|
+
const validationErrors = extractZodErrors(responseJson);
|
|
626
|
+
validationErrors.forEach((error) => {
|
|
627
|
+
client.validationErrorCounter.addValidationError({
|
|
628
|
+
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
629
|
+
method: c.req.method,
|
|
630
|
+
path: c.req.routePath,
|
|
631
|
+
...error
|
|
632
|
+
});
|
|
633
|
+
});
|
|
634
|
+
response = newResponse2;
|
|
635
|
+
}
|
|
636
|
+
if (c.error) {
|
|
637
|
+
client.serverErrorCounter.addServerError({
|
|
638
|
+
consumer: consumer == null ? void 0 : consumer.identifier,
|
|
639
|
+
method: c.req.method,
|
|
640
|
+
path: c.req.routePath,
|
|
641
|
+
type: c.error.name,
|
|
642
|
+
msg: c.error.message,
|
|
643
|
+
traceback: c.error.stack || ""
|
|
644
|
+
});
|
|
645
|
+
}
|
|
646
|
+
c.res = response;
|
|
647
|
+
};
|
|
648
|
+
}, "getMiddleware");
|
|
649
|
+
var getConsumer = /* @__PURE__ */ __name((c) => {
|
|
650
|
+
const consumer = c.get("apitallyConsumer");
|
|
651
|
+
if (consumer) {
|
|
652
|
+
return consumerFromStringOrObject(consumer);
|
|
653
|
+
}
|
|
654
|
+
return null;
|
|
655
|
+
}, "getConsumer");
|
|
656
|
+
var measureResponseSize = /* @__PURE__ */ __name(async (response) => {
|
|
657
|
+
const [newResponse1, newResponse2] = await teeResponse(response);
|
|
658
|
+
let size = 0;
|
|
659
|
+
if (newResponse2.body) {
|
|
660
|
+
let done = false;
|
|
661
|
+
const reader = newResponse2.body.getReader();
|
|
662
|
+
while (!done) {
|
|
663
|
+
const result = await reader.read();
|
|
664
|
+
done = result.done;
|
|
665
|
+
if (!done && result.value) {
|
|
666
|
+
size += result.value.byteLength;
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
return [
|
|
671
|
+
size,
|
|
672
|
+
newResponse1
|
|
673
|
+
];
|
|
674
|
+
}, "measureResponseSize");
|
|
675
|
+
var getResponseJson = /* @__PURE__ */ __name(async (response) => {
|
|
676
|
+
const contentType = response.headers.get("content-type");
|
|
677
|
+
if (contentType && contentType.includes("application/json")) {
|
|
678
|
+
const [newResponse1, newResponse2] = await teeResponse(response);
|
|
679
|
+
const responseJson = await newResponse2.json();
|
|
680
|
+
return [
|
|
681
|
+
responseJson,
|
|
682
|
+
newResponse1
|
|
683
|
+
];
|
|
684
|
+
}
|
|
685
|
+
return [
|
|
686
|
+
null,
|
|
687
|
+
response
|
|
688
|
+
];
|
|
689
|
+
}, "getResponseJson");
|
|
690
|
+
var teeResponse = /* @__PURE__ */ __name(async (response) => {
|
|
691
|
+
if (!response.body) {
|
|
692
|
+
return [
|
|
693
|
+
response,
|
|
694
|
+
response
|
|
695
|
+
];
|
|
696
|
+
}
|
|
697
|
+
const [stream1, stream2] = response.body.tee();
|
|
698
|
+
const newResponse1 = new Response(stream1, {
|
|
699
|
+
status: response.status,
|
|
700
|
+
statusText: response.statusText,
|
|
701
|
+
headers: response.headers
|
|
702
|
+
});
|
|
703
|
+
const newResponse2 = new Response(stream2, {
|
|
704
|
+
status: response.status,
|
|
705
|
+
statusText: response.statusText,
|
|
706
|
+
headers: response.headers
|
|
707
|
+
});
|
|
708
|
+
return [
|
|
709
|
+
newResponse1,
|
|
710
|
+
newResponse2
|
|
711
|
+
];
|
|
712
|
+
}, "teeResponse");
|
|
713
|
+
var extractZodErrors = /* @__PURE__ */ __name((responseJson) => {
|
|
714
|
+
const errors = [];
|
|
715
|
+
if (responseJson && responseJson.success === false && responseJson.error && responseJson.error.name === "ZodError") {
|
|
716
|
+
const zodError = responseJson.error;
|
|
717
|
+
zodError.issues.forEach((zodIssue) => {
|
|
718
|
+
errors.push({
|
|
719
|
+
loc: zodIssue.path.join("."),
|
|
720
|
+
msg: zodIssue.message,
|
|
721
|
+
type: zodIssue.code
|
|
722
|
+
});
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
return errors;
|
|
726
|
+
}, "extractZodErrors");
|
|
727
|
+
var getAppInfo = /* @__PURE__ */ __name((app, appVersion) => {
|
|
728
|
+
const versions = [];
|
|
729
|
+
if (process.versions.node) {
|
|
730
|
+
versions.push([
|
|
731
|
+
"nodejs",
|
|
732
|
+
process.versions.node
|
|
733
|
+
]);
|
|
734
|
+
}
|
|
735
|
+
if (process.versions.bun) {
|
|
736
|
+
versions.push([
|
|
737
|
+
"bun",
|
|
738
|
+
process.versions.bun
|
|
739
|
+
]);
|
|
740
|
+
}
|
|
741
|
+
const honoVersion = getPackageVersion("hono");
|
|
742
|
+
const apitallyVersion = getPackageVersion("../..");
|
|
743
|
+
if (honoVersion) {
|
|
744
|
+
versions.push([
|
|
745
|
+
"hono",
|
|
746
|
+
honoVersion
|
|
747
|
+
]);
|
|
748
|
+
}
|
|
749
|
+
if (apitallyVersion) {
|
|
750
|
+
versions.push([
|
|
751
|
+
"apitally",
|
|
752
|
+
apitallyVersion
|
|
753
|
+
]);
|
|
754
|
+
}
|
|
755
|
+
if (appVersion) {
|
|
756
|
+
versions.push([
|
|
757
|
+
"app",
|
|
758
|
+
appVersion
|
|
759
|
+
]);
|
|
760
|
+
}
|
|
761
|
+
return {
|
|
762
|
+
paths: listEndpoints(app),
|
|
763
|
+
versions: Object.fromEntries(versions),
|
|
764
|
+
client: "js:hono"
|
|
765
|
+
};
|
|
766
|
+
}, "getAppInfo");
|
|
767
|
+
var listEndpoints = /* @__PURE__ */ __name((app) => {
|
|
768
|
+
const endpoints = [];
|
|
769
|
+
app.routes.forEach((route) => {
|
|
770
|
+
if (route.method !== "ALL" && !(0, import_handler.isMiddleware)(route.handler)) {
|
|
771
|
+
endpoints.push({
|
|
772
|
+
method: route.method.toUpperCase(),
|
|
773
|
+
path: route.path
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
});
|
|
777
|
+
return endpoints;
|
|
778
|
+
}, "listEndpoints");
|
|
779
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
780
|
+
0 && (module.exports = {
|
|
781
|
+
useApitally
|
|
782
|
+
});
|
|
783
|
+
//# sourceMappingURL=index.cjs.map
|