@distilled.cloud/core 1.0.0-rc.2 → 1.0.0-rc.21

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 (321) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +33 -0
  3. package/lib/_bundle/aws.js +2 -0
  4. package/lib/_bundle/aws.js.map +1 -0
  5. package/lib/_bundle/base.js +5 -0
  6. package/lib/_bundle/base.js.map +1 -0
  7. package/lib/_bundle/graphql.js +3 -0
  8. package/lib/_bundle/graphql.js.map +1 -0
  9. package/lib/_bundle/grpc.js +3 -0
  10. package/lib/_bundle/grpc.js.map +1 -0
  11. package/lib/_bundle/rest.js +2 -0
  12. package/lib/_bundle/rest.js.map +1 -0
  13. package/lib/_bundle/xml.js +4 -0
  14. package/lib/_bundle/xml.js.map +1 -0
  15. package/lib/annotations.d.ts +17 -0
  16. package/lib/annotations.d.ts.map +1 -0
  17. package/lib/annotations.js +2 -0
  18. package/lib/annotations.js.map +1 -0
  19. package/lib/api.d.ts +220 -51
  20. package/lib/api.d.ts.map +1 -1
  21. package/lib/api.js +1 -178
  22. package/lib/category.d.ts +19 -16
  23. package/lib/category.d.ts.map +1 -1
  24. package/lib/category.js +1 -280
  25. package/lib/chunks.d.ts +3 -0
  26. package/lib/chunks.d.ts.map +1 -0
  27. package/lib/chunks.js +1 -0
  28. package/lib/config.d.ts +81 -0
  29. package/lib/config.d.ts.map +1 -0
  30. package/lib/config.js +1 -0
  31. package/lib/crypto.d.ts +76 -0
  32. package/lib/crypto.d.ts.map +1 -0
  33. package/lib/crypto.js +1 -0
  34. package/lib/error-category.d.ts +1 -1
  35. package/lib/error-category.d.ts.map +1 -1
  36. package/lib/error-category.js +1 -46
  37. package/lib/errors.d.ts +99 -74
  38. package/lib/errors.d.ts.map +1 -1
  39. package/lib/errors.js +1 -186
  40. package/lib/graphql.d.ts +420 -0
  41. package/lib/graphql.d.ts.map +1 -0
  42. package/lib/graphql.js +1 -0
  43. package/lib/graphql.types.d.ts +11 -0
  44. package/lib/graphql.types.d.ts.map +1 -0
  45. package/lib/graphql.types.js +1 -0
  46. package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
  47. package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
  48. package/lib/grpc-transport-cloudflare-http2.js +6 -0
  49. package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
  50. package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
  51. package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
  52. package/lib/grpc-transport-cloudflare-sockets.js +5 -0
  53. package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
  54. package/lib/grpc-transport-node-http2.d.ts +19 -0
  55. package/lib/grpc-transport-node-http2.d.ts.map +1 -0
  56. package/lib/grpc-transport-node-http2.js +2 -0
  57. package/lib/grpc-transport-node-http2.js.map +1 -0
  58. package/lib/grpc-transport.d.ts +111 -0
  59. package/lib/grpc-transport.d.ts.map +1 -0
  60. package/lib/grpc-transport.js +1 -0
  61. package/lib/hpack.d.ts +34 -0
  62. package/lib/hpack.d.ts.map +1 -0
  63. package/lib/hpack.js +2 -0
  64. package/lib/hpack.js.map +1 -0
  65. package/lib/index.d.ts +32 -0
  66. package/lib/index.d.ts.map +1 -0
  67. package/lib/index.js +17 -0
  68. package/lib/max-message-bytes.d.ts +42 -0
  69. package/lib/max-message-bytes.d.ts.map +1 -0
  70. package/lib/max-message-bytes.js +2 -0
  71. package/lib/max-message-bytes.js.map +1 -0
  72. package/lib/ndjson.d.ts +3 -0
  73. package/lib/ndjson.d.ts.map +1 -0
  74. package/lib/ndjson.js +2 -0
  75. package/lib/ndjson.js.map +1 -0
  76. package/lib/pagination.d.ts +105 -25
  77. package/lib/pagination.d.ts.map +1 -1
  78. package/lib/pagination.js +1 -182
  79. package/lib/plain-values.d.ts +21 -0
  80. package/lib/plain-values.d.ts.map +1 -0
  81. package/lib/plain-values.js +2 -0
  82. package/lib/plain-values.js.map +1 -0
  83. package/lib/protobuf.d.ts +85 -0
  84. package/lib/protobuf.d.ts.map +1 -0
  85. package/lib/protobuf.js +1 -0
  86. package/lib/protocol-grpc.d.ts +123 -0
  87. package/lib/protocol-grpc.d.ts.map +1 -0
  88. package/lib/protocol-grpc.js +1 -0
  89. package/lib/protocol-http.d.ts +206 -25
  90. package/lib/protocol-http.d.ts.map +1 -1
  91. package/lib/protocol-http.js +1 -554
  92. package/lib/protocol-rest.d.ts +258 -64
  93. package/lib/protocol-rest.d.ts.map +1 -1
  94. package/lib/protocol-rest.js +1 -242
  95. package/lib/protocol.d.ts +113 -0
  96. package/lib/protocol.d.ts.map +1 -0
  97. package/lib/protocol.js +0 -0
  98. package/lib/query.d.ts +29 -0
  99. package/lib/query.d.ts.map +1 -0
  100. package/lib/query.js +1 -0
  101. package/lib/response-validation-strict.d.ts +48 -0
  102. package/lib/response-validation-strict.d.ts.map +1 -0
  103. package/lib/response-validation-strict.js +1 -0
  104. package/lib/response-validation.d.ts +86 -0
  105. package/lib/response-validation.d.ts.map +1 -0
  106. package/lib/response-validation.js +1 -0
  107. package/lib/retry-after.d.ts +4 -4
  108. package/lib/retry-after.d.ts.map +1 -1
  109. package/lib/retry-after.js +1 -112
  110. package/lib/retry-state.d.ts +26 -0
  111. package/lib/retry-state.d.ts.map +1 -0
  112. package/lib/retry-state.js +2 -0
  113. package/lib/retry-state.js.map +1 -0
  114. package/lib/retry.d.ts +141 -42
  115. package/lib/retry.d.ts.map +1 -1
  116. package/lib/retry.js +1 -210
  117. package/lib/schema-lite-impl.d.ts +179 -0
  118. package/lib/schema-lite-impl.d.ts.map +1 -0
  119. package/lib/schema-lite-impl.js +1 -0
  120. package/lib/schema-lite-typed.d.ts +41 -0
  121. package/lib/schema-lite-typed.d.ts.map +1 -0
  122. package/lib/schema-lite-typed.js +1 -0
  123. package/lib/schema-lite.d.ts +41 -0
  124. package/lib/schema-lite.d.ts.map +1 -0
  125. package/lib/schema-lite.js +1 -0
  126. package/lib/schema.d.ts +21 -7
  127. package/lib/schema.d.ts.map +1 -1
  128. package/lib/schema.js +1 -48
  129. package/lib/sdk-error.d.ts +31 -0
  130. package/lib/sdk-error.d.ts.map +1 -0
  131. package/lib/sdk-error.js +1 -0
  132. package/lib/send.d.ts +37 -0
  133. package/lib/send.d.ts.map +1 -0
  134. package/lib/send.js +2 -0
  135. package/lib/send.js.map +1 -0
  136. package/lib/sensitive.d.ts +28 -0
  137. package/lib/sensitive.d.ts.map +1 -0
  138. package/lib/sensitive.js +2 -0
  139. package/lib/sensitive.js.map +1 -0
  140. package/lib/telemetry-debug.d.ts +6 -0
  141. package/lib/telemetry-debug.d.ts.map +1 -0
  142. package/lib/telemetry-debug.js +2 -0
  143. package/lib/telemetry-debug.js.map +1 -0
  144. package/lib/telemetry-hooks.d.ts +32 -0
  145. package/lib/telemetry-hooks.d.ts.map +1 -0
  146. package/lib/telemetry-hooks.js +2 -0
  147. package/lib/telemetry-hooks.js.map +1 -0
  148. package/lib/telemetry-host-rules.d.ts +23 -0
  149. package/lib/telemetry-host-rules.d.ts.map +1 -0
  150. package/lib/telemetry-host-rules.js +2 -0
  151. package/lib/telemetry-host-rules.js.map +1 -0
  152. package/lib/telemetry-lambda-context.d.ts +17 -0
  153. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  154. package/lib/telemetry-lambda-context.js +2 -0
  155. package/lib/telemetry-lambda-context.js.map +1 -0
  156. package/lib/telemetry-message-context.d.ts +52 -0
  157. package/lib/telemetry-message-context.d.ts.map +1 -0
  158. package/lib/telemetry-message-context.js +2 -0
  159. package/lib/telemetry-message-context.js.map +1 -0
  160. package/lib/telemetry-metrics.d.ts +6 -0
  161. package/lib/telemetry-metrics.d.ts.map +1 -0
  162. package/lib/telemetry-metrics.js +2 -0
  163. package/lib/telemetry-metrics.js.map +1 -0
  164. package/lib/telemetry-name-template.d.ts +13 -0
  165. package/lib/telemetry-name-template.d.ts.map +1 -0
  166. package/lib/telemetry-name-template.js +2 -0
  167. package/lib/telemetry-name-template.js.map +1 -0
  168. package/lib/telemetry-stream.d.ts +11 -0
  169. package/lib/telemetry-stream.d.ts.map +1 -0
  170. package/lib/telemetry-stream.js +2 -0
  171. package/lib/telemetry-stream.js.map +1 -0
  172. package/lib/telemetry-xray.d.ts +28 -0
  173. package/lib/telemetry-xray.d.ts.map +1 -0
  174. package/lib/telemetry-xray.js +2 -0
  175. package/lib/telemetry-xray.js.map +1 -0
  176. package/lib/telemetry.d.ts +317 -0
  177. package/lib/telemetry.d.ts.map +1 -0
  178. package/lib/telemetry.js +3 -0
  179. package/lib/telemetry.js.map +1 -0
  180. package/lib/token-cache.d.ts +31 -0
  181. package/lib/token-cache.d.ts.map +1 -0
  182. package/lib/token-cache.js +2 -0
  183. package/lib/token-cache.js.map +1 -0
  184. package/lib/trait.d.ts +94 -20
  185. package/lib/trait.d.ts.map +1 -1
  186. package/lib/trait.js +1 -107
  187. package/lib/unknown-error.d.ts +18 -0
  188. package/lib/unknown-error.d.ts.map +1 -0
  189. package/lib/unknown-error.js +1 -0
  190. package/lib/xml.d.ts +44 -0
  191. package/lib/xml.d.ts.map +1 -0
  192. package/lib/xml.js +1 -0
  193. package/package.json +13 -13
  194. package/src/annotations.ts +53 -0
  195. package/src/api.ts +1597 -234
  196. package/src/category.ts +97 -134
  197. package/src/chunks.ts +30 -0
  198. package/src/config.ts +261 -0
  199. package/src/crypto.ts +202 -0
  200. package/src/error-category.ts +16 -29
  201. package/src/errors.ts +99 -77
  202. package/src/graphql.ts +1817 -0
  203. package/src/graphql.types.ts +120 -0
  204. package/src/grpc-transport-cloudflare-http2.ts +569 -0
  205. package/src/grpc-transport-cloudflare-sockets.ts +368 -0
  206. package/src/grpc-transport-node-http2.ts +307 -0
  207. package/src/grpc-transport.ts +287 -0
  208. package/src/hpack.ts +331 -0
  209. package/src/index.ts +31 -0
  210. package/src/max-message-bytes.ts +58 -0
  211. package/src/ndjson.ts +55 -0
  212. package/src/pagination.ts +379 -94
  213. package/src/plain-values.ts +70 -0
  214. package/src/protobuf.ts +1367 -0
  215. package/src/protocol-grpc.ts +811 -0
  216. package/src/protocol-http.ts +1045 -371
  217. package/src/protocol-rest.ts +908 -255
  218. package/src/protocol.ts +150 -0
  219. package/src/query.ts +39 -0
  220. package/src/response-validation-strict.ts +333 -0
  221. package/src/response-validation.ts +161 -0
  222. package/src/retry-after.ts +8 -14
  223. package/src/retry-state.ts +105 -0
  224. package/src/retry.ts +260 -145
  225. package/src/schema-lite-impl.ts +621 -0
  226. package/src/schema-lite-typed.ts +44 -0
  227. package/src/schema-lite.ts +45 -0
  228. package/src/schema.ts +259 -15
  229. package/src/sdk-error.ts +37 -0
  230. package/src/send.ts +156 -0
  231. package/src/sensitive.ts +188 -0
  232. package/src/telemetry-debug.ts +179 -0
  233. package/src/telemetry-hooks.ts +33 -0
  234. package/src/telemetry-host-rules.ts +39 -0
  235. package/src/telemetry-lambda-context.ts +46 -0
  236. package/src/telemetry-message-context.ts +170 -0
  237. package/src/telemetry-metrics.ts +69 -0
  238. package/src/telemetry-name-template.ts +26 -0
  239. package/src/telemetry-stream.ts +100 -0
  240. package/src/telemetry-xray.ts +66 -0
  241. package/src/telemetry.ts +800 -0
  242. package/src/token-cache.ts +117 -0
  243. package/src/trait.ts +139 -67
  244. package/src/unknown-error.ts +38 -0
  245. package/src/xml.ts +346 -0
  246. package/lib/api.js.map +0 -1
  247. package/lib/category.js.map +0 -1
  248. package/lib/codegen/cli.d.ts +0 -29
  249. package/lib/codegen/cli.d.ts.map +0 -1
  250. package/lib/codegen/cli.js +0 -165
  251. package/lib/codegen/cli.js.map +0 -1
  252. package/lib/codegen/emit.d.ts +0 -129
  253. package/lib/codegen/emit.d.ts.map +0 -1
  254. package/lib/codegen/emit.js +0 -105
  255. package/lib/codegen/emit.js.map +0 -1
  256. package/lib/codegen/format.d.ts +0 -23
  257. package/lib/codegen/format.d.ts.map +0 -1
  258. package/lib/codegen/format.js +0 -28
  259. package/lib/codegen/format.js.map +0 -1
  260. package/lib/codegen/generator.d.ts +0 -334
  261. package/lib/codegen/generator.d.ts.map +0 -1
  262. package/lib/codegen/generator.js +0 -691
  263. package/lib/codegen/generator.js.map +0 -1
  264. package/lib/codegen/graph.d.ts +0 -36
  265. package/lib/codegen/graph.d.ts.map +0 -1
  266. package/lib/codegen/graph.js +0 -136
  267. package/lib/codegen/graph.js.map +0 -1
  268. package/lib/codegen/members.d.ts +0 -25
  269. package/lib/codegen/members.d.ts.map +0 -1
  270. package/lib/codegen/members.js +0 -55
  271. package/lib/codegen/members.js.map +0 -1
  272. package/lib/codegen/naming.d.ts +0 -29
  273. package/lib/codegen/naming.d.ts.map +0 -1
  274. package/lib/codegen/naming.js +0 -74
  275. package/lib/codegen/naming.js.map +0 -1
  276. package/lib/codegen/openapi-cli.d.ts +0 -38
  277. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  278. package/lib/codegen/openapi-cli.js +0 -107
  279. package/lib/codegen/openapi-cli.js.map +0 -1
  280. package/lib/codegen/openapi.d.ts +0 -115
  281. package/lib/codegen/openapi.d.ts.map +0 -1
  282. package/lib/codegen/openapi.js +0 -1220
  283. package/lib/codegen/openapi.js.map +0 -1
  284. package/lib/codegen/operations.d.ts +0 -24
  285. package/lib/codegen/operations.d.ts.map +0 -1
  286. package/lib/codegen/operations.js +0 -56
  287. package/lib/codegen/operations.js.map +0 -1
  288. package/lib/codegen/pagination.d.ts +0 -39
  289. package/lib/codegen/pagination.d.ts.map +0 -1
  290. package/lib/codegen/pagination.js +0 -33
  291. package/lib/codegen/pagination.js.map +0 -1
  292. package/lib/codegen/prelude.d.ts +0 -15
  293. package/lib/codegen/prelude.d.ts.map +0 -1
  294. package/lib/codegen/prelude.js +0 -60
  295. package/lib/codegen/prelude.js.map +0 -1
  296. package/lib/error-category.js.map +0 -1
  297. package/lib/errors.js.map +0 -1
  298. package/lib/json-patch.d.ts +0 -44
  299. package/lib/json-patch.d.ts.map +0 -1
  300. package/lib/json-patch.js +0 -174
  301. package/lib/json-patch.js.map +0 -1
  302. package/lib/pagination.js.map +0 -1
  303. package/lib/protocol-http.js.map +0 -1
  304. package/lib/protocol-rest.js.map +0 -1
  305. package/lib/retry-after.js.map +0 -1
  306. package/lib/retry.js.map +0 -1
  307. package/lib/schema.js.map +0 -1
  308. package/lib/trait.js.map +0 -1
  309. package/src/codegen/cli.ts +0 -268
  310. package/src/codegen/emit.ts +0 -207
  311. package/src/codegen/format.ts +0 -47
  312. package/src/codegen/generator.ts +0 -1153
  313. package/src/codegen/graph.ts +0 -151
  314. package/src/codegen/members.ts +0 -71
  315. package/src/codegen/naming.ts +0 -86
  316. package/src/codegen/openapi-cli.ts +0 -166
  317. package/src/codegen/openapi.ts +0 -1450
  318. package/src/codegen/operations.ts +0 -76
  319. package/src/codegen/pagination.ts +0 -71
  320. package/src/codegen/prelude.ts +0 -70
  321. package/src/json-patch.ts +0 -222
@@ -0,0 +1,800 @@
1
+ /**
2
+ * Telemetry shared by every distilled SDK.
3
+ *
4
+ * operation spans (always): one span per operation call, around every retry.
5
+ * Its name, kind and attributes come from the model's
6
+ * `com.distilled.telemetry` traits (see
7
+ * `packages/dev/src/codegen/telemetry-traits.md`), carried by the generated
8
+ * operation's `telemetry` and `span` config, plus the
9
+ * request's host and method and the response's status. It
10
+ * replaces Effect's HTTP span. Retries are attributes on it
11
+ * (attempts, errors, total backoff). A failure gets the
12
+ * user's call site as a stack frame, so `Cause.pretty`
13
+ * shows it.
14
+ * debug (opt in): spans for distilled's internals too, INTERNAL spans
15
+ * at trace level `Debug`: first-call setup, serialize, sign,
16
+ * deserialize, one `Attempt` per try, backoff sleeps, and the
17
+ * caller's `code.*` attributes; and `Effect.logDebug` lines
18
+ * for each call and HTTP exchange, the same for every SDK,
19
+ * with or without an exporter. Its code lives in
20
+ * `./telemetry-debug.ts`, so only programs that import it
21
+ * bundle it:
22
+ *
23
+ * ```ts
24
+ * import { TelemetryDebug } from "@distilled.cloud/core/telemetry-debug";
25
+ * program.pipe(Effect.provide(TelemetryDebug.layer));
26
+ * ```
27
+ *
28
+ * No span is recorded unless the app installs a tracer (an exporter).
29
+ */
30
+ import * as Context from "effect/Context";
31
+ import * as Effect from "effect/Effect";
32
+ import type * as Exit from "effect/Exit";
33
+ import * as Fiber from "effect/Fiber";
34
+ import * as HttpClient from "effect/http/HttpClient";
35
+ import type * as HttpClientError from "effect/http/HttpClientError";
36
+ import * as HttpClientRequest from "effect/http/HttpClientRequest";
37
+ import type * as HttpClientResponse from "effect/http/HttpClientResponse";
38
+ import * as Redacted from "effect/Redacted";
39
+ import type * as AST from "effect/SchemaAST";
40
+ import type * as Stream from "effect/Stream";
41
+ import * as Tracer from "effect/Tracer";
42
+ import { getAnn, getProps } from "./annotations.ts";
43
+
44
+ /**
45
+ * Debug mode's implementation, provided by `TelemetryDebug.layer`
46
+ * (`./telemetry-debug.ts`); undefined, the default, is operation spans only.
47
+ * The per-call path only checks whether it is set.
48
+ */
49
+ export interface DebugHooks {
50
+ /** An INTERNAL span around one of distilled's steps. */
51
+ readonly phase: <A, E, R>(
52
+ name: string,
53
+ effect: Effect.Effect<A, E, R>,
54
+ attributes?: Record<string, unknown>,
55
+ ) => Effect.Effect<A, E, R>;
56
+ /** Try `n` (1-based) as its own `Attempt` span. */
57
+ readonly attempt: <A, E, R>(base: Effect.Effect<A, E, R>, n: number) => Effect.Effect<A, E, R>;
58
+ /** The caller's read of a streamed output member, as a span under `parent`. */
59
+ readonly readStream: <A, E, R>(
60
+ stream: Stream.Stream<A, E, R>,
61
+ parent: Tracer.Span,
62
+ member: string,
63
+ ) => Stream.Stream<A, E, R>;
64
+ /**
65
+ * The operation call with its debug log lines: `Effect.logDebug` at the
66
+ * start (with the input) and on exit (with the output), every line inside
67
+ * annotated with the operation. With `schemas`, input and output are
68
+ * logged with their sensitive values `Redacted` (`./sensitive.ts`);
69
+ * without, they are left out.
70
+ */
71
+ readonly call: <A, E, R>(
72
+ info: OperationInfo,
73
+ input: unknown,
74
+ schemas: OperationSchemas | undefined,
75
+ effect: Effect.Effect<A, E, R>,
76
+ ) => Effect.Effect<A, E, R>;
77
+ /** One HTTP exchange (`sent`) with its debug log lines. */
78
+ readonly http: (
79
+ request: HttpClientRequest.HttpClientRequest,
80
+ sent: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
81
+ ) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>;
82
+ /** OTel `code.*` attributes for the caller's line. */
83
+ readonly callSite: (
84
+ callSite: (() => string | undefined) | undefined,
85
+ ) => Record<string, unknown> | undefined;
86
+ }
87
+
88
+ /** An operation's input and output schemas, for the debug log lines. */
89
+ export interface OperationSchemas {
90
+ readonly input: AST.AST;
91
+ readonly output: AST.AST;
92
+ }
93
+
94
+ export const Debug = /*@__PURE__*/ Context.Reference<DebugHooks | undefined>(
95
+ "@distilled.cloud/core/Telemetry/Debug",
96
+ { defaultValue: () => undefined },
97
+ );
98
+
99
+ /**
100
+ * The traced call running on this fiber: its operation span, the debug-mode
101
+ * attempt span of the current try, and the retry history so far. Protocols
102
+ * write through {@link annotate} synchronously, without an extra effect.
103
+ */
104
+ export interface Call {
105
+ readonly span: Tracer.Span;
106
+ readonly info: OperationInfo;
107
+ attempt: Tracer.Span | undefined;
108
+ readonly retryErrors: Array<string>;
109
+ retryDelayMs: number;
110
+ }
111
+
112
+ export const OperationSpan = /*@__PURE__*/ Context.Reference<Call | undefined>(
113
+ "@distilled.cloud/core/Telemetry/OperationSpan",
114
+ { defaultValue: () => undefined },
115
+ );
116
+
117
+ /**
118
+ * The untraced call's propagation (no exporter, so no operation span): the
119
+ * caller's parent span and the service's header format. Requests carry the
120
+ * parent's own trace context, as an OTel no-op tracer forwards it.
121
+ */
122
+ interface Forward {
123
+ readonly span: Tracer.AnySpan;
124
+ readonly propagate: NonNullable<ServiceTelemetry["propagate"]>;
125
+ }
126
+
127
+ const Forward = /*@__PURE__*/ Context.Reference<Forward | undefined>(
128
+ "@distilled.cloud/core/Telemetry/Forward",
129
+ { defaultValue: () => undefined },
130
+ );
131
+
132
+ //#region traits
133
+
134
+ /**
135
+ * How a value becomes an attribute value (`com.distilled.telemetry`
136
+ * transforms; see `packages/dev/src/codegen/telemetry-traits.md`).
137
+ */
138
+ export type Transform =
139
+ | "list"
140
+ | "keys"
141
+ | "count"
142
+ | "lastPathSegment"
143
+ | "arnResource"
144
+ | "arn"
145
+ | "jsonList"
146
+ | "nonZero";
147
+
148
+ export interface AttributeRule {
149
+ readonly name: string;
150
+ /** Dotted path into the member's value, read before the transform. */
151
+ readonly field?: string;
152
+ readonly transform?: Transform;
153
+ }
154
+
155
+ /**
156
+ * Extra facts for a request, by host (`hostRules` in
157
+ * `./telemetry-host-rules.ts`): `set` records an attribute on the span.
158
+ */
159
+ export type RequestHook = (
160
+ host: string,
161
+ span: Tracer.Span,
162
+ set: (key: string, value: unknown) => void,
163
+ ) => void;
164
+
165
+ /** The `com.distilled.telemetry#service` trait, as generated code carries it. */
166
+ export interface ServiceTelemetry {
167
+ readonly system: string;
168
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
169
+ readonly responseHeaders?: ReadonlyArray<AttributeRule & { readonly header: string }>;
170
+ /** From the trait's `hosts`. */
171
+ readonly onRequest?: RequestHook;
172
+ /**
173
+ * The rules every operation of this module follows, so its generated
174
+ * `span` holds only what differs (see {@link operationInfo}): span name
175
+ * `<prefix>.<op>`, `rpc.method` `<service>/<op>`, and each path label
176
+ * recorded as `<labels>.<label in snake_case>`.
177
+ */
178
+ readonly prefix?: string;
179
+ readonly service?: string;
180
+ readonly labels?: string;
181
+ /** Path labels named another way than `<labels>.<snake_case>`, by property. */
182
+ readonly labelNames?: Readonly<Record<string, string>>;
183
+ /** `false`: operations do not derive `url.template` (RPC protocols). */
184
+ readonly templates?: false;
185
+ /**
186
+ * How requests carry the span's trace context, from the trait's
187
+ * `propagation`: `"w3c"`, a `traceparent` header; or a function returning
188
+ * the header to set (X-Ray, `./telemetry-xray.ts`).
189
+ */
190
+ readonly propagate?: "w3c" | ((span: Tracer.AnySpan) => readonly [header: string, value: string]);
191
+ }
192
+
193
+ /** A span name for one call from its input attributes; undefined keeps the trait's `name`. */
194
+ export type SpanRename = (attributes: Readonly<Record<string, unknown>>) => string | undefined;
195
+
196
+ /**
197
+ * Runs an operation call in its span and keeps the span open after the call
198
+ * returns, until the caller has read a streamed output member (the trait's
199
+ * `stream`; built by `./telemetry-stream.ts`). Every other operation uses
200
+ * `Effect.useSpan`, which ends the span on return.
201
+ */
202
+ export type SpanHold = <A, E, R>(
203
+ fiber: Fiber.Fiber<unknown, unknown>,
204
+ name: string,
205
+ options: Tracer.SpanOptionsNoTrace,
206
+ debug: DebugHooks | undefined,
207
+ inSpan: (span: Tracer.Span) => Effect.Effect<A, E, R>,
208
+ ) => Effect.Effect<A, E, R>;
209
+
210
+ /** Read trace context back from an operation's messages (the trait's `extract`). */
211
+ export interface MessageExtract {
212
+ /** The input asking the service to return the trace context. */
213
+ readonly request: (input: unknown) => unknown;
214
+ /** Links to the spans the output's messages name. */
215
+ readonly links: (output: unknown) => ReadonlyArray<Tracer.SpanLink>;
216
+ }
217
+
218
+ /**
219
+ * The `com.distilled.telemetry#operation` trait plus its input members'
220
+ * rules. The trait's `nameTemplate`, `inject` and `extract` arrive as the
221
+ * functions `./telemetry-name-template.ts` and
222
+ * `./telemetry-message-context.ts` build from them.
223
+ */
224
+ export interface SpanConfig {
225
+ /**
226
+ * The operation's model name. With it, whatever this config leaves out
227
+ * follows the service's rules and the input schema's annotations.
228
+ */
229
+ readonly op?: string;
230
+ /** `false`: no `url.template`, whatever the service's rule. */
231
+ readonly template?: false;
232
+ readonly name?: string;
233
+ readonly method?: string;
234
+ readonly kind?: "client" | "producer" | "consumer";
235
+ /** Fixed attributes; `null` drops one the service sets. */
236
+ readonly attributes?: Readonly<Record<string, string | number | boolean | null>>;
237
+ /** `com.distilled.telemetry#attributes` of the input members, by property name. */
238
+ readonly input?: Readonly<Record<string, ReadonlyArray<AttributeRule>>>;
239
+ /**
240
+ * Attributes recorded under a second name once the request is built:
241
+ * `{ "cloud.region": "faas.invoked_region" }`.
242
+ */
243
+ readonly copy?: Readonly<Record<string, string>>;
244
+ /** The same, for output members: recorded when the call succeeds. */
245
+ readonly output?: Readonly<Record<string, ReadonlyArray<AttributeRule>>>;
246
+ readonly rename?: SpanRename;
247
+ /** Write the span's trace context into the request's messages. */
248
+ readonly inject?: (span: Tracer.Span, input: unknown) => unknown;
249
+ readonly extract?: MessageExtract;
250
+ /** Keep the span open until the caller has read a streamed output member. */
251
+ readonly hold?: SpanHold;
252
+ }
253
+
254
+ /** One operation's span facts, built once per operation. */
255
+ export interface OperationInfo {
256
+ /** Span name, e.g. `S3.GetObject`. */
257
+ readonly name: string;
258
+ readonly kind: "client" | "producer" | "consumer";
259
+ /** Fixed attributes: rpc.system.name, rpc.method, service and operation attributes. */
260
+ readonly attributes: Readonly<Record<string, unknown>>;
261
+ /** Input property and rule pairs, flattened. */
262
+ readonly input: ReadonlyArray<readonly [property: string, rule: AttributeRule]>;
263
+ readonly output: ReadonlyArray<readonly [property: string, rule: AttributeRule]>;
264
+ readonly responseHeaders: ReadonlyArray<AttributeRule & { readonly header: string }>;
265
+ readonly onRequest: RequestHook | undefined;
266
+ readonly propagate: ServiceTelemetry["propagate"];
267
+ readonly copy: SpanConfig["copy"];
268
+ readonly rename: SpanRename | undefined;
269
+ readonly inject: SpanConfig["inject"];
270
+ readonly extract: MessageExtract | undefined;
271
+ readonly hold: SpanHold | undefined;
272
+ }
273
+
274
+ const isScalar = (value: unknown): value is string | number | boolean =>
275
+ typeof value === "string" || typeof value === "number" || typeof value === "boolean";
276
+
277
+ const fieldOf = (value: unknown, path: string): unknown => {
278
+ let at = value;
279
+ for (const key of path.split(".")) {
280
+ if (at === null || typeof at !== "object") return undefined;
281
+ at = (at as Record<string, unknown>)[key];
282
+ }
283
+ return at;
284
+ };
285
+
286
+ const transform = (rule: AttributeRule, raw: unknown): unknown => {
287
+ const value = rule.field === undefined ? raw : fieldOf(raw, rule.field);
288
+ if (value === undefined || value === null || Redacted.isRedacted(value)) return undefined;
289
+ switch (rule.transform) {
290
+ case undefined:
291
+ return isScalar(value) || (Array.isArray(value) && value.length > 0 && value.every(isScalar))
292
+ ? value
293
+ : undefined;
294
+ case "nonZero":
295
+ return typeof value === "number" && value !== 0 ? value : undefined;
296
+ case "list":
297
+ return typeof value === "string" ? [value] : undefined;
298
+ case "keys":
299
+ return value !== null && typeof value === "object" ? Object.keys(value) : undefined;
300
+ case "count":
301
+ return Array.isArray(value) ? value.length : undefined;
302
+ case "lastPathSegment":
303
+ return typeof value === "string" ? value.slice(value.lastIndexOf("/") + 1) : undefined;
304
+ case "arnResource":
305
+ return typeof value === "string" ? value.slice(value.lastIndexOf(":") + 1) : undefined;
306
+ case "arn":
307
+ return typeof value === "string" && value.startsWith("arn:") ? value : undefined;
308
+ case "jsonList":
309
+ return Array.isArray(value)
310
+ ? value.map((v) => JSON.stringify(v))
311
+ : typeof value === "object"
312
+ ? [JSON.stringify(value)]
313
+ : undefined;
314
+ }
315
+ };
316
+
317
+ const HTTP = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/http");
318
+ const LABEL = /*@__PURE__*/ Symbol.for("@distilled.cloud/core/http/label");
319
+
320
+ /** `zoneId` / `zone-id` / `ZoneID` -> `zone_id`, as the trait defaults spell labels. */
321
+ const snakeCase = (name: string): string =>
322
+ name
323
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
324
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
325
+ .replace(/[^A-Za-z0-9]+/g, "_")
326
+ .toLowerCase();
327
+
328
+ /**
329
+ * The span facts of an operation from its generated `telemetry` and `span`
330
+ * config. A `span` naming its `op` (a string is just the op) derives what it
331
+ * leaves out, from the service's rules and the input schema:
332
+ *
333
+ * name `<service.prefix>.<op>`
334
+ * rpc.method `<service.service>/<op>`
335
+ * url.template the path of the input's `T.Http` uri, unless the service
336
+ * or the span says `false`
337
+ * input each `T.Label` property as `<service.labels>.<snake_case>`;
338
+ * an explicit entry replaces it (`[]` records nothing)
339
+ *
340
+ * The generator emits only what differs from these rules, so the result is
341
+ * exactly the model's `com.distilled.telemetry` traits. An operation
342
+ * generated without traits gets its operation name, or
343
+ * `distilled.operation`.
344
+ */
345
+ export const operationInfo = (
346
+ service: ServiceTelemetry | undefined,
347
+ config: SpanConfig | string | undefined,
348
+ operationName: string | undefined,
349
+ inputAst?: AST.AST,
350
+ ): OperationInfo => {
351
+ const span: SpanConfig | undefined = typeof config === "string" ? { op: config } : config;
352
+ const op = span?.op;
353
+ let rules = span?.input;
354
+ let template: string | undefined;
355
+ if (op !== undefined && inputAst !== undefined) {
356
+ if (service?.templates !== false && span?.template !== false) {
357
+ template = (getAnn(inputAst, HTTP) as { readonly uri?: string } | undefined)?.uri?.split(
358
+ "?",
359
+ )[0];
360
+ }
361
+ if (service?.labels !== undefined) {
362
+ const derived: Record<string, ReadonlyArray<AttributeRule>> = {};
363
+ for (const prop of getProps(inputAst)) {
364
+ if (getAnn(prop.type, LABEL) === undefined) continue;
365
+ const property = String(prop.name);
366
+ derived[property] = [
367
+ { name: service.labelNames?.[property] ?? `${service.labels}.${snakeCase(property)}` },
368
+ ];
369
+ }
370
+ rules = { ...derived, ...rules };
371
+ }
372
+ }
373
+ const input = flatten(rules);
374
+ const attributes: Record<string, unknown> = {
375
+ ...(service ? { "rpc.system.name": service.system } : {}),
376
+ ...service?.attributes,
377
+ ...(template !== undefined ? { "url.template": template } : {}),
378
+ ...span?.attributes,
379
+ };
380
+ for (const key in span?.attributes) if (attributes[key] === null) delete attributes[key];
381
+ const method =
382
+ span?.method ??
383
+ (op !== undefined && service?.service !== undefined ? `${service.service}/${op}` : undefined);
384
+ return {
385
+ name:
386
+ span?.name ??
387
+ (op !== undefined && service?.prefix !== undefined ? `${service.prefix}.${op}` : undefined) ??
388
+ operationName ??
389
+ "distilled.operation",
390
+ kind: span?.kind ?? "client",
391
+ attributes: method === undefined ? attributes : { "rpc.method": method, ...attributes },
392
+ input,
393
+ output: flatten(span?.output),
394
+ responseHeaders: service?.responseHeaders ?? [],
395
+ onRequest: service?.onRequest,
396
+ propagate: service?.propagate,
397
+ copy: span?.copy,
398
+ rename: span?.rename,
399
+ inject: span?.inject,
400
+ extract: span?.extract,
401
+ hold: span?.hold,
402
+ };
403
+ };
404
+
405
+ export const flatten = (
406
+ rules: Readonly<Record<string, ReadonlyArray<AttributeRule>>> | undefined,
407
+ ): Array<readonly [string, AttributeRule]> => {
408
+ const out: Array<readonly [string, AttributeRule]> = [];
409
+ for (const property in rules) {
410
+ for (const rule of rules[property]!) out.push([property, rule]);
411
+ }
412
+ return out;
413
+ };
414
+
415
+ /** Attributes the rules read from a value (the input or the output). Redacted values are skipped. */
416
+ export const readRules = (
417
+ rules: OperationInfo["input"],
418
+ value: unknown,
419
+ set: (key: string, value: unknown) => void,
420
+ ): void => {
421
+ if (rules.length === 0 || value === null || typeof value !== "object") return;
422
+ for (const [property, rule] of rules) {
423
+ const read = transform(rule, (value as Record<string, unknown>)[property]);
424
+ if (read !== undefined) set(rule.name, read);
425
+ }
426
+ };
427
+
428
+ /**
429
+ * An opt-in observer of every operation call (`./telemetry-metrics.ts`):
430
+ * wraps the call, whether or not a span is recorded.
431
+ */
432
+ export type Measure = <A, E, R>(
433
+ info: OperationInfo,
434
+ effect: Effect.Effect<A, E, R>,
435
+ ) => Effect.Effect<A, E, R>;
436
+
437
+ export const Metrics = /*@__PURE__*/ Context.Reference<Measure | undefined>(
438
+ "@distilled.cloud/core/Telemetry/Metrics",
439
+ { defaultValue: () => undefined },
440
+ );
441
+
442
+ /** App callbacks on each recorded operation span (`./telemetry-hooks.ts`). */
443
+ export interface SpanHooks {
444
+ readonly onStart?: (
445
+ span: Tracer.Span,
446
+ call: { readonly name: string; readonly method: unknown; readonly input: unknown },
447
+ ) => void;
448
+ readonly onEnd?: (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => void;
449
+ }
450
+
451
+ export const Hooks = /*@__PURE__*/ Context.Reference<SpanHooks | undefined>(
452
+ "@distilled.cloud/core/Telemetry/Hooks",
453
+ { defaultValue: () => undefined },
454
+ );
455
+
456
+ //#endregion
457
+
458
+ export const isDebug = (context: Context.Context<any>): boolean =>
459
+ Context.get(context, Debug) !== undefined;
460
+
461
+ /**
462
+ * Record a fact about the current try (status, request id, host): on the
463
+ * operation span, where the last try wins, and on the debug attempt span.
464
+ */
465
+ export const annotate = (context: Context.Context<any>, key: string, value: unknown): void => {
466
+ const call = Context.get(context, OperationSpan);
467
+ if (call === undefined) return;
468
+ call.span.attribute(key, value);
469
+ call.attempt?.attribute(key, value);
470
+ };
471
+
472
+ /**
473
+ * The request facts, recorded when it is sent (so a call that never gets a
474
+ * response still has them): method, host and port. Host only: the full URL
475
+ * can carry a presigned signature.
476
+ */
477
+ export const annotateRequest = (
478
+ context: Context.Context<any>,
479
+ method: string,
480
+ url: string,
481
+ ): void => {
482
+ if (Context.get(context, OperationSpan) === undefined) return;
483
+ const schemeEnd = url.indexOf("://");
484
+ const hostStart = schemeEnd + 3;
485
+ let hostEnd = hostStart;
486
+ while (hostEnd < url.length && !"/?#".includes(url[hostEnd]!)) hostEnd++;
487
+ const authority = url.slice(hostStart, hostEnd);
488
+ const colon = authority.lastIndexOf(":");
489
+ const hasPort = colon !== -1 && !authority.endsWith("]");
490
+ const host = hasPort ? authority.slice(0, colon) : authority;
491
+ annotate(context, "http.request.method", method);
492
+ annotate(context, "server.address", host);
493
+ annotate(
494
+ context,
495
+ "server.port",
496
+ hasPort ? Number(authority.slice(colon + 1)) : url.startsWith("https") ? 443 : 80,
497
+ );
498
+ const call = Context.get(context, OperationSpan)!;
499
+ call.info.onRequest?.(host, call.span, (key, value) => annotate(context, key, value));
500
+ for (const from in call.info.copy) {
501
+ const value = call.span.attributes.get(from);
502
+ if (value !== undefined) annotate(context, call.info.copy[from]!, value);
503
+ }
504
+ };
505
+
506
+ /**
507
+ * The response facts, for every protocol: status, and the response
508
+ * headers the service trait lists (request ids).
509
+ */
510
+ export const annotateResponse = (
511
+ context: Context.Context<any>,
512
+ status: number,
513
+ headers: Readonly<Record<string, string | undefined>>,
514
+ ): void => {
515
+ const call = Context.get(context, OperationSpan);
516
+ if (call === undefined) return;
517
+ annotate(context, "http.response.status_code", status);
518
+ for (const rule of call.info.responseHeaders) {
519
+ const value = headers[rule.header];
520
+ if (value !== undefined) annotate(context, rule.name, transform(rule, value));
521
+ }
522
+ };
523
+
524
+ /** The trace header for `span` in the service's format. */
525
+ const traceHeader = (
526
+ request: HttpClientRequest.HttpClientRequest,
527
+ propagate: NonNullable<ServiceTelemetry["propagate"]>,
528
+ span: Tracer.AnySpan,
529
+ ): HttpClientRequest.HttpClientRequest =>
530
+ propagate === "w3c"
531
+ ? HttpClientRequest.setHeader(
532
+ request,
533
+ "traceparent",
534
+ `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`,
535
+ )
536
+ : HttpClientRequest.setHeader(request, ...propagate(span));
537
+
538
+ /**
539
+ * `client.execute(request)` for the traced call on this fiber: the
540
+ * request facts before it is sent, the response facts when it returns.
541
+ * Untraced calls pay two context reads, and forward the caller's trace
542
+ * header if there is a parent span.
543
+ */
544
+ export const execute = (
545
+ context: Context.Context<any>,
546
+ client: HttpClient.HttpClient,
547
+ request: HttpClientRequest.HttpClientRequest,
548
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> => {
549
+ const debug = Context.get(context, Debug);
550
+ const sent = tracedExecute(context, client, request);
551
+ return debug === undefined ? sent : debug.http(request, sent);
552
+ };
553
+
554
+ const tracedExecute = (
555
+ context: Context.Context<any>,
556
+ client: HttpClient.HttpClient,
557
+ request: HttpClientRequest.HttpClientRequest,
558
+ ): Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError> => {
559
+ const call = Context.get(context, OperationSpan);
560
+ if (call === undefined) {
561
+ const forward = Context.get(context, Forward);
562
+ return client.execute(
563
+ forward === undefined ? request : traceHeader(request, forward.propagate, forward.span),
564
+ );
565
+ }
566
+ annotateRequest(context, request.method, request.url);
567
+ const propagate = call.info.propagate;
568
+ if (propagate !== undefined) request = traceHeader(request, propagate, call.attempt ?? call.span);
569
+ return Effect.map(client.execute(request), (response) => {
570
+ annotateResponse(
571
+ context,
572
+ response.status,
573
+ response.headers as Readonly<Record<string, string | undefined>>,
574
+ );
575
+ return response;
576
+ });
577
+ };
578
+
579
+ //#region retries
580
+
581
+ export const tagOf = (error: unknown): string =>
582
+ (error as { _tag?: string } | null)?._tag ?? "_OTHER";
583
+
584
+ /**
585
+ * Try `n` failed with `error` and the call retries after `delayMs`. The
586
+ * operation span carries the history, so a slow call shows why:
587
+ *
588
+ * distilled.attempts 5 (tries so far, including the next one)
589
+ * distilled.retry.errors ["SlowDown", "SlowDown", "SlowDown", "SlowDown"]
590
+ * distilled.retry.delay_ms 4087 (total backoff)
591
+ *
592
+ * A call that succeeds first time has none of them.
593
+ */
594
+ export const retried = (
595
+ context: Context.Context<any>,
596
+ n: number,
597
+ error: unknown,
598
+ delayMs: number,
599
+ ): void => {
600
+ const call = Context.get(context, OperationSpan);
601
+ if (call === undefined) return;
602
+ call.retryErrors.push(tagOf(error));
603
+ call.retryDelayMs += delayMs;
604
+ call.span.attribute("distilled.attempts", n + 1);
605
+ call.span.attribute("distilled.retry.errors", call.retryErrors.slice());
606
+ call.span.attribute("distilled.retry.delay_ms", Math.round(call.retryDelayMs));
607
+ };
608
+
609
+ //#endregion
610
+
611
+ /** Debug-only internal span around `effect`; `effect` itself otherwise. */
612
+ export const phase = <A, E, R>(
613
+ context: Context.Context<any>,
614
+ name: string,
615
+ effect: Effect.Effect<A, E, R>,
616
+ attributes?: Record<string, unknown>,
617
+ ): Effect.Effect<A, E, R> => {
618
+ const debug = Context.get(context, Debug);
619
+ return debug === undefined ? effect : debug.phase(name, effect, attributes);
620
+ };
621
+
622
+ //#region call site
623
+
624
+ // Frames inside any distilled package (workspace sources or installed).
625
+ const CORE_FRAME =
626
+ /[\\/](?:packages[\\/][^\\/]+[\\/](?:src|lib)[\\/]|@distilled\.cloud[\\/])|node:internal/;
627
+
628
+ /**
629
+ * Capture the caller of an operation, cheaply: `Error.captureStackTrace`
630
+ * drops `entry` (the operation function the user called) and every frame
631
+ * above it, so 2 frames are enough. V8 records them now and formats them
632
+ * only if someone reads `.stack` (an error rendered with `Cause.pretty`, or
633
+ * a debug span exporting `code.*`). Skipped when `Error.stackTraceLimit`
634
+ * is 0, the rule Effect's own spans follow.
635
+ */
636
+ export const captureCallSite = (entry: Function): (() => string | undefined) | undefined => {
637
+ const limit = Error.stackTraceLimit;
638
+ if (limit === 0) return undefined;
639
+ const holder: { stack?: string } = {};
640
+ Error.stackTraceLimit = 2;
641
+ if (typeof Error.captureStackTrace === "function") Error.captureStackTrace(holder, entry);
642
+ else holder.stack = new Error().stack;
643
+ Error.stackTraceLimit = limit;
644
+ let cache: string | undefined | null = null;
645
+ return () => {
646
+ if (cache !== null) return cache;
647
+ const lines = holder.stack?.split("\n") ?? [];
648
+ // Skip the "Error" line and any frame still inside distilled.
649
+ cache = lines
650
+ .slice(1)
651
+ .find((line) => !CORE_FRAME.test(line))
652
+ ?.trim();
653
+ return cache;
654
+ };
655
+ };
656
+
657
+ /**
658
+ * Build typed errors without a JS stack: their own
659
+ * frames all point into distilled's response decoder (noise), and the
660
+ * failure frame supplies the caller's line instead. Saves the frame capture
661
+ * on every error. Defects keep their stacks. Use inline:
662
+ *
663
+ * const saved = suppressStack();
664
+ * try { error = new Cls(...) } finally { restoreStack(saved) }
665
+ */
666
+ export const suppressStack = (): number | undefined => {
667
+ const limit = Error.stackTraceLimit;
668
+ if (limit === 0) return undefined;
669
+ Error.stackTraceLimit = 0;
670
+ return limit;
671
+ };
672
+
673
+ export const restoreStack = (saved: number | undefined): void => {
674
+ if (saved !== undefined) Error.stackTraceLimit = saved;
675
+ };
676
+
677
+ //#endregion
678
+
679
+ //#region operation span
680
+
681
+ const always = () => true;
682
+
683
+ /** Whether an app installed a tracer (an exporter); the native tracer exports nothing. */
684
+ const exporting = (fiber: Fiber.Fiber<unknown, unknown>): boolean => {
685
+ const tracer = fiber.cache.tracer;
686
+ return tracer !== undefined && tracer !== Tracer.nativeTracer;
687
+ };
688
+
689
+ /**
690
+ * One operation call (every attempt), with or without debug hooks.
691
+ *
692
+ * no exporter: no span. Effect's HTTP span is switched off too (nobody
693
+ * would see it); the failure frame still names the call.
694
+ * Requests still carry the caller's parent span, if any,
695
+ * in the service's trace header (`traceparent`, X-Ray).
696
+ * operation: one CLIENT span. Effect's HTTP span is switched off and
697
+ * protocols copy its facts (status, host, request id) onto
698
+ * this span, so one span per call.
699
+ * debug: the span is the parent of Effect's HTTP span (one per
700
+ * attempt) and of distilled's internal spans.
701
+ *
702
+ * Failures set `error.type` to the error's tag; Effect sets the status.
703
+ * An operation whose trait names a streamed output member (`stream`:
704
+ * Bedrock ConverseStream) keeps the span open until the caller has read
705
+ * that stream (`./telemetry-stream.ts`); every other span ends when the
706
+ * call returns, after the response headers.
707
+ */
708
+ export const operationSpan = <A, E, R>(
709
+ fiber: Fiber.Fiber<unknown, unknown>,
710
+ debug: DebugHooks | undefined,
711
+ info: OperationInfo,
712
+ callSite: (() => string | undefined) | undefined,
713
+ input: unknown,
714
+ run: (input: unknown) => Effect.Effect<A, E, R>,
715
+ schemas?: OperationSchemas,
716
+ ): Effect.Effect<A, E, R> => {
717
+ const measure = fiber.getRef(Metrics);
718
+ let traced = traceCall(fiber, debug, info, callSite, input, run);
719
+ if (debug !== undefined) traced = debug.call(info, input, schemas, traced);
720
+ return measure === undefined ? traced : measure(info, traced);
721
+ };
722
+
723
+ const traceCall = <A, E, R>(
724
+ fiber: Fiber.Fiber<unknown, unknown>,
725
+ debug: DebugHooks | undefined,
726
+ info: OperationInfo,
727
+ callSite: (() => string | undefined) | undefined,
728
+ input: unknown,
729
+ run: (input: unknown) => Effect.Effect<A, E, R>,
730
+ ): Effect.Effect<A, E, R> => {
731
+ if (!exporting(fiber)) {
732
+ let body = run(input);
733
+ if (debug === undefined)
734
+ body = Effect.provideService(body, HttpClient.TracerDisabledWhen, always);
735
+ const propagate = info.propagate;
736
+ if (propagate !== undefined) {
737
+ const span = Context.getOrUndefined(fiber.context, Tracer.ParentSpan);
738
+ if (span !== undefined) body = Effect.provideService(body, Forward, { span, propagate });
739
+ }
740
+ return body;
741
+ }
742
+ const attributes: Record<string, unknown> =
743
+ debug !== undefined
744
+ ? { ...info.attributes, ...debug.callSite(callSite) }
745
+ : { ...info.attributes };
746
+ readRules(info.input, input, (key, value) => (attributes[key] = value));
747
+ const hooks = fiber.getRef(Hooks);
748
+ const inSpan = (span: Tracer.Span): Effect.Effect<A, E, R> => {
749
+ const extract = info.extract;
750
+ let sent = info.inject === undefined ? input : info.inject(span, input);
751
+ if (extract !== undefined) sent = extract.request(sent);
752
+ let body = Effect.tapError(run(sent), (error) =>
753
+ Effect.sync(() => span.attribute("error.type", tagOf(error))),
754
+ );
755
+ if (extract !== undefined || info.output.length > 0) {
756
+ body = Effect.tap(body, (output) =>
757
+ Effect.sync(() => {
758
+ readRules(info.output, output, (key, value) => span.attribute(key, value));
759
+ if (extract !== undefined) {
760
+ const links = extract.links(output);
761
+ if (links.length > 0) span.addLinks(links);
762
+ }
763
+ }),
764
+ );
765
+ }
766
+ if (hooks !== undefined) {
767
+ hooks.onStart?.(span, { name: info.name, method: info.attributes["rpc.method"], input });
768
+ const onEnd = hooks.onEnd;
769
+ if (onEnd !== undefined) {
770
+ body = Effect.onExit(body, (exit) => Effect.sync(() => onEnd(span, exit)));
771
+ }
772
+ }
773
+ const call: Call = {
774
+ span,
775
+ info,
776
+ attempt: undefined,
777
+ retryErrors: [],
778
+ retryDelayMs: 0,
779
+ };
780
+ if (debug !== undefined) {
781
+ // ParentSpan directly: withParentSpan would also push a name-only
782
+ // stack frame, printed twice next to the failure frame.
783
+ return Effect.updateContext(body, (context: Context.Context<any>) =>
784
+ Context.add(Context.add(context, OperationSpan, call), Tracer.ParentSpan, span),
785
+ );
786
+ }
787
+ return Effect.updateContext(body, (context: Context.Context<any>) =>
788
+ Context.add(Context.add(context, OperationSpan, call), HttpClient.TracerDisabledWhen, always),
789
+ );
790
+ };
791
+ const name = info.rename?.(attributes) ?? info.name;
792
+ const options = { kind: info.kind, attributes };
793
+ const traced =
794
+ info.hold === undefined
795
+ ? Effect.useSpan(name, options, inSpan)
796
+ : info.hold(fiber, name, options, debug, inSpan);
797
+ return traced;
798
+ };
799
+
800
+ //#endregion