@brickkit/core 0.16.0-beta.4 → 0.16.0-beta.5

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.
@@ -2,7 +2,7 @@ import { A as STANDARD_ERRORS, B as signSeq, C as actionMeta, D as SOCKET_MAX_BY
2
2
  import { createRequire } from "node:module";
3
3
  import { AsyncLocalStorage } from "node:async_hooks";
4
4
  import { format, formatWithOptions, inspect } from "node:util";
5
- import { SpanKind, SpanStatusCode, context, propagation, trace } from "@opentelemetry/api";
5
+ import { SpanKind, SpanStatusCode, context, isSpanContextValid, propagation, trace } from "@opentelemetry/api";
6
6
  import { Kind, Type as Type$1, TypeRegistry } from "@sinclair/typebox";
7
7
  import { TypeCompiler } from "@sinclair/typebox/compiler";
8
8
  import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
@@ -471,7 +471,36 @@ function withSpan(name, attributes, fn, kind = SpanKind.INTERNAL) {
471
471
  * already traced. Calls made outside instrumented requests run unchanged.
472
472
  */
473
473
  function withCallSpan(name, attributes, fn) {
474
- return trace.getActiveSpan() ? withSpan(name, attributes, fn) : fn();
474
+ return inTrace() ? withSpan(name, attributes, fn) : fn();
475
+ }
476
+ /**
477
+ * Whether a child span would join a trace: the active span is recording and
478
+ * has a valid context. A non-recording span, such as one from a tracer that
479
+ * never got the registered provider, would make each child a root trace.
480
+ */
481
+ function inTrace() {
482
+ const span = trace.getActiveSpan();
483
+ return Boolean(span?.isRecording()) && isSpanContextValid(span.spanContext());
484
+ }
485
+ /**
486
+ * Run one try of a schedule as a root span, `schedule <name>`, so the SQL,
487
+ * fetch calls and log lines of the run share its trace. Never a child of
488
+ * whatever context started the tick, such as the request that triggered it.
489
+ */
490
+ function traceScheduleRun(run, fn) {
491
+ return trace.getTracer(INSTRUMENTATION_SCOPE).startActiveSpan(`schedule ${run.schedule}`, {
492
+ root: true,
493
+ attributes: {
494
+ [ATTR.schedule]: run.schedule,
495
+ [ATTR.scheduleTrigger]: run.trigger,
496
+ [ATTR.scheduleAttempt]: run.attempt,
497
+ [ATTR.scheduleSlot]: run.slot
498
+ }
499
+ }, (span) => settle(fn, (outcome) => {
500
+ span.setAttribute(ATTR.scheduleOutcome, outcome.failed ? "failed" : "succeeded");
501
+ if (outcome.failed) recordThrown(span, outcome.error);
502
+ span.end();
503
+ }));
475
504
  }
476
505
  /**
477
506
  * Wrap a raw route handler so each of its requests gets a server span. Use it
@@ -577,7 +606,7 @@ function instrumentFetch() {
577
606
  get: (target, key) => key === FETCH_INSTRUMENTED ? true : Reflect.get(target, key),
578
607
  apply(target, self, args) {
579
608
  const [input, init] = args;
580
- if (!trace.getActiveSpan()) return Reflect.apply(target, self, args);
609
+ if (!inTrace()) return Reflect.apply(target, self, args);
581
610
  let url;
582
611
  try {
583
612
  url = new URL(input instanceof Request ? input.url : String(input));
@@ -637,7 +666,7 @@ function instrumentPostgres(client) {
637
666
  const unsafe = client.unsafe.bind(client);
638
667
  client.unsafe = (sql, ...rest) => {
639
668
  const query = unsafe(sql, ...rest);
640
- if (!trace.getActiveSpan() || typeof query?.then !== "function") return query;
669
+ if (!inTrace() || typeof query?.then !== "function") return query;
641
670
  const span = startStatementSpan(sql, "postgresql");
642
671
  let finished = false;
643
672
  const finish = (outcome) => {
@@ -665,7 +694,7 @@ function instrumentPostgres(client) {
665
694
  };
666
695
  }
667
696
  function recordStatement(sql, system, fn) {
668
- if (!trace.getActiveSpan()) return fn();
697
+ if (!inTrace()) return fn();
669
698
  return withSpan(statementName(sql), statementAttributes(sql, system), fn, SpanKind.CLIENT);
670
699
  }
671
700
  function startStatementSpan(sql, system) {
@@ -6070,6 +6099,7 @@ async function stopAllEvents() {
6070
6099
  */
6071
6100
  var EventsHub = class {
6072
6101
  deps;
6102
+ telemetry;
6073
6103
  byName = /* @__PURE__ */ new Map();
6074
6104
  dispatchers = /* @__PURE__ */ new Map();
6075
6105
  deliverables = /* @__PURE__ */ new Map();
@@ -6084,9 +6114,11 @@ var EventsHub = class {
6084
6114
  * @param options - The `events` option.
6085
6115
  * @param deps - The deps of the app's services, which `useDeps()` returns in
6086
6116
  * its listeners, schedules and workflow steps.
6117
+ * @param telemetry - Trace each schedule run, as `brick({ telemetry })` does requests.
6087
6118
  */
6088
- constructor(options, deps = {}) {
6119
+ constructor(options, deps = {}, telemetry = false) {
6089
6120
  this.deps = deps;
6121
+ this.telemetry = telemetry;
6090
6122
  for (const listener of options.listeners ?? []) {
6091
6123
  validateListener(listener);
6092
6124
  if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
@@ -6176,7 +6208,10 @@ var EventsHub = class {
6176
6208
  if (found.size !== 1) throw new Error(found.size ? "Brick: schedules need exactly one scheduleTable(), but several databases hold one." : "Brick: schedules keep their state in a scheduleTable(), and no service database holds one. Add scheduleTable() to a database's tables.");
6177
6209
  const [[table, db]] = [...found];
6178
6210
  const options = this.dispatchOptions || {};
6179
- this.scheduler = new Scheduler(db, table, this.scheduleList, (schedule, run) => schedule.workflow ? this.runtime.startScheduled(schedule, run) : runWithDeps(this.deps, async () => schedule.run(run)), {
6211
+ this.scheduler = new Scheduler(db, table, this.scheduleList, (schedule, run) => {
6212
+ const start = () => schedule.workflow ? this.runtime.startScheduled(schedule, run) : runWithDeps(this.deps, async () => schedule.run(run));
6213
+ return this.telemetry ? traceScheduleRun(run, start) : start();
6214
+ }, {
6180
6215
  timer: options.timer ?? true,
6181
6216
  intervalMs: options.intervalMs ?? 1e3,
6182
6217
  claimTimeoutMs: options.claimTimeoutMs ?? 6e4
@@ -6924,7 +6959,7 @@ function brick(options = {}) {
6924
6959
  ...options.events,
6925
6960
  listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
6926
6961
  } : options.events;
6927
- const events = eventsOptions ? new EventsHub(eventsOptions, appDeps(services)).attach(services) : void 0;
6962
+ const events = eventsOptions ? new EventsHub(eventsOptions, appDeps(services), telemetry).attach(services) : void 0;
6928
6963
  if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
6929
6964
  if (telemetry) {
6930
6965
  for (const service of services) instrumentDatabase(service.getDb());