hobots 1.3.5 → 1.5.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/dist/index.js CHANGED
@@ -58,7 +58,7 @@ function parseStacktrace(stack) {
58
58
 
59
59
  // src/utils.ts
60
60
  var SDK_NAME = "hobots";
61
- var SDK_VERSION = true ? "1.3.4" : "0.0.0-dev";
61
+ var SDK_VERSION = true ? "1.5.0" : "0.0.0-dev";
62
62
  function isNode() {
63
63
  return typeof process !== "undefined" && typeof process.versions?.node === "string";
64
64
  }
@@ -88,11 +88,26 @@ function sleep(ms) {
88
88
  var PREFIX = "[hobots-monitor]";
89
89
  function makeLogger(enabled, prefix = PREFIX) {
90
90
  return {
91
- debug: (...args) => enabled && console.debug(prefix, ...args),
92
- warn: (...args) => enabled && console.warn(prefix, ...args),
93
- error: (...args) => console.error(prefix, ...args)
91
+ debug: (...args) => enabled && console.debug(colorize(prefix, "gray"), ...args),
92
+ warn: (...args) => enabled && console.warn(colorize(prefix, "yellow"), ...args),
93
+ error: (...args) => console.error(colorize(prefix, "red"), ...args)
94
94
  };
95
95
  }
96
+ var ANSI = {
97
+ reset: "\x1B[0m",
98
+ gray: "\x1B[90m",
99
+ cyan: "\x1B[36m",
100
+ yellow: "\x1B[33m",
101
+ red: "\x1B[31m"
102
+ };
103
+ function colorEnabled() {
104
+ if (!isNode()) return false;
105
+ return Boolean(process.stdout?.isTTY) && !process.env.NO_COLOR;
106
+ }
107
+ function colorize(text, color) {
108
+ if (!colorEnabled()) return text;
109
+ return `${ANSI[color]}${text}${ANSI.reset}`;
110
+ }
96
111
 
97
112
  // src/eventbuilder.ts
98
113
  function safeString(value) {
@@ -564,11 +579,12 @@ var Span = class {
564
579
  }
565
580
  };
566
581
  var Transaction = class {
567
- constructor(client2, name, op, sampled = true) {
582
+ constructor(client2, name, op, sampled = true, runId) {
568
583
  this.client = client2;
569
584
  this.name = name;
570
585
  this.op = op;
571
586
  this.sampled = sampled;
587
+ this.runId = runId;
572
588
  }
573
589
  eventId = uuid4();
574
590
  spanId = spanId();
@@ -611,7 +627,8 @@ var Transaction = class {
611
627
  start_timestamp: this.startTimestamp,
612
628
  timestamp: nowISO(),
613
629
  spans: this.spans.map((span) => span.toJSON()),
614
- tags: Object.keys(this.tags).length > 0 ? this.tags : void 0
630
+ tags: Object.keys(this.tags).length > 0 ? this.tags : void 0,
631
+ run_id: this.runId
615
632
  };
616
633
  this.client.sendTransaction(payload);
617
634
  }
@@ -746,6 +763,17 @@ var ManagerApi = class {
746
763
  };
747
764
 
748
765
  // src/manager/context.ts
766
+ var LOG_LEVEL_COLOR = {
767
+ debug: "gray",
768
+ info: "cyan",
769
+ warning: "yellow",
770
+ error: "red"
771
+ };
772
+ function printRunLog(task, level, message) {
773
+ const line = colorize(`[hobots:${task}] ${level.toUpperCase()}`, LOG_LEVEL_COLOR[level]);
774
+ const method = level === "warning" ? "warn" : level;
775
+ console[method](line, message);
776
+ }
749
777
  function runCanceledError() {
750
778
  return Object.assign(new Error("execu\xE7\xE3o cancelada"), { name: "RunCanceled" });
751
779
  }
@@ -775,7 +803,7 @@ var MAX_LOGS_PER_RUN = 500;
775
803
  var MAX_LOGS_PER_PATCH = 100;
776
804
  var FLUSH_AT_BUFFERED = 20;
777
805
  var RunReporter = class {
778
- constructor(api, runId, task, logger, flushIntervalMs, cancelCheckIntervalMs) {
806
+ constructor(api, runId, task, logger, tx, flushIntervalMs, cancelCheckIntervalMs) {
779
807
  this.api = api;
780
808
  this.runId = runId;
781
809
  this.logger = logger;
@@ -795,6 +823,7 @@ var RunReporter = class {
795
823
  runId,
796
824
  task,
797
825
  log,
826
+ tx,
798
827
  signal,
799
828
  throwIfCanceled: () => {
800
829
  if (signal.aborted) throw runCanceledError();
@@ -835,6 +864,7 @@ var RunReporter = class {
835
864
  }
836
865
  log(level, message) {
837
866
  if (this.dead) return;
867
+ printRunLog(this.context.task, level, message);
838
868
  if (this.loggedCount >= MAX_LOGS_PER_RUN) {
839
869
  this.droppedCount++;
840
870
  return;
@@ -948,6 +978,24 @@ var RunReporter = class {
948
978
  }
949
979
  };
950
980
 
981
+ // src/manager/run-context-store.ts
982
+ var storage;
983
+ var initPromise;
984
+ async function ensureStorage() {
985
+ if (storage || !isNode()) return;
986
+ initPromise ??= import("async_hooks").then(({ AsyncLocalStorage: ALS }) => {
987
+ storage = new ALS();
988
+ });
989
+ await initPromise;
990
+ }
991
+ async function runWithRunId(runId, fn) {
992
+ await ensureStorage();
993
+ return storage ? storage.run({ runId }, fn) : fn();
994
+ }
995
+ function currentRunId() {
996
+ return storage?.getStore()?.runId;
997
+ }
998
+
951
999
  // src/manager/shutdown.ts
952
1000
  var WATCHED_SIGNALS = ["SIGINT", "SIGTERM"];
953
1001
  function installShutdownHandlers(agent2) {
@@ -1009,6 +1057,7 @@ var ManagerAgent = class {
1009
1057
  this.logger = makeLogger(options.debug ?? false, "[hobots-manager]");
1010
1058
  const config = resolveConfig(options, "[hobots-manager]");
1011
1059
  this.api = new ManagerApi({ baseUrl: config.managerBaseUrl, key: config.key, logger: this.logger });
1060
+ this.client = options.client;
1012
1061
  this.pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
1013
1062
  this.concurrency = Math.min(MAX_CONCURRENCY, Math.max(1, options.concurrency ?? 1));
1014
1063
  this.instanceId = options.instanceId;
@@ -1019,6 +1068,7 @@ var ManagerAgent = class {
1019
1068
  }
1020
1069
  logger;
1021
1070
  api;
1071
+ client;
1022
1072
  pollIntervalMs;
1023
1073
  concurrency;
1024
1074
  instanceId;
@@ -1156,7 +1206,8 @@ var ManagerAgent = class {
1156
1206
  this.activeRuns.add(promise);
1157
1207
  }
1158
1208
  async executeRun(run) {
1159
- const reporter = new RunReporter(this.api, run.id, run.task, this.logger, this.logFlushIntervalMs, this.cancelCheckIntervalMs);
1209
+ const tx = new Transaction(this.client, `run:${run.task}`, "manager.run", true, run.id);
1210
+ const reporter = new RunReporter(this.api, run.id, run.task, this.logger, tx, this.logFlushIntervalMs, this.cancelCheckIntervalMs);
1160
1211
  this.reporters.add(reporter);
1161
1212
  try {
1162
1213
  const handler = this.registry.get(run.task);
@@ -1166,22 +1217,29 @@ var ManagerAgent = class {
1166
1217
  message: `tarefa n\xE3o registrada no agente: ${run.task}`
1167
1218
  });
1168
1219
  await reporter.finalize();
1220
+ tx.setStatus("error");
1221
+ tx.finish();
1169
1222
  return;
1170
1223
  }
1171
1224
  const ok = await reporter.reportRunning();
1172
1225
  if (!ok) {
1173
1226
  this.logger.debug(`run ${run.id} cancelada antes de iniciar \u2014 handler n\xE3o executado`);
1227
+ tx.setStatus("cancelled");
1228
+ tx.finish();
1174
1229
  return;
1175
1230
  }
1176
1231
  this.logger.debug(`executando run ${run.id} (${run.task})`);
1177
1232
  try {
1178
- await this.invokeWithTimeout(handler, run, reporter);
1233
+ await runWithRunId(run.id, () => this.invokeWithTimeout(handler, run, reporter));
1179
1234
  reporter.reportSuccess();
1235
+ tx.setStatus("ok");
1180
1236
  this.logger.debug(`run ${run.id} conclu\xEDda`);
1181
1237
  } catch (error) {
1182
1238
  reporter.reportFailure(toRunError(error));
1239
+ tx.setStatus("error");
1183
1240
  this.logger.debug(`run ${run.id} falhou: ${String(error)}`);
1184
1241
  }
1242
+ tx.finish();
1185
1243
  await reporter.finalize();
1186
1244
  } finally {
1187
1245
  this.reporters.delete(reporter);
@@ -1252,7 +1310,7 @@ function init(options) {
1252
1310
  if (options.manager) {
1253
1311
  const managerOptions = options.manager === true ? {} : options.manager;
1254
1312
  agent = new ManagerAgent(
1255
- { ...managerOptions, clientSecret: options.clientSecret, instanceId: options.instanceId, debug: options.debug },
1313
+ { ...managerOptions, clientSecret: options.clientSecret, instanceId: options.instanceId, debug: options.debug, client },
1256
1314
  registry
1257
1315
  );
1258
1316
  }
@@ -1297,7 +1355,7 @@ function withScope(callback) {
1297
1355
  function startTransaction(name, op) {
1298
1356
  const rate = client?.options.tracesSampleRate ?? 1;
1299
1357
  const sampled = rate >= 1 || Math.random() < rate;
1300
- return new Transaction(client, name, op, sampled);
1358
+ return new Transaction(client, name, op, sampled, currentRunId());
1301
1359
  }
1302
1360
  function checkIn(options) {
1303
1361
  return client ? sendCheckIn(client, options) : void 0;