@distilled.cloud/core 1.0.0-rc.17 → 1.0.0-rc.19

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