hobots 1.0.0 → 1.1.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/README.md +128 -84
- package/dist/index.cjs +478 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +144 -19
- package/dist/index.d.ts +144 -19
- package/dist/index.js +522 -33
- package/dist/index.js.map +1 -1
- package/dist/manager/protocol.cjs.map +1 -1
- package/dist/manager/protocol.d.cts +3 -3
- package/dist/manager/protocol.d.ts +3 -3
- package/dist/protocol.cjs.map +1 -1
- package/dist/protocol.d.cts +6 -3
- package/dist/protocol.d.ts +6 -3
- package/docs/README.md +24 -17
- package/docs/api-reference.md +32 -20
- package/docs/getting-started.md +46 -29
- package/docs/manager.md +30 -25
- package/docs/monitor.md +28 -26
- package/docs/protocol.md +26 -12
- package/package.json +11 -16
- package/dist/chunk-FW32OR7V.js +0 -75
- package/dist/chunk-FW32OR7V.js.map +0 -1
- package/dist/manager.cjs +0 -519
- package/dist/manager.cjs.map +0 -1
- package/dist/manager.d.cts +0 -118
- package/dist/manager.d.ts +0 -118
- package/dist/manager.js +0 -464
- package/dist/manager.js.map +0 -1
- package/dist/utils-LReLqjzN.d.cts +0 -7
- package/dist/utils-LReLqjzN.d.ts +0 -7
package/dist/chunk-FW32OR7V.js
DELETED
|
@@ -1,75 +0,0 @@
|
|
|
1
|
-
// src/dsn.ts
|
|
2
|
-
function parseDsnUrl(dsn, prefix) {
|
|
3
|
-
let url;
|
|
4
|
-
try {
|
|
5
|
-
url = new URL(dsn);
|
|
6
|
-
} catch {
|
|
7
|
-
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}"`);
|
|
8
|
-
}
|
|
9
|
-
const key = url.username;
|
|
10
|
-
const path = url.pathname.replace(/^\/+/, "");
|
|
11
|
-
if (!key || !path) {
|
|
12
|
-
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}" \u2014 esperado https://<key>@host/<projeto>`);
|
|
13
|
-
}
|
|
14
|
-
return { key, path, origin: `${url.protocol}//${url.host}` };
|
|
15
|
-
}
|
|
16
|
-
function parseDsn(dsn) {
|
|
17
|
-
const { key, path, origin } = parseDsnUrl(dsn, "[hobots-monitor]");
|
|
18
|
-
return {
|
|
19
|
-
publicKey: key,
|
|
20
|
-
projectId: path,
|
|
21
|
-
endpoint: `${origin}/api/ingest/${key}`
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// src/utils.ts
|
|
26
|
-
var SDK_NAME = "hobots";
|
|
27
|
-
var SDK_VERSION = "1.0.0";
|
|
28
|
-
function isNode() {
|
|
29
|
-
return typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
30
|
-
}
|
|
31
|
-
function uuid4() {
|
|
32
|
-
const cryptoRef = globalThis.crypto;
|
|
33
|
-
if (cryptoRef && typeof cryptoRef.randomUUID === "function") {
|
|
34
|
-
return cryptoRef.randomUUID().replace(/-/g, "");
|
|
35
|
-
}
|
|
36
|
-
let out = "";
|
|
37
|
-
for (let i = 0; i < 32; i++) {
|
|
38
|
-
out += Math.floor(Math.random() * 16).toString(16);
|
|
39
|
-
}
|
|
40
|
-
return out;
|
|
41
|
-
}
|
|
42
|
-
function nowISO() {
|
|
43
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
44
|
-
}
|
|
45
|
-
function unrefTimer(timer) {
|
|
46
|
-
timer?.unref?.();
|
|
47
|
-
}
|
|
48
|
-
function sleep(ms) {
|
|
49
|
-
return new Promise((resolve) => {
|
|
50
|
-
const timer = setTimeout(resolve, ms);
|
|
51
|
-
unrefTimer(timer);
|
|
52
|
-
});
|
|
53
|
-
}
|
|
54
|
-
var PREFIX = "[hobots-monitor]";
|
|
55
|
-
function makeLogger(enabled, prefix = PREFIX) {
|
|
56
|
-
return {
|
|
57
|
-
debug: (...args) => enabled && console.debug(prefix, ...args),
|
|
58
|
-
warn: (...args) => enabled && console.warn(prefix, ...args),
|
|
59
|
-
error: (...args) => console.error(prefix, ...args)
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
export {
|
|
64
|
-
parseDsnUrl,
|
|
65
|
-
parseDsn,
|
|
66
|
-
SDK_NAME,
|
|
67
|
-
SDK_VERSION,
|
|
68
|
-
isNode,
|
|
69
|
-
uuid4,
|
|
70
|
-
nowISO,
|
|
71
|
-
unrefTimer,
|
|
72
|
-
sleep,
|
|
73
|
-
makeLogger
|
|
74
|
-
};
|
|
75
|
-
//# sourceMappingURL=chunk-FW32OR7V.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/dsn.ts","../src/utils.ts"],"sourcesContent":["export interface ParsedDsn {\n publicKey: string;\n projectId: string;\n /** URL de ingestão derivada: <origin>/api/ingest/<publicKey> */\n endpoint: string;\n}\n\ninterface ParsedDsnUrl {\n key: string;\n path: string;\n origin: string;\n}\n\n/** Parser baixo nível compartilhado entre Monitor e Manager (não exportado no barrel). */\nexport function parseDsnUrl(dsn: string, prefix: string): ParsedDsnUrl {\n let url: URL;\n try {\n url = new URL(dsn);\n } catch {\n throw new Error(`${prefix} DSN inválido: \"${dsn}\"`);\n }\n\n const key = url.username;\n const path = url.pathname.replace(/^\\/+/, '');\n if (!key || !path) {\n throw new Error(`${prefix} DSN inválido: \"${dsn}\" — esperado https://<key>@host/<projeto>`);\n }\n\n return { key, path, origin: `${url.protocol}//${url.host}` };\n}\n\n/** Formato: https://<publicKey>@host[:porta]/<projectId> */\nexport function parseDsn(dsn: string): ParsedDsn {\n const { key, path, origin } = parseDsnUrl(dsn, '[hobots-monitor]');\n return {\n publicKey: key,\n projectId: path,\n endpoint: `${origin}/api/ingest/${key}`,\n };\n}\n","export const SDK_NAME = 'hobots';\nexport const SDK_VERSION = '1.0.0';\n\nexport function isNode(): boolean {\n return typeof process !== 'undefined' && typeof process.versions?.node === 'string';\n}\n\n/** uuid v4 sem hífens (32 hex). Fallback para contextos sem crypto.randomUUID. */\nexport function uuid4(): string {\n const cryptoRef = (globalThis as { crypto?: Crypto }).crypto;\n if (cryptoRef && typeof cryptoRef.randomUUID === 'function') {\n return cryptoRef.randomUUID().replace(/-/g, '');\n }\n let out = '';\n for (let i = 0; i < 32; i++) {\n out += Math.floor(Math.random() * 16).toString(16);\n }\n return out;\n}\n\nexport function nowISO(): string {\n return new Date().toISOString();\n}\n\n/** Timers não devem segurar o processo Node aberto. */\nexport function unrefTimer(timer: unknown): void {\n (timer as { unref?: () => void } | undefined)?.unref?.();\n}\n\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => {\n const timer = setTimeout(resolve, ms);\n unrefTimer(timer);\n });\n}\n\nexport interface Logger {\n debug: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n}\n\nconst PREFIX = '[hobots-monitor]';\n\nexport function makeLogger(enabled: boolean, prefix: string = PREFIX): Logger {\n return {\n debug: (...args) => enabled && console.debug(prefix, ...args),\n warn: (...args) => enabled && console.warn(prefix, ...args),\n error: (...args) => console.error(prefix, ...args),\n };\n}\n"],"mappings":";AAcO,SAAS,YAAY,KAAa,QAA8B;AACrE,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,GAAG;AAAA,EACnB,QAAQ;AACN,UAAM,IAAI,MAAM,GAAG,MAAM,sBAAmB,GAAG,GAAG;AAAA,EACpD;AAEA,QAAM,MAAM,IAAI;AAChB,QAAM,OAAO,IAAI,SAAS,QAAQ,QAAQ,EAAE;AAC5C,MAAI,CAAC,OAAO,CAAC,MAAM;AACjB,UAAM,IAAI,MAAM,GAAG,MAAM,sBAAmB,GAAG,gDAA2C;AAAA,EAC5F;AAEA,SAAO,EAAE,KAAK,MAAM,QAAQ,GAAG,IAAI,QAAQ,KAAK,IAAI,IAAI,GAAG;AAC7D;AAGO,SAAS,SAAS,KAAwB;AAC/C,QAAM,EAAE,KAAK,MAAM,OAAO,IAAI,YAAY,KAAK,kBAAkB;AACjE,SAAO;AAAA,IACL,WAAW;AAAA,IACX,WAAW;AAAA,IACX,UAAU,GAAG,MAAM,eAAe,GAAG;AAAA,EACvC;AACF;;;ACvCO,IAAM,WAAW;AACjB,IAAM,cAAc;AAEpB,SAAS,SAAkB;AAChC,SAAO,OAAO,YAAY,eAAe,OAAO,QAAQ,UAAU,SAAS;AAC7E;AAGO,SAAS,QAAgB;AAC9B,QAAM,YAAa,WAAmC;AACtD,MAAI,aAAa,OAAO,UAAU,eAAe,YAAY;AAC3D,WAAO,UAAU,WAAW,EAAE,QAAQ,MAAM,EAAE;AAAA,EAChD;AACA,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,WAAO,KAAK,MAAM,KAAK,OAAO,IAAI,EAAE,EAAE,SAAS,EAAE;AAAA,EACnD;AACA,SAAO;AACT;AAEO,SAAS,SAAiB;AAC/B,UAAO,oBAAI,KAAK,GAAE,YAAY;AAChC;AAGO,SAAS,WAAW,OAAsB;AAC/C,EAAC,OAA8C,QAAQ;AACzD;AAEO,SAAS,MAAM,IAA2B;AAC/C,SAAO,IAAI,QAAQ,aAAW;AAC5B,UAAM,QAAQ,WAAW,SAAS,EAAE;AACpC,eAAW,KAAK;AAAA,EAClB,CAAC;AACH;AAQA,IAAM,SAAS;AAER,SAAS,WAAW,SAAkB,SAAiB,QAAgB;AAC5E,SAAO;AAAA,IACL,OAAO,IAAI,SAAS,WAAW,QAAQ,MAAM,QAAQ,GAAG,IAAI;AAAA,IAC5D,MAAM,IAAI,SAAS,WAAW,QAAQ,KAAK,QAAQ,GAAG,IAAI;AAAA,IAC1D,OAAO,IAAI,SAAS,QAAQ,MAAM,QAAQ,GAAG,IAAI;AAAA,EACnD;AACF;","names":[]}
|
package/dist/manager.cjs
DELETED
|
@@ -1,519 +0,0 @@
|
|
|
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/manager.ts
|
|
21
|
-
var manager_exports = {};
|
|
22
|
-
__export(manager_exports, {
|
|
23
|
-
ManagerAgent: () => ManagerAgent,
|
|
24
|
-
ManagerApi: () => ManagerApi,
|
|
25
|
-
ManagerApiError: () => ManagerApiError,
|
|
26
|
-
init: () => init,
|
|
27
|
-
parseManagerDsn: () => parseManagerDsn,
|
|
28
|
-
register: () => register,
|
|
29
|
-
start: () => start,
|
|
30
|
-
stop: () => stop
|
|
31
|
-
});
|
|
32
|
-
module.exports = __toCommonJS(manager_exports);
|
|
33
|
-
|
|
34
|
-
// src/utils.ts
|
|
35
|
-
var SDK_VERSION = "1.0.0";
|
|
36
|
-
function isNode() {
|
|
37
|
-
return typeof process !== "undefined" && typeof process.versions?.node === "string";
|
|
38
|
-
}
|
|
39
|
-
function nowISO() {
|
|
40
|
-
return (/* @__PURE__ */ new Date()).toISOString();
|
|
41
|
-
}
|
|
42
|
-
function unrefTimer(timer) {
|
|
43
|
-
timer?.unref?.();
|
|
44
|
-
}
|
|
45
|
-
function sleep(ms) {
|
|
46
|
-
return new Promise((resolve) => {
|
|
47
|
-
const timer = setTimeout(resolve, ms);
|
|
48
|
-
unrefTimer(timer);
|
|
49
|
-
});
|
|
50
|
-
}
|
|
51
|
-
var PREFIX = "[hobots-monitor]";
|
|
52
|
-
function makeLogger(enabled, prefix = PREFIX) {
|
|
53
|
-
return {
|
|
54
|
-
debug: (...args) => enabled && console.debug(prefix, ...args),
|
|
55
|
-
warn: (...args) => enabled && console.warn(prefix, ...args),
|
|
56
|
-
error: (...args) => console.error(prefix, ...args)
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// src/manager/api.ts
|
|
61
|
-
var RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
62
|
-
var ManagerApiError = class extends Error {
|
|
63
|
-
constructor(message, status) {
|
|
64
|
-
super(message);
|
|
65
|
-
this.status = status;
|
|
66
|
-
this.name = "ManagerApiError";
|
|
67
|
-
}
|
|
68
|
-
};
|
|
69
|
-
var ManagerApi = class {
|
|
70
|
-
baseUrl;
|
|
71
|
-
key;
|
|
72
|
-
logger;
|
|
73
|
-
constructor(options) {
|
|
74
|
-
this.baseUrl = options.baseUrl;
|
|
75
|
-
this.key = options.key;
|
|
76
|
-
this.logger = options.logger;
|
|
77
|
-
}
|
|
78
|
-
headers() {
|
|
79
|
-
return {
|
|
80
|
-
"content-type": "application/json",
|
|
81
|
-
authorization: `Bearer ${this.key}`
|
|
82
|
-
};
|
|
83
|
-
}
|
|
84
|
-
/** Um request só — o loop de polling é quem decide o backoff entre tentativas. */
|
|
85
|
-
async poll(request, signal) {
|
|
86
|
-
const response = await fetch(`${this.baseUrl}/poll`, {
|
|
87
|
-
method: "POST",
|
|
88
|
-
headers: this.headers(),
|
|
89
|
-
body: JSON.stringify(request),
|
|
90
|
-
signal
|
|
91
|
-
});
|
|
92
|
-
if (!response.ok) {
|
|
93
|
-
throw new ManagerApiError(`poll falhou (HTTP ${response.status})`, response.status);
|
|
94
|
-
}
|
|
95
|
-
return await response.json();
|
|
96
|
-
}
|
|
97
|
-
/**
|
|
98
|
-
* PATCH de status/logs com retry em falha de rede/5xx/429.
|
|
99
|
-
* 4xx é definitivo e vira ManagerApiError imediato (409 = run cancelada/transição inválida).
|
|
100
|
-
*/
|
|
101
|
-
async updateRun(runId, update) {
|
|
102
|
-
for (let attempt = 0; ; attempt++) {
|
|
103
|
-
let retriable;
|
|
104
|
-
try {
|
|
105
|
-
const response = await fetch(`${this.baseUrl}/runs/${encodeURIComponent(runId)}`, {
|
|
106
|
-
method: "PATCH",
|
|
107
|
-
headers: this.headers(),
|
|
108
|
-
body: JSON.stringify(update)
|
|
109
|
-
});
|
|
110
|
-
if (response.ok) return;
|
|
111
|
-
if (response.status >= 400 && response.status < 500 && response.status !== 429) {
|
|
112
|
-
throw new ManagerApiError(`update rejeitado (HTTP ${response.status})`, response.status);
|
|
113
|
-
}
|
|
114
|
-
retriable = new Error(`HTTP ${response.status}`);
|
|
115
|
-
} catch (error) {
|
|
116
|
-
if (error instanceof ManagerApiError) throw error;
|
|
117
|
-
retriable = error;
|
|
118
|
-
}
|
|
119
|
-
const delay = RETRY_DELAYS_MS[attempt];
|
|
120
|
-
if (delay === void 0) {
|
|
121
|
-
throw new Error(`update da run ${runId} descartado ap\xF3s retries: ${String(retriable)}`);
|
|
122
|
-
}
|
|
123
|
-
this.logger.warn(`falha no update da run ${runId} (${String(retriable)}), retry em ${delay}ms`);
|
|
124
|
-
await sleep(delay);
|
|
125
|
-
}
|
|
126
|
-
}
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
// src/manager/context.ts
|
|
130
|
-
var DEFAULT_LOG_FLUSH_INTERVAL_MS = 2e3;
|
|
131
|
-
var MAX_LOG_MESSAGE_CHARS = 1e4;
|
|
132
|
-
var MAX_LOGS_PER_RUN = 500;
|
|
133
|
-
var MAX_LOGS_PER_PATCH = 100;
|
|
134
|
-
var FLUSH_AT_BUFFERED = 20;
|
|
135
|
-
var MAX_RESULT_CHARS = 1e5;
|
|
136
|
-
var RunReporter = class {
|
|
137
|
-
constructor(api, runId, task, logger, flushIntervalMs) {
|
|
138
|
-
this.api = api;
|
|
139
|
-
this.runId = runId;
|
|
140
|
-
this.logger = logger;
|
|
141
|
-
this.flushIntervalMs = flushIntervalMs ?? DEFAULT_LOG_FLUSH_INTERVAL_MS;
|
|
142
|
-
this.context = {
|
|
143
|
-
runId,
|
|
144
|
-
task,
|
|
145
|
-
log: (level, message) => this.log(level, message),
|
|
146
|
-
signal: this.abortController.signal
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
context;
|
|
150
|
-
buffer = [];
|
|
151
|
-
loggedCount = 0;
|
|
152
|
-
droppedCount = 0;
|
|
153
|
-
dead = false;
|
|
154
|
-
chain = Promise.resolve();
|
|
155
|
-
timer;
|
|
156
|
-
abortController = new AbortController();
|
|
157
|
-
flushIntervalMs;
|
|
158
|
-
get isDead() {
|
|
159
|
-
return this.dead;
|
|
160
|
-
}
|
|
161
|
-
/** Aborta o ctx.signal sem matar o reporter (timeout/shutdown ainda reportam o terminal). */
|
|
162
|
-
abort() {
|
|
163
|
-
if (!this.abortController.signal.aborted) this.abortController.abort();
|
|
164
|
-
}
|
|
165
|
-
log(level, message) {
|
|
166
|
-
if (this.dead) return;
|
|
167
|
-
if (this.loggedCount >= MAX_LOGS_PER_RUN) {
|
|
168
|
-
this.droppedCount++;
|
|
169
|
-
return;
|
|
170
|
-
}
|
|
171
|
-
this.loggedCount++;
|
|
172
|
-
const truncated = message.length > MAX_LOG_MESSAGE_CHARS ? `${message.slice(0, MAX_LOG_MESSAGE_CHARS)}\u2026 [truncado]` : message;
|
|
173
|
-
this.buffer.push({ ts: nowISO(), level, message: truncated });
|
|
174
|
-
if (this.buffer.length >= FLUSH_AT_BUFFERED) {
|
|
175
|
-
this.flushLogs();
|
|
176
|
-
} else {
|
|
177
|
-
this.scheduleFlush();
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
scheduleFlush() {
|
|
181
|
-
if (this.timer) return;
|
|
182
|
-
this.timer = setTimeout(() => {
|
|
183
|
-
this.timer = void 0;
|
|
184
|
-
this.flushLogs();
|
|
185
|
-
}, this.flushIntervalMs);
|
|
186
|
-
unrefTimer(this.timer);
|
|
187
|
-
}
|
|
188
|
-
clearFlushTimer() {
|
|
189
|
-
if (this.timer) {
|
|
190
|
-
clearTimeout(this.timer);
|
|
191
|
-
this.timer = void 0;
|
|
192
|
-
}
|
|
193
|
-
}
|
|
194
|
-
takeLogs() {
|
|
195
|
-
const logs = this.buffer.splice(0, this.buffer.length);
|
|
196
|
-
if (this.droppedCount > 0) {
|
|
197
|
-
logs.push({
|
|
198
|
-
ts: nowISO(),
|
|
199
|
-
level: "warning",
|
|
200
|
-
message: `${this.droppedCount} logs descartados (limite de ${MAX_LOGS_PER_RUN} por execu\xE7\xE3o)`
|
|
201
|
-
});
|
|
202
|
-
this.droppedCount = 0;
|
|
203
|
-
}
|
|
204
|
-
return logs;
|
|
205
|
-
}
|
|
206
|
-
/** Flush incremental: envia o buffer como status 'running' (em chunks). */
|
|
207
|
-
flushLogs() {
|
|
208
|
-
this.clearFlushTimer();
|
|
209
|
-
if (this.dead || this.buffer.length === 0) return;
|
|
210
|
-
const logs = this.buffer.splice(0, this.buffer.length);
|
|
211
|
-
for (let i = 0; i < logs.length; i += MAX_LOGS_PER_PATCH) {
|
|
212
|
-
this.enqueue({ status: "running", logs: logs.slice(i, i + MAX_LOGS_PER_PATCH) });
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
/** Primeiro PATCH (claimed → running). Retorna false se a run já morreu (cancelada). */
|
|
216
|
-
async reportRunning() {
|
|
217
|
-
this.enqueue({ status: "running" });
|
|
218
|
-
await this.chain;
|
|
219
|
-
return !this.dead;
|
|
220
|
-
}
|
|
221
|
-
reportSuccess(result) {
|
|
222
|
-
this.clearFlushTimer();
|
|
223
|
-
this.enqueue({ status: "succeeded", result: serializeResult(result, this.logger), logs: this.takeLogs() });
|
|
224
|
-
}
|
|
225
|
-
reportFailure(error) {
|
|
226
|
-
this.clearFlushTimer();
|
|
227
|
-
this.enqueue({ status: "failed", error, logs: this.takeLogs() });
|
|
228
|
-
}
|
|
229
|
-
/** Aguarda a fila de PATCHes esvaziar (chame depois do terminal). */
|
|
230
|
-
finalize() {
|
|
231
|
-
return this.chain;
|
|
232
|
-
}
|
|
233
|
-
enqueue(update) {
|
|
234
|
-
if (this.dead) return;
|
|
235
|
-
this.chain = this.chain.then(async () => {
|
|
236
|
-
if (this.dead) return;
|
|
237
|
-
const payload = update.logs && update.logs.length === 0 ? { ...update, logs: void 0 } : update;
|
|
238
|
-
try {
|
|
239
|
-
await this.api.updateRun(this.runId, payload);
|
|
240
|
-
} catch (error) {
|
|
241
|
-
if (error instanceof ManagerApiError && (error.status === 409 || error.status === 404)) {
|
|
242
|
-
this.dead = true;
|
|
243
|
-
this.abort();
|
|
244
|
-
this.buffer = [];
|
|
245
|
-
this.logger.warn(`run ${this.runId} cancelada/removida no servidor \u2014 reporte suprimido`);
|
|
246
|
-
return;
|
|
247
|
-
}
|
|
248
|
-
this.logger.error(`update da run ${this.runId} perdido:`, error);
|
|
249
|
-
}
|
|
250
|
-
});
|
|
251
|
-
}
|
|
252
|
-
};
|
|
253
|
-
function serializeResult(result, logger) {
|
|
254
|
-
if (result === void 0) return void 0;
|
|
255
|
-
let json;
|
|
256
|
-
try {
|
|
257
|
-
json = JSON.stringify(result);
|
|
258
|
-
} catch {
|
|
259
|
-
logger.warn("result n\xE3o serializ\xE1vel (circular/BigInt?) \u2014 descartado");
|
|
260
|
-
return { __truncated: true, message: "resultado n\xE3o serializ\xE1vel e foi descartado pelo SDK" };
|
|
261
|
-
}
|
|
262
|
-
if (json === void 0) return void 0;
|
|
263
|
-
if (json.length > MAX_RESULT_CHARS) {
|
|
264
|
-
logger.warn(`result excede ${MAX_RESULT_CHARS} chars \u2014 descartado`);
|
|
265
|
-
return { __truncated: true, message: "resultado excede 100KB e foi descartado pelo SDK" };
|
|
266
|
-
}
|
|
267
|
-
return result;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// src/dsn.ts
|
|
271
|
-
function parseDsnUrl(dsn, prefix) {
|
|
272
|
-
let url;
|
|
273
|
-
try {
|
|
274
|
-
url = new URL(dsn);
|
|
275
|
-
} catch {
|
|
276
|
-
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}"`);
|
|
277
|
-
}
|
|
278
|
-
const key = url.username;
|
|
279
|
-
const path = url.pathname.replace(/^\/+/, "");
|
|
280
|
-
if (!key || !path) {
|
|
281
|
-
throw new Error(`${prefix} DSN inv\xE1lido: "${dsn}" \u2014 esperado https://<key>@host/<projeto>`);
|
|
282
|
-
}
|
|
283
|
-
return { key, path, origin: `${url.protocol}//${url.host}` };
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
// src/manager/dsn.ts
|
|
287
|
-
function parseManagerDsn(dsn) {
|
|
288
|
-
const { key, path, origin } = parseDsnUrl(dsn, "[hobots-manager]");
|
|
289
|
-
return {
|
|
290
|
-
key,
|
|
291
|
-
projectSlug: path,
|
|
292
|
-
origin,
|
|
293
|
-
baseUrl: `${origin}/api/manager`
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
// src/manager/agent.ts
|
|
298
|
-
var DEFAULT_POLL_INTERVAL_MS = 5e3;
|
|
299
|
-
var MIN_POLL_INTERVAL_MS = 1e3;
|
|
300
|
-
var MAX_CONCURRENCY = 5;
|
|
301
|
-
var POLL_RETRY_DELAYS_MS = [1e3, 4e3, 16e3];
|
|
302
|
-
var AUTH_FAILURE_INTERVAL_MS = 3e4;
|
|
303
|
-
function defaultAgentName() {
|
|
304
|
-
if (!isNode()) return void 0;
|
|
305
|
-
return process.env.HOSTNAME || process.env.COMPUTERNAME || void 0;
|
|
306
|
-
}
|
|
307
|
-
var ManagerAgent = class {
|
|
308
|
-
constructor(options, registry2) {
|
|
309
|
-
this.options = options;
|
|
310
|
-
this.registry = registry2;
|
|
311
|
-
this.logger = makeLogger(options.debug ?? false, "[hobots-manager]");
|
|
312
|
-
const dsn = parseManagerDsn(options.dsn);
|
|
313
|
-
this.api = new ManagerApi({ baseUrl: dsn.baseUrl, key: dsn.key, logger: this.logger });
|
|
314
|
-
this.pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
|
|
315
|
-
this.concurrency = Math.min(MAX_CONCURRENCY, Math.max(1, options.concurrency ?? 1));
|
|
316
|
-
this.agentName = options.agentName ?? defaultAgentName();
|
|
317
|
-
this.taskTimeoutMs = options.taskTimeoutMs;
|
|
318
|
-
this.logFlushIntervalMs = options.logFlushIntervalMs;
|
|
319
|
-
this.logger.debug("agente configurado", { baseUrl: dsn.baseUrl, projectSlug: dsn.projectSlug });
|
|
320
|
-
}
|
|
321
|
-
logger;
|
|
322
|
-
api;
|
|
323
|
-
pollIntervalMs;
|
|
324
|
-
concurrency;
|
|
325
|
-
agentName;
|
|
326
|
-
taskTimeoutMs;
|
|
327
|
-
logFlushIntervalMs;
|
|
328
|
-
state = "idle";
|
|
329
|
-
timer;
|
|
330
|
-
pollAbort;
|
|
331
|
-
consecutiveFailures = 0;
|
|
332
|
-
consecutiveAuthFailures = 0;
|
|
333
|
-
activeRuns = /* @__PURE__ */ new Set();
|
|
334
|
-
reporters = /* @__PURE__ */ new Set();
|
|
335
|
-
get activeCount() {
|
|
336
|
-
return this.activeRuns.size;
|
|
337
|
-
}
|
|
338
|
-
start() {
|
|
339
|
-
if (this.state === "started") return;
|
|
340
|
-
if (this.state === "stopping") {
|
|
341
|
-
throw new Error("[hobots-manager] start() chamado durante stop() \u2014 aguarde o stop terminar");
|
|
342
|
-
}
|
|
343
|
-
if (this.registry.size === 0) {
|
|
344
|
-
throw new Error("[hobots-manager] nenhuma task registrada \u2014 chame register() antes de start()");
|
|
345
|
-
}
|
|
346
|
-
this.state = "started";
|
|
347
|
-
this.logger.debug(`polling iniciado (tasks: ${[...this.registry.keys()].join(", ")})`);
|
|
348
|
-
this.schedule(0);
|
|
349
|
-
}
|
|
350
|
-
/** Para o polling e aguarda as runs ativas (até timeoutMs). Retorna true se tudo terminou a tempo. */
|
|
351
|
-
async stop(timeoutMs = 3e4) {
|
|
352
|
-
if (this.state === "idle") return true;
|
|
353
|
-
this.state = "stopping";
|
|
354
|
-
if (this.timer) {
|
|
355
|
-
clearTimeout(this.timer);
|
|
356
|
-
this.timer = void 0;
|
|
357
|
-
}
|
|
358
|
-
this.pollAbort?.abort();
|
|
359
|
-
const all = Promise.allSettled([...this.activeRuns]).then(() => true);
|
|
360
|
-
const finished = timeoutMs > 0 ? await Promise.race([all, sleep(timeoutMs).then(() => false)]) : false;
|
|
361
|
-
if (!finished && this.activeRuns.size > 0) {
|
|
362
|
-
this.logger.warn(`${this.activeRuns.size} run(s) ainda em execu\xE7\xE3o ap\xF3s ${timeoutMs}ms \u2014 abandonando a espera`);
|
|
363
|
-
for (const reporter of this.reporters) reporter.abort();
|
|
364
|
-
}
|
|
365
|
-
this.state = "idle";
|
|
366
|
-
return finished;
|
|
367
|
-
}
|
|
368
|
-
/** Timer intencionalmente NÃO unref'd: o agente é a razão do processo existir. */
|
|
369
|
-
schedule(delayMs) {
|
|
370
|
-
if (this.state !== "started" || this.timer) return;
|
|
371
|
-
this.timer = setTimeout(() => {
|
|
372
|
-
this.timer = void 0;
|
|
373
|
-
void this.tick();
|
|
374
|
-
}, delayMs);
|
|
375
|
-
}
|
|
376
|
-
async tick() {
|
|
377
|
-
if (this.state !== "started") return;
|
|
378
|
-
if (this.activeRuns.size >= this.concurrency) {
|
|
379
|
-
this.schedule(this.pollIntervalMs);
|
|
380
|
-
return;
|
|
381
|
-
}
|
|
382
|
-
this.pollAbort = new AbortController();
|
|
383
|
-
try {
|
|
384
|
-
const response = await this.api.poll(
|
|
385
|
-
{
|
|
386
|
-
agent: {
|
|
387
|
-
name: this.agentName,
|
|
388
|
-
version: SDK_VERSION,
|
|
389
|
-
host: defaultAgentName(),
|
|
390
|
-
tasks: [...this.registry.keys()]
|
|
391
|
-
},
|
|
392
|
-
max: Math.min(MAX_CONCURRENCY, this.concurrency - this.activeRuns.size),
|
|
393
|
-
tasks: [...this.registry.keys()]
|
|
394
|
-
},
|
|
395
|
-
this.pollAbort.signal
|
|
396
|
-
);
|
|
397
|
-
this.consecutiveFailures = 0;
|
|
398
|
-
this.consecutiveAuthFailures = 0;
|
|
399
|
-
for (const run of response.runs) {
|
|
400
|
-
this.dispatch(run);
|
|
401
|
-
}
|
|
402
|
-
this.schedule(response.runs.length > 0 ? 0 : this.pollIntervalMs);
|
|
403
|
-
} catch (error) {
|
|
404
|
-
if (this.state !== "started") return;
|
|
405
|
-
this.schedule(this.delayAfterPollError(error));
|
|
406
|
-
} finally {
|
|
407
|
-
this.pollAbort = void 0;
|
|
408
|
-
}
|
|
409
|
-
}
|
|
410
|
-
delayAfterPollError(error) {
|
|
411
|
-
if (error instanceof ManagerApiError && error.status === 401) {
|
|
412
|
-
this.consecutiveAuthFailures++;
|
|
413
|
-
if (this.consecutiveAuthFailures === 1 || this.consecutiveAuthFailures % 10 === 0) {
|
|
414
|
-
this.logger.error("chave do agente rejeitada (401) \u2014 verifique a chave em /manager/agents");
|
|
415
|
-
}
|
|
416
|
-
return Math.max(this.pollIntervalMs, AUTH_FAILURE_INTERVAL_MS);
|
|
417
|
-
}
|
|
418
|
-
this.consecutiveFailures++;
|
|
419
|
-
const ladder = POLL_RETRY_DELAYS_MS[Math.min(this.consecutiveFailures - 1, POLL_RETRY_DELAYS_MS.length - 1)];
|
|
420
|
-
const delay = Math.min(Math.max(ladder, 0), Math.max(this.pollIntervalMs, 16e3));
|
|
421
|
-
this.logger.warn(`poll falhou (${String(error)}), pr\xF3xima tentativa em ${delay}ms`);
|
|
422
|
-
return delay;
|
|
423
|
-
}
|
|
424
|
-
dispatch(run) {
|
|
425
|
-
const promise = this.executeRun(run).catch((error) => this.logger.error(`erro inesperado na run ${run.id}:`, error)).finally(() => {
|
|
426
|
-
this.activeRuns.delete(promise);
|
|
427
|
-
if (this.state === "started") this.schedule(0);
|
|
428
|
-
});
|
|
429
|
-
this.activeRuns.add(promise);
|
|
430
|
-
}
|
|
431
|
-
async executeRun(run) {
|
|
432
|
-
const reporter = new RunReporter(this.api, run.id, run.task, this.logger, this.logFlushIntervalMs);
|
|
433
|
-
this.reporters.add(reporter);
|
|
434
|
-
try {
|
|
435
|
-
const handler = this.registry.get(run.task);
|
|
436
|
-
if (!handler) {
|
|
437
|
-
reporter.reportFailure({
|
|
438
|
-
type: "HandlerNotFound",
|
|
439
|
-
message: `tarefa n\xE3o registrada no agente: ${run.task}`
|
|
440
|
-
});
|
|
441
|
-
await reporter.finalize();
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
const ok = await reporter.reportRunning();
|
|
445
|
-
if (!ok) {
|
|
446
|
-
this.logger.debug(`run ${run.id} cancelada antes de iniciar \u2014 handler n\xE3o executado`);
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
this.logger.debug(`executando run ${run.id} (${run.task})`);
|
|
450
|
-
try {
|
|
451
|
-
const result = await this.invokeWithTimeout(handler, run, reporter);
|
|
452
|
-
reporter.reportSuccess(result);
|
|
453
|
-
this.logger.debug(`run ${run.id} conclu\xEDda`);
|
|
454
|
-
} catch (error) {
|
|
455
|
-
reporter.reportFailure(toRunError(error));
|
|
456
|
-
this.logger.debug(`run ${run.id} falhou: ${String(error)}`);
|
|
457
|
-
}
|
|
458
|
-
await reporter.finalize();
|
|
459
|
-
} finally {
|
|
460
|
-
this.reporters.delete(reporter);
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
async invokeWithTimeout(handler, run, reporter) {
|
|
464
|
-
const invocation = Promise.resolve().then(() => handler(run.params, reporter.context));
|
|
465
|
-
if (!this.taskTimeoutMs || this.taskTimeoutMs <= 0) return invocation;
|
|
466
|
-
const timeoutMs = this.taskTimeoutMs;
|
|
467
|
-
const timeout = sleep(timeoutMs).then(() => TIMEOUT_SENTINEL);
|
|
468
|
-
const outcome = await Promise.race([invocation, timeout]);
|
|
469
|
-
if (outcome !== TIMEOUT_SENTINEL) return outcome;
|
|
470
|
-
reporter.abort();
|
|
471
|
-
invocation.then(() => this.logger.warn(`run ${run.id} terminou depois do timeout de ${timeoutMs}ms (resultado descartado)`)).catch(() => this.logger.warn(`run ${run.id} falhou depois do timeout de ${timeoutMs}ms (erro descartado)`));
|
|
472
|
-
throw Object.assign(new Error(`timeout ap\xF3s ${timeoutMs}ms (o handler pode continuar em background)`), {
|
|
473
|
-
name: "TaskTimeout"
|
|
474
|
-
});
|
|
475
|
-
}
|
|
476
|
-
};
|
|
477
|
-
var TIMEOUT_SENTINEL = /* @__PURE__ */ Symbol("task-timeout");
|
|
478
|
-
var MAX_ERROR_MESSAGE_CHARS = 1e4;
|
|
479
|
-
var MAX_ERROR_STACK_CHARS = 2e4;
|
|
480
|
-
function truncate(value, max) {
|
|
481
|
-
return value.length > max ? `${value.slice(0, max)}\u2026 [truncado]` : value;
|
|
482
|
-
}
|
|
483
|
-
function toRunError(error) {
|
|
484
|
-
if (error instanceof Error) {
|
|
485
|
-
return {
|
|
486
|
-
type: error.name,
|
|
487
|
-
message: truncate(error.message, MAX_ERROR_MESSAGE_CHARS),
|
|
488
|
-
stack: error.stack ? truncate(error.stack, MAX_ERROR_STACK_CHARS) : void 0
|
|
489
|
-
};
|
|
490
|
-
}
|
|
491
|
-
return { message: truncate(String(error), MAX_ERROR_MESSAGE_CHARS) };
|
|
492
|
-
}
|
|
493
|
-
|
|
494
|
-
// src/manager/core.ts
|
|
495
|
-
var agent;
|
|
496
|
-
var registry = /* @__PURE__ */ new Map();
|
|
497
|
-
function init(options) {
|
|
498
|
-
if (agent) {
|
|
499
|
-
agent.logger.warn("init() chamado mais de uma vez \u2014 substituindo o agente anterior");
|
|
500
|
-
void agent.stop(0);
|
|
501
|
-
}
|
|
502
|
-
agent = new ManagerAgent(options, registry);
|
|
503
|
-
}
|
|
504
|
-
function register(task, handler) {
|
|
505
|
-
if (registry.has(task)) {
|
|
506
|
-
agent?.logger.warn(`register('${task}') sobrescreveu um handler existente`);
|
|
507
|
-
}
|
|
508
|
-
registry.set(task, handler);
|
|
509
|
-
}
|
|
510
|
-
function start() {
|
|
511
|
-
if (!agent) {
|
|
512
|
-
throw new Error("[hobots-manager] init() precisa ser chamado antes de start()");
|
|
513
|
-
}
|
|
514
|
-
agent.start();
|
|
515
|
-
}
|
|
516
|
-
function stop(timeoutMs) {
|
|
517
|
-
return agent ? agent.stop(timeoutMs) : Promise.resolve(true);
|
|
518
|
-
}
|
|
519
|
-
//# sourceMappingURL=manager.cjs.map
|