hobots 0.3.1 → 1.1.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/LICENSE +21 -0
- package/README.md +389 -0
- package/dist/index.cjs +1203 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +312 -0
- package/dist/index.d.ts +312 -0
- package/dist/index.js +1180 -0
- package/dist/index.js.map +1 -0
- package/dist/manager/protocol.cjs +19 -0
- package/dist/manager/protocol.cjs.map +1 -0
- package/dist/manager/protocol.d.cts +72 -0
- package/dist/manager/protocol.d.ts +72 -0
- package/dist/manager/protocol.js +1 -0
- package/dist/manager/protocol.js.map +1 -0
- package/dist/protocol.cjs +19 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +129 -0
- package/dist/protocol.d.ts +129 -0
- package/dist/protocol.js +1 -0
- package/dist/protocol.js.map +1 -0
- package/docs/README.md +41 -0
- package/docs/api-reference.md +153 -0
- package/docs/getting-started.md +103 -0
- package/docs/manager.md +95 -0
- package/docs/monitor.md +138 -0
- package/docs/protocol.md +101 -0
- package/package.json +46 -3
- package/auth/index.d.ts +0 -10
- package/csv/index.d.ts +0 -9
- package/datasets/index.d.ts +0 -2
- package/db/drizzle.config.d.ts +0 -8
- package/db/index.d.ts +0 -9
- package/db/migrate.d.ts +0 -3
- package/db/schema.d.ts +0 -215
- package/db/storages/base.d.ts +0 -23
- package/db/storages/index.d.ts +0 -3
- package/db/storages/job.d.ts +0 -233
- package/exceptions/break.d.ts +0 -6
- package/exceptions/ignore.d.ts +0 -6
- package/exceptions/index.d.ts +0 -4
- package/exceptions/warning.d.ts +0 -6
- package/foreach/foreach.d.ts +0 -7
- package/foreach/index.d.ts +0 -5
- package/foreach/item.d.ts +0 -13
- package/hobots/samples/bot.d.ts +0 -2
- package/hobots/samples/index.d.ts +0 -2
- package/hobots/src/auth/index.d.ts +0 -10
- package/hobots/src/csv/index.d.ts +0 -9
- package/hobots/src/datasets/index.d.ts +0 -2
- package/hobots/src/db/drizzle.config.d.ts +0 -8
- package/hobots/src/db/index.d.ts +0 -9
- package/hobots/src/db/migrate.d.ts +0 -3
- package/hobots/src/db/schema.d.ts +0 -215
- package/hobots/src/db/storages/base.d.ts +0 -23
- package/hobots/src/db/storages/index.d.ts +0 -3
- package/hobots/src/db/storages/job.d.ts +0 -233
- package/hobots/src/exceptions/break.d.ts +0 -6
- package/hobots/src/exceptions/ignore.d.ts +0 -6
- package/hobots/src/exceptions/index.d.ts +0 -4
- package/hobots/src/exceptions/warning.d.ts +0 -6
- package/hobots/src/foreach/foreach.d.ts +0 -7
- package/hobots/src/foreach/index.d.ts +0 -5
- package/hobots/src/foreach/item.d.ts +0 -13
- package/hobots/src/index.d.ts +0 -9
- package/hobots/src/reports/data-report.d.ts +0 -9
- package/hobots/src/reports/index.d.ts +0 -3
- package/hobots/src/reports/job-report.d.ts +0 -22
- package/hobots/src/setup.d.ts +0 -20
- package/hobots/src/sheets/index.d.ts +0 -13
- package/hobots/src/types/hobots-types.d.ts +0 -20
- package/hobots/src/utils/date.d.ts +0 -117
- package/hobots/src/utils/dist.d.ts +0 -8
- package/hobots/src/utils/garbage.d.ts +0 -2
- package/hobots/src/utils/index.d.ts +0 -10
- package/hobots/src/utils/logger.d.ts +0 -21
- package/hobots/src/utils/manifest.d.ts +0 -2
- package/hobots/src/utils/path.d.ts +0 -13
- package/hobots/src/utils/publish.d.ts +0 -2
- package/hobots/src/utils/retry.d.ts +0 -5
- package/hobots/src/utils/text.d.ts +0 -74
- package/hobots/src/utils/timer.d.ts +0 -3
- package/index.d.ts +0 -9
- package/index.js +0 -131866
- package/index.js.map +0 -1
- package/reports/data-report.d.ts +0 -9
- package/reports/index.d.ts +0 -3
- package/reports/job-report.d.ts +0 -22
- package/setup.d.ts +0 -20
- package/sheets/index.d.ts +0 -13
- package/types/hobots-types.d.ts +0 -20
- package/utils/date.d.ts +0 -117
- package/utils/dist.d.ts +0 -8
- package/utils/garbage.d.ts +0 -2
- package/utils/index.d.ts +0 -10
- package/utils/logger.d.ts +0 -21
- package/utils/manifest.d.ts +0 -2
- package/utils/path.d.ts +0 -13
- package/utils/publish.d.ts +0 -2
- package/utils/retry.d.ts +0 -5
- package/utils/src/path.d.ts +0 -14
- package/utils/text.d.ts +0 -74
- package/utils/timer.d.ts +0 -3
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var src_exports = {};
|
|
22
|
+
__export(src_exports, {
|
|
23
|
+
Client: () => Client,
|
|
24
|
+
ManagerAgent: () => ManagerAgent,
|
|
25
|
+
ManagerApi: () => ManagerApi,
|
|
26
|
+
ManagerApiError: () => ManagerApiError,
|
|
27
|
+
Scope: () => Scope,
|
|
28
|
+
Span: () => Span,
|
|
29
|
+
Transaction: () => Transaction,
|
|
30
|
+
addBreadcrumb: () => addBreadcrumb,
|
|
31
|
+
captureException: () => captureException,
|
|
32
|
+
captureMessage: () => captureMessage,
|
|
33
|
+
checkIn: () => checkIn,
|
|
34
|
+
close: () => close,
|
|
35
|
+
flush: () => flush,
|
|
36
|
+
getClient: () => getClient,
|
|
37
|
+
init: () => init,
|
|
38
|
+
parseDsn: () => parseDsn,
|
|
39
|
+
register: () => register,
|
|
40
|
+
setContext: () => setContext,
|
|
41
|
+
setExtra: () => setExtra,
|
|
42
|
+
setTag: () => setTag,
|
|
43
|
+
setTags: () => setTags,
|
|
44
|
+
setUser: () => setUser,
|
|
45
|
+
start: () => start,
|
|
46
|
+
startTransaction: () => startTransaction,
|
|
47
|
+
stop: () => stop,
|
|
48
|
+
withMonitor: () => withMonitor,
|
|
49
|
+
withScope: () => withScope
|
|
50
|
+
});
|
|
51
|
+
module.exports = __toCommonJS(src_exports);
|
|
52
|
+
|
|
53
|
+
// src/dsn.ts
|
|
54
|
+
function parseDsnUrl(dsn, prefix) {
|
|
55
|
+
let url;
|
|
56
|
+
try {
|
|
57
|
+
url = new URL(dsn);
|
|
58
|
+
} catch {
|
|
59
|
+
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}"`);
|
|
60
|
+
}
|
|
61
|
+
const key = url.username;
|
|
62
|
+
const path = url.pathname.replace(/^\/+/, "");
|
|
63
|
+
if (!key || !path) {
|
|
64
|
+
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}" \u2014 esperado https://<key>@host/<projeto>`);
|
|
65
|
+
}
|
|
66
|
+
return { key, path, origin: `${url.protocol}//${url.host}` };
|
|
67
|
+
}
|
|
68
|
+
function parseDsn(dsn) {
|
|
69
|
+
const { key, path, origin } = parseDsnUrl(dsn, "[hobots]");
|
|
70
|
+
return {
|
|
71
|
+
key,
|
|
72
|
+
projectSlug: path,
|
|
73
|
+
origin,
|
|
74
|
+
ingestEndpoint: `${origin}/api/ingest`,
|
|
75
|
+
managerBaseUrl: `${origin}/api/manager`
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/stacktrace.ts
|
|
80
|
+
var MAX_FRAMES = 50;
|
|
81
|
+
var FRAME_RE = /^\s*at\s+(?:async\s+)?(?:(.+?)\s+\()?(.+?)\)?$/;
|
|
82
|
+
var LOCATION_RE = /^(.*?):(\d+):(\d+)$/;
|
|
83
|
+
function isInApp(filename) {
|
|
84
|
+
if (!filename) return false;
|
|
85
|
+
if (filename.startsWith("node:")) return false;
|
|
86
|
+
if (filename.startsWith("internal/")) return false;
|
|
87
|
+
if (filename.includes("node_modules")) return false;
|
|
88
|
+
if (filename === "<anonymous>") return false;
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
function parseStacktrace(stack) {
|
|
92
|
+
if (!stack) return [];
|
|
93
|
+
const frames = [];
|
|
94
|
+
for (const line of stack.split("\n")) {
|
|
95
|
+
if (frames.length >= MAX_FRAMES) break;
|
|
96
|
+
const match = FRAME_RE.exec(line);
|
|
97
|
+
if (!match || !line.trimStart().startsWith("at ")) continue;
|
|
98
|
+
const [, fn, location] = match;
|
|
99
|
+
const loc = LOCATION_RE.exec(location ?? "");
|
|
100
|
+
const filename = loc ? loc[1] : location;
|
|
101
|
+
frames.push({
|
|
102
|
+
function: fn || "<anonymous>",
|
|
103
|
+
filename: filename || void 0,
|
|
104
|
+
lineno: loc?.[2] ? Number(loc[2]) : void 0,
|
|
105
|
+
colno: loc?.[3] ? Number(loc[3]) : void 0,
|
|
106
|
+
in_app: isInApp(filename)
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
return frames;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// src/utils.ts
|
|
113
|
+
var SDK_NAME = "hobots";
|
|
114
|
+
var SDK_VERSION = "1.0.0";
|
|
115
|
+
function isNode() {
|
|
116
|
+
return typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
117
|
+
}
|
|
118
|
+
function uuid4() {
|
|
119
|
+
const cryptoRef = globalThis.crypto;
|
|
120
|
+
if (cryptoRef && typeof cryptoRef.randomUUID === "function") {
|
|
121
|
+
return cryptoRef.randomUUID().replace(/-/g, "");
|
|
122
|
+
}
|
|
123
|
+
let out = "";
|
|
124
|
+
for (let i = 0; i < 32; i++) {
|
|
125
|
+
out += Math.floor(Math.random() * 16).toString(16);
|
|
126
|
+
}
|
|
127
|
+
return out;
|
|
128
|
+
}
|
|
129
|
+
function nowISO() {
|
|
130
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
131
|
+
}
|
|
132
|
+
function unrefTimer(timer) {
|
|
133
|
+
timer?.unref?.();
|
|
134
|
+
}
|
|
135
|
+
function sleep(ms) {
|
|
136
|
+
return new Promise((resolve) => {
|
|
137
|
+
const timer = setTimeout(resolve, ms);
|
|
138
|
+
unrefTimer(timer);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
var PREFIX = "[hobots-monitor]";
|
|
142
|
+
function makeLogger(enabled, prefix = PREFIX) {
|
|
143
|
+
return {
|
|
144
|
+
debug: (...args) => enabled && console.debug(prefix, ...args),
|
|
145
|
+
warn: (...args) => enabled && console.warn(prefix, ...args),
|
|
146
|
+
error: (...args) => console.error(prefix, ...args)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/eventbuilder.ts
|
|
151
|
+
function safeString(value) {
|
|
152
|
+
if (typeof value === "string") return value;
|
|
153
|
+
try {
|
|
154
|
+
const json = JSON.stringify(value);
|
|
155
|
+
if (json && json !== "{}") return json;
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
return String(value);
|
|
159
|
+
}
|
|
160
|
+
function eventFromException(error, level = "error") {
|
|
161
|
+
let type;
|
|
162
|
+
let value;
|
|
163
|
+
let frames = [];
|
|
164
|
+
if (error instanceof Error) {
|
|
165
|
+
type = error.name || "Error";
|
|
166
|
+
value = error.message;
|
|
167
|
+
frames = parseStacktrace(error.stack);
|
|
168
|
+
} else {
|
|
169
|
+
type = "NonError";
|
|
170
|
+
value = safeString(error);
|
|
171
|
+
}
|
|
172
|
+
return {
|
|
173
|
+
event_id: uuid4(),
|
|
174
|
+
timestamp: nowISO(),
|
|
175
|
+
level,
|
|
176
|
+
exception: {
|
|
177
|
+
type,
|
|
178
|
+
value,
|
|
179
|
+
...frames.length > 0 ? { stacktrace: { frames } } : {}
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function eventFromMessage(message, level = "info") {
|
|
184
|
+
return {
|
|
185
|
+
event_id: uuid4(),
|
|
186
|
+
timestamp: nowISO(),
|
|
187
|
+
level,
|
|
188
|
+
message
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/transport.ts
|
|
193
|
+
var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
194
|
+
var DEFAULT_FLUSH_INTERVAL_MS = 2e3;
|
|
195
|
+
var DEFAULT_MAX_BATCH_SIZE = 10;
|
|
196
|
+
var DEFAULT_MAX_QUEUE_SIZE = 200;
|
|
197
|
+
var Transport = class {
|
|
198
|
+
endpoint;
|
|
199
|
+
key;
|
|
200
|
+
logger;
|
|
201
|
+
flushIntervalMs;
|
|
202
|
+
maxBatchSize;
|
|
203
|
+
maxQueueSize;
|
|
204
|
+
buffer = [];
|
|
205
|
+
timer;
|
|
206
|
+
pending = /* @__PURE__ */ new Set();
|
|
207
|
+
closed = false;
|
|
208
|
+
constructor(options) {
|
|
209
|
+
this.endpoint = options.endpoint;
|
|
210
|
+
this.key = options.key;
|
|
211
|
+
this.logger = options.logger;
|
|
212
|
+
this.flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
|
|
213
|
+
this.maxBatchSize = options.maxBatchSize ?? DEFAULT_MAX_BATCH_SIZE;
|
|
214
|
+
this.maxQueueSize = options.maxQueueSize ?? DEFAULT_MAX_QUEUE_SIZE;
|
|
215
|
+
}
|
|
216
|
+
enqueue(item) {
|
|
217
|
+
if (this.closed) {
|
|
218
|
+
this.logger.warn("transport fechado, item descartado:", item.type);
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
if (this.buffer.length >= this.maxQueueSize) {
|
|
222
|
+
this.buffer.shift();
|
|
223
|
+
this.logger.warn("fila cheia, item mais antigo descartado");
|
|
224
|
+
}
|
|
225
|
+
this.buffer.push(item);
|
|
226
|
+
if (this.buffer.length >= this.maxBatchSize) {
|
|
227
|
+
void this.flushBuffer();
|
|
228
|
+
} else {
|
|
229
|
+
this.schedule();
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
schedule() {
|
|
233
|
+
if (this.timer) return;
|
|
234
|
+
this.timer = setTimeout(() => {
|
|
235
|
+
this.timer = void 0;
|
|
236
|
+
void this.flushBuffer();
|
|
237
|
+
}, this.flushIntervalMs);
|
|
238
|
+
unrefTimer(this.timer);
|
|
239
|
+
}
|
|
240
|
+
flushBuffer() {
|
|
241
|
+
if (this.timer) {
|
|
242
|
+
clearTimeout(this.timer);
|
|
243
|
+
this.timer = void 0;
|
|
244
|
+
}
|
|
245
|
+
if (this.buffer.length === 0) return Promise.resolve();
|
|
246
|
+
const items = this.buffer.splice(0, this.buffer.length);
|
|
247
|
+
const envelope = {
|
|
248
|
+
sdk: { name: SDK_NAME, version: SDK_VERSION },
|
|
249
|
+
sent_at: nowISO(),
|
|
250
|
+
items
|
|
251
|
+
};
|
|
252
|
+
const request = this.sendWithRetry(envelope).finally(() => {
|
|
253
|
+
this.pending.delete(request);
|
|
254
|
+
});
|
|
255
|
+
this.pending.add(request);
|
|
256
|
+
return request;
|
|
257
|
+
}
|
|
258
|
+
async sendWithRetry(envelope) {
|
|
259
|
+
for (let attempt = 0; ; attempt++) {
|
|
260
|
+
try {
|
|
261
|
+
const response = await fetch(this.endpoint, {
|
|
262
|
+
method: "POST",
|
|
263
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${this.key}` },
|
|
264
|
+
body: JSON.stringify(envelope)
|
|
265
|
+
});
|
|
266
|
+
if (response.ok) {
|
|
267
|
+
this.logger.debug(`envelope enviado (${envelope.items.length} itens)`);
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
|
|
271
|
+
this.logger.error(`envelope rejeitado (HTTP ${response.status}), descartado`);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
throw new Error(`HTTP ${response.status}`);
|
|
275
|
+
} catch (error) {
|
|
276
|
+
const delay = RETRY_DELAYS_MS[attempt];
|
|
277
|
+
if (delay === void 0) {
|
|
278
|
+
this.logger.error("envelope descartado ap\xF3s retries:", error);
|
|
279
|
+
return;
|
|
280
|
+
}
|
|
281
|
+
this.logger.warn(`falha no envio (${String(error)}), retry em ${delay}ms`);
|
|
282
|
+
await sleep(delay);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Envia o que estiver na fila e aguarda envios em andamento (até timeoutMs). */
|
|
287
|
+
async flush(timeoutMs = 5e3) {
|
|
288
|
+
void this.flushBuffer();
|
|
289
|
+
const all = Promise.allSettled([...this.pending]).then(() => true);
|
|
290
|
+
return Promise.race([all, sleep(timeoutMs).then(() => false)]);
|
|
291
|
+
}
|
|
292
|
+
async close(timeoutMs = 5e3) {
|
|
293
|
+
const result = await this.flush(timeoutMs);
|
|
294
|
+
this.closed = true;
|
|
295
|
+
return result;
|
|
296
|
+
}
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
// src/client.ts
|
|
300
|
+
function runtimeContexts() {
|
|
301
|
+
if (isNode()) {
|
|
302
|
+
return {
|
|
303
|
+
runtime: { name: "node", version: process.version },
|
|
304
|
+
os: { name: process.platform, arch: process.arch }
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
return { runtime: { name: "browser" } };
|
|
308
|
+
}
|
|
309
|
+
var Client = class {
|
|
310
|
+
options;
|
|
311
|
+
dsn;
|
|
312
|
+
logger;
|
|
313
|
+
transport;
|
|
314
|
+
constructor(options) {
|
|
315
|
+
this.options = options;
|
|
316
|
+
this.logger = makeLogger(!!options.debug);
|
|
317
|
+
this.dsn = parseDsn(options.dsn);
|
|
318
|
+
this.transport = new Transport({
|
|
319
|
+
endpoint: this.dsn.ingestEndpoint,
|
|
320
|
+
key: this.dsn.key,
|
|
321
|
+
logger: this.logger,
|
|
322
|
+
flushIntervalMs: options.flushIntervalMs,
|
|
323
|
+
maxBatchSize: options.maxBatchSize
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
captureException(error, hint, scope2) {
|
|
327
|
+
return this.captureEvent(eventFromException(error, hint?.level ?? "error"), hint, scope2);
|
|
328
|
+
}
|
|
329
|
+
captureMessage(message, level, hint, scope2) {
|
|
330
|
+
return this.captureEvent(eventFromMessage(message, level), hint, scope2);
|
|
331
|
+
}
|
|
332
|
+
captureEvent(event, hint, scope2) {
|
|
333
|
+
const sampleRate = this.options.sampleRate ?? 1;
|
|
334
|
+
if (sampleRate < 1 && Math.random() >= sampleRate) {
|
|
335
|
+
this.logger.debug("evento descartado por sampleRate");
|
|
336
|
+
return event.event_id;
|
|
337
|
+
}
|
|
338
|
+
const prepared = this.prepareEvent(event, hint, scope2);
|
|
339
|
+
const final = this.options.beforeSend ? this.options.beforeSend(prepared) : prepared;
|
|
340
|
+
if (!final) {
|
|
341
|
+
this.logger.debug("evento descartado por beforeSend");
|
|
342
|
+
return event.event_id;
|
|
343
|
+
}
|
|
344
|
+
this.transport.enqueue({ type: "event", payload: final });
|
|
345
|
+
return final.event_id;
|
|
346
|
+
}
|
|
347
|
+
prepareEvent(event, hint, scope2) {
|
|
348
|
+
const tags = { ...this.options.tags, ...scope2.tags, ...event.tags, ...hint?.tags };
|
|
349
|
+
const extra = { ...scope2.extra, ...event.extra, ...hint?.extra };
|
|
350
|
+
return {
|
|
351
|
+
...event,
|
|
352
|
+
level: hint?.level ?? event.level ?? scope2.level ?? "error",
|
|
353
|
+
release: event.release ?? this.options.release,
|
|
354
|
+
environment: event.environment ?? this.options.environment ?? "production",
|
|
355
|
+
tags: Object.keys(tags).length > 0 ? tags : void 0,
|
|
356
|
+
extra: Object.keys(extra).length > 0 ? extra : void 0,
|
|
357
|
+
user: event.user ?? scope2.user,
|
|
358
|
+
contexts: { ...runtimeContexts(), ...scope2.contexts, ...event.contexts },
|
|
359
|
+
breadcrumbs: scope2.breadcrumbs.length > 0 ? [...scope2.breadcrumbs] : event.breadcrumbs,
|
|
360
|
+
fingerprint: hint?.fingerprint ?? event.fingerprint ?? scope2.fingerprint
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
sendTransaction(payload) {
|
|
364
|
+
this.transport.enqueue({
|
|
365
|
+
type: "transaction",
|
|
366
|
+
payload: {
|
|
367
|
+
...payload,
|
|
368
|
+
release: payload.release ?? this.options.release,
|
|
369
|
+
environment: payload.environment ?? this.options.environment ?? "production",
|
|
370
|
+
tags: { ...this.options.tags, ...payload.tags }
|
|
371
|
+
}
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
sendCheckIn(payload) {
|
|
375
|
+
this.transport.enqueue({
|
|
376
|
+
type: "check_in",
|
|
377
|
+
payload: {
|
|
378
|
+
...payload,
|
|
379
|
+
release: payload.release ?? this.options.release,
|
|
380
|
+
environment: payload.environment ?? this.options.environment ?? "production"
|
|
381
|
+
}
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
sendHeartbeat(payload) {
|
|
385
|
+
this.transport.enqueue({
|
|
386
|
+
type: "heartbeat",
|
|
387
|
+
payload: { ...payload, release: payload.release ?? this.options.release }
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
flush(timeoutMs) {
|
|
391
|
+
return this.transport.flush(timeoutMs);
|
|
392
|
+
}
|
|
393
|
+
close(timeoutMs) {
|
|
394
|
+
return this.transport.close(timeoutMs);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
|
|
398
|
+
// src/heartbeat.ts
|
|
399
|
+
var DEFAULT_INTERVAL_MS = 3e4;
|
|
400
|
+
var Heartbeat = class {
|
|
401
|
+
constructor(client2, options = {}, instanceId) {
|
|
402
|
+
this.client = client2;
|
|
403
|
+
this.intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
404
|
+
this.instanceId = instanceId;
|
|
405
|
+
this.name = options.name ?? instanceId;
|
|
406
|
+
this.metadata = options.metadata;
|
|
407
|
+
}
|
|
408
|
+
intervalMs;
|
|
409
|
+
instanceId;
|
|
410
|
+
name;
|
|
411
|
+
metadata;
|
|
412
|
+
timer;
|
|
413
|
+
start() {
|
|
414
|
+
if (this.timer) return;
|
|
415
|
+
this.beat();
|
|
416
|
+
this.timer = setInterval(() => this.beat(), this.intervalMs);
|
|
417
|
+
unrefTimer(this.timer);
|
|
418
|
+
}
|
|
419
|
+
stop() {
|
|
420
|
+
if (this.timer) {
|
|
421
|
+
clearInterval(this.timer);
|
|
422
|
+
this.timer = void 0;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
beat() {
|
|
426
|
+
this.client.sendHeartbeat({
|
|
427
|
+
instance_id: this.instanceId,
|
|
428
|
+
name: this.name,
|
|
429
|
+
interval_ms: this.intervalMs,
|
|
430
|
+
timestamp: nowISO(),
|
|
431
|
+
metadata: this.metadata
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
// src/instrument.ts
|
|
437
|
+
var installed = false;
|
|
438
|
+
function installGlobalHandlers(client2, getScope) {
|
|
439
|
+
if (installed) return;
|
|
440
|
+
installed = true;
|
|
441
|
+
if (isNode()) {
|
|
442
|
+
process.on("uncaughtException", (error) => {
|
|
443
|
+
client2.captureException(error, { level: "fatal", tags: { mechanism: "uncaughtException" } }, getScope());
|
|
444
|
+
void client2.flush(2e3).then(() => {
|
|
445
|
+
if (process.listenerCount("uncaughtException") <= 1) {
|
|
446
|
+
console.error(error);
|
|
447
|
+
process.exit(1);
|
|
448
|
+
}
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
process.on("unhandledRejection", (reason) => {
|
|
452
|
+
client2.captureException(reason, { level: "error", tags: { mechanism: "unhandledRejection" } }, getScope());
|
|
453
|
+
void client2.flush(2e3);
|
|
454
|
+
});
|
|
455
|
+
process.on("beforeExit", () => {
|
|
456
|
+
void client2.flush(2e3);
|
|
457
|
+
});
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (typeof window !== "undefined") {
|
|
461
|
+
window.addEventListener("error", (event) => {
|
|
462
|
+
client2.captureException(event.error ?? event.message, { tags: { mechanism: "onerror" } }, getScope());
|
|
463
|
+
});
|
|
464
|
+
window.addEventListener("unhandledrejection", (event) => {
|
|
465
|
+
client2.captureException(event.reason, { tags: { mechanism: "onunhandledrejection" } }, getScope());
|
|
466
|
+
});
|
|
467
|
+
window.addEventListener("pagehide", () => {
|
|
468
|
+
void client2.flush(1e3);
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
// src/scope.ts
|
|
474
|
+
var Scope = class _Scope {
|
|
475
|
+
tags = {};
|
|
476
|
+
user;
|
|
477
|
+
contexts = {};
|
|
478
|
+
extra = {};
|
|
479
|
+
level;
|
|
480
|
+
fingerprint;
|
|
481
|
+
breadcrumbs = [];
|
|
482
|
+
setTag(key, value) {
|
|
483
|
+
this.tags[key] = value;
|
|
484
|
+
return this;
|
|
485
|
+
}
|
|
486
|
+
setTags(tags) {
|
|
487
|
+
Object.assign(this.tags, tags);
|
|
488
|
+
return this;
|
|
489
|
+
}
|
|
490
|
+
setUser(user) {
|
|
491
|
+
this.user = user ?? void 0;
|
|
492
|
+
return this;
|
|
493
|
+
}
|
|
494
|
+
setContext(name, context) {
|
|
495
|
+
if (context === null) {
|
|
496
|
+
delete this.contexts[name];
|
|
497
|
+
} else {
|
|
498
|
+
this.contexts[name] = context;
|
|
499
|
+
}
|
|
500
|
+
return this;
|
|
501
|
+
}
|
|
502
|
+
setExtra(key, value) {
|
|
503
|
+
this.extra[key] = value;
|
|
504
|
+
return this;
|
|
505
|
+
}
|
|
506
|
+
setExtras(extras) {
|
|
507
|
+
Object.assign(this.extra, extras);
|
|
508
|
+
return this;
|
|
509
|
+
}
|
|
510
|
+
setLevel(level) {
|
|
511
|
+
this.level = level;
|
|
512
|
+
return this;
|
|
513
|
+
}
|
|
514
|
+
setFingerprint(fingerprint) {
|
|
515
|
+
this.fingerprint = fingerprint;
|
|
516
|
+
return this;
|
|
517
|
+
}
|
|
518
|
+
addBreadcrumb(crumb, maxBreadcrumbs) {
|
|
519
|
+
this.breadcrumbs.push({ timestamp: nowISO(), ...crumb });
|
|
520
|
+
if (this.breadcrumbs.length > maxBreadcrumbs) {
|
|
521
|
+
this.breadcrumbs.splice(0, this.breadcrumbs.length - maxBreadcrumbs);
|
|
522
|
+
}
|
|
523
|
+
return this;
|
|
524
|
+
}
|
|
525
|
+
clearBreadcrumbs() {
|
|
526
|
+
this.breadcrumbs = [];
|
|
527
|
+
return this;
|
|
528
|
+
}
|
|
529
|
+
clone() {
|
|
530
|
+
const next = new _Scope();
|
|
531
|
+
next.tags = { ...this.tags };
|
|
532
|
+
next.user = this.user ? { ...this.user } : void 0;
|
|
533
|
+
next.contexts = Object.fromEntries(Object.entries(this.contexts).map(([k, v]) => [k, { ...v }]));
|
|
534
|
+
next.extra = { ...this.extra };
|
|
535
|
+
next.level = this.level;
|
|
536
|
+
next.fingerprint = this.fingerprint ? [...this.fingerprint] : void 0;
|
|
537
|
+
next.breadcrumbs = [...this.breadcrumbs];
|
|
538
|
+
return next;
|
|
539
|
+
}
|
|
540
|
+
};
|
|
541
|
+
|
|
542
|
+
// src/transaction.ts
|
|
543
|
+
function spanId() {
|
|
544
|
+
return uuid4().slice(0, 16);
|
|
545
|
+
}
|
|
546
|
+
var Span = class {
|
|
547
|
+
constructor(transaction, parentSpanId, op, description) {
|
|
548
|
+
this.transaction = transaction;
|
|
549
|
+
this.parentSpanId = parentSpanId;
|
|
550
|
+
this.op = op;
|
|
551
|
+
this.description = description;
|
|
552
|
+
}
|
|
553
|
+
spanId = spanId();
|
|
554
|
+
startTimestamp = nowISO();
|
|
555
|
+
status = "ok";
|
|
556
|
+
endTimestamp;
|
|
557
|
+
data;
|
|
558
|
+
setStatus(status) {
|
|
559
|
+
this.status = status;
|
|
560
|
+
return this;
|
|
561
|
+
}
|
|
562
|
+
setData(key, value) {
|
|
563
|
+
this.data = { ...this.data, [key]: value };
|
|
564
|
+
return this;
|
|
565
|
+
}
|
|
566
|
+
/** Span aninhado (filho deste span). */
|
|
567
|
+
startChild(op, description) {
|
|
568
|
+
return this.transaction.createSpan(this.spanId, op, description);
|
|
569
|
+
}
|
|
570
|
+
finish() {
|
|
571
|
+
if (!this.endTimestamp) this.endTimestamp = nowISO();
|
|
572
|
+
}
|
|
573
|
+
toJSON() {
|
|
574
|
+
return {
|
|
575
|
+
span_id: this.spanId,
|
|
576
|
+
parent_span_id: this.parentSpanId,
|
|
577
|
+
op: this.op,
|
|
578
|
+
description: this.description,
|
|
579
|
+
status: this.status,
|
|
580
|
+
start_timestamp: this.startTimestamp,
|
|
581
|
+
timestamp: this.endTimestamp ?? nowISO(),
|
|
582
|
+
data: this.data
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
var Transaction = class {
|
|
587
|
+
constructor(client2, name, op, sampled = true) {
|
|
588
|
+
this.client = client2;
|
|
589
|
+
this.name = name;
|
|
590
|
+
this.op = op;
|
|
591
|
+
this.sampled = sampled;
|
|
592
|
+
}
|
|
593
|
+
eventId = uuid4();
|
|
594
|
+
spanId = spanId();
|
|
595
|
+
startTimestamp = nowISO();
|
|
596
|
+
status = "ok";
|
|
597
|
+
spans = [];
|
|
598
|
+
tags = {};
|
|
599
|
+
finished = false;
|
|
600
|
+
createSpan(parentSpanId, op, description) {
|
|
601
|
+
const span = new Span(this, parentSpanId, op, description);
|
|
602
|
+
this.spans.push(span);
|
|
603
|
+
return span;
|
|
604
|
+
}
|
|
605
|
+
/** Span direto da transaction. */
|
|
606
|
+
startChild(op, description) {
|
|
607
|
+
return this.createSpan(this.spanId, op, description);
|
|
608
|
+
}
|
|
609
|
+
setTag(key, value) {
|
|
610
|
+
this.tags[key] = value;
|
|
611
|
+
return this;
|
|
612
|
+
}
|
|
613
|
+
setStatus(status) {
|
|
614
|
+
this.status = status;
|
|
615
|
+
return this;
|
|
616
|
+
}
|
|
617
|
+
setName(name) {
|
|
618
|
+
this.name = name;
|
|
619
|
+
return this;
|
|
620
|
+
}
|
|
621
|
+
finish() {
|
|
622
|
+
if (this.finished) return;
|
|
623
|
+
this.finished = true;
|
|
624
|
+
for (const span of this.spans) span.finish();
|
|
625
|
+
if (!this.sampled || !this.client) return;
|
|
626
|
+
const payload = {
|
|
627
|
+
event_id: this.eventId,
|
|
628
|
+
name: this.name,
|
|
629
|
+
op: this.op,
|
|
630
|
+
status: this.status,
|
|
631
|
+
start_timestamp: this.startTimestamp,
|
|
632
|
+
timestamp: nowISO(),
|
|
633
|
+
spans: this.spans.map((span) => span.toJSON()),
|
|
634
|
+
tags: Object.keys(this.tags).length > 0 ? this.tags : void 0
|
|
635
|
+
};
|
|
636
|
+
this.client.sendTransaction(payload);
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
|
|
640
|
+
// src/checkin.ts
|
|
641
|
+
function sendCheckIn(client2, options) {
|
|
642
|
+
const checkInId = options.checkInId ?? uuid4();
|
|
643
|
+
client2.sendCheckIn({
|
|
644
|
+
check_in_id: checkInId,
|
|
645
|
+
monitor_slug: options.monitorSlug,
|
|
646
|
+
status: options.status,
|
|
647
|
+
duration_ms: options.durationMs,
|
|
648
|
+
schedule: options.schedule,
|
|
649
|
+
timezone: options.timezone
|
|
650
|
+
});
|
|
651
|
+
return checkInId;
|
|
652
|
+
}
|
|
653
|
+
async function withMonitorImpl(client2, captureError, monitorSlug, fn, options) {
|
|
654
|
+
const checkInId = sendCheckIn(client2, {
|
|
655
|
+
monitorSlug,
|
|
656
|
+
status: "in_progress",
|
|
657
|
+
schedule: options?.schedule,
|
|
658
|
+
timezone: options?.timezone
|
|
659
|
+
});
|
|
660
|
+
const startedAt = Date.now();
|
|
661
|
+
try {
|
|
662
|
+
const result = await fn();
|
|
663
|
+
sendCheckIn(client2, {
|
|
664
|
+
monitorSlug,
|
|
665
|
+
status: "ok",
|
|
666
|
+
checkInId,
|
|
667
|
+
durationMs: Date.now() - startedAt,
|
|
668
|
+
schedule: options?.schedule,
|
|
669
|
+
timezone: options?.timezone
|
|
670
|
+
});
|
|
671
|
+
return result;
|
|
672
|
+
} catch (error) {
|
|
673
|
+
sendCheckIn(client2, {
|
|
674
|
+
monitorSlug,
|
|
675
|
+
status: "error",
|
|
676
|
+
checkInId,
|
|
677
|
+
durationMs: Date.now() - startedAt,
|
|
678
|
+
schedule: options?.schedule,
|
|
679
|
+
timezone: options?.timezone
|
|
680
|
+
});
|
|
681
|
+
captureError(error);
|
|
682
|
+
throw error;
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// src/manager/api.ts
|
|
687
|
+
var RETRY_DELAYS_MS2 = [1e3, 4e3, 16e3];
|
|
688
|
+
var ManagerApiError = class extends Error {
|
|
689
|
+
constructor(message, status) {
|
|
690
|
+
super(message);
|
|
691
|
+
this.status = status;
|
|
692
|
+
this.name = "ManagerApiError";
|
|
693
|
+
}
|
|
694
|
+
};
|
|
695
|
+
var ManagerApi = class {
|
|
696
|
+
baseUrl;
|
|
697
|
+
key;
|
|
698
|
+
logger;
|
|
699
|
+
constructor(options) {
|
|
700
|
+
this.baseUrl = options.baseUrl;
|
|
701
|
+
this.key = options.key;
|
|
702
|
+
this.logger = options.logger;
|
|
703
|
+
}
|
|
704
|
+
headers() {
|
|
705
|
+
return {
|
|
706
|
+
"content-type": "application/json",
|
|
707
|
+
authorization: `Bearer ${this.key}`
|
|
708
|
+
};
|
|
709
|
+
}
|
|
710
|
+
/** Um request só — o loop de polling é quem decide o backoff entre tentativas. */
|
|
711
|
+
async poll(request, signal) {
|
|
712
|
+
const response = await fetch(`${this.baseUrl}/poll`, {
|
|
713
|
+
method: "POST",
|
|
714
|
+
headers: this.headers(),
|
|
715
|
+
body: JSON.stringify(request),
|
|
716
|
+
signal
|
|
717
|
+
});
|
|
718
|
+
if (!response.ok) {
|
|
719
|
+
throw new ManagerApiError(`poll falhou (HTTP ${response.status})`, response.status);
|
|
720
|
+
}
|
|
721
|
+
return await response.json();
|
|
722
|
+
}
|
|
723
|
+
/**
|
|
724
|
+
* PATCH de status/logs com retry em falha de rede/5xx/429.
|
|
725
|
+
* 4xx é definitivo e vira ManagerApiError imediato (409 = run cancelada/transição inválida).
|
|
726
|
+
*/
|
|
727
|
+
async updateRun(runId, update) {
|
|
728
|
+
for (let attempt = 0; ; attempt++) {
|
|
729
|
+
let retriable;
|
|
730
|
+
try {
|
|
731
|
+
const response = await fetch(`${this.baseUrl}/runs/${encodeURIComponent(runId)}`, {
|
|
732
|
+
method: "PATCH",
|
|
733
|
+
headers: this.headers(),
|
|
734
|
+
body: JSON.stringify(update)
|
|
735
|
+
});
|
|
736
|
+
if (response.ok) return;
|
|
737
|
+
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
|
|
738
|
+
throw new ManagerApiError(`update rejeitado (HTTP ${response.status})`, response.status);
|
|
739
|
+
}
|
|
740
|
+
retriable = new Error(`HTTP ${response.status}`);
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (error instanceof ManagerApiError) throw error;
|
|
743
|
+
retriable = error;
|
|
744
|
+
}
|
|
745
|
+
const delay = RETRY_DELAYS_MS2[attempt];
|
|
746
|
+
if (delay === void 0) {
|
|
747
|
+
throw new Error(`update da run ${runId} descartado ap\xF3s retries: ${String(retriable)}`);
|
|
748
|
+
}
|
|
749
|
+
this.logger.warn(`falha no update da run ${runId} (${String(retriable)}), retry em ${delay}ms`);
|
|
750
|
+
await sleep(delay);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
// src/manager/context.ts
|
|
756
|
+
var DEFAULT_LOG_FLUSH_INTERVAL_MS = 2e3;
|
|
757
|
+
var MAX_LOG_MESSAGE_CHARS = 1e4;
|
|
758
|
+
var MAX_LOGS_PER_RUN = 500;
|
|
759
|
+
var MAX_LOGS_PER_PATCH = 100;
|
|
760
|
+
var FLUSH_AT_BUFFERED = 20;
|
|
761
|
+
var RunReporter = class {
|
|
762
|
+
constructor(api, runId, task, logger, flushIntervalMs) {
|
|
763
|
+
this.api = api;
|
|
764
|
+
this.runId = runId;
|
|
765
|
+
this.logger = logger;
|
|
766
|
+
this.flushIntervalMs = flushIntervalMs ?? DEFAULT_LOG_FLUSH_INTERVAL_MS;
|
|
767
|
+
this.context = {
|
|
768
|
+
runId,
|
|
769
|
+
task,
|
|
770
|
+
log: (level, message) => this.log(level, message),
|
|
771
|
+
signal: this.abortController.signal
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
context;
|
|
775
|
+
buffer = [];
|
|
776
|
+
loggedCount = 0;
|
|
777
|
+
droppedCount = 0;
|
|
778
|
+
dead = false;
|
|
779
|
+
chain = Promise.resolve();
|
|
780
|
+
timer;
|
|
781
|
+
abortController = new AbortController();
|
|
782
|
+
flushIntervalMs;
|
|
783
|
+
get isDead() {
|
|
784
|
+
return this.dead;
|
|
785
|
+
}
|
|
786
|
+
/** Aborta o ctx.signal sem matar o reporter (timeout/shutdown ainda reportam o terminal). */
|
|
787
|
+
abort() {
|
|
788
|
+
if (!this.abortController.signal.aborted) this.abortController.abort();
|
|
789
|
+
}
|
|
790
|
+
log(level, message) {
|
|
791
|
+
if (this.dead) return;
|
|
792
|
+
if (this.loggedCount >= MAX_LOGS_PER_RUN) {
|
|
793
|
+
this.droppedCount++;
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
this.loggedCount++;
|
|
797
|
+
const truncated = message.length > MAX_LOG_MESSAGE_CHARS ? `${message.slice(0, MAX_LOG_MESSAGE_CHARS)}\u2026 [truncado]` : message;
|
|
798
|
+
this.buffer.push({ ts: nowISO(), level, message: truncated });
|
|
799
|
+
if (this.buffer.length >= FLUSH_AT_BUFFERED) {
|
|
800
|
+
this.flushLogs();
|
|
801
|
+
} else {
|
|
802
|
+
this.scheduleFlush();
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
scheduleFlush() {
|
|
806
|
+
if (this.timer) return;
|
|
807
|
+
this.timer = setTimeout(() => {
|
|
808
|
+
this.timer = void 0;
|
|
809
|
+
this.flushLogs();
|
|
810
|
+
}, this.flushIntervalMs);
|
|
811
|
+
unrefTimer(this.timer);
|
|
812
|
+
}
|
|
813
|
+
clearFlushTimer() {
|
|
814
|
+
if (this.timer) {
|
|
815
|
+
clearTimeout(this.timer);
|
|
816
|
+
this.timer = void 0;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
takeLogs() {
|
|
820
|
+
const logs = this.buffer.splice(0, this.buffer.length);
|
|
821
|
+
if (this.droppedCount > 0) {
|
|
822
|
+
logs.push({
|
|
823
|
+
ts: nowISO(),
|
|
824
|
+
level: "warning",
|
|
825
|
+
message: `${this.droppedCount} logs descartados (limite de ${MAX_LOGS_PER_RUN} por execu\xE7\xE3o)`
|
|
826
|
+
});
|
|
827
|
+
this.droppedCount = 0;
|
|
828
|
+
}
|
|
829
|
+
return logs;
|
|
830
|
+
}
|
|
831
|
+
/** Flush incremental: envia o buffer como status 'running' (em chunks). */
|
|
832
|
+
flushLogs() {
|
|
833
|
+
this.clearFlushTimer();
|
|
834
|
+
if (this.dead || this.buffer.length === 0) return;
|
|
835
|
+
const logs = this.buffer.splice(0, this.buffer.length);
|
|
836
|
+
for (let i = 0; i < logs.length; i += MAX_LOGS_PER_PATCH) {
|
|
837
|
+
this.enqueue({ status: "running", logs: logs.slice(i, i + MAX_LOGS_PER_PATCH) });
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
/** Primeiro PATCH (claimed → running). Retorna false se a run já morreu (cancelada). */
|
|
841
|
+
async reportRunning() {
|
|
842
|
+
this.enqueue({ status: "running" });
|
|
843
|
+
await this.chain;
|
|
844
|
+
return !this.dead;
|
|
845
|
+
}
|
|
846
|
+
reportSuccess() {
|
|
847
|
+
this.clearFlushTimer();
|
|
848
|
+
this.enqueue({ status: "succeeded", logs: this.takeLogs() });
|
|
849
|
+
}
|
|
850
|
+
reportFailure(error) {
|
|
851
|
+
this.clearFlushTimer();
|
|
852
|
+
this.enqueue({ status: "failed", error, logs: this.takeLogs() });
|
|
853
|
+
}
|
|
854
|
+
/** Aguarda a fila de PATCHes esvaziar (chame depois do terminal). */
|
|
855
|
+
finalize() {
|
|
856
|
+
return this.chain;
|
|
857
|
+
}
|
|
858
|
+
enqueue(update) {
|
|
859
|
+
if (this.dead) return;
|
|
860
|
+
this.chain = this.chain.then(async () => {
|
|
861
|
+
if (this.dead) return;
|
|
862
|
+
const payload = update.logs && update.logs.length === 0 ? { ...update, logs: void 0 } : update;
|
|
863
|
+
try {
|
|
864
|
+
await this.api.updateRun(this.runId, payload);
|
|
865
|
+
} catch (error) {
|
|
866
|
+
if (error instanceof ManagerApiError && (error.status === 409 || error.status === 404)) {
|
|
867
|
+
this.dead = true;
|
|
868
|
+
this.abort();
|
|
869
|
+
this.buffer = [];
|
|
870
|
+
this.logger.warn(`run ${this.runId} cancelada/removida no servidor \u2014 reporte suprimido`);
|
|
871
|
+
return;
|
|
872
|
+
}
|
|
873
|
+
this.logger.error(`update da run ${this.runId} perdido:`, error);
|
|
874
|
+
}
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
|
|
879
|
+
// src/manager/agent.ts
|
|
880
|
+
var DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
881
|
+
var MIN_POLL_INTERVAL_MS = 1e3;
|
|
882
|
+
var MAX_CONCURRENCY = 5;
|
|
883
|
+
var POLL_RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
884
|
+
var AUTH_FAILURE_INTERVAL_MS = 3e4;
|
|
885
|
+
function hostname() {
|
|
886
|
+
if (!isNode()) return void 0;
|
|
887
|
+
return process.env.HOSTNAME || process.env.COMPUTERNAME || void 0;
|
|
888
|
+
}
|
|
889
|
+
var ManagerAgent = class {
|
|
890
|
+
constructor(options, registry2) {
|
|
891
|
+
this.options = options;
|
|
892
|
+
this.registry = registry2;
|
|
893
|
+
this.logger = makeLogger(options.debug ?? false, "[hobots-manager]");
|
|
894
|
+
const dsn = parseDsn(options.dsn);
|
|
895
|
+
this.api = new ManagerApi({ baseUrl: dsn.managerBaseUrl, key: dsn.key, logger: this.logger });
|
|
896
|
+
this.pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
|
|
897
|
+
this.concurrency = Math.min(MAX_CONCURRENCY, Math.max(1, options.concurrency ?? 1));
|
|
898
|
+
this.instanceId = options.instanceId;
|
|
899
|
+
this.taskTimeoutMs = options.taskTimeoutMs;
|
|
900
|
+
this.logFlushIntervalMs = options.logFlushIntervalMs;
|
|
901
|
+
this.logger.debug("agente configurado", { baseUrl: dsn.managerBaseUrl, projectSlug: dsn.projectSlug });
|
|
902
|
+
}
|
|
903
|
+
logger;
|
|
904
|
+
api;
|
|
905
|
+
pollIntervalMs;
|
|
906
|
+
concurrency;
|
|
907
|
+
instanceId;
|
|
908
|
+
taskTimeoutMs;
|
|
909
|
+
logFlushIntervalMs;
|
|
910
|
+
state = "idle";
|
|
911
|
+
timer;
|
|
912
|
+
pollAbort;
|
|
913
|
+
consecutiveFailures = 0;
|
|
914
|
+
consecutiveAuthFailures = 0;
|
|
915
|
+
activeRuns = /* @__PURE__ */ new Set();
|
|
916
|
+
reporters = /* @__PURE__ */ new Set();
|
|
917
|
+
get activeCount() {
|
|
918
|
+
return this.activeRuns.size;
|
|
919
|
+
}
|
|
920
|
+
start() {
|
|
921
|
+
if (this.state === "started") return;
|
|
922
|
+
if (this.state === "stopping") {
|
|
923
|
+
throw new Error("[hobots-manager] start() chamado durante stop() \u2014 aguarde o stop terminar");
|
|
924
|
+
}
|
|
925
|
+
if (this.registry.size === 0) {
|
|
926
|
+
throw new Error("[hobots-manager] nenhuma task registrada \u2014 chame register() antes de start()");
|
|
927
|
+
}
|
|
928
|
+
this.state = "started";
|
|
929
|
+
this.logger.debug(`polling iniciado (tasks: ${[...this.registry.keys()].join(", ")})`);
|
|
930
|
+
this.schedule(0);
|
|
931
|
+
}
|
|
932
|
+
/** Para o polling e aguarda as runs ativas (até timeoutMs). Retorna true se tudo terminou a tempo. */
|
|
933
|
+
async stop(timeoutMs = 3e4) {
|
|
934
|
+
if (this.state === "idle") return true;
|
|
935
|
+
this.state = "stopping";
|
|
936
|
+
if (this.timer) {
|
|
937
|
+
clearTimeout(this.timer);
|
|
938
|
+
this.timer = void 0;
|
|
939
|
+
}
|
|
940
|
+
this.pollAbort?.abort();
|
|
941
|
+
const all = Promise.allSettled([...this.activeRuns]).then(() => true);
|
|
942
|
+
const finished = timeoutMs > 0 ? await Promise.race([all, sleep(timeoutMs).then(() => false)]) : false;
|
|
943
|
+
if (!finished && this.activeRuns.size > 0) {
|
|
944
|
+
this.logger.warn(`${this.activeRuns.size} run(s) ainda em execu\xE7\xE3o ap\xF3s ${timeoutMs}ms \u2014 abandonando a espera`);
|
|
945
|
+
for (const reporter of this.reporters) reporter.abort();
|
|
946
|
+
}
|
|
947
|
+
this.state = "idle";
|
|
948
|
+
return finished;
|
|
949
|
+
}
|
|
950
|
+
/** Timer intencionalmente NÃO unref'd: o agente é a razão do processo existir. */
|
|
951
|
+
schedule(delayMs) {
|
|
952
|
+
if (this.state !== "started" || this.timer) return;
|
|
953
|
+
this.timer = setTimeout(() => {
|
|
954
|
+
this.timer = void 0;
|
|
955
|
+
void this.tick();
|
|
956
|
+
}, delayMs);
|
|
957
|
+
}
|
|
958
|
+
async tick() {
|
|
959
|
+
if (this.state !== "started") return;
|
|
960
|
+
if (this.activeRuns.size >= this.concurrency) {
|
|
961
|
+
this.schedule(this.pollIntervalMs);
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
this.pollAbort = new AbortController();
|
|
965
|
+
try {
|
|
966
|
+
const response = await this.api.poll(
|
|
967
|
+
{
|
|
968
|
+
agent: {
|
|
969
|
+
// identidade canônica do agente no painel — o mesmo instanceId do
|
|
970
|
+
// heartbeat do Monitor, então os dois canais convergem em um agente
|
|
971
|
+
instance_id: this.instanceId,
|
|
972
|
+
version: SDK_VERSION,
|
|
973
|
+
host: hostname(),
|
|
974
|
+
tasks: [...this.registry.keys()]
|
|
975
|
+
},
|
|
976
|
+
max: Math.min(MAX_CONCURRENCY, this.concurrency - this.activeRuns.size),
|
|
977
|
+
tasks: [...this.registry.keys()]
|
|
978
|
+
},
|
|
979
|
+
this.pollAbort.signal
|
|
980
|
+
);
|
|
981
|
+
this.consecutiveFailures = 0;
|
|
982
|
+
this.consecutiveAuthFailures = 0;
|
|
983
|
+
for (const run of response.runs) {
|
|
984
|
+
this.dispatch(run);
|
|
985
|
+
}
|
|
986
|
+
this.schedule(response.runs.length > 0 ? 0 : this.pollIntervalMs);
|
|
987
|
+
} catch (error) {
|
|
988
|
+
if (this.state !== "started") return;
|
|
989
|
+
this.schedule(this.delayAfterPollError(error));
|
|
990
|
+
} finally {
|
|
991
|
+
this.pollAbort = void 0;
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
delayAfterPollError(error) {
|
|
995
|
+
if (error instanceof ManagerApiError && error.status === 401) {
|
|
996
|
+
this.consecutiveAuthFailures++;
|
|
997
|
+
if (this.consecutiveAuthFailures === 1 || this.consecutiveAuthFailures % 10 === 0) {
|
|
998
|
+
this.logger.error("chave rejeitada (401) \u2014 verifique a DSN do projeto em Configura\xE7\xF5es \u2192 Agentes");
|
|
999
|
+
}
|
|
1000
|
+
return Math.max(this.pollIntervalMs, AUTH_FAILURE_INTERVAL_MS);
|
|
1001
|
+
}
|
|
1002
|
+
this.consecutiveFailures++;
|
|
1003
|
+
const ladder = POLL_RETRY_DELAYS_MS[Math.min(this.consecutiveFailures - 1, POLL_RETRY_DELAYS_MS.length - 1)];
|
|
1004
|
+
const delay = Math.min(Math.max(ladder, 0), Math.max(this.pollIntervalMs, 16e3));
|
|
1005
|
+
this.logger.warn(`poll falhou (${String(error)}), pr\xF3xima tentativa em ${delay}ms`);
|
|
1006
|
+
return delay;
|
|
1007
|
+
}
|
|
1008
|
+
dispatch(run) {
|
|
1009
|
+
const promise = this.executeRun(run).catch((error) => this.logger.error(`erro inesperado na run ${run.id}:`, error)).finally(() => {
|
|
1010
|
+
this.activeRuns.delete(promise);
|
|
1011
|
+
if (this.state === "started") this.schedule(0);
|
|
1012
|
+
});
|
|
1013
|
+
this.activeRuns.add(promise);
|
|
1014
|
+
}
|
|
1015
|
+
async executeRun(run) {
|
|
1016
|
+
const reporter = new RunReporter(this.api, run.id, run.task, this.logger, this.logFlushIntervalMs);
|
|
1017
|
+
this.reporters.add(reporter);
|
|
1018
|
+
try {
|
|
1019
|
+
const handler = this.registry.get(run.task);
|
|
1020
|
+
if (!handler) {
|
|
1021
|
+
reporter.reportFailure({
|
|
1022
|
+
type: "HandlerNotFound",
|
|
1023
|
+
message: `tarefa n\xE3o registrada no agente: ${run.task}`
|
|
1024
|
+
});
|
|
1025
|
+
await reporter.finalize();
|
|
1026
|
+
return;
|
|
1027
|
+
}
|
|
1028
|
+
const ok = await reporter.reportRunning();
|
|
1029
|
+
if (!ok) {
|
|
1030
|
+
this.logger.debug(`run ${run.id} cancelada antes de iniciar \u2014 handler n\xE3o executado`);
|
|
1031
|
+
return;
|
|
1032
|
+
}
|
|
1033
|
+
this.logger.debug(`executando run ${run.id} (${run.task})`);
|
|
1034
|
+
try {
|
|
1035
|
+
await this.invokeWithTimeout(handler, run, reporter);
|
|
1036
|
+
reporter.reportSuccess();
|
|
1037
|
+
this.logger.debug(`run ${run.id} conclu\xEDda`);
|
|
1038
|
+
} catch (error) {
|
|
1039
|
+
reporter.reportFailure(toRunError(error));
|
|
1040
|
+
this.logger.debug(`run ${run.id} falhou: ${String(error)}`);
|
|
1041
|
+
}
|
|
1042
|
+
await reporter.finalize();
|
|
1043
|
+
} finally {
|
|
1044
|
+
this.reporters.delete(reporter);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
async invokeWithTimeout(handler, run, reporter) {
|
|
1048
|
+
const invocation = Promise.resolve().then(() => handler(run.params, reporter.context));
|
|
1049
|
+
if (!this.taskTimeoutMs || this.taskTimeoutMs <= 0) {
|
|
1050
|
+
await invocation;
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
const timeoutMs = this.taskTimeoutMs;
|
|
1054
|
+
const timeout = sleep(timeoutMs).then(() => TIMEOUT_SENTINEL);
|
|
1055
|
+
const outcome = await Promise.race([invocation, timeout]);
|
|
1056
|
+
if (outcome !== TIMEOUT_SENTINEL) return;
|
|
1057
|
+
reporter.abort();
|
|
1058
|
+
invocation.then(() => this.logger.warn(`run ${run.id} terminou depois do timeout de ${timeoutMs}ms`)).catch(() => this.logger.warn(`run ${run.id} falhou depois do timeout de ${timeoutMs}ms (erro descartado)`));
|
|
1059
|
+
throw Object.assign(new Error(`timeout ap\xF3s ${timeoutMs}ms (o handler pode continuar em background)`), {
|
|
1060
|
+
name: "TaskTimeout"
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
};
|
|
1064
|
+
var TIMEOUT_SENTINEL = /* @__PURE__ */ Symbol("task-timeout");
|
|
1065
|
+
var MAX_ERROR_MESSAGE_CHARS = 1e4;
|
|
1066
|
+
var MAX_ERROR_STACK_CHARS = 2e4;
|
|
1067
|
+
function truncate(value, max) {
|
|
1068
|
+
return value.length > max ? `${value.slice(0, max)}\u2026 [truncado]` : value;
|
|
1069
|
+
}
|
|
1070
|
+
function toRunError(error) {
|
|
1071
|
+
if (error instanceof Error) {
|
|
1072
|
+
return {
|
|
1073
|
+
type: error.name,
|
|
1074
|
+
message: truncate(error.message, MAX_ERROR_MESSAGE_CHARS),
|
|
1075
|
+
stack: error.stack ? truncate(error.stack, MAX_ERROR_STACK_CHARS) : void 0
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
return { message: truncate(String(error), MAX_ERROR_MESSAGE_CHARS) };
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// src/core.ts
|
|
1082
|
+
var DEFAULT_MAX_BREADCRUMBS = 100;
|
|
1083
|
+
var client;
|
|
1084
|
+
var scope = new Scope();
|
|
1085
|
+
var heartbeat;
|
|
1086
|
+
var agent;
|
|
1087
|
+
var registry = /* @__PURE__ */ new Map();
|
|
1088
|
+
var warnedManagerDisabled = false;
|
|
1089
|
+
function init(options) {
|
|
1090
|
+
if (client) {
|
|
1091
|
+
client.logger.warn("init() chamado mais de uma vez \u2014 substituindo o client anterior");
|
|
1092
|
+
heartbeat?.stop();
|
|
1093
|
+
heartbeat = void 0;
|
|
1094
|
+
}
|
|
1095
|
+
if (agent) {
|
|
1096
|
+
void agent.stop(0);
|
|
1097
|
+
agent = void 0;
|
|
1098
|
+
}
|
|
1099
|
+
warnedManagerDisabled = false;
|
|
1100
|
+
client = new Client(options);
|
|
1101
|
+
if (options.captureUnhandled !== false) {
|
|
1102
|
+
installGlobalHandlers(client, () => scope);
|
|
1103
|
+
}
|
|
1104
|
+
if (options.heartbeat) {
|
|
1105
|
+
const heartbeatOptions = options.heartbeat === true ? {} : options.heartbeat;
|
|
1106
|
+
heartbeat = new Heartbeat(client, heartbeatOptions, options.instanceId);
|
|
1107
|
+
heartbeat.start();
|
|
1108
|
+
}
|
|
1109
|
+
if (options.manager) {
|
|
1110
|
+
const managerOptions = options.manager === true ? {} : options.manager;
|
|
1111
|
+
agent = new ManagerAgent(
|
|
1112
|
+
{ ...managerOptions, dsn: options.dsn, instanceId: options.instanceId, debug: options.debug },
|
|
1113
|
+
registry
|
|
1114
|
+
);
|
|
1115
|
+
}
|
|
1116
|
+
client.logger.debug("inicializado", { endpoint: client.dsn.ingestEndpoint });
|
|
1117
|
+
}
|
|
1118
|
+
function getClient() {
|
|
1119
|
+
return client;
|
|
1120
|
+
}
|
|
1121
|
+
function captureException(error, hint) {
|
|
1122
|
+
return client?.captureException(error, hint, scope);
|
|
1123
|
+
}
|
|
1124
|
+
function captureMessage(message, level = "info", hint) {
|
|
1125
|
+
return client?.captureMessage(message, level, hint, scope);
|
|
1126
|
+
}
|
|
1127
|
+
function addBreadcrumb(crumb) {
|
|
1128
|
+
scope.addBreadcrumb(crumb, client?.options.maxBreadcrumbs ?? DEFAULT_MAX_BREADCRUMBS);
|
|
1129
|
+
}
|
|
1130
|
+
function setTag(key, value) {
|
|
1131
|
+
scope.setTag(key, value);
|
|
1132
|
+
}
|
|
1133
|
+
function setTags(tags) {
|
|
1134
|
+
scope.setTags(tags);
|
|
1135
|
+
}
|
|
1136
|
+
function setUser(user) {
|
|
1137
|
+
scope.setUser(user);
|
|
1138
|
+
}
|
|
1139
|
+
function setContext(name, context) {
|
|
1140
|
+
scope.setContext(name, context);
|
|
1141
|
+
}
|
|
1142
|
+
function setExtra(key, value) {
|
|
1143
|
+
scope.setExtra(key, value);
|
|
1144
|
+
}
|
|
1145
|
+
function withScope(callback) {
|
|
1146
|
+
const previous = scope;
|
|
1147
|
+
scope = previous.clone();
|
|
1148
|
+
try {
|
|
1149
|
+
return callback(scope);
|
|
1150
|
+
} finally {
|
|
1151
|
+
scope = previous;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
function startTransaction(name, op) {
|
|
1155
|
+
const rate = client?.options.tracesSampleRate ?? 1;
|
|
1156
|
+
const sampled = rate >= 1 || Math.random() < rate;
|
|
1157
|
+
return new Transaction(client, name, op, sampled);
|
|
1158
|
+
}
|
|
1159
|
+
function checkIn(options) {
|
|
1160
|
+
return client ? sendCheckIn(client, options) : void 0;
|
|
1161
|
+
}
|
|
1162
|
+
async function withMonitor(monitorSlug, fn, options) {
|
|
1163
|
+
if (!client) return fn();
|
|
1164
|
+
return withMonitorImpl(
|
|
1165
|
+
client,
|
|
1166
|
+
(error) => captureException(error, { tags: { monitor: monitorSlug } }),
|
|
1167
|
+
monitorSlug,
|
|
1168
|
+
fn,
|
|
1169
|
+
options
|
|
1170
|
+
);
|
|
1171
|
+
}
|
|
1172
|
+
function flush(timeoutMs) {
|
|
1173
|
+
return client ? client.flush(timeoutMs) : Promise.resolve(true);
|
|
1174
|
+
}
|
|
1175
|
+
function register(task, handler) {
|
|
1176
|
+
if (registry.has(task)) {
|
|
1177
|
+
(agent?.logger ?? client?.logger)?.warn(`register('${task}') sobrescreveu um handler existente`);
|
|
1178
|
+
}
|
|
1179
|
+
if (client && !agent && !warnedManagerDisabled) {
|
|
1180
|
+
warnedManagerDisabled = true;
|
|
1181
|
+
client.logger.warn(
|
|
1182
|
+
`register('${task}') com o Manager desabilitado \u2014 passe manager: true (ou op\xE7\xF5es) no init()`
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
registry.set(task, handler);
|
|
1186
|
+
}
|
|
1187
|
+
function start() {
|
|
1188
|
+
if (!agent) {
|
|
1189
|
+
throw new Error("[hobots] Manager n\xE3o configurado \u2014 passe manager: true (ou op\xE7\xF5es) no init() antes de start()");
|
|
1190
|
+
}
|
|
1191
|
+
agent.start();
|
|
1192
|
+
}
|
|
1193
|
+
function stop(timeoutMs) {
|
|
1194
|
+
return agent ? agent.stop(timeoutMs) : Promise.resolve(true);
|
|
1195
|
+
}
|
|
1196
|
+
async function close(timeoutMs) {
|
|
1197
|
+
const agentStopped = agent ? await agent.stop(timeoutMs) : true;
|
|
1198
|
+
heartbeat?.stop();
|
|
1199
|
+
heartbeat = void 0;
|
|
1200
|
+
const clientClosed = client ? await client.close(timeoutMs) : true;
|
|
1201
|
+
return agentStopped && clientClosed;
|
|
1202
|
+
}
|
|
1203
|
+
//# sourceMappingURL=index.cjs.map
|