@brickkit/core 0.16.0-beta.3 → 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";
@@ -449,6 +449,7 @@ const INSTRUMENTATION_SCOPE = "@brickkit/core";
449
449
  const MAX_TEXT_LENGTH = 500;
450
450
  const MAX_STATEMENT_LENGTH = 2e3;
451
451
  const DATABASE_INSTRUMENTED = Symbol.for("brickkit.telemetry.database");
452
+ const FETCH_INSTRUMENTED = Symbol.for("brickkit.telemetry.fetch");
452
453
  const SQLITE_STATEMENT_METHODS = [
453
454
  "all",
454
455
  "get",
@@ -470,7 +471,36 @@ function withSpan(name, attributes, fn, kind = SpanKind.INTERNAL) {
470
471
  * already traced. Calls made outside instrumented requests run unchanged.
471
472
  */
472
473
  function withCallSpan(name, attributes, fn) {
473
- 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
+ }));
474
504
  }
475
505
  /**
476
506
  * Wrap a raw route handler so each of its requests gets a server span. Use it
@@ -569,6 +599,53 @@ function instrumentDatabase(db) {
569
599
  else return;
570
600
  driver[DATABASE_INSTRUMENTED] = true;
571
601
  }
602
+ function instrumentFetch() {
603
+ const original = globalThis.fetch;
604
+ if (original[FETCH_INSTRUMENTED]) return;
605
+ const wrapped = new Proxy(original, {
606
+ get: (target, key) => key === FETCH_INSTRUMENTED ? true : Reflect.get(target, key),
607
+ apply(target, self, args) {
608
+ const [input, init] = args;
609
+ if (!inTrace()) return Reflect.apply(target, self, args);
610
+ let url;
611
+ try {
612
+ url = new URL(input instanceof Request ? input.url : String(input));
613
+ } catch {
614
+ return Reflect.apply(target, self, args);
615
+ }
616
+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();
617
+ const span = trace.getTracer(INSTRUMENTATION_SCOPE).startSpan(truncate(redactText(`${method} ${url.host}${url.pathname}`)), {
618
+ kind: SpanKind.CLIENT,
619
+ attributes: {
620
+ [ATTR.httpMethod]: method,
621
+ [ATTR.urlFull]: truncate(redactText(`${url.origin}${url.pathname}`)),
622
+ [ATTR.serverAddress]: url.hostname
623
+ }
624
+ }, context.active());
625
+ const fail = (error) => {
626
+ recordThrown(span, error);
627
+ span.end();
628
+ throw error;
629
+ };
630
+ let pending;
631
+ try {
632
+ pending = Reflect.apply(target, self, args);
633
+ } catch (error) {
634
+ return fail(error);
635
+ }
636
+ return pending.then((response) => {
637
+ span.setAttribute(ATTR.httpStatus, response.status);
638
+ if (response.status >= 400) span.setStatus({
639
+ code: SpanStatusCode.ERROR,
640
+ message: `HTTP ${response.status}`
641
+ });
642
+ span.end();
643
+ return response;
644
+ }, fail);
645
+ }
646
+ });
647
+ globalThis.fetch = wrapped;
648
+ }
572
649
  function instrumentBunSqlite(client) {
573
650
  const prepare = client.prepare.bind(client);
574
651
  client.prepare = (sql) => {
@@ -589,7 +666,7 @@ function instrumentPostgres(client) {
589
666
  const unsafe = client.unsafe.bind(client);
590
667
  client.unsafe = (sql, ...rest) => {
591
668
  const query = unsafe(sql, ...rest);
592
- if (!trace.getActiveSpan() || typeof query?.then !== "function") return query;
669
+ if (!inTrace() || typeof query?.then !== "function") return query;
593
670
  const span = startStatementSpan(sql, "postgresql");
594
671
  let finished = false;
595
672
  const finish = (outcome) => {
@@ -617,7 +694,7 @@ function instrumentPostgres(client) {
617
694
  };
618
695
  }
619
696
  function recordStatement(sql, system, fn) {
620
- if (!trace.getActiveSpan()) return fn();
697
+ if (!inTrace()) return fn();
621
698
  return withSpan(statementName(sql), statementAttributes(sql, system), fn, SpanKind.CLIENT);
622
699
  }
623
700
  function startStatementSpan(sql, system) {
@@ -6022,6 +6099,7 @@ async function stopAllEvents() {
6022
6099
  */
6023
6100
  var EventsHub = class {
6024
6101
  deps;
6102
+ telemetry;
6025
6103
  byName = /* @__PURE__ */ new Map();
6026
6104
  dispatchers = /* @__PURE__ */ new Map();
6027
6105
  deliverables = /* @__PURE__ */ new Map();
@@ -6036,9 +6114,11 @@ var EventsHub = class {
6036
6114
  * @param options - The `events` option.
6037
6115
  * @param deps - The deps of the app's services, which `useDeps()` returns in
6038
6116
  * its listeners, schedules and workflow steps.
6117
+ * @param telemetry - Trace each schedule run, as `brick({ telemetry })` does requests.
6039
6118
  */
6040
- constructor(options, deps = {}) {
6119
+ constructor(options, deps = {}, telemetry = false) {
6041
6120
  this.deps = deps;
6121
+ this.telemetry = telemetry;
6042
6122
  for (const listener of options.listeners ?? []) {
6043
6123
  validateListener(listener);
6044
6124
  if (this.byName.has(listener.name)) throw new DuplicateNameError(`Duplicate event listener '${listener.name}'`);
@@ -6128,7 +6208,10 @@ var EventsHub = class {
6128
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.");
6129
6209
  const [[table, db]] = [...found];
6130
6210
  const options = this.dispatchOptions || {};
6131
- 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
+ }, {
6132
6215
  timer: options.timer ?? true,
6133
6216
  intervalMs: options.intervalMs ?? 1e3,
6134
6217
  claimTimeoutMs: options.claimTimeoutMs ?? 6e4
@@ -6876,9 +6959,12 @@ function brick(options = {}) {
6876
6959
  ...options.events,
6877
6960
  listeners: [...options.events?.listeners ?? [], ...plugins.listeners]
6878
6961
  } : options.events;
6879
- 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;
6880
6963
  if (events?.workflows) app.all(WEBHOOK_ROUTE, ({ request }) => events.webhook(request));
6881
- if (telemetry) for (const service of services) instrumentDatabase(service.getDb());
6964
+ if (telemetry) {
6965
+ for (const service of services) instrumentDatabase(service.getDb());
6966
+ instrumentFetch();
6967
+ }
6882
6968
  for (const service of services) service.build();
6883
6969
  for (const service of services) checkFileStorages(service, [portOf(service).deps, ...installedPlugins(service).map(pluginDepsOf)]);
6884
6970
  const localDirs = localFileDirs([...services.map((service) => portOf(service).deps), ...plugins.deps]);