@osfactory/otel-hook 0.8.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
@@ -18,7 +18,7 @@ import {
18
18
  } from "@opentelemetry/semantic-conventions/incubating";
19
19
 
20
20
  // src/version.ts
21
- var VERSION = "0.8.0";
21
+ var VERSION = "0.9.0";
22
22
 
23
23
  // src/telemetry/export-identity.ts
24
24
  import { ATTR_SESSION_ID } from "@opentelemetry/semantic-conventions/incubating";
@@ -1405,7 +1405,7 @@ var canonicalEventsToReadableSpans = (events, options) => {
1405
1405
 
1406
1406
  // src/telemetry/spool-queue.ts
1407
1407
  import { randomBytes } from "crypto";
1408
- import { mkdir, readFile, readdir, rename, unlink, writeFile } from "fs/promises";
1408
+ import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "fs/promises";
1409
1409
  import * as path from "path";
1410
1410
 
1411
1411
  // src/state/keys.ts
@@ -1424,6 +1424,62 @@ var namespaceSegments = (namespace) => [
1424
1424
  ];
1425
1425
 
1426
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
+ };
1427
1483
  var DEFAULT_DRAIN_MAX_BATCHES = 20;
1428
1484
  var isErrnoException = (thrown, code) => thrown instanceof Error && thrown.code === code;
1429
1485
  var createSpoolQueue = (options) => {
@@ -1464,27 +1520,132 @@ var createSpoolQueue = (options) => {
1464
1520
  }
1465
1521
  return entries.filter((entry) => entry.endsWith(".json") && !entry.startsWith(".tmp-")).sort();
1466
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;
1467
1575
  const enqueue = async (batch) => {
1468
1576
  await ensureDirs();
1469
- const existing = await listSorted();
1470
- if (existing.length >= options.maxFiles) {
1577
+ const serialized = JSON.stringify(batch);
1578
+ const bytes = Buffer.byteLength(serialized, "utf8");
1579
+ const refuse = async (reason) => {
1471
1580
  options.logger?.warn("durable spool at capacity; batch dropped", {
1472
1581
  "spool.max_files": options.maxFiles,
1582
+ ...options.maxBytes === void 0 ? {} : { "spool.max_bytes": options.maxBytes },
1473
1583
  "spool.queue": options.queueName
1474
1584
  });
1585
+ await recordDrops(reason, 1);
1475
1586
  return { spooled: false, reason: "capacity-exceeded" };
1587
+ };
1588
+ if (options.maxBytes !== void 0 && bytes > options.maxBytes) {
1589
+ return refuse("size");
1476
1590
  }
1477
- const fileName = `${String(options.clock.now()).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
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
+ }
1625
+ }
1626
+ const fileName = `${String(now).padStart(16, "0")}-${randomBytes(6).toString("hex")}.json`;
1478
1627
  const target = path.join(queueDir, fileName);
1479
1628
  const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString("hex")}.json`);
1480
- await writeFile(tmp, JSON.stringify(batch), "utf8");
1629
+ await writeFile(tmp, serialized, "utf8");
1481
1630
  await rename(tmp, target);
1482
1631
  return { spooled: true };
1483
1632
  };
1484
1633
  const drain = async (send, drainOptions) => {
1485
1634
  await ensureDirs();
1486
1635
  const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;
1487
- 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
+ }
1488
1649
  let drained = 0;
1489
1650
  let failed = 0;
1490
1651
  let quarantined = 0;
@@ -1529,6 +1690,12 @@ var createSpoolQueue = (options) => {
1529
1690
  } catch {
1530
1691
  delivered = false;
1531
1692
  }
1693
+ if (delivered === "discard") {
1694
+ if (await unlink(filePath).then(() => true, () => false)) {
1695
+ await recordDrops("rejected", 1);
1696
+ }
1697
+ continue;
1698
+ }
1532
1699
  if (delivered) {
1533
1700
  await unlink(filePath).catch(() => void 0);
1534
1701
  drained += 1;
@@ -1546,7 +1713,8 @@ var createSpoolQueue = (options) => {
1546
1713
  size: async () => {
1547
1714
  await ensureDirs();
1548
1715
  return (await listSorted()).length;
1549
- }
1716
+ },
1717
+ stats: () => readSpoolQueueStats(queueDir)
1550
1718
  };
1551
1719
  };
1552
1720
 
@@ -1638,7 +1806,10 @@ var createFileDurableSpool = (options) => createSpoolQueue({
1638
1806
  clock: options.clock,
1639
1807
  ...options.logger === void 0 ? {} : { logger: options.logger },
1640
1808
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,
1641
- 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 },
1642
1813
  validate: validateSpoolBatch
1643
1814
  });
1644
1815
 
@@ -1672,6 +1843,40 @@ var createErrorInfo = (input) => {
1672
1843
  ...input.occurredAt === void 0 ? {} : { occurredAt: input.occurredAt }
1673
1844
  });
1674
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
+ };
1675
1880
 
1676
1881
  // src/diagnostics/health.ts
1677
1882
  var createHealthTracker = (subsystem, options = {}) => {
@@ -1706,11 +1911,19 @@ var createHealthTracker = (subsystem, options = {}) => {
1706
1911
  consecutiveFailures,
1707
1912
  ...lastSuccessAt === void 0 ? {} : { lastSuccessAt },
1708
1913
  ...lastFailureAt === void 0 ? {} : { lastFailureAt },
1709
- ...lastErrorCode === void 0 ? {} : { lastErrorCode }
1914
+ ...lastErrorCode === void 0 ? {} : { lastErrorCode },
1915
+ ...options.destination === void 0 ? {} : { destination: options.destination }
1710
1916
  })
1711
1917
  };
1712
1918
  };
1713
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
+
1714
1927
  // src/telemetry/exporter-resource.ts
1715
1928
  import { resourceFromAttributes } from "@opentelemetry/resources";
1716
1929
 
@@ -1948,8 +2161,11 @@ var deserializeSpan = (serialized, resource, scope) => assembleReadableSpan({
1948
2161
  resource,
1949
2162
  instrumentationScope: scope
1950
2163
  });
1951
- var createDisabledSink = () => {
1952
- const health = createHealthTracker("telemetry-sink");
2164
+ var createDisabledSink = (destination) => {
2165
+ const health = createHealthTracker(
2166
+ "telemetry-sink",
2167
+ destination === void 0 ? {} : { destination }
2168
+ );
1953
2169
  return {
1954
2170
  emit: (events) => {
1955
2171
  health.recordSuccess(events.length);
@@ -1962,22 +2178,27 @@ var createDisabledSink = () => {
1962
2178
  };
1963
2179
  };
1964
2180
  var createOtlpTraceSink = (options) => {
2181
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
1965
2182
  if (!options.exporter.enabled || options.exporter.protocol === "none") {
1966
- return createDisabledSink();
2183
+ return createDisabledSink(options.destination);
1967
2184
  }
1968
2185
  if (options.exporter.endpoint === void 0) {
1969
- options.logger?.warn("otlp sink disabled: no endpoint configured", {});
1970
- return createDisabledSink();
2186
+ options.logger?.warn("otlp sink disabled: no endpoint configured", destinationFields);
2187
+ return createDisabledSink(options.destination);
1971
2188
  }
1972
2189
  if (options.exporter.protocol !== "http/protobuf") {
1973
2190
  options.logger?.warn("otlp sink: protocol not supported by this build, falling back to disabled", {
1974
- "exporter.protocol": options.exporter.protocol
2191
+ "exporter.protocol": options.exporter.protocol,
2192
+ ...destinationFields
1975
2193
  });
1976
- return createDisabledSink();
2194
+ return createDisabledSink(options.destination);
1977
2195
  }
1978
2196
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
1979
2197
  const resource = resourceFromExporterPolicy(options.exporter);
1980
- const health = createHealthTracker("telemetry-sink");
2198
+ const health = createHealthTracker(
2199
+ "telemetry-sink",
2200
+ options.destination === void 0 ? {} : { destination: options.destination }
2201
+ );
1981
2202
  const exporter = new OTLPTraceExporter({
1982
2203
  url: options.exporter.endpoint,
1983
2204
  headers: { ...options.headers },
@@ -1999,7 +2220,10 @@ var createOtlpTraceSink = (options) => {
1999
2220
  const batchResource = replayResource(batch.resourceAttributes, options.exporter);
2000
2221
  const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));
2001
2222
  const result = await exportSpans(spans);
2002
- return result.code === ExportResultCode.SUCCESS;
2223
+ if (result.code === ExportResultCode.SUCCESS) {
2224
+ return true;
2225
+ }
2226
+ return isPermanentExportFailure(result) ? "discard" : false;
2003
2227
  };
2004
2228
  const resolveCorrelations = async (events) => {
2005
2229
  if (options.correlate === void 0) {
@@ -2027,6 +2251,9 @@ var createOtlpTraceSink = (options) => {
2027
2251
  let accepted = 0;
2028
2252
  let rejected = 0;
2029
2253
  for (const batch of chunk(spans, options.exporter.maxBatchSize)) {
2254
+ if (batch.length === 0) {
2255
+ continue;
2256
+ }
2030
2257
  let result;
2031
2258
  try {
2032
2259
  result = await exportSpans(batch);
@@ -2039,13 +2266,18 @@ var createOtlpTraceSink = (options) => {
2039
2266
  continue;
2040
2267
  }
2041
2268
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2042
- if (options.spool !== void 0) {
2269
+ const permanent = isPermanentExportFailure(result);
2270
+ if (options.spool !== void 0 && !permanent) {
2043
2271
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2044
2272
  spooled: false,
2045
2273
  reason: "capacity-exceeded"
2046
2274
  }));
2047
2275
  if (spoolResult.spooled) {
2048
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
+ });
2049
2281
  continue;
2050
2282
  }
2051
2283
  }
@@ -2054,8 +2286,8 @@ var createOtlpTraceSink = (options) => {
2054
2286
  createErrorInfo({
2055
2287
  code: "telemetry-export-failure",
2056
2288
  phase: "export",
2057
- detail: "collector rejected or was unreachable for a span batch",
2058
- 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 }
2059
2291
  })
2060
2292
  );
2061
2293
  }
@@ -2612,7 +2844,10 @@ var createFileDurableLogSpool = (options) => createSpoolQueue({
2612
2844
  clock: options.clock,
2613
2845
  ...options.logger === void 0 ? {} : { logger: options.logger },
2614
2846
  maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,
2615
- 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 },
2616
2851
  validate: validateLogSpoolBatch
2617
2852
  });
2618
2853
 
@@ -2715,8 +2950,11 @@ var chunk2 = (items, size) => {
2715
2950
  }
2716
2951
  return chunks;
2717
2952
  };
2718
- var createDisabledSink2 = () => {
2719
- const health = createHealthTracker("telemetry-log-sink");
2953
+ var createDisabledSink2 = (destination) => {
2954
+ const health = createHealthTracker(
2955
+ "telemetry-log-sink",
2956
+ destination === void 0 ? {} : { destination }
2957
+ );
2720
2958
  return {
2721
2959
  emit: (events) => {
2722
2960
  health.recordSuccess(events.length);
@@ -2755,19 +2993,24 @@ var DISABLED_DETAIL = Object.freeze({
2755
2993
  "no-endpoint": "otlp log sink disabled: no logs endpoint configured and none could be derived"
2756
2994
  });
2757
2995
  var createOtlpLogSink = (options) => {
2996
+ const destinationFields = options.destination === void 0 ? {} : { "export.destination": options.destination };
2758
2997
  const deliverability = describeLogsDeliverability(options.exporter);
2759
2998
  if (deliverability.status === "disabled") {
2760
2999
  if (deliverability.reason !== "logs-disabled") {
2761
3000
  options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {
2762
- "exporter.protocol": options.exporter.protocol
3001
+ "exporter.protocol": options.exporter.protocol,
3002
+ ...destinationFields
2763
3003
  });
2764
3004
  }
2765
- return createDisabledSink2();
3005
+ return createDisabledSink2(options.destination);
2766
3006
  }
2767
3007
  const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;
2768
3008
  const resource = resourceFromExporterPolicy(options.exporter);
2769
3009
  const content = options.content ?? NO_LOG_CONTENT;
2770
- const health = createHealthTracker("telemetry-log-sink");
3010
+ const health = createHealthTracker(
3011
+ "telemetry-log-sink",
3012
+ options.destination === void 0 ? {} : { destination: options.destination }
3013
+ );
2771
3014
  const exporter = new OTLPLogExporter({
2772
3015
  url: deliverability.endpoint,
2773
3016
  headers: { ...options.headers },
@@ -2794,7 +3037,10 @@ var createOtlpLogSink = (options) => {
2794
3037
  (record) => deserializeRecord(record, batchResource, batch.instrumentationScope)
2795
3038
  );
2796
3039
  const result = await exportRecords(records);
2797
- return result.code === ExportResultCode2.SUCCESS;
3040
+ if (result.code === ExportResultCode2.SUCCESS) {
3041
+ return true;
3042
+ }
3043
+ return isPermanentExportFailure(result) ? "discard" : false;
2798
3044
  };
2799
3045
  const resolveCorrelations = async (events) => {
2800
3046
  if (options.correlate === void 0) {
@@ -2846,13 +3092,18 @@ var createOtlpLogSink = (options) => {
2846
3092
  continue;
2847
3093
  }
2848
3094
  health.recordFailure("telemetry-export-failure", batch.length, options.clock.now());
2849
- if (options.spool !== void 0) {
3095
+ const permanent = isPermanentExportFailure(result);
3096
+ if (options.spool !== void 0 && !permanent) {
2850
3097
  const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({
2851
3098
  spooled: false,
2852
3099
  reason: "capacity-exceeded"
2853
3100
  }));
2854
3101
  if (spoolResult.spooled) {
2855
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
+ });
2856
3107
  continue;
2857
3108
  }
2858
3109
  }
@@ -2861,8 +3112,12 @@ var createOtlpLogSink = (options) => {
2861
3112
  createErrorInfo({
2862
3113
  code: "telemetry-export-failure",
2863
3114
  phase: "export",
2864
- detail: "collector rejected or was unreachable for a log record batch",
2865
- 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
+ }
2866
3121
  })
2867
3122
  );
2868
3123
  }
@@ -2948,6 +3203,339 @@ var shareCorrelationPerBatch = (correlate) => {
2948
3203
  return result;
2949
3204
  };
2950
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
+ };
2951
3539
  export {
2952
3540
  DEFAULT_INSTRUMENTATION_SCOPE,
2953
3541
  LOG_MAPPING_VERSION,
@@ -2961,18 +3549,23 @@ export {
2961
3549
  canonicalEventTraceIdentities,
2962
3550
  canonicalEventsToLogRecords,
2963
3551
  canonicalEventsToReadableSpans,
3552
+ createDestinationFanout,
3553
+ createExportDestinationSinks,
2964
3554
  createFileDurableLogSpool,
2965
3555
  createFileDurableSpool,
2966
3556
  createOtlpLogSink,
2967
3557
  createOtlpTraceSink,
2968
3558
  createSignalFanout,
2969
3559
  describeLogsDeliverability,
3560
+ exporterPolicyForDestination,
3561
+ isPermanentExportFailure,
2970
3562
  logSignalOf,
2971
3563
  logSignalsForLifecycleEvents,
2972
3564
  parentScopeRefOf,
2973
3565
  resolveLogsEndpoint,
2974
3566
  shareCorrelationPerBatch,
2975
3567
  spanScopeRefOf,
3568
+ spoolQueueNamesFor,
2976
3569
  startOnlySpanAttributes
2977
3570
  };
2978
3571
  //# sourceMappingURL=telemetry.js.map