@smthrs/observability 0.35.0 → 1.0.0-rc.13

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.
Files changed (363) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +1 -1
  3. package/README.md +87 -0
  4. package/dist/cjs/BrowserOtel.d.ts +37 -0
  5. package/dist/cjs/BrowserOtel.d.ts.map +1 -0
  6. package/dist/cjs/BrowserOtel.js +47 -0
  7. package/dist/cjs/BrowserOtel.js.map +7 -0
  8. package/dist/cjs/Endpoint.d.ts +70 -0
  9. package/dist/cjs/Endpoint.d.ts.map +1 -0
  10. package/dist/cjs/Endpoint.js +85 -0
  11. package/dist/cjs/Endpoint.js.map +7 -0
  12. package/dist/cjs/JournalLogger.d.ts +232 -0
  13. package/dist/cjs/JournalLogger.d.ts.map +1 -0
  14. package/dist/cjs/JournalLogger.js +415 -0
  15. package/dist/cjs/JournalLogger.js.map +7 -0
  16. package/dist/cjs/Logger.d.ts +56 -0
  17. package/dist/cjs/Logger.d.ts.map +1 -0
  18. package/dist/cjs/Logger.js +72 -0
  19. package/dist/cjs/Logger.js.map +7 -0
  20. package/dist/cjs/Metric.d.ts +67 -0
  21. package/dist/cjs/Metric.d.ts.map +1 -0
  22. package/dist/cjs/Metric.js +68 -0
  23. package/dist/cjs/Metric.js.map +7 -0
  24. package/dist/cjs/NodeOtel.d.ts +42 -0
  25. package/dist/cjs/NodeOtel.d.ts.map +1 -0
  26. package/dist/cjs/NodeOtel.js +78 -0
  27. package/dist/cjs/NodeOtel.js.map +7 -0
  28. package/dist/cjs/Otel.d.ts +63 -0
  29. package/dist/cjs/Otel.d.ts.map +1 -0
  30. package/dist/cjs/Otel.js +75 -0
  31. package/dist/cjs/Otel.js.map +7 -0
  32. package/dist/cjs/Otlp.d.ts +203 -0
  33. package/dist/cjs/Otlp.d.ts.map +1 -0
  34. package/dist/cjs/Otlp.js +251 -0
  35. package/dist/cjs/Otlp.js.map +7 -0
  36. package/dist/cjs/Resource.d.ts +163 -0
  37. package/dist/cjs/Resource.d.ts.map +1 -0
  38. package/dist/cjs/Resource.js +186 -0
  39. package/dist/cjs/Resource.js.map +7 -0
  40. package/dist/cjs/index.d.ts +61 -0
  41. package/dist/cjs/index.d.ts.map +1 -0
  42. package/dist/cjs/index.js +47 -0
  43. package/dist/cjs/index.js.map +7 -0
  44. package/dist/cjs/internal/schemaIssuePath.d.ts +31 -0
  45. package/dist/cjs/internal/schemaIssuePath.d.ts.map +1 -0
  46. package/dist/cjs/internal/schemaIssuePath.js +49 -0
  47. package/dist/cjs/internal/schemaIssuePath.js.map +7 -0
  48. package/dist/cjs/package.json +1 -0
  49. package/dist/esm/BrowserOtel.d.ts +37 -0
  50. package/dist/esm/BrowserOtel.d.ts.map +1 -0
  51. package/dist/esm/BrowserOtel.js +24 -0
  52. package/dist/esm/BrowserOtel.js.map +1 -0
  53. package/dist/esm/Endpoint.d.ts +70 -0
  54. package/dist/esm/Endpoint.d.ts.map +1 -0
  55. package/dist/esm/Endpoint.js +110 -0
  56. package/dist/esm/Endpoint.js.map +1 -0
  57. package/dist/esm/JournalLogger.d.ts +232 -0
  58. package/dist/esm/JournalLogger.d.ts.map +1 -0
  59. package/dist/esm/JournalLogger.js +520 -0
  60. package/dist/esm/JournalLogger.js.map +1 -0
  61. package/dist/esm/Logger.d.ts +56 -0
  62. package/dist/esm/Logger.d.ts.map +1 -0
  63. package/dist/esm/Logger.js +61 -0
  64. package/dist/esm/Logger.js.map +1 -0
  65. package/dist/esm/Metric.d.ts +67 -0
  66. package/dist/esm/Metric.d.ts.map +1 -0
  67. package/dist/esm/Metric.js +80 -0
  68. package/dist/esm/Metric.js.map +1 -0
  69. package/dist/esm/NodeOtel.d.ts +42 -0
  70. package/dist/esm/NodeOtel.d.ts.map +1 -0
  71. package/dist/esm/NodeOtel.js +56 -0
  72. package/dist/esm/NodeOtel.js.map +1 -0
  73. package/dist/esm/Otel.d.ts +63 -0
  74. package/dist/esm/Otel.d.ts.map +1 -0
  75. package/dist/esm/Otel.js +52 -0
  76. package/dist/esm/Otel.js.map +1 -0
  77. package/dist/esm/Otlp.d.ts +203 -0
  78. package/dist/esm/Otlp.d.ts.map +1 -0
  79. package/dist/esm/Otlp.js +384 -0
  80. package/dist/esm/Otlp.js.map +1 -0
  81. package/dist/esm/Resource.d.ts +163 -0
  82. package/dist/esm/Resource.d.ts.map +1 -0
  83. package/dist/esm/Resource.js +238 -0
  84. package/dist/esm/Resource.js.map +1 -0
  85. package/dist/esm/index.d.ts +61 -0
  86. package/dist/esm/index.d.ts.map +1 -0
  87. package/dist/esm/index.js +61 -0
  88. package/dist/esm/index.js.map +1 -0
  89. package/dist/esm/internal/schemaIssuePath.d.ts +31 -0
  90. package/dist/esm/internal/schemaIssuePath.d.ts.map +1 -0
  91. package/dist/esm/internal/schemaIssuePath.js +59 -0
  92. package/dist/esm/internal/schemaIssuePath.js.map +1 -0
  93. package/docs/README.md +164 -0
  94. package/docs/api.md +780 -0
  95. package/docs/concepts/instrumentation-and-export.md +98 -0
  96. package/docs/concepts/layer-map.md +73 -0
  97. package/docs/concepts/validated-acquisition.md +106 -0
  98. package/docs/guides/export-to-a-collector.md +190 -0
  99. package/docs/guides/forward-logs-to-the-journal.md +226 -0
  100. package/docs/guides/install-a-logger.md +111 -0
  101. package/docs/guides/read-runtime-metrics.md +83 -0
  102. package/docs/guides/testing.md +134 -0
  103. package/docs/guides/wire-an-opentelemetry-sdk.md +226 -0
  104. package/docs/installation.md +102 -0
  105. package/docs/quickstart.md +145 -0
  106. package/docs/troubleshooting.md +168 -0
  107. package/package.json +221 -32
  108. package/src/BrowserOtel.ts +51 -0
  109. package/src/Endpoint.ts +131 -0
  110. package/src/JournalLogger.ts +635 -0
  111. package/src/Logger.ts +107 -0
  112. package/src/Metric.ts +88 -0
  113. package/src/NodeOtel.ts +90 -0
  114. package/src/Otel.ts +118 -0
  115. package/src/Otlp.ts +514 -0
  116. package/src/Resource.ts +325 -0
  117. package/src/index.ts +67 -0
  118. package/src/internal/schemaIssuePath.ts +65 -0
  119. package/docker-compose.otel.yml +0 -104
  120. package/grafana/dashboards/smithers-dashboard.json +0 -453
  121. package/grafana/provisioning/dashboards/dashboards.yml +0 -12
  122. package/grafana/provisioning/datasources/datasources.yml +0 -49
  123. package/loki/loki-config.yaml +0 -35
  124. package/otel-collector-config.yml +0 -38
  125. package/prometheus/prometheus.yml +0 -8
  126. package/src/MetricName.ts +0 -1
  127. package/src/MetricsServiceLive.js +0 -9
  128. package/src/README.md +0 -28
  129. package/src/ResolvedSmithersObservabilityOptions.ts +0 -12
  130. package/src/SmithersEvent.ts +0 -843
  131. package/src/SmithersLogFormat.ts +0 -1
  132. package/src/SmithersMetricDefinition.ts +0 -15
  133. package/src/SmithersMetricType.ts +0 -1
  134. package/src/SmithersMetricUnit.ts +0 -1
  135. package/src/SmithersObservability.js +0 -15
  136. package/src/SmithersObservabilityOptions.ts +0 -12
  137. package/src/SmithersObservabilityService.ts +0 -13
  138. package/src/_coreCorrelation/CorrelationContext.ts +0 -10
  139. package/src/_coreCorrelation/CorrelationContextLive.js +0 -11
  140. package/src/_coreCorrelation/CorrelationContextService.js +0 -15
  141. package/src/_coreCorrelation/CorrelationContextServiceShape.ts +0 -12
  142. package/src/_coreCorrelation/CorrelationPatch.ts +0 -3
  143. package/src/_coreCorrelation/README.md +0 -20
  144. package/src/_coreCorrelation/_correlationStorage.js +0 -4
  145. package/src/_coreCorrelation/correlationContextFiberRef.js +0 -5
  146. package/src/_coreCorrelation/correlationContextToLogAnnotations.js +0 -18
  147. package/src/_coreCorrelation/getCurrentCorrelationContext.js +0 -9
  148. package/src/_coreCorrelation/getCurrentCorrelationContextEffect.js +0 -11
  149. package/src/_coreCorrelation/index.js +0 -14
  150. package/src/_coreCorrelation/mergeCorrelationContext.js +0 -51
  151. package/src/_coreCorrelation/runWithCorrelationContext.js +0 -14
  152. package/src/_coreCorrelation/updateCurrentCorrelationContext.js +0 -17
  153. package/src/_coreCorrelation/withCorrelationContext.js +0 -38
  154. package/src/_coreCorrelation/withCurrentCorrelationContext.js +0 -11
  155. package/src/_coreMetrics.js +0 -14
  156. package/src/_coreMetricsShape.ts +0 -44
  157. package/src/_corePrometheus.js +0 -91
  158. package/src/_corePrometheusShape.ts +0 -11
  159. package/src/_coreTracing.js +0 -132
  160. package/src/_coreTracingShape.ts +0 -17
  161. package/src/_otelLogBuilders.js +0 -102
  162. package/src/_sessionFileResolvers.js +0 -164
  163. package/src/_smithersSpanAttributeAliases.js +0 -19
  164. package/src/_smithersTraceSpanStorage.js +0 -3
  165. package/src/_traceEventNormalizers.js +0 -499
  166. package/src/_traceRedaction.js +0 -162
  167. package/src/agentSessionEventToOtelLogRecord.js +0 -55
  168. package/src/agentTrace.ts +0 -144
  169. package/src/agentTraceCapabilities.js +0 -151
  170. package/src/annotateSmithersTrace.js +0 -11
  171. package/src/canonicalTraceEventToOtelLogRecord.js +0 -55
  172. package/src/correlation.js +0 -56
  173. package/src/createSmithersObservabilityLayer.js +0 -59
  174. package/src/createSmithersOtelLayer.js +0 -23
  175. package/src/createSmithersRuntimeLayer.js +0 -2
  176. package/src/detectAgentFamily.js +0 -26
  177. package/src/detectCaptureMode.js +0 -29
  178. package/src/emitOtelLogRecord.js +0 -19
  179. package/src/getCurrentSmithersTraceAnnotations.js +0 -14
  180. package/src/getCurrentSmithersTraceSpan.js +0 -7
  181. package/src/index.d.ts +0 -1392
  182. package/src/index.js +0 -137
  183. package/src/kindPhase.js +0 -17
  184. package/src/logging.js +0 -264
  185. package/src/makeSmithersSpanAttributes.js +0 -20
  186. package/src/metrics/README.md +0 -22
  187. package/src/metrics/SmithersMetricDefinition.ts +0 -17
  188. package/src/metrics/SmithersMetricType.ts +0 -1
  189. package/src/metrics/SmithersMetricUnit.ts +0 -1
  190. package/src/metrics/_asyncExternalWaitCounts.js +0 -4
  191. package/src/metrics/_buckets.js +0 -37
  192. package/src/metrics/_incrementGauge.js +0 -11
  193. package/src/metrics/_processStartMs.js +0 -1
  194. package/src/metrics/activeNodes.js +0 -2
  195. package/src/metrics/activeRuns.js +0 -2
  196. package/src/metrics/agentActionsTotal.js +0 -2
  197. package/src/metrics/agentDurationMs.js +0 -3
  198. package/src/metrics/agentErrorsTotal.js +0 -2
  199. package/src/metrics/agentEventsTotal.js +0 -2
  200. package/src/metrics/agentInvocationsTotal.js +0 -2
  201. package/src/metrics/agentRetriesTotal.js +0 -2
  202. package/src/metrics/agentSessionsTotal.js +0 -2
  203. package/src/metrics/agentTokensTotal.js +0 -2
  204. package/src/metrics/alertDeliveriesAttempted.js +0 -2
  205. package/src/metrics/alertDeliveriesSuppressed.js +0 -2
  206. package/src/metrics/alertsAcknowledgedTotal.js +0 -2
  207. package/src/metrics/alertsActive.js +0 -2
  208. package/src/metrics/alertsEscalatedTotal.js +0 -2
  209. package/src/metrics/alertsFiredTotal.js +0 -2
  210. package/src/metrics/alertsReopenedTotal.js +0 -2
  211. package/src/metrics/alertsResolvedTotal.js +0 -2
  212. package/src/metrics/alertsSilencedTotal.js +0 -2
  213. package/src/metrics/approvalPending.js +0 -2
  214. package/src/metrics/approvalWaitDuration.js +0 -5
  215. package/src/metrics/approvalsDenied.js +0 -2
  216. package/src/metrics/approvalsGranted.js +0 -2
  217. package/src/metrics/approvalsRequested.js +0 -2
  218. package/src/metrics/attemptDuration.js +0 -3
  219. package/src/metrics/attentionBacklog.js +0 -2
  220. package/src/metrics/cacheHits.js +0 -2
  221. package/src/metrics/cacheMisses.js +0 -2
  222. package/src/metrics/dbQueryDuration.js +0 -3
  223. package/src/metrics/dbRetries.js +0 -2
  224. package/src/metrics/dbTransactionDuration.js +0 -3
  225. package/src/metrics/dbTransactionRetries.js +0 -2
  226. package/src/metrics/dbTransactionRollbacks.js +0 -2
  227. package/src/metrics/devtoolsActiveSubscribers.js +0 -2
  228. package/src/metrics/devtoolsBackpressureDisconnectTotal.js +0 -2
  229. package/src/metrics/devtoolsDeltaBuildMs.js +0 -3
  230. package/src/metrics/devtoolsEventBytes.js +0 -3
  231. package/src/metrics/devtoolsEventTotal.js +0 -2
  232. package/src/metrics/devtoolsSnapshotBuildMs.js +0 -5
  233. package/src/metrics/devtoolsSubscribeTotal.js +0 -2
  234. package/src/metrics/errorsTotal.js +0 -2
  235. package/src/metrics/eventsEmittedTotal.js +0 -2
  236. package/src/metrics/externalWaitAsyncPending.js +0 -2
  237. package/src/metrics/gatewayApprovalDecisionsTotal.js +0 -2
  238. package/src/metrics/gatewayAuthEventsTotal.js +0 -2
  239. package/src/metrics/gatewayConnectionsActive.js +0 -2
  240. package/src/metrics/gatewayConnectionsClosedTotal.js +0 -2
  241. package/src/metrics/gatewayConnectionsTotal.js +0 -2
  242. package/src/metrics/gatewayCronTriggersTotal.js +0 -2
  243. package/src/metrics/gatewayErrorsTotal.js +0 -2
  244. package/src/metrics/gatewayHeartbeatTicksTotal.js +0 -2
  245. package/src/metrics/gatewayMessagesReceivedTotal.js +0 -2
  246. package/src/metrics/gatewayMessagesSentTotal.js +0 -2
  247. package/src/metrics/gatewayRpcCallsTotal.js +0 -2
  248. package/src/metrics/gatewayRpcDuration.js +0 -3
  249. package/src/metrics/gatewayRunEventBackpressureDisconnectTotal.js +0 -4
  250. package/src/metrics/gatewayRunsCompletedTotal.js +0 -2
  251. package/src/metrics/gatewayRunsStartedTotal.js +0 -2
  252. package/src/metrics/gatewaySignalsTotal.js +0 -2
  253. package/src/metrics/gatewayWebhooksReceivedTotal.js +0 -2
  254. package/src/metrics/gatewayWebhooksRejectedTotal.js +0 -2
  255. package/src/metrics/gatewayWebhooksVerifiedTotal.js +0 -2
  256. package/src/metrics/heartbeatDataSizeBytes.js +0 -5
  257. package/src/metrics/heartbeatIntervalMs.js +0 -3
  258. package/src/metrics/hotReloadDuration.js +0 -3
  259. package/src/metrics/hotReloadFailures.js +0 -2
  260. package/src/metrics/hotReloads.js +0 -2
  261. package/src/metrics/httpRequestDuration.js +0 -3
  262. package/src/metrics/httpRequests.js +0 -2
  263. package/src/metrics/index.d.ts +0 -1222
  264. package/src/metrics/index.js +0 -168
  265. package/src/metrics/memoryFactReads.js +0 -3
  266. package/src/metrics/memoryFactWrites.js +0 -3
  267. package/src/metrics/memoryMessageSaves.js +0 -3
  268. package/src/metrics/memoryRecallDuration.js +0 -11
  269. package/src/metrics/memoryRecallQueries.js +0 -3
  270. package/src/metrics/metricsServiceAdapter.js +0 -181
  271. package/src/metrics/nodeDuration.js +0 -3
  272. package/src/metrics/nodeRetriesTotal.js +0 -2
  273. package/src/metrics/nodesFailed.js +0 -2
  274. package/src/metrics/nodesFinished.js +0 -2
  275. package/src/metrics/nodesStarted.js +0 -2
  276. package/src/metrics/openApiToolCallErrorsTotal.js +0 -3
  277. package/src/metrics/openApiToolCallsTotal.js +0 -3
  278. package/src/metrics/openApiToolDuration.js +0 -9
  279. package/src/metrics/processHeapUsedBytes.js +0 -2
  280. package/src/metrics/processMemoryRssBytes.js +0 -2
  281. package/src/metrics/processUptimeSeconds.js +0 -2
  282. package/src/metrics/promptSizeBytes.js +0 -3
  283. package/src/metrics/replaysStarted.js +0 -3
  284. package/src/metrics/responseSizeBytes.js +0 -3
  285. package/src/metrics/rewindDurationMs.js +0 -3
  286. package/src/metrics/rewindFramesDeleted.js +0 -3
  287. package/src/metrics/rewindRollbackTotal.js +0 -2
  288. package/src/metrics/rewindSandboxesReverted.js +0 -3
  289. package/src/metrics/rewindTotal.js +0 -2
  290. package/src/metrics/runDuration.js +0 -3
  291. package/src/metrics/runForksCreated.js +0 -3
  292. package/src/metrics/runsAncestryDepth.js +0 -3
  293. package/src/metrics/runsCancelledTotal.js +0 -2
  294. package/src/metrics/runsCarriedStateBytes.js +0 -5
  295. package/src/metrics/runsContinuedTotal.js +0 -2
  296. package/src/metrics/runsFailedTotal.js +0 -2
  297. package/src/metrics/runsFinishedTotal.js +0 -2
  298. package/src/metrics/runsResumedTotal.js +0 -2
  299. package/src/metrics/runsTotal.js +0 -2
  300. package/src/metrics/sandboxActive.js +0 -2
  301. package/src/metrics/sandboxBundleSizeBytes.js +0 -5
  302. package/src/metrics/sandboxCompletedTotal.js +0 -2
  303. package/src/metrics/sandboxCreatedTotal.js +0 -2
  304. package/src/metrics/sandboxDurationMs.js +0 -3
  305. package/src/metrics/sandboxPatchCount.js +0 -3
  306. package/src/metrics/sandboxTransportDurationMs.js +0 -5
  307. package/src/metrics/schedulerConcurrencyUtilization.js +0 -2
  308. package/src/metrics/schedulerQueueDepth.js +0 -2
  309. package/src/metrics/schedulerWaitDuration.js +0 -5
  310. package/src/metrics/scorerDuration.js +0 -9
  311. package/src/metrics/scorerEventsFailed.js +0 -2
  312. package/src/metrics/scorerEventsFinished.js +0 -2
  313. package/src/metrics/scorerEventsStarted.js +0 -2
  314. package/src/metrics/scorersFailed.js +0 -3
  315. package/src/metrics/scorersFinished.js +0 -3
  316. package/src/metrics/scorersStarted.js +0 -3
  317. package/src/metrics/smithersMetricCatalog.js +0 -893
  318. package/src/metrics/smithersMetricCatalogByKey.js +0 -2
  319. package/src/metrics/smithersMetricCatalogByName.js +0 -2
  320. package/src/metrics/smithersMetricCatalogByPrometheusName.js +0 -4
  321. package/src/metrics/snapshotDuration.js +0 -9
  322. package/src/metrics/snapshotsCaptured.js +0 -3
  323. package/src/metrics/supervisorPollDuration.js +0 -5
  324. package/src/metrics/supervisorPollsTotal.js +0 -2
  325. package/src/metrics/supervisorResumeLag.js +0 -5
  326. package/src/metrics/supervisorResumedTotal.js +0 -2
  327. package/src/metrics/supervisorSkippedTotal.js +0 -2
  328. package/src/metrics/supervisorStaleDetected.js +0 -2
  329. package/src/metrics/taskHeartbeatTimeoutTotal.js +0 -2
  330. package/src/metrics/taskHeartbeatsTotal.js +0 -2
  331. package/src/metrics/timerDelayDuration.js +0 -3
  332. package/src/metrics/timersCancelled.js +0 -2
  333. package/src/metrics/timersCreated.js +0 -2
  334. package/src/metrics/timersFired.js +0 -2
  335. package/src/metrics/timersPending.js +0 -2
  336. package/src/metrics/toPrometheusMetricName.js +0 -8
  337. package/src/metrics/tokensCacheReadTotal.js +0 -2
  338. package/src/metrics/tokensCacheWriteTotal.js +0 -2
  339. package/src/metrics/tokensContextWindowBucketTotal.js +0 -2
  340. package/src/metrics/tokensContextWindowPerCall.js +0 -5
  341. package/src/metrics/tokensInputPerCall.js +0 -3
  342. package/src/metrics/tokensInputTotal.js +0 -2
  343. package/src/metrics/tokensOutputPerCall.js +0 -3
  344. package/src/metrics/tokensOutputTotal.js +0 -2
  345. package/src/metrics/tokensReasoningTotal.js +0 -2
  346. package/src/metrics/toolCallErrorsTotal.js +0 -2
  347. package/src/metrics/toolCallsTotal.js +0 -2
  348. package/src/metrics/toolDuration.js +0 -3
  349. package/src/metrics/toolOutputTruncatedTotal.js +0 -2
  350. package/src/metrics/trackEvent.js +0 -608
  351. package/src/metrics/updateAsyncExternalWaitPending.js +0 -18
  352. package/src/metrics/updateProcessMetrics.js +0 -20
  353. package/src/metrics/vcsDuration.js +0 -3
  354. package/src/normalizeStructuredEvent.js +0 -15
  355. package/src/prometheusContentType.js +0 -1
  356. package/src/renderPrometheusMetrics.js +0 -212
  357. package/src/resolveAgentTraceCapabilities.js +0 -59
  358. package/src/resolveSmithersObservabilityOptions.js +0 -109
  359. package/src/smithersMetrics.js +0 -2
  360. package/src/smithersSpanNames.js +0 -6
  361. package/src/unsupportedKindsForCapabilities.js +0 -32
  362. package/src/withSmithersSpan.js +0 -17
  363. package/tempo/tempo.yml +0 -17
@@ -0,0 +1,635 @@
1
+ /**
2
+ * Non-blocking forwarding of bounded operational logs to the durable journal.
3
+ *
4
+ * @since 0.1.0
5
+ */
6
+
7
+ import * as Journal from "@smthrs/journal/Journal"
8
+ import * as JournalEvent from "@smthrs/journal/JournalEvent"
9
+ import * as Redaction from "@smthrs/journal/Redaction"
10
+ import * as Cause from "effect/Cause"
11
+ import * as Context from "effect/Context"
12
+ import * as Effect from "effect/Effect"
13
+ import * as Layer from "effect/Layer"
14
+ import * as Logger from "effect/Logger"
15
+ import type * as LogLevel from "effect/LogLevel"
16
+ import * as EffectMetric from "effect/Metric"
17
+ import * as Option from "effect/Option"
18
+ import * as Queue from "effect/Queue"
19
+ import * as References from "effect/References"
20
+ import * as Schema from "effect/Schema"
21
+ import * as Tracer from "effect/Tracer"
22
+ import { schemaIssuePath } from "./internal/schemaIssuePath.ts"
23
+ import { droppedLogRecords } from "./Metric.ts"
24
+
25
+ /**
26
+ * Largest queue accepted by the forwarding logger.
27
+ *
28
+ * @category constants
29
+ * @since 1.0.0-rc.0
30
+ */
31
+ export const maximumCapacity = 65_536
32
+
33
+ /**
34
+ * Largest detached log payload admitted to the asynchronous queue.
35
+ *
36
+ * @category constants
37
+ * @since 1.0.0-rc.0
38
+ */
39
+ export const maximumSnapshotBytes = 1024 * 1024
40
+
41
+ /**
42
+ * Largest number of container members copied into one detached log payload.
43
+ *
44
+ * @category constants
45
+ * @since 1.0.0-rc.0
46
+ */
47
+ export const maximumSnapshotMembers = 4_096
48
+
49
+ /**
50
+ * Deepest container path copied into one detached log payload.
51
+ *
52
+ * @category constants
53
+ * @since 1.0.0-rc.0
54
+ */
55
+ export const maximumSnapshotDepth = 64
56
+
57
+ /**
58
+ * What a hostile or unreadable logged value becomes.
59
+ *
60
+ * @category constants
61
+ * @since 1.0.0-rc.0
62
+ */
63
+ export const unrenderableMarker = "[Unrenderable]"
64
+
65
+ /**
66
+ * What a value beyond a logger resource ceiling becomes.
67
+ *
68
+ * @category constants
69
+ * @since 1.0.0-rc.0
70
+ */
71
+ export const truncatedMarker = "[Truncated]"
72
+
73
+ /**
74
+ * Options for the journal forwarding logger.
75
+ *
76
+ * @category models
77
+ * @since 1.0.0-rc.0
78
+ */
79
+ export interface Options {
80
+ /** The run every forwarded record is attributed to. */
81
+ readonly runId: JournalEvent.RunId
82
+ /** Queue depth, 1 through {@link maximumCapacity}. Defaults to 256. */
83
+ readonly capacity?: number | undefined
84
+ /**
85
+ * Pins `References.MinimumLogLevel` for the whole application. Omitted, the
86
+ * layer leaves that reference alone and Effect's own `Info` default applies.
87
+ */
88
+ readonly minimumLogLevel?: LogLevel.LogLevel | undefined
89
+ /**
90
+ * Keeps the ambient loggers alongside the forwarder. Defaults to `false`,
91
+ * which replaces the ambient logger set.
92
+ */
93
+ readonly mergeWithExisting?: boolean | undefined
94
+ }
95
+
96
+ /**
97
+ * A stable logger configuration refusal.
98
+ *
99
+ * @category errors
100
+ * @since 1.0.0-rc.0
101
+ */
102
+ export class InvalidJournalLoggerOptions extends Schema.TaggedError<InvalidJournalLoggerOptions>()(
103
+ "@smthrs/observability/InvalidJournalLoggerOptions",
104
+ {
105
+ code: Schema.Literal("invalid_journal_logger_options"),
106
+ path: Schema.String,
107
+ message: Schema.String
108
+ }
109
+ ) {}
110
+
111
+ /**
112
+ * One typed failure retained from an Effect cause.
113
+ *
114
+ * @category schemas
115
+ * @since 1.0.0-rc.0
116
+ */
117
+ export const TelemetryFail = Schema.Struct({
118
+ _tag: Schema.Literal("Fail"),
119
+ error: Schema.Unknown
120
+ })
121
+
122
+ /**
123
+ * One unexpected defect retained from an Effect cause.
124
+ *
125
+ * @category schemas
126
+ * @since 1.0.0-rc.0
127
+ */
128
+ export const TelemetryDie = Schema.Struct({
129
+ _tag: Schema.Literal("Die"),
130
+ defect: Schema.Unknown
131
+ })
132
+
133
+ /**
134
+ * One interruption retained from an Effect cause.
135
+ *
136
+ * @category schemas
137
+ * @since 1.0.0-rc.0
138
+ */
139
+ export const TelemetryInterrupt = Schema.Struct({
140
+ _tag: Schema.Literal("Interrupt"),
141
+ fiberId: Schema.NullOr(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)))
142
+ })
143
+
144
+ /**
145
+ * One reason in a persisted telemetry cause.
146
+ *
147
+ * @category schemas
148
+ * @since 1.0.0-rc.0
149
+ */
150
+ export const TelemetryCauseReason = Schema.Union([TelemetryFail, TelemetryDie, TelemetryInterrupt])
151
+
152
+ /**
153
+ * One reason in a persisted telemetry cause.
154
+ *
155
+ * @category models
156
+ * @since 1.0.0-rc.0
157
+ */
158
+ export type TelemetryCauseReason = typeof TelemetryCauseReason.Type
159
+
160
+ /**
161
+ * A versioned structural Effect cause.
162
+ *
163
+ * Effect 4 stores composed failures as an ordered reason list. The projection
164
+ * preserves that order and each fail, defect, or interrupt discriminator.
165
+ *
166
+ * @category schemas
167
+ * @since 1.0.0-rc.0
168
+ */
169
+ export const TelemetryCause = Schema.Struct({
170
+ version: Schema.Literal(1),
171
+ reasons: Schema.Array(TelemetryCauseReason)
172
+ })
173
+
174
+ /**
175
+ * A versioned structural Effect cause.
176
+ *
177
+ * @category models
178
+ * @since 1.0.0-rc.0
179
+ */
180
+ export type TelemetryCause = typeof TelemetryCause.Type
181
+
182
+ /**
183
+ * Runtime schema for the operational log payload written to the journal.
184
+ *
185
+ * @category schemas
186
+ * @since 1.0.0-rc.0
187
+ */
188
+ export const TelemetryLog = Schema.Struct({
189
+ version: Schema.Literal(1),
190
+ level: Schema.Literals(["All", "Fatal", "Error", "Warn", "Info", "Debug", "Trace", "None"]),
191
+ message: Schema.Unknown,
192
+ annotations: Schema.Record(Schema.String, Schema.Unknown),
193
+ cause: TelemetryCause,
194
+ fiberId: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
195
+ traceId: Schema.optionalKey(Schema.String),
196
+ spanId: Schema.optionalKey(Schema.String),
197
+ timestamp: Schema.String
198
+ })
199
+
200
+ /**
201
+ * Versioned operational log payload written to the journal.
202
+ *
203
+ * @category models
204
+ * @since 1.0.0-rc.0
205
+ */
206
+ export type TelemetryLog = typeof TelemetryLog.Type
207
+
208
+ const sourceId = "flows/observability/logger" as JournalEvent.SourceId
209
+ const encoder = new TextEncoder()
210
+
211
+ const OptionsSchema = Schema.Struct({
212
+ runId: JournalEvent.RunId,
213
+ capacity: Schema.optional(
214
+ Schema.Int.check(
215
+ Schema.isGreaterThanOrEqualTo(1),
216
+ Schema.isLessThanOrEqualTo(maximumCapacity)
217
+ )
218
+ ),
219
+ minimumLogLevel: Schema.optional(
220
+ Schema.Literals(["All", "Fatal", "Error", "Warn", "Info", "Debug", "Trace", "None"])
221
+ ),
222
+ mergeWithExisting: Schema.optional(Schema.Boolean)
223
+ })
224
+
225
+ const validateOptions = (options: Options) =>
226
+ Schema.decodeUnknownEffect(OptionsSchema)(options).pipe(
227
+ Effect.mapError((cause) => {
228
+ const path = schemaIssuePath(cause, "options")
229
+ return new InvalidJournalLoggerOptions({
230
+ code: "invalid_journal_logger_options",
231
+ path,
232
+ message: `journal logger ${path} is invalid`
233
+ })
234
+ })
235
+ )
236
+
237
+ interface SnapshotBudget {
238
+ bytes: number
239
+ members: number
240
+ }
241
+
242
+ const reserve = (budget: SnapshotBudget, bytes: number): boolean => {
243
+ if (bytes > budget.bytes) return false
244
+ budget.bytes -= bytes
245
+ return true
246
+ }
247
+
248
+ const textBytes = (value: string): number => encoder.encode(JSON.stringify(value)).byteLength
249
+
250
+ const shortEscapes = new Set([0x08, 0x09, 0x0a, 0x0c, 0x0d])
251
+
252
+ /** Bytes one non-surrogate code unit occupies inside a JSON string body. */
253
+ const unitBytes = (code: number): number => {
254
+ if (code === 0x22 || code === 0x5c) return 2
255
+ if (code < 0x20) return shortEscapes.has(code) ? 2 : 6
256
+ if (code < 0x80) return 1
257
+ if (code < 0x800) return 2
258
+ return 3
259
+ }
260
+
261
+ const isLowSurrogate = (code: number): boolean => code >= 0xdc00 && code <= 0xdfff
262
+
263
+ /** Code units that occupy exactly one byte inside a JSON string body. */
264
+ const plainRun = /[\x20\x21\x23-\x5b\x5d-\x7f]*/y
265
+
266
+ /** One-byte units read one at a time before the rest of their run is matched natively. */
267
+ const plainStreak = 16
268
+
269
+ /**
270
+ * The longest prefix whose JSON string body fits `limit` bytes, measured in one
271
+ * forward pass. A surrogate pair is admitted or refused whole, so the retained
272
+ * text is well formed whenever the input is.
273
+ *
274
+ * Plain text is one byte per unit, so once a streak of it starts, the rest of
275
+ * the run is matched natively instead of unit by unit. The match reads a window
276
+ * one unit past the bytes still free, never the tail the cut drops.
277
+ */
278
+ const boundedPrefix = (value: string, limit: number): { readonly text: string; readonly bytes: number } => {
279
+ let bytes = 0
280
+ let index = 0
281
+ let streak = 0
282
+ while (index < value.length) {
283
+ if (streak >= plainStreak) {
284
+ plainRun.lastIndex = 0
285
+ plainRun.test(value.slice(index, index + limit - bytes + 1))
286
+ const run = plainRun.lastIndex
287
+ const admitted = Math.min(run, limit - bytes)
288
+ bytes += admitted
289
+ index += admitted
290
+ if (admitted < run) break
291
+ streak = 0
292
+ continue
293
+ }
294
+ const code = value.charCodeAt(index)
295
+ let width = 1
296
+ let cost: number
297
+ if (code >= 0xd800 && code <= 0xdbff && isLowSurrogate(value.charCodeAt(index + 1))) {
298
+ width = 2
299
+ cost = 4
300
+ } else if (code >= 0xd800 && code <= 0xdfff) {
301
+ cost = 6
302
+ } else {
303
+ cost = unitBytes(code)
304
+ }
305
+ if (bytes + cost > limit) break
306
+ bytes += cost
307
+ index += width
308
+ streak = cost === 1 ? streak + 1 : 0
309
+ }
310
+ return { text: value.slice(0, index), bytes }
311
+ }
312
+
313
+ const boundedText = (value: string, budget: SnapshotBudget): string => {
314
+ if (value.length <= maximumSnapshotBytes && reserve(budget, textBytes(value))) return value
315
+ const markerBytes = textBytes(truncatedMarker)
316
+ const prefix = boundedPrefix(value, Math.max(0, budget.bytes - markerBytes))
317
+ budget.bytes = Math.max(0, budget.bytes - prefix.bytes - markerBytes)
318
+ return `${prefix.text}${truncatedMarker}`
319
+ }
320
+
321
+ /**
322
+ * Error fields read through the prototype chain, in the order the snapshot
323
+ * projects them before any own data property the error added.
324
+ */
325
+ const standardErrorKeys = ["name", "message", "stack", "cause"] as const
326
+
327
+ /** Reads inherited data fields without invoking accessors or walking forever. */
328
+ const errorField = (value: object, key: string): unknown => {
329
+ let current: object | null = value
330
+ for (let depth = 0; current !== null && depth <= maximumSnapshotDepth; depth++) {
331
+ const descriptor = Object.getOwnPropertyDescriptor(current, key)
332
+ if (descriptor !== undefined) return "value" in descriptor ? descriptor.value : unrenderableMarker
333
+ current = Object.getPrototypeOf(current)
334
+ }
335
+ return current === null ? undefined : truncatedMarker
336
+ }
337
+
338
+ const snapshotValue = (
339
+ value: unknown,
340
+ budget: SnapshotBudget,
341
+ ancestors: WeakSet<object>,
342
+ depth = 0
343
+ ): unknown => {
344
+ if (budget.bytes <= 0) return truncatedMarker
345
+ if (depth > maximumSnapshotDepth) return Redaction.depthMarker
346
+ if (typeof value === "string") return boundedText(value, budget)
347
+ if (typeof value === "number") {
348
+ const projected = Number.isFinite(value) ? value : String(value)
349
+ reserve(budget, String(projected).length)
350
+ return projected
351
+ }
352
+ if (typeof value === "boolean" || value === null) {
353
+ reserve(budget, value === null ? 4 : value ? 4 : 5)
354
+ return value
355
+ }
356
+ if (typeof value === "bigint") return boundedText(`${value}n`, budget)
357
+ if (value === undefined) return boundedText("[Undefined]", budget)
358
+ if (typeof value === "function") return boundedText(Redaction.functionMarker, budget)
359
+ if (typeof value === "symbol") return boundedText(Redaction.symbolMarker, budget)
360
+ try {
361
+ if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer) {
362
+ return boundedText(Redaction.binaryMarker, budget)
363
+ }
364
+ } catch {
365
+ return boundedText(unrenderableMarker, budget)
366
+ }
367
+ if (ancestors.has(value)) return boundedText("[Circular]", budget)
368
+ ancestors.add(value)
369
+ try {
370
+ if (value instanceof Date) {
371
+ try {
372
+ return boundedText(Date.prototype.toISOString.call(value), budget)
373
+ } catch {
374
+ return boundedText(unrenderableMarker, budget)
375
+ }
376
+ }
377
+ if (value instanceof Error) {
378
+ const record: Record<string, unknown> = Object.create(null)
379
+ for (const key of standardErrorKeys.slice(0, budget.members)) {
380
+ budget.members--
381
+ try {
382
+ record[key] = snapshotValue(errorField(value, key), budget, ancestors, depth + 1)
383
+ } catch {
384
+ record[key] = unrenderableMarker
385
+ }
386
+ }
387
+ // Tagged failures (`_tag`, domain fields) and system errors (`code`,
388
+ // `path`, `syscall`) keep their diagnostics as own data properties, so
389
+ // the walk that projects plain records runs over the remaining keys.
390
+ let names: ReadonlyArray<string>
391
+ try {
392
+ names = Object.getOwnPropertyNames(value).filter((key) =>
393
+ !(standardErrorKeys as ReadonlyArray<string>).includes(key)
394
+ )
395
+ } catch {
396
+ return record
397
+ }
398
+ let projected = 0
399
+ let collided = false
400
+ for (; projected < names.length && budget.members > 0; projected++) {
401
+ budget.members--
402
+ const key = names[projected]!
403
+ const boundedKey = boundedText(key, budget)
404
+ if (Object.hasOwn(record, boundedKey)) {
405
+ collided = true
406
+ continue
407
+ }
408
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)
409
+ record[boundedKey] = descriptor !== undefined && "value" in descriptor
410
+ ? snapshotValue(descriptor.value, budget, ancestors, depth + 1)
411
+ : unrenderableMarker
412
+ }
413
+ if (collided || projected < names.length) record[truncatedMarker] = truncatedMarker
414
+ return record
415
+ }
416
+ if (Array.isArray(value)) {
417
+ const output: Array<unknown> = []
418
+ const length = value.length
419
+ for (let index = 0; index < length && budget.members > 0; index++) {
420
+ budget.members--
421
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index))
422
+ output.push(
423
+ descriptor === undefined || !("value" in descriptor)
424
+ ? unrenderableMarker
425
+ : snapshotValue(descriptor.value, budget, ancestors, depth + 1)
426
+ )
427
+ }
428
+ if (output.length < length) output.push(truncatedMarker)
429
+ return output
430
+ }
431
+ const record: Record<string, unknown> = Object.create(null)
432
+ const names = Object.getOwnPropertyNames(value)
433
+ for (let index = 0; index < names.length && budget.members > 0; index++) {
434
+ budget.members--
435
+ const key = names[index]!
436
+ const descriptor = Object.getOwnPropertyDescriptor(value, key)
437
+ const boundedKey = boundedText(key, budget)
438
+ // A key truncated to fit the budget can read exactly like one already
439
+ // copied. The first member keeps its slot; the later one is dropped and
440
+ // the record is marked truncated below rather than silently overwritten.
441
+ if (Object.hasOwn(record, boundedKey)) continue
442
+ record[boundedKey] = descriptor !== undefined && "value" in descriptor
443
+ ? snapshotValue(descriptor.value, budget, ancestors, depth + 1)
444
+ : unrenderableMarker
445
+ }
446
+ if (Object.keys(record).length < names.length) record[truncatedMarker] = truncatedMarker
447
+ return record
448
+ } catch {
449
+ return boundedText(unrenderableMarker, budget)
450
+ } finally {
451
+ ancestors.delete(value)
452
+ }
453
+ }
454
+
455
+ const snapshotCause = (cause: Cause.Cause<unknown>, budget: SnapshotBudget): TelemetryCause => ({
456
+ version: 1,
457
+ reasons: cause.reasons.slice(0, maximumSnapshotMembers).map((reason): TelemetryCauseReason => {
458
+ switch (reason._tag) {
459
+ case "Fail":
460
+ return { _tag: "Fail", error: snapshotValue(reason.error, budget, new WeakSet()) }
461
+ case "Die":
462
+ return { _tag: "Die", defect: snapshotValue(reason.defect, budget, new WeakSet()) }
463
+ case "Interrupt":
464
+ return { _tag: "Interrupt", fiberId: reason.fiberId ?? null }
465
+ }
466
+ })
467
+ })
468
+
469
+ const isTelemetryLog = Schema.is(TelemetryLog)
470
+
471
+ /**
472
+ * Annotations are a container in the durable schema, so a snapshot that spent
473
+ * the budget names the loss inside a record instead of replacing the record
474
+ * with a scalar the schema refuses.
475
+ */
476
+ const snapshotAnnotations = (value: unknown, budget: SnapshotBudget): Readonly<Record<string, unknown>> => {
477
+ const snapshot = snapshotValue(value, budget, new WeakSet())
478
+ return typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot)
479
+ ? snapshot as Readonly<Record<string, unknown>>
480
+ : { [truncatedMarker]: truncatedMarker }
481
+ }
482
+
483
+ const snapshotLog = (options: Logger.Options<unknown>): TelemetryLog => {
484
+ const budget: SnapshotBudget = {
485
+ bytes: maximumSnapshotBytes,
486
+ members: maximumSnapshotMembers
487
+ }
488
+ try {
489
+ const span = Option.getOrUndefined(Context.getOption(options.fiber.context, Tracer.ParentSpan))
490
+ let candidate: TelemetryLog = {
491
+ version: 1,
492
+ level: options.logLevel,
493
+ message: typeof options.message === "string" ? "" : snapshotValue(options.message, budget, new WeakSet()),
494
+ annotations: snapshotAnnotations(options.fiber.getRef(References.CurrentLogAnnotations), budget),
495
+ cause: snapshotCause(options.cause, budget),
496
+ fiberId: options.fiber.id,
497
+ ...(span === undefined ? {} : { traceId: span.traceId, spanId: span.spanId }),
498
+ timestamp: options.date.toISOString()
499
+ }
500
+ // A scalar message can spend the whole value budget. Reserve the actual
501
+ // record envelope first so the final size check does not discard its prefix.
502
+ if (typeof options.message === "string") {
503
+ budget.bytes = Math.max(0, maximumSnapshotBytes - encoder.encode(JSON.stringify(candidate)).byteLength + 2)
504
+ candidate = { ...candidate, message: boundedText(options.message, budget) }
505
+ }
506
+ const redacted = Redaction.redact(candidate, { onTooDeep: "name" }) as TelemetryLog
507
+ // The durable row is only useful if the exported schema decodes it, so an
508
+ // oversized or schema-invalid projection degrades to the total record
509
+ // rather than to a payload every consumer throws on.
510
+ return encoder.encode(JSON.stringify(redacted)).byteLength <= maximumSnapshotBytes && isTelemetryLog(redacted)
511
+ ? redacted
512
+ : { ...candidate, message: truncatedMarker, annotations: {}, cause: { version: 1, reasons: [] } }
513
+ } catch {
514
+ return {
515
+ version: 1,
516
+ level: options.logLevel,
517
+ message: unrenderableMarker,
518
+ annotations: {},
519
+ cause: { version: 1, reasons: [] },
520
+ fiberId: options.fiber.id,
521
+ timestamp: options.date.toISOString()
522
+ }
523
+ }
524
+ }
525
+
526
+ const makeLog = (options: Logger.Options<unknown>, runId: JournalEvent.RunId): JournalEvent.Input =>
527
+ new JournalEvent.Input({
528
+ runId,
529
+ sourceId,
530
+ // The journal owns the durable per-run/source allocation. A local counter
531
+ // starts over when a layer is rebuilt and makes distinct records collide.
532
+ eventType: "telemetry.log",
533
+ payload: snapshotLog(options),
534
+ meta: {
535
+ version: 1,
536
+ source: "/observability"
537
+ }
538
+ })
539
+
540
+ /**
541
+ * Installs a bounded, drop-on-overflow logger forwarder for one explicit run.
542
+ *
543
+ * Configuration is decoded before a worker starts. The callback reads the
544
+ * queue's remaining room first, snapshots and redacts a bounded DTO
545
+ * synchronously only when a slot is free, then performs only non-blocking
546
+ * queue admission. A record a saturated queue cannot take is counted and
547
+ * discarded without being snapshotted. Queue overflow, journal `Dropped` receipts, delivery failures,
548
+ * and journal defects each advance `Metric.droppedLogRecords`. The two failure
549
+ * paths also warn through the ambient loggers with a fixed code and run id,
550
+ * and the worker keeps draining. `Accepted` and `Duplicate` do not advance the
551
+ * counter. Admission receipts cannot identify later drop-oldest evictions of
552
+ * these records or report asynchronous persistence failures or shutdown losses.
553
+ * Closing the scope interrupts the worker and may drop records still queued
554
+ * behind an in-flight write without advancing the counter.
555
+ *
556
+ * The layer replaces the ambient logger set unless `mergeWithExisting` is
557
+ * `true`, and provides `MinimumLogLevel` only when `minimumLogLevel` is given,
558
+ * so an application that set that reference elsewhere keeps it.
559
+ *
560
+ * @category layers
561
+ * @since 1.0.0-rc.0
562
+ */
563
+ export const layerJournalForwarding = (
564
+ options: Options
565
+ ): Layer.Layer<never, InvalidJournalLoggerOptions, Journal.Journal> =>
566
+ Layer.unwrap(
567
+ Effect.map(validateOptions(options), (configured) =>
568
+ Layer.merge(
569
+ Layer.effect(
570
+ Logger.CurrentLoggers,
571
+ Effect.gen(function*() {
572
+ const journal = yield* Journal.Journal
573
+ const queue = yield* Queue.bounded<JournalEvent.Input>(configured.capacity ?? 256)
574
+ const dropped = EffectMetric.update(droppedLogRecords, 1)
575
+ // This worker is forked before the logger it feeds is installed, so
576
+ // its ambient logger set cannot contain that logger and a warning
577
+ // here cannot enqueue itself. Delivery stays lossy; the loss is
578
+ // reported and counted instead of vanishing. Warning annotations
579
+ // use fixed codes so ambient sinks never receive raw failures.
580
+ const forward = Effect.fn("JournalLogger.forward")((input: JournalEvent.Input) =>
581
+ journal.emitLossy(input).pipe(
582
+ Effect.tap((receipt) => receipt._tag === "Dropped" ? dropped : Effect.void),
583
+ Effect.catch(() =>
584
+ dropped.pipe(
585
+ Effect.andThen(
586
+ Effect.annotateLogs(Effect.logWarning("A telemetry log record could not be forwarded"), {
587
+ runId: configured.runId,
588
+ code: "journal_forwarding_failed"
589
+ })
590
+ )
591
+ )
592
+ )
593
+ )
594
+ )
595
+ yield* Effect.forever(
596
+ Queue.take(queue).pipe(
597
+ Effect.flatMap(forward),
598
+ // A defect from a journal implementation would otherwise end
599
+ // this fiber for the rest of the run, silently, while the layer
600
+ // still looks installed. Interruption stays fatal.
601
+ Effect.catchCause((cause) =>
602
+ Cause.hasInterruptsOnly(cause)
603
+ ? Effect.failCause(cause)
604
+ : dropped.pipe(
605
+ Effect.andThen(
606
+ Effect.annotateLogs(
607
+ Effect.logWarning("The telemetry forwarding worker recovered from a defect"),
608
+ { runId: configured.runId, code: "journal_forwarding_defect" }
609
+ )
610
+ )
611
+ )
612
+ )
613
+ )
614
+ ).pipe(Effect.forkScoped)
615
+
616
+ const logger = Logger.make<unknown, void>((logOptions) => {
617
+ // Snapshotting and redacting the record is the expensive half of
618
+ // admission, and saturation is exactly when that work is thrown
619
+ // away, so a queue with no room refuses before the record is
620
+ // built. Nothing else runs between this read and the offer, so
621
+ // the check cannot refuse a record the queue would have taken,
622
+ // and the offer still reports a queue that closed underneath it.
623
+ const accepted = !Queue.isFullUnsafe(queue)
624
+ && Queue.offerUnsafe(queue, makeLog(logOptions, configured.runId))
625
+ if (!accepted) droppedLogRecords.updateUnsafe(1, logOptions.fiber.context)
626
+ })
627
+ const current = yield* Effect.withFiber((fiber) => Effect.sync(() => fiber.getRef(Logger.CurrentLoggers)))
628
+ return new Set(configured.mergeWithExisting === true ? current : []).add(logger)
629
+ })
630
+ ),
631
+ configured.minimumLogLevel === undefined
632
+ ? Layer.empty
633
+ : Layer.succeed(References.MinimumLogLevel, configured.minimumLogLevel)
634
+ ))
635
+ )