@osfactory/otel-hook 0.7.0 → 0.9.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/telemetry.js CHANGED
@@ -1,27 +1,7 @@
1
1
  // src/telemetry/semconv.ts
2
2
  import { createHash } from "crypto";
3
3
  import { SpanKind, SpanStatusCode, TraceFlags } from "@opentelemetry/api";
4
-
5
- // node_modules/@opentelemetry/core/build/esm/common/time.js
6
- var NANOSECOND_DIGITS = 9;
7
- var NANOSECOND_DIGITS_IN_MILLIS = 6;
8
- var MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);
9
- var SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);
10
- function millisToHrTime(epochMillis) {
11
- const epochSeconds = epochMillis / 1e3;
12
- const seconds = Math.trunc(epochSeconds);
13
- const nanos = Math.round(epochMillis % 1e3 * MILLISECONDS_TO_NANOSECONDS);
14
- return [seconds, nanos];
15
- }
16
-
17
- // node_modules/@opentelemetry/core/build/esm/ExportResult.js
18
- var ExportResultCode;
19
- (function(ExportResultCode2) {
20
- ExportResultCode2[ExportResultCode2["SUCCESS"] = 0] = "SUCCESS";
21
- ExportResultCode2[ExportResultCode2["FAILED"] = 1] = "FAILED";
22
- })(ExportResultCode || (ExportResultCode = {}));
23
-
24
- // src/telemetry/semconv.ts
4
+ import { millisToHrTime } from "@opentelemetry/core";
25
5
  import {
26
6
  ATTR_ERROR_TYPE,
27
7
  ATTR_GEN_AI_OPERATION_NAME,
@@ -38,7 +18,7 @@ import {
38
18
  } from "@opentelemetry/semantic-conventions/incubating";
39
19
 
40
20
  // src/version.ts
41
- var VERSION = "0.7.0";
21
+ var VERSION = "0.9.0";
42
22
 
43
23
  // src/telemetry/export-identity.ts
44
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -851,10 +831,13 @@ var targetAttributes = (event2) => {
851
831
  };
852
832
  var usageTemporalityAttributes = (usage) => usage === void 0 ? {} : { [ATTR_OTELHOOK_USAGE_TEMPORALITY]: usage.temporality };
853
833
  var isPrimitiveAttribute = (value) => typeof value === "string" || typeof value === "number" || typeof value === "boolean";
854
- var passthroughHarAttributes = (resource) => {
834
+ var PASSTHROUGH_RESOURCE_PREFIXES = Object.freeze(["har.", "factory.", "vcs."]);
835
+ var LOCAL_ONLY_RESOURCE_PREFIX = "factory.local.";
836
+ var isPassthroughKey = (key) => PASSTHROUGH_RESOURCE_PREFIXES.some((prefix) => key.startsWith(prefix)) && !key.startsWith(LOCAL_ONLY_RESOURCE_PREFIX) && key !== "factory.local";
837
+ var passthroughResourceAttributes = (resource) => {
855
838
  const attributes = {};
856
839
  for (const [key, value] of Object.entries(resource.attributes)) {
857
- if (key.startsWith("har.") && isPrimitiveAttribute(value)) {
840
+ if (isPassthroughKey(key) && isPrimitiveAttribute(value)) {
858
841
  attributes[key] = value;
859
842
  }
860
843
  }
@@ -888,7 +871,7 @@ var exportIdentityAttributes = (event2, resource, ids) => {
888
871
  ...event2.provenance.providerVersion === void 0 ? {} : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event2.provenance.providerVersion },
889
872
  [ATTR_OTELHOOK_WORKSPACE_ID]: event2.workspace.workspaceId,
890
873
  ...event2.subagentId === void 0 ? {} : { [ATTR_OTELHOOK_SUBAGENT_ID]: event2.subagentId },
891
- ...passthroughHarAttributes(resource),
874
+ ...passthroughResourceAttributes(resource),
892
875
  ...hexTraceAttributes(ids)
893
876
  };
894
877
  };
@@ -1038,12 +1021,12 @@ var pickTarget = (attributes) => {
1038
1021
  }
1039
1022
  return picked;
1040
1023
  };
1041
- var withoutTarget = (attributes) => {
1024
+ var withoutTarget = (attributes, resource) => {
1042
1025
  const rest = { ...attributes };
1043
1026
  for (const key of TARGET_KEYS) {
1044
1027
  delete rest[key];
1045
1028
  }
1046
- return rest;
1029
+ return { ...rest, ...pickTarget(passthroughResourceAttributes(resource)) };
1047
1030
  };
1048
1031
  var rankOf = (candidate) => {
1049
1032
  const source = candidate[ATTR_OTELHOOK_TARGET_SOURCE];
@@ -1148,7 +1131,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1148
1131
  name = "session";
1149
1132
  kind = SpanKind.INTERNAL;
1150
1133
  attributes = {
1151
- ...withoutTarget(attributes),
1134
+ ...withoutTarget(attributes, resource),
1152
1135
  ...strongestTarget([pickTarget(resolved.recovered), start === void 0 ? {} : targetAttributes(start)]),
1153
1136
  ...start?.agentName === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName },
1154
1137
  ...start?.agentVersion === void 0 ? {} : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion },
@@ -1189,7 +1172,7 @@ var buildLifecycleSpan = (plan, resource, scope) => {
1189
1172
  kind = SpanKind.CLIENT;
1190
1173
  attributes = {
1191
1174
  // Target keys are re-chosen below as one unit, never mixed across edges.
1192
- ...withoutTarget(attributes),
1175
+ ...withoutTarget(attributes, resource),
1193
1176
  [ATTR_GEN_AI_TOOL_NAME]: toolName,
1194
1177
  [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,
1195
1178
  ...start?.toolKind === void 0 ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind },
@@ -1422,7 +1405,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1422
1405
 
1423
1406
  // src/telemetry/spool-queue.ts
1424
1407
  import { randomBytes } from "crypto";
1425
- import { mkdir, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
1408
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1426
1409
  import * as path from "path";
1427
1410
 
1428
1411
  // src/state/keys.ts
@@ -1441,6 +1424,62 @@ var namespaceSegments = (namespace) => [
1441
1424
  ];
1442
1425
 
1443
1426
  // src/telemetry/spool-queue.ts
1427
+ var EMPTY_SPOOL_DROP_COUNTS = Object.freeze({
1428
+ total: 0,
1429
+ age: 0,
1430
+ size: 0,
1431
+ count: 0,
1432
+ rejected: 0
1433
+ });
1434
+ var SPOOL_DROPS_FILE = ".drops";
1435
+ var enqueuedAtOf = (fileName) => {
1436
+ const match = /^(\d{16})-/.exec(fileName);
1437
+ return match?.[1] === void 0 ? void 0 : Number(match[1]);
1438
+ };
1439
+ var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
1440
+ var readSpoolDropCounts = async (queueDir) => {
1441
+ try {
1442
+ const parsed = JSON.parse(await readFile(path.join(queueDir, SPOOL_DROPS_FILE), "utf8"));
1443
+ if (typeof parsed !== "object" || parsed === null) {
1444
+ return EMPTY_SPOOL_DROP_COUNTS;
1445
+ }
1446
+ const record = parsed;
1447
+ const field = (name) => isCount(record[name]) ? record[name] : 0;
1448
+ return {
1449
+ total: field("total"),
1450
+ age: field("age"),
1451
+ size: field("size"),
1452
+ count: field("count"),
1453
+ rejected: field("rejected"),
1454
+ ...isCount(record.lastDroppedAt) ? { lastDroppedAt: record.lastDroppedAt } : {}
1455
+ };
1456
+ } catch {
1457
+ return EMPTY_SPOOL_DROP_COUNTS;
1458
+ }
1459
+ };
1460
+ var readSpoolQueueStats = async (queueDir) => {
1461
+ let entries;
1462
+ try {
1463
+ entries = await readdir(queueDir);
1464
+ } catch {
1465
+ return { batches: 0, bytes: 0, dropped: await readSpoolDropCounts(queueDir) };
1466
+ }
1467
+ const files = entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
1468
+ let bytes = 0;
1469
+ for (const file of files) {
1470
+ try {
1471
+ bytes += (await stat(path.join(queueDir, file))).size;
1472
+ } catch {
1473
+ }
1474
+ }
1475
+ const oldest = files[0] === void 0 ? void 0 : enqueuedAtOf(files[0]);
1476
+ return {
1477
+ batches: files.length,
1478
+ bytes,
1479
+ ...oldest === void 0 ? {} : { oldestEnqueuedAt: oldest },
1480
+ dropped: await readSpoolDropCounts(queueDir)
1481
+ };
1482
+ };
1444
1483
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1445
1484
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
1446
1485
  var createSpoolQueue = (options) => {
@@ -1481,27 +1520,132 @@ var createSpoolQueue = (options) => {
1481
1520
  }
1482
1521
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
1483
1522
  };
1523
+ const recordDrops = async (reason, dropped) => {
1524
+ if (dropped <= 0) {
1525
+ return;
1526
+ }
1527
+ try {
1528
+ const current = await readSpoolDropCounts(queueDir);
1529
+ const next = {
1530
+ ...current,
1531
+ total: current.total + dropped,
1532
+ [reason]: current[reason] + dropped,
1533
+ lastDroppedAt: options.clock.now()
1534
+ };
1535
+ const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.drops`);
1536
+ await writeFile(tmp, JSON.stringify(next), "utf8");
1537
+ await rename(tmp, path.join(queueDir, SPOOL_DROPS_FILE));
1538
+ } catch {
1539
+ }
1540
+ options.logger?.warn("durable spool dropped batches", {
1541
+ "spool.queue": options.queueName,
1542
+ "spool.drop_reason": reason,
1543
+ "spool.dropped": dropped
1544
+ });
1545
+ };
1546
+ const listWithSizes = async () => {
1547
+ const names = await listSorted();
1548
+ const files = [];
1549
+ for (const name of names) {
1550
+ let bytes = 0;
1551
+ if (options.maxBytes !== void 0) {
1552
+ try {
1553
+ bytes = (await stat(path.join(queueDir, name))).size;
1554
+ } catch {
1555
+ continue;
1556
+ }
1557
+ }
1558
+ const enqueuedAt = enqueuedAtOf(name);
1559
+ files.push({ name, bytes, ...enqueuedAt === void 0 ? {} : { enqueuedAt } });
1560
+ }
1561
+ return files;
1562
+ };
1563
+ const evict = async (files) => {
1564
+ let removed = 0;
1565
+ for (const file of files) {
1566
+ try {
1567
+ await unlink(path.join(queueDir, file.name));
1568
+ removed += 1;
1569
+ } catch {
1570
+ }
1571
+ }
1572
+ return removed;
1573
+ };
1574
+ const isExpired = (file, now) => options.maxAgeMillis !== void 0 && file.enqueuedAt !== void 0 && now - file.enqueuedAt > options.maxAgeMillis;
1484
1575
  const enqueue = async (batch) => {
1485
1576
  await ensureDirs();
1486
- const existing = await listSorted();
1487
- if (existing.length >= options.maxFiles) {
1577
+ const serialized = JSON.stringify(batch);
1578
+ const bytes = Buffer.byteLength(serialized, "utf8");
1579
+ const refuse = async (reason) => {
1488
1580
  options.logger?.warn("durable spool at capacity; batch dropped", {
1489
1581
  "spool.max_files": options.maxFiles,
1582
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
1490
1583
  "spool.queue": options.queueName
1491
1584
  });
1585
+ await recordDrops(reason, 1);
1492
1586
  return { spooled: false, reason: "capacity-exceeded" };
1587
+ };
1588
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
1589
+ return refuse("size");
1590
+ }
1591
+ let queued = await listWithSizes();
1592
+ const now = options.clock.now();
1593
+ const expired = queued.filter((file) => isExpired(file, now));
1594
+ if (expired.length > 0) {
1595
+ await recordDrops("age", await evict(expired));
1596
+ queued = queued.filter((file) => !isExpired(file, now));
1597
+ }
1598
+ const overflow = options.overflow ?? "refuse-new";
1599
+ const totalBytes = () => queued.reduce((sum, file) => sum + file.bytes, 0);
1600
+ if (overflow === "refuse-new") {
1601
+ if (queued.length >= options.maxFiles) {
1602
+ return refuse("count");
1603
+ }
1604
+ if (options.maxBytes !== void 0 && totalBytes() + bytes > options.maxBytes) {
1605
+ return refuse("size");
1606
+ }
1607
+ } else {
1608
+ const overCount = Math.max(0, queued.length + 1 - options.maxFiles);
1609
+ if (overCount > 0) {
1610
+ await recordDrops("count", await evict(queued.slice(0, overCount)));
1611
+ queued = queued.slice(overCount);
1612
+ }
1613
+ if (options.maxBytes !== void 0) {
1614
+ let excess = totalBytes() + bytes - options.maxBytes;
1615
+ let cut = 0;
1616
+ while (excess > 0 && cut < queued.length) {
1617
+ excess -= queued[cut]?.bytes ?? 0;
1618
+ cut += 1;
1619
+ }
1620
+ if (cut > 0) {
1621
+ await recordDrops("size", await evict(queued.slice(0, cut)));
1622
+ queued = queued.slice(cut);
1623
+ }
1624
+ }
1493
1625
  }
1494
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
1626
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
1495
1627
  const target = path.join(queueDir, fileName);
1496
1628
  const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.json`);
1497
- await writeFile(tmp, JSON.stringify(batch), "utf8");
1629
+ await writeFile(tmp, serialized, "utf8");
1498
1630
  await rename(tmp, target);
1499
1631
  return { spooled: true };
1500
1632
  };
1501
1633
  const drain = async (send, drainOptions) => {
1502
1634
  await ensureDirs();
1503
1635
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
1504
- const files = await listSorted();
1636
+ let files = await listSorted();
1637
+ if (options.maxAgeMillis !== void 0) {
1638
+ const now = options.clock.now();
1639
+ const expired = files.map((name) => {
1640
+ const enqueuedAt = enqueuedAtOf(name);
1641
+ return { name, bytes: 0, ...enqueuedAt === void 0 ? {} : { enqueuedAt } };
1642
+ }).filter((file) => isExpired(file, now));
1643
+ if (expired.length > 0) {
1644
+ await recordDrops("age", await evict(expired));
1645
+ const gone = new Set(expired.map((file) => file.name));
1646
+ files = files.filter((name) => !gone.has(name));
1647
+ }
1648
+ }
1505
1649
  let drained = 0;
1506
1650
  let failed = 0;
1507
1651
  let quarantined = 0;
@@ -1546,6 +1690,12 @@ var createSpoolQueue = (options) => {
1546
1690
  } catch {
1547
1691
  delivered = false;
1548
1692
  }
1693
+ if (delivered === "discard") {
1694
+ if (await unlink(filePath).then(() => true, () => false)) {
1695
+ await recordDrops("rejected", 1);
1696
+ }
1697
+ continue;
1698
+ }
1549
1699
  if (delivered) {
1550
1700
  await unlink(filePath).catch(() => void 0);
1551
1701
  drained += 1;
@@ -1563,7 +1713,8 @@ var createSpoolQueue = (options) => {
1563
1713
  size: async () => {
1564
1714
  await ensureDirs();
1565
1715
  return (await listSorted()).length;
1566
- }
1716
+ },
1717
+ stats: () => readSpoolQueueStats(queueDir)
1567
1718
  };
1568
1719
  };
1569
1720
 
@@ -1655,11 +1806,15 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1655
1806
  clock: options.clock,
1656
1807
  ...options.logger === void 0 ? {} : { logger: options.logger },
1657
1808
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
1658
- queueName: "spool",
1809
+ queueName: options.queueName ?? "spool",
1810
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
1811
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
1812
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
1659
1813
  validate: validateSpoolBatch
1660
1814
  });
1661
1815
 
1662
1816
  // src/telemetry/otlp-sink.ts
1817
+ import { ExportResultCode } from "@opentelemetry/core";
1663
1818
  import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
1664
1819
 
1665
1820
  // src/errors/index.ts
@@ -1688,6 +1843,40 @@ var createErrorInfo = (input) => {
1688
1843
  ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1689
1844
  });
1690
1845
  };
1846
+ var OtelHookError = class _OtelHookError extends Error {
1847
+ info;
1848
+ constructor(info) {
1849
+ super(info.message);
1850
+ this.name = "OtelHookError";
1851
+ this.info = info;
1852
+ }
1853
+ static of(input) {
1854
+ return new _OtelHookError(createErrorInfo(input));
1855
+ }
1856
+ };
1857
+ var isOtelHookError = (value) => value instanceof OtelHookError;
1858
+ var describeThrown = (thrown) => {
1859
+ if (thrown instanceof Error) {
1860
+ return {
1861
+ errorName: thrown.name.slice(0, 64) || "Error",
1862
+ hasMessage: typeof thrown.message === "string" && thrown.message.length > 0
1863
+ };
1864
+ }
1865
+ return { errorName: typeof thrown, hasMessage: false };
1866
+ };
1867
+ var errorInfoFromThrown = (thrown, input) => {
1868
+ if (isOtelHookError(thrown)) {
1869
+ return thrown.info;
1870
+ }
1871
+ const described = describeThrown(thrown);
1872
+ return createErrorInfo({
1873
+ code: input.code ?? "internal-error",
1874
+ phase: input.phase,
1875
+ detail: `contained ${described.errorName}`,
1876
+ details: { "error.name": described.errorName, "error.has_message": described.hasMessage },
1877
+ ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1878
+ });
1879
+ };
1691
1880
 
1692
1881
  // src/diagnostics/health.ts
1693
1882
  var createHealthTracker = (subsystem, options = {}) => {
@@ -1722,11 +1911,19 @@ var createHealthTracker = (subsystem, options = {}) => {
1722
1911
  consecutiveFailures,
1723
1912
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
1724
1913
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
1725
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
1914
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
1915
+ ...options.destination === void 0 ? {} : { destination: options.destination }
1726
1916
  })
1727
1917
  };
1728
1918
  };
1729
1919
 
1920
+ // src/telemetry/export-failure.ts
1921
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
1922
+ var isPermanentExportFailure = (result) => {
1923
+ const code = result.error?.code;
1924
+ return typeof code === "number" && Number.isInteger(code) && code >= 400 && code < 600 && !RETRYABLE_HTTP_STATUSES.has(code);
1925
+ };
1926
+
1730
1927
  // src/telemetry/exporter-resource.ts
1731
1928
  import { resourceFromAttributes } from "@opentelemetry/resources";
1732
1929
 
@@ -1964,8 +2161,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
1964
2161
  resource,
1965
2162
  instrumentationScope: scope
1966
2163
  });
1967
- var createDisabledSink = () => {
1968
- const health = createHealthTracker("telemetry-sink");
2164
+ var createDisabledSink = (destination) => {
2165
+ const health = createHealthTracker(
2166
+ "telemetry-sink",
2167
+ destination === void 0 ? {} : { destination }
2168
+ );
1969
2169
  return {
1970
2170
  emit: (events) => {
1971
2171
  health.recordSuccess(events.length);
@@ -1978,22 +2178,27 @@ var createDisabledSink = () => {
1978
2178
  };
1979
2179
  };
1980
2180
  var createOtlpTraceSink = (options) => {
2181
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
1981
2182
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
1982
- return createDisabledSink();
2183
+ return createDisabledSink(options.destination);
1983
2184
  }
1984
2185
  if (options.exporter.endpoint === void 0) {
1985
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
1986
- return createDisabledSink();
2186
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
2187
+ return createDisabledSink(options.destination);
1987
2188
  }
1988
2189
  if (options.exporter.protocol !== "http/protobuf") {
1989
2190
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
1990
- "exporter.protocol": options.exporter.protocol
2191
+ "exporter.protocol": options.exporter.protocol,
2192
+ ...destinationFields
1991
2193
  });
1992
- return createDisabledSink();
2194
+ return createDisabledSink(options.destination);
1993
2195
  }
1994
2196
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1995
2197
  const resource = resourceFromExporterPolicy(options.exporter);
1996
- const health = createHealthTracker("telemetry-sink");
2198
+ const health = createHealthTracker(
2199
+ "telemetry-sink",
2200
+ options.destination === void 0 ? {} : { destination: options.destination }
2201
+ );
1997
2202
  const exporter = new OTLPTraceExporter({
1998
2203
  url: options.exporter.endpoint,
1999
2204
  headers: { ...options.headers },
@@ -2015,7 +2220,10 @@ var createOtlpTraceSink = (options) => {
2015
2220
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2016
2221
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2017
2222
  const result = await exportSpans(spans);
2018
- return result.code === ExportResultCode.SUCCESS;
2223
+ if (result.code === ExportResultCode.SUCCESS) {
2224
+ return true;
2225
+ }
2226
+ return isPermanentExportFailure(result) ? "discard" : false;
2019
2227
  };
2020
2228
  const resolveCorrelations = async (events) => {
2021
2229
  if (options.correlate === void 0) {
@@ -2043,6 +2251,9 @@ var createOtlpTraceSink = (options) => {
2043
2251
  let accepted = 0;
2044
2252
  let rejected = 0;
2045
2253
  for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
2254
+ if (batch.length === 0) {
2255
+ continue;
2256
+ }
2046
2257
  let result;
2047
2258
  try {
2048
2259
  result = await exportSpans(batch);
@@ -2055,13 +2266,18 @@ var createOtlpTraceSink = (options) => {
2055
2266
  continue;
2056
2267
  }
2057
2268
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2058
- if (options.spool !== void 0) {
2269
+ const permanent = isPermanentExportFailure(result);
2270
+ if (options.spool !== void 0 && !permanent) {
2059
2271
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2060
2272
  spooled: false,
2061
2273
  reason: "capacity-exceeded"
2062
2274
  }));
2063
2275
  if (spoolResult.spooled) {
2064
2276
  accepted += batch.length;
2277
+ options.logger?.warn("span batch not delivered; spooled for the next invocation", {
2278
+ "export.batch_size": batch.length,
2279
+ ...destinationFields
2280
+ });
2065
2281
  continue;
2066
2282
  }
2067
2283
  }
@@ -2070,8 +2286,8 @@ var createOtlpTraceSink = (options) => {
2070
2286
  createErrorInfo({
2071
2287
  code: "telemetry-export-failure",
2072
2288
  phase: "export",
2073
- detail: "collector rejected or was unreachable for a span batch",
2074
- details: { "export.batch_size": batch.length }
2289
+ detail: permanent ? "collector refused a span batch with a non-retryable status" : "collector rejected or was unreachable for a span batch",
2290
+ details: { "export.batch_size": batch.length, ...destinationFields }
2075
2291
  })
2076
2292
  );
2077
2293
  }
@@ -2115,8 +2331,8 @@ var createOtlpTraceSink = (options) => {
2115
2331
  };
2116
2332
 
2117
2333
  // src/telemetry/log-records.ts
2118
- import { TraceFlags as TraceFlags2 } from "@opentelemetry/api";
2119
- import { SeverityNumber } from "@opentelemetry/api-logs";
2334
+ import { SeverityNumber, TraceFlags as TraceFlags2 } from "@opentelemetry/api";
2335
+ import { millisToHrTime as millisToHrTime2 } from "@opentelemetry/core";
2120
2336
  import {
2121
2337
  ATTR_ERROR_TYPE as ATTR_ERROR_TYPE2,
2122
2338
  ATTR_GEN_AI_OPERATION_NAME as ATTR_GEN_AI_OPERATION_NAME2,
@@ -2437,14 +2653,14 @@ var contentAttributes = (fact, body) => ({
2437
2653
  });
2438
2654
  var buildRecord = (input) => {
2439
2655
  const severityNumber = severityFor(input.event);
2440
- const hrTime2 = millisToHrTime(input.event.occurredAt);
2656
+ const hrTime = millisToHrTime2(input.event.occurredAt);
2441
2657
  return {
2442
- hrTime: hrTime2,
2658
+ hrTime,
2443
2659
  // A hook observes an event that already happened, and this mapping is pure —
2444
2660
  // there is no clock here to read a real observation time from. Reporting the
2445
2661
  // occurrence time for both is the honest answer: it says "this is when it
2446
2662
  // happened" twice rather than inventing a second, wrong timestamp.
2447
- hrTimeObserved: hrTime2,
2663
+ hrTimeObserved: hrTime,
2448
2664
  spanContext: input.spanContext,
2449
2665
  severityNumber,
2450
2666
  severityText: SEVERITY_TEXT[severityNumber] ?? "INFO",
@@ -2628,13 +2844,25 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2628
2844
  clock: options.clock,
2629
2845
  ...options.logger === void 0 ? {} : { logger: options.logger },
2630
2846
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
2631
- queueName: "spool-logs",
2847
+ queueName: options.queueName ?? "spool-logs",
2848
+ ...options.maxBytes === void 0 ? {} : { maxBytes: options.maxBytes },
2849
+ ...options.maxAgeMillis === void 0 ? {} : { maxAgeMillis: options.maxAgeMillis },
2850
+ ...options.overflow === void 0 ? {} : { overflow: options.overflow },
2632
2851
  validate: validateLogSpoolBatch
2633
2852
  });
2634
2853
 
2635
2854
  // src/telemetry/otlp-log-sink.ts
2636
2855
  import { TraceFlags as TraceFlags3 } from "@opentelemetry/api";
2856
+ import { ExportResultCode as ExportResultCode2 } from "@opentelemetry/core";
2857
+ import { millisToHrTime as millisToHrTime3 } from "@opentelemetry/core";
2637
2858
  import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
2859
+
2860
+ // src/config/otlp-endpoint.ts
2861
+ var OTLP_ENDPOINT_VARIABLES = Object.freeze({
2862
+ generic: "OTEL_EXPORTER_OTLP_ENDPOINT",
2863
+ traces: "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
2864
+ logs: "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT"
2865
+ });
2638
2866
  var OTLP_TRACES_PATH = "/v1/traces";
2639
2867
  var OTLP_LOGS_PATH = "/v1/logs";
2640
2868
  var withoutTrailingSlashes = (value) => {
@@ -2644,6 +2872,8 @@ var withoutTrailingSlashes = (value) => {
2644
2872
  }
2645
2873
  return value.slice(0, end);
2646
2874
  };
2875
+
2876
+ // src/telemetry/otlp-log-sink.ts
2647
2877
  var resolveLogsEndpoint = (exporter) => {
2648
2878
  if (exporter.logs.endpoint !== void 0) {
2649
2879
  return { endpoint: exporter.logs.endpoint, derived: false };
@@ -2697,8 +2927,8 @@ var deserializeRecord = (serialized, resource, scope) => {
2697
2927
  isRemote: false
2698
2928
  };
2699
2929
  return {
2700
- hrTime: millisToHrTime(serialized.timeMillis),
2701
- hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),
2930
+ hrTime: millisToHrTime3(serialized.timeMillis),
2931
+ hrTimeObserved: millisToHrTime3(serialized.observedTimeMillis),
2702
2932
  ...spanContext === void 0 ? {} : { spanContext },
2703
2933
  severityNumber: serialized.severityNumber,
2704
2934
  ...serialized.severityText === void 0 ? {} : { severityText: serialized.severityText },
@@ -2720,8 +2950,11 @@ var chunk2 = (items, size) => {
2720
2950
  }
2721
2951
  return chunks;
2722
2952
  };
2723
- var createDisabledSink2 = () => {
2724
- const health = createHealthTracker("telemetry-log-sink");
2953
+ var createDisabledSink2 = (destination) => {
2954
+ const health = createHealthTracker(
2955
+ "telemetry-log-sink",
2956
+ destination === void 0 ? {} : { destination }
2957
+ );
2725
2958
  return {
2726
2959
  emit: (events) => {
2727
2960
  health.recordSuccess(events.length);
@@ -2760,19 +2993,24 @@ var DISABLED_DETAIL = Object.freeze({
2760
2993
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
2761
2994
  });
2762
2995
  var createOtlpLogSink = (options) => {
2996
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
2763
2997
  const deliverability = describeLogsDeliverability(options.exporter);
2764
2998
  if (deliverability.status === "disabled") {
2765
2999
  if (deliverability.reason !== "logs-disabled") {
2766
3000
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
2767
- "exporter.protocol": options.exporter.protocol
3001
+ "exporter.protocol": options.exporter.protocol,
3002
+ ...destinationFields
2768
3003
  });
2769
3004
  }
2770
- return createDisabledSink2();
3005
+ return createDisabledSink2(options.destination);
2771
3006
  }
2772
3007
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
2773
3008
  const resource = resourceFromExporterPolicy(options.exporter);
2774
3009
  const content = options.content ?? NO_LOG_CONTENT;
2775
- const health = createHealthTracker("telemetry-log-sink");
3010
+ const health = createHealthTracker(
3011
+ "telemetry-log-sink",
3012
+ options.destination === void 0 ? {} : { destination: options.destination }
3013
+ );
2776
3014
  const exporter = new OTLPLogExporter({
2777
3015
  url: deliverability.endpoint,
2778
3016
  headers: { ...options.headers },
@@ -2799,7 +3037,10 @@ var createOtlpLogSink = (options) => {
2799
3037
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
2800
3038
  );
2801
3039
  const result = await exportRecords(records);
2802
- return result.code === ExportResultCode.SUCCESS;
3040
+ if (result.code === ExportResultCode2.SUCCESS) {
3041
+ return true;
3042
+ }
3043
+ return isPermanentExportFailure(result) ? "discard" : false;
2803
3044
  };
2804
3045
  const resolveCorrelations = async (events) => {
2805
3046
  if (options.correlate === void 0) {
@@ -2841,23 +3082,28 @@ var createOtlpLogSink = (options) => {
2841
3082
  result = await exportRecords(batch);
2842
3083
  } catch (thrown) {
2843
3084
  result = {
2844
- code: ExportResultCode.FAILED,
3085
+ code: ExportResultCode2.FAILED,
2845
3086
  error: thrown instanceof Error ? thrown : new Error("export threw")
2846
3087
  };
2847
3088
  }
2848
- if (result.code === ExportResultCode.SUCCESS) {
3089
+ if (result.code === ExportResultCode2.SUCCESS) {
2849
3090
  accepted += batch.length;
2850
3091
  health.recordSuccess(batch.length, options.clock.now());
2851
3092
  continue;
2852
3093
  }
2853
3094
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2854
- if (options.spool !== void 0) {
3095
+ const permanent = isPermanentExportFailure(result);
3096
+ if (options.spool !== void 0 && !permanent) {
2855
3097
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2856
3098
  spooled: false,
2857
3099
  reason: "capacity-exceeded"
2858
3100
  }));
2859
3101
  if (spoolResult.spooled) {
2860
3102
  accepted += batch.length;
3103
+ options.logger?.warn("log record batch not delivered; spooled for the next invocation", {
3104
+ "export.batch_size": batch.length,
3105
+ ...destinationFields
3106
+ });
2861
3107
  continue;
2862
3108
  }
2863
3109
  }
@@ -2866,8 +3112,12 @@ var createOtlpLogSink = (options) => {
2866
3112
  createErrorInfo({
2867
3113
  code: "telemetry-export-failure",
2868
3114
  phase: "export",
2869
- detail: "collector rejected or was unreachable for a log record batch",
2870
- details: { "export.batch_size": batch.length, "export.signal": "logs" }
3115
+ detail: permanent ? "collector refused a log record batch with a non-retryable status" : "collector rejected or was unreachable for a log record batch",
3116
+ details: {
3117
+ "export.batch_size": batch.length,
3118
+ "export.signal": "logs",
3119
+ ...destinationFields
3120
+ }
2871
3121
  })
2872
3122
  );
2873
3123
  }
@@ -2953,6 +3203,339 @@ var shareCorrelationPerBatch = (correlate) => {
2953
3203
  return result;
2954
3204
  };
2955
3205
  };
3206
+
3207
+ // src/config/destinations.ts
3208
+ import { z as z13 } from "zod";
3209
+
3210
+ // src/config/header-value.ts
3211
+ var isUnsafeHeaderValue = (value) => [...value].some((char) => {
3212
+ const code = char.codePointAt(0) ?? 0;
3213
+ return code < 32 && code !== 9 || code === 127 || code > 255;
3214
+ });
3215
+
3216
+ // src/config/otlp-headers.ts
3217
+ var MAX_OTLP_HEADERS = 32;
3218
+ var OTLP_HEADER_VARIABLES = Object.freeze({
3219
+ generic: "OTEL_EXPORTER_OTLP_HEADERS",
3220
+ traces: "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
3221
+ logs: "OTEL_EXPORTER_OTLP_LOGS_HEADERS"
3222
+ });
3223
+
3224
+ // src/config/destinations.ts
3225
+ var DEFAULT_DESTINATION_NAME = "default";
3226
+ var DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;
3227
+ var MAX_EXPORT_DESTINATIONS = 16;
3228
+ var MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;
3229
+ var HEADER_ENV_REFERENCE_PREFIX = "env:";
3230
+ var HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;
3231
+ var ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;
3232
+ var MAX_HEADER_VALUE_LENGTH = 8192;
3233
+ var exportSignalSchema = z13.enum(["traces", "logs"]);
3234
+ var headerValueSchema = z13.string().min(1).max(MAX_HEADER_VALUE_LENGTH).refine(
3235
+ (value) => !isUnsafeHeaderValue(value),
3236
+ "header values may not contain line breaks, control characters, or characters beyond Latin-1"
3237
+ ).refine(
3238
+ (value) => !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) || ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),
3239
+ "an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN"
3240
+ );
3241
+ var endpointSchema = z13.string().url().max(2048);
3242
+ var exportDestinationSchema = z13.strictObject({
3243
+ /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */
3244
+ name: z13.string().regex(DESTINATION_NAME_PATTERN, "destination names are lowercase letters, digits, _ and -"),
3245
+ /** Default true. A disabled destination is neither sent to nor drained. */
3246
+ enabled: z13.boolean().optional(),
3247
+ /**
3248
+ * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is
3249
+ * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.
3250
+ */
3251
+ endpoint: endpointSchema.optional(),
3252
+ /** Per-signal override of `endpoint` for traces. */
3253
+ tracesEndpoint: endpointSchema.optional(),
3254
+ /** Per-signal override of the derived logs URL. */
3255
+ logsEndpoint: endpointSchema.optional(),
3256
+ /** Defaults to `exporter.protocol`. */
3257
+ protocol: z13.enum(["http/protobuf", "http/json", "none"]).optional(),
3258
+ /**
3259
+ * Header name to value. A value of the form `env:NAME` is read from that
3260
+ * environment variable at send time, so a credential never has to be written
3261
+ * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.
3262
+ */
3263
+ headers: z13.record(z13.string().regex(HEADER_NAME_PATTERN, "not a valid header name"), headerValueSchema).refine(
3264
+ (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,
3265
+ `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`
3266
+ ).optional(),
3267
+ /**
3268
+ * Which signals this destination receives. Default: both. The logs signal is
3269
+ * still governed by `exporter.logs.enabled`, which stays the one opt-in for a
3270
+ * second stream leaving the host.
3271
+ */
3272
+ signals: z13.array(exportSignalSchema).min(1).max(2).readonly().optional()
3273
+ }).refine(
3274
+ (destination) => destination.endpoint !== void 0 || destination.tracesEndpoint !== void 0 || destination.logsEndpoint !== void 0,
3275
+ "a destination needs an endpoint, or a tracesEndpoint / logsEndpoint"
3276
+ );
3277
+ var exportDestinationsSchema = z13.array(exportDestinationSchema).max(MAX_EXPORT_DESTINATIONS).readonly().superRefine((destinations, context) => {
3278
+ const seen = /* @__PURE__ */ new Set();
3279
+ destinations.forEach((destination, index) => {
3280
+ if (destination.name === DEFAULT_DESTINATION_NAME) {
3281
+ context.addIssue({
3282
+ code: "custom",
3283
+ path: [index, "name"],
3284
+ message: 'the name "default" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables'
3285
+ });
3286
+ }
3287
+ if (seen.has(destination.name)) {
3288
+ context.addIssue({
3289
+ code: "custom",
3290
+ path: [index, "name"],
3291
+ message: `duplicate destination name "${destination.name}"`
3292
+ });
3293
+ }
3294
+ seen.add(destination.name);
3295
+ });
3296
+ });
3297
+ var spoolPolicySchema = z13.strictObject({
3298
+ /** Total bytes of queued batches. Default 16 MiB. */
3299
+ maxBytes: z13.number().int().min(1024).max(1073741824),
3300
+ /** A batch older than this is dropped instead of sent. Default 72 hours. */
3301
+ maxAgeMillis: z13.number().int().min(1e3).max(30 * 24 * 60 * 60 * 1e3),
3302
+ /** Number of queued batches. Default 500. */
3303
+ maxBatches: z13.number().int().min(1).max(65536)
3304
+ });
3305
+ var DEFAULT_SPOOL_POLICY = Object.freeze({
3306
+ maxBytes: 16 * 1024 * 1024,
3307
+ maxAgeMillis: 72 * 60 * 60 * 1e3,
3308
+ maxBatches: 500
3309
+ });
3310
+ var effectiveSpoolPolicy = (exporter) => ({
3311
+ maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,
3312
+ maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,
3313
+ maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches
3314
+ });
3315
+ var legacyDestination = (exporter) => ({
3316
+ name: DEFAULT_DESTINATION_NAME,
3317
+ source: "exporter",
3318
+ protocol: exporter.protocol,
3319
+ ...exporter.endpoint === void 0 ? {} : { endpoint: exporter.endpoint },
3320
+ ...exporter.logs.endpoint === void 0 ? {} : { logsEndpoint: exporter.logs.endpoint },
3321
+ signals: { traces: true, logs: exporter.logs.enabled },
3322
+ headers: {}
3323
+ });
3324
+ var hasConfiguredDestinations = (exporter) => exporter.destinations !== void 0 && exporter.destinations.length > 0;
3325
+ var resolveExportDestinations = (exporter) => {
3326
+ if (!hasConfiguredDestinations(exporter)) {
3327
+ return [legacyDestination(exporter)];
3328
+ }
3329
+ const resolved = [];
3330
+ if (exporter.endpoint !== void 0 || exporter.logs.endpoint !== void 0) {
3331
+ resolved.push(legacyDestination(exporter));
3332
+ }
3333
+ for (const destination of exporter.destinations ?? []) {
3334
+ if (destination.enabled === false) {
3335
+ continue;
3336
+ }
3337
+ const signals = destination.signals ?? exportSignalSchema.options;
3338
+ resolved.push({
3339
+ name: destination.name,
3340
+ source: "destinations",
3341
+ protocol: destination.protocol ?? exporter.protocol,
3342
+ ...destination.endpoint === void 0 ? {} : { endpoint: destination.endpoint },
3343
+ ...destination.tracesEndpoint === void 0 ? {} : { tracesEndpoint: destination.tracesEndpoint },
3344
+ ...destination.logsEndpoint === void 0 ? {} : { logsEndpoint: destination.logsEndpoint },
3345
+ signals: {
3346
+ traces: signals.includes("traces"),
3347
+ logs: exporter.logs.enabled && signals.includes("logs")
3348
+ },
3349
+ headers: { ...destination.headers ?? {} }
3350
+ });
3351
+ }
3352
+ return resolved;
3353
+ };
3354
+ var parseHeaderValueReference = (value) => value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ? { kind: "env", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) } : { kind: "literal" };
3355
+ var resolveDestinationHeaders = (headers, environment) => {
3356
+ const values = {};
3357
+ const missing = [];
3358
+ for (const [name, value] of Object.entries(headers)) {
3359
+ const reference = parseHeaderValueReference(value);
3360
+ if (reference.kind === "literal") {
3361
+ values[name] = value;
3362
+ continue;
3363
+ }
3364
+ const resolved = environment?.[reference.variable];
3365
+ if (resolved === void 0 || resolved === "") {
3366
+ missing.push(reference.variable);
3367
+ continue;
3368
+ }
3369
+ values[name] = resolved;
3370
+ }
3371
+ return { values, missingVariables: [...new Set(missing)].sort() };
3372
+ };
3373
+
3374
+ // src/telemetry/export-destinations.ts
3375
+ var spoolQueueNamesFor = (destination) => destination === DEFAULT_DESTINATION_NAME ? { traces: "spool", logs: "spool-logs" } : { traces: `destinations/${destination}/spool`, logs: `destinations/${destination}/spool-logs` };
3376
+ var exporterPolicyForDestination = (exporter, destination) => {
3377
+ if (destination.source === "exporter") {
3378
+ return exporter;
3379
+ }
3380
+ const { destinations, endpoint, logs, ...shared } = exporter;
3381
+ void destinations;
3382
+ void endpoint;
3383
+ const tracesEndpoint = destination.tracesEndpoint ?? destination.endpoint;
3384
+ const derivedLogs = destination.logsEndpoint ?? (destination.endpoint === void 0 ? void 0 : (() => {
3385
+ const derived = resolveLogsEndpoint({
3386
+ ...exporter,
3387
+ endpoint: destination.endpoint,
3388
+ logs: { enabled: true, includeContent: false, maxBatchSize: logs.maxBatchSize }
3389
+ });
3390
+ return "endpoint" in derived ? derived.endpoint : void 0;
3391
+ })());
3392
+ return {
3393
+ ...shared,
3394
+ protocol: destination.protocol,
3395
+ ...tracesEndpoint === void 0 ? {} : { endpoint: tracesEndpoint },
3396
+ headerNames: Object.keys(destination.headers).sort(),
3397
+ logs: {
3398
+ ...logs,
3399
+ enabled: destination.signals.logs,
3400
+ ...derivedLogs === void 0 ? {} : { endpoint: derivedLogs }
3401
+ }
3402
+ };
3403
+ };
3404
+ var createOptedOutTraceSink = (destination) => {
3405
+ const health = createHealthTracker(
3406
+ "telemetry-sink",
3407
+ destination === void 0 ? {} : { destination }
3408
+ );
3409
+ return {
3410
+ emit: () => Promise.resolve({ accepted: 0, rejected: 0, errors: [] }),
3411
+ flush: () => Promise.resolve(),
3412
+ shutdown: () => Promise.resolve(),
3413
+ health: () => health.snapshot(),
3414
+ drainSpool: () => Promise.resolve({ drained: 0, remaining: 0, failed: 0 })
3415
+ };
3416
+ };
3417
+ var createExportDestinationSinks = (options) => {
3418
+ const labelled = hasConfiguredDestinations(options.exporter);
3419
+ const spoolPolicy = effectiveSpoolPolicy(options.exporter);
3420
+ const destinations = [];
3421
+ const skipped = [];
3422
+ for (const destination of resolveExportDestinations(options.exporter)) {
3423
+ let headers;
3424
+ let logHeaders;
3425
+ if (destination.source === "exporter") {
3426
+ headers = options.defaultHeaders;
3427
+ logHeaders = options.defaultLogHeaders ?? options.defaultHeaders;
3428
+ } else {
3429
+ const resolved = resolveDestinationHeaders(destination.headers, options.headerEnvironment);
3430
+ if (resolved.missingVariables.length > 0) {
3431
+ options.logger?.warn("export destination skipped: a header references an unset environment variable", {
3432
+ "export.destination": destination.name,
3433
+ "config.variables": [...resolved.missingVariables]
3434
+ });
3435
+ skipped.push({
3436
+ name: destination.name,
3437
+ reason: "header-variable-missing",
3438
+ missingVariables: resolved.missingVariables
3439
+ });
3440
+ continue;
3441
+ }
3442
+ headers = resolved.values;
3443
+ logHeaders = resolved.values;
3444
+ }
3445
+ const label = labelled ? destination.name : void 0;
3446
+ const policy = exporterPolicyForDestination(options.exporter, destination);
3447
+ const queues = spoolQueueNamesFor(destination.name);
3448
+ const bounds = {
3449
+ maxSpoolFiles: spoolPolicy.maxBatches,
3450
+ maxBytes: spoolPolicy.maxBytes,
3451
+ maxAgeMillis: spoolPolicy.maxAgeMillis,
3452
+ overflow: "drop-oldest"
3453
+ };
3454
+ const shared = {
3455
+ providerId: options.providerId,
3456
+ installationId: options.installationId,
3457
+ clock: options.clock,
3458
+ ...options.logger === void 0 ? {} : { logger: options.logger }
3459
+ };
3460
+ const spool = options.spoolRootDir === void 0 || !destination.signals.traces ? void 0 : createFileDurableSpool({
3461
+ rootDir: options.spoolRootDir,
3462
+ ...shared,
3463
+ ...bounds,
3464
+ queueName: queues.traces
3465
+ });
3466
+ const logSpool = options.spoolRootDir === void 0 || !destination.signals.logs ? void 0 : createFileDurableLogSpool({
3467
+ rootDir: options.spoolRootDir,
3468
+ ...shared,
3469
+ ...bounds,
3470
+ queueName: queues.logs
3471
+ });
3472
+ const sinkShared = {
3473
+ exporter: policy,
3474
+ ...shared,
3475
+ ...options.correlate === void 0 ? {} : { correlate: options.correlate },
3476
+ ...label === void 0 ? {} : { destination: label }
3477
+ };
3478
+ const traces = destination.signals.traces ? createOtlpTraceSink({
3479
+ ...sinkShared,
3480
+ ...headers === void 0 || Object.keys(headers).length === 0 ? {} : { headers },
3481
+ ...spool === void 0 ? {} : { spool }
3482
+ }) : createOptedOutTraceSink(label);
3483
+ const logs = createOtlpLogSink({
3484
+ ...sinkShared,
3485
+ ...logHeaders === void 0 || Object.keys(logHeaders).length === 0 ? {} : { headers: logHeaders },
3486
+ ...logSpool === void 0 ? {} : { spool: logSpool },
3487
+ content: options.logContent
3488
+ });
3489
+ destinations.push({
3490
+ name: destination.name,
3491
+ traces,
3492
+ logs,
3493
+ ...spool === void 0 ? {} : { spool },
3494
+ ...logSpool === void 0 ? {} : { logSpool }
3495
+ });
3496
+ }
3497
+ return { destinations, skipped };
3498
+ };
3499
+ var createDestinationFanout = (destinations) => {
3500
+ const fanouts = destinations.map((destination) => ({
3501
+ name: destination.name,
3502
+ sink: createSignalFanout({ traces: destination.traces, logs: destination.logs })
3503
+ }));
3504
+ const only = fanouts.length === 1 ? fanouts[0] : void 0;
3505
+ if (only !== void 0) {
3506
+ return only.sink;
3507
+ }
3508
+ const emit = async (events) => {
3509
+ const results = await Promise.all(
3510
+ fanouts.map(
3511
+ (fanout) => fanout.sink.emit(events).catch(
3512
+ (thrown) => ({
3513
+ accepted: 0,
3514
+ rejected: events.length,
3515
+ errors: [errorInfoFromThrown(thrown, { code: "telemetry-export-failure", phase: "export" })]
3516
+ })
3517
+ )
3518
+ )
3519
+ );
3520
+ const errors = results.flatMap((result) => result.errors);
3521
+ return {
3522
+ accepted: results.reduce((sum, result) => sum + result.accepted, 0),
3523
+ rejected: results.reduce((sum, result) => sum + result.rejected, 0),
3524
+ errors
3525
+ };
3526
+ };
3527
+ const settleAll = async (run) => {
3528
+ await Promise.all(fanouts.map((fanout) => run(fanout.sink).catch(() => void 0)));
3529
+ };
3530
+ return {
3531
+ emit,
3532
+ // Each destination drains its own spool in its flush; in parallel, so one
3533
+ // unreachable destination's drain cannot use up the others' flush window.
3534
+ flush: () => settleAll((sink) => sink.flush()),
3535
+ shutdown: () => settleAll((sink) => sink.shutdown()),
3536
+ health: () => fanouts.flatMap((fanout) => fanout.sink.health())
3537
+ };
3538
+ };
2956
3539
  export {
2957
3540
  DEFAULT_INSTRUMENTATION_SCOPE,
2958
3541
  LOG_MAPPING_VERSION,
@@ -2966,18 +3549,23 @@ export {
2966
3549
  canonicalEventTraceIdentities,
2967
3550
  canonicalEventsToLogRecords,
2968
3551
  canonicalEventsToReadableSpans,
3552
+ createDestinationFanout,
3553
+ createExportDestinationSinks,
2969
3554
  createFileDurableLogSpool,
2970
3555
  createFileDurableSpool,
2971
3556
  createOtlpLogSink,
2972
3557
  createOtlpTraceSink,
2973
3558
  createSignalFanout,
2974
3559
  describeLogsDeliverability,
3560
+ exporterPolicyForDestination,
3561
+ isPermanentExportFailure,
2975
3562
  logSignalOf,
2976
3563
  logSignalsForLifecycleEvents,
2977
3564
  parentScopeRefOf,
2978
3565
  resolveLogsEndpoint,
2979
3566
  shareCorrelationPerBatch,
2980
3567
  spanScopeRefOf,
3568
+ spoolQueueNamesFor,
2981
3569
  startOnlySpanAttributes
2982
3570
  };
2983
3571
  //# sourceMappingURL=telemetry.js.map