@distilled.cloud/core 1.0.0-rc.16 → 1.0.0-rc.18

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 (306) hide show
  1. package/lib/_bundle/aws.js +2 -0
  2. package/lib/_bundle/aws.js.map +1 -0
  3. package/lib/_bundle/base.js +5 -0
  4. package/lib/_bundle/base.js.map +1 -0
  5. package/lib/_bundle/graphql.js +3 -0
  6. package/lib/_bundle/graphql.js.map +1 -0
  7. package/lib/_bundle/rest.js +2 -0
  8. package/lib/_bundle/rest.js.map +1 -0
  9. package/lib/_bundle/xml.js +4 -0
  10. package/lib/_bundle/xml.js.map +1 -0
  11. package/lib/annotations.d.ts +15 -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 +15 -0
  16. package/lib/api.d.ts.map +1 -1
  17. package/lib/api.js +1 -796
  18. package/lib/category.d.ts.map +1 -1
  19. package/lib/category.js +1 -278
  20. package/lib/chunks.js +1 -11
  21. package/lib/config.d.ts +54 -13
  22. package/lib/config.d.ts.map +1 -1
  23. package/lib/config.js +1 -161
  24. package/lib/crypto.js +1 -130
  25. package/lib/debug.d.ts.map +1 -1
  26. package/lib/debug.js +1 -8
  27. package/lib/error-category.d.ts.map +1 -1
  28. package/lib/error-category.js +1 -47
  29. package/lib/errors.d.ts +2 -13
  30. package/lib/errors.d.ts.map +1 -1
  31. package/lib/errors.js +1 -198
  32. package/lib/graphql.d.ts +14 -0
  33. package/lib/graphql.d.ts.map +1 -1
  34. package/lib/graphql.js +1 -1058
  35. package/lib/graphql.types.js +1 -6
  36. package/lib/index.d.ts +3 -2
  37. package/lib/index.d.ts.map +1 -1
  38. package/lib/index.js +1 -15
  39. package/lib/pagination.d.ts +34 -2
  40. package/lib/pagination.d.ts.map +1 -1
  41. package/lib/pagination.js +1 -271
  42. package/lib/plain-values.js +1 -39
  43. package/lib/plain-values.js.map +1 -1
  44. package/lib/protocol-http.d.ts +30 -6
  45. package/lib/protocol-http.d.ts.map +1 -1
  46. package/lib/protocol-http.js +1 -812
  47. package/lib/protocol-rest.d.ts +53 -39
  48. package/lib/protocol-rest.d.ts.map +1 -1
  49. package/lib/protocol-rest.js +1 -375
  50. package/lib/query.js +1 -27
  51. package/lib/response-validation-strict.js +1 -284
  52. package/lib/response-validation.d.ts +4 -3
  53. package/lib/response-validation.d.ts.map +1 -1
  54. package/lib/response-validation.js +1 -118
  55. package/lib/retry-after.js +1 -112
  56. package/lib/retry.js +1 -197
  57. package/lib/schema-lite-impl.js +1 -341
  58. package/lib/schema-lite-typed.js +1 -27
  59. package/lib/schema-lite.js +1 -31
  60. package/lib/schema.js +1 -220
  61. package/lib/telemetry-debug.d.ts +14 -0
  62. package/lib/telemetry-debug.d.ts.map +1 -0
  63. package/lib/telemetry-debug.js +2 -0
  64. package/lib/telemetry-debug.js.map +1 -0
  65. package/lib/telemetry-hooks.d.ts +32 -0
  66. package/lib/telemetry-hooks.d.ts.map +1 -0
  67. package/lib/telemetry-hooks.js +2 -0
  68. package/lib/telemetry-hooks.js.map +1 -0
  69. package/lib/telemetry-host-rules.d.ts +23 -0
  70. package/lib/telemetry-host-rules.d.ts.map +1 -0
  71. package/lib/telemetry-host-rules.js +2 -0
  72. package/lib/telemetry-host-rules.js.map +1 -0
  73. package/lib/telemetry-lambda-context.d.ts +17 -0
  74. package/lib/telemetry-lambda-context.d.ts.map +1 -0
  75. package/lib/telemetry-lambda-context.js +2 -0
  76. package/lib/telemetry-lambda-context.js.map +1 -0
  77. package/lib/telemetry-message-context.d.ts +52 -0
  78. package/lib/telemetry-message-context.d.ts.map +1 -0
  79. package/lib/telemetry-message-context.js +2 -0
  80. package/lib/telemetry-message-context.js.map +1 -0
  81. package/lib/telemetry-metrics.d.ts +6 -0
  82. package/lib/telemetry-metrics.d.ts.map +1 -0
  83. package/lib/telemetry-metrics.js +2 -0
  84. package/lib/telemetry-metrics.js.map +1 -0
  85. package/lib/telemetry-name-template.d.ts +13 -0
  86. package/lib/telemetry-name-template.d.ts.map +1 -0
  87. package/lib/telemetry-name-template.js +2 -0
  88. package/lib/telemetry-name-template.js.map +1 -0
  89. package/lib/telemetry-stream.d.ts +9 -0
  90. package/lib/telemetry-stream.d.ts.map +1 -0
  91. package/lib/telemetry-stream.js +2 -0
  92. package/lib/telemetry-stream.js.map +1 -0
  93. package/lib/telemetry-xray.d.ts +28 -0
  94. package/lib/telemetry-xray.d.ts.map +1 -0
  95. package/lib/telemetry-xray.js +2 -0
  96. package/lib/telemetry-xray.js.map +1 -0
  97. package/lib/telemetry.d.ts +269 -0
  98. package/lib/telemetry.d.ts.map +1 -0
  99. package/lib/telemetry.js +3 -0
  100. package/lib/telemetry.js.map +1 -0
  101. package/lib/trait.js +1 -131
  102. package/lib/xml.js +1 -323
  103. package/package.json +1 -3
  104. package/src/annotations.ts +37 -0
  105. package/src/api.ts +130 -30
  106. package/src/category.ts +21 -22
  107. package/src/config.ts +58 -29
  108. package/src/debug.ts +9 -6
  109. package/src/error-category.ts +12 -14
  110. package/src/errors.ts +7 -7
  111. package/src/graphql.ts +123 -18
  112. package/src/index.ts +3 -2
  113. package/src/pagination.ts +119 -6
  114. package/src/protocol-http.ts +63 -43
  115. package/src/protocol-rest.ts +201 -140
  116. package/src/response-validation.ts +4 -3
  117. package/src/telemetry-debug.ts +135 -0
  118. package/src/telemetry-hooks.ts +33 -0
  119. package/src/telemetry-host-rules.ts +39 -0
  120. package/src/telemetry-lambda-context.ts +46 -0
  121. package/src/telemetry-message-context.ts +170 -0
  122. package/src/telemetry-metrics.ts +69 -0
  123. package/src/telemetry-name-template.ts +26 -0
  124. package/src/telemetry-stream.ts +91 -0
  125. package/src/telemetry-xray.ts +66 -0
  126. package/src/telemetry.ts +768 -0
  127. package/lib/api.js.map +0 -1
  128. package/lib/category.js.map +0 -1
  129. package/lib/chunks.js.map +0 -1
  130. package/lib/codegen/boolean-string-enums.d.ts +0 -36
  131. package/lib/codegen/boolean-string-enums.d.ts.map +0 -1
  132. package/lib/codegen/boolean-string-enums.js +0 -147
  133. package/lib/codegen/boolean-string-enums.js.map +0 -1
  134. package/lib/codegen/chunk.d.ts +0 -7
  135. package/lib/codegen/chunk.d.ts.map +0 -1
  136. package/lib/codegen/chunk.js +0 -139
  137. package/lib/codegen/chunk.js.map +0 -1
  138. package/lib/codegen/cli.d.ts +0 -80
  139. package/lib/codegen/cli.d.ts.map +0 -1
  140. package/lib/codegen/cli.js +0 -166
  141. package/lib/codegen/cli.js.map +0 -1
  142. package/lib/codegen/datafy.d.ts +0 -14
  143. package/lib/codegen/datafy.d.ts.map +0 -1
  144. package/lib/codegen/datafy.js +0 -853
  145. package/lib/codegen/datafy.js.map +0 -1
  146. package/lib/codegen/dedupe.d.ts +0 -5
  147. package/lib/codegen/dedupe.d.ts.map +0 -1
  148. package/lib/codegen/dedupe.js +0 -153
  149. package/lib/codegen/dedupe.js.map +0 -1
  150. package/lib/codegen/emit.d.ts +0 -125
  151. package/lib/codegen/emit.d.ts.map +0 -1
  152. package/lib/codegen/emit.js +0 -99
  153. package/lib/codegen/emit.js.map +0 -1
  154. package/lib/codegen/format.d.ts +0 -11
  155. package/lib/codegen/format.d.ts.map +0 -1
  156. package/lib/codegen/format.js +0 -32
  157. package/lib/codegen/format.js.map +0 -1
  158. package/lib/codegen/generated-at.d.ts +0 -29
  159. package/lib/codegen/generated-at.d.ts.map +0 -1
  160. package/lib/codegen/generated-at.js +0 -78
  161. package/lib/codegen/generated-at.js.map +0 -1
  162. package/lib/codegen/generator.d.ts +0 -353
  163. package/lib/codegen/generator.d.ts.map +0 -1
  164. package/lib/codegen/generator.js +0 -810
  165. package/lib/codegen/generator.js.map +0 -1
  166. package/lib/codegen/graph.d.ts +0 -36
  167. package/lib/codegen/graph.d.ts.map +0 -1
  168. package/lib/codegen/graph.js +0 -136
  169. package/lib/codegen/graph.js.map +0 -1
  170. package/lib/codegen/graphql-client.d.ts +0 -70
  171. package/lib/codegen/graphql-client.d.ts.map +0 -1
  172. package/lib/codegen/graphql-client.js +0 -439
  173. package/lib/codegen/graphql-client.js.map +0 -1
  174. package/lib/codegen/graphql.d.ts +0 -207
  175. package/lib/codegen/graphql.d.ts.map +0 -1
  176. package/lib/codegen/graphql.js +0 -786
  177. package/lib/codegen/graphql.js.map +0 -1
  178. package/lib/codegen/latin1.d.ts +0 -3
  179. package/lib/codegen/latin1.d.ts.map +0 -1
  180. package/lib/codegen/latin1.js +0 -126
  181. package/lib/codegen/latin1.js.map +0 -1
  182. package/lib/codegen/members.d.ts +0 -32
  183. package/lib/codegen/members.d.ts.map +0 -1
  184. package/lib/codegen/members.js +0 -62
  185. package/lib/codegen/members.js.map +0 -1
  186. package/lib/codegen/model-diff.d.ts +0 -10
  187. package/lib/codegen/model-diff.d.ts.map +0 -1
  188. package/lib/codegen/model-diff.js +0 -67
  189. package/lib/codegen/model-diff.js.map +0 -1
  190. package/lib/codegen/naming.d.ts +0 -29
  191. package/lib/codegen/naming.d.ts.map +0 -1
  192. package/lib/codegen/naming.js +0 -74
  193. package/lib/codegen/naming.js.map +0 -1
  194. package/lib/codegen/openapi-cli.d.ts +0 -52
  195. package/lib/codegen/openapi-cli.d.ts.map +0 -1
  196. package/lib/codegen/openapi-cli.js +0 -84
  197. package/lib/codegen/openapi-cli.js.map +0 -1
  198. package/lib/codegen/openapi.d.ts +0 -209
  199. package/lib/codegen/openapi.d.ts.map +0 -1
  200. package/lib/codegen/openapi.js +0 -1548
  201. package/lib/codegen/openapi.js.map +0 -1
  202. package/lib/codegen/operations.d.ts +0 -24
  203. package/lib/codegen/operations.d.ts.map +0 -1
  204. package/lib/codegen/operations.js +0 -56
  205. package/lib/codegen/operations.js.map +0 -1
  206. package/lib/codegen/pagination.d.ts +0 -39
  207. package/lib/codegen/pagination.d.ts.map +0 -1
  208. package/lib/codegen/pagination.js +0 -31
  209. package/lib/codegen/pagination.js.map +0 -1
  210. package/lib/codegen/patch-audit.d.ts +0 -84
  211. package/lib/codegen/patch-audit.d.ts.map +0 -1
  212. package/lib/codegen/patch-audit.js +0 -366
  213. package/lib/codegen/patch-audit.js.map +0 -1
  214. package/lib/codegen/patches.d.ts +0 -129
  215. package/lib/codegen/patches.d.ts.map +0 -1
  216. package/lib/codegen/patches.js +0 -472
  217. package/lib/codegen/patches.js.map +0 -1
  218. package/lib/codegen/prelude.d.ts +0 -15
  219. package/lib/codegen/prelude.d.ts.map +0 -1
  220. package/lib/codegen/prelude.js +0 -60
  221. package/lib/codegen/prelude.js.map +0 -1
  222. package/lib/codegen/privatize.d.ts +0 -21
  223. package/lib/codegen/privatize.d.ts.map +0 -1
  224. package/lib/codegen/privatize.js +0 -176
  225. package/lib/codegen/privatize.js.map +0 -1
  226. package/lib/codegen/proto.d.ts +0 -121
  227. package/lib/codegen/proto.d.ts.map +0 -1
  228. package/lib/codegen/proto.js +0 -960
  229. package/lib/codegen/proto.js.map +0 -1
  230. package/lib/codegen/pure.d.ts +0 -6
  231. package/lib/codegen/pure.d.ts.map +0 -1
  232. package/lib/codegen/pure.js +0 -91
  233. package/lib/codegen/pure.js.map +0 -1
  234. package/lib/codegen/rewrite-operation-ids.d.ts +0 -154
  235. package/lib/codegen/rewrite-operation-ids.d.ts.map +0 -1
  236. package/lib/codegen/rewrite-operation-ids.js +0 -1117
  237. package/lib/codegen/rewrite-operation-ids.js.map +0 -1
  238. package/lib/codegen/spec-path.d.ts +0 -16
  239. package/lib/codegen/spec-path.d.ts.map +0 -1
  240. package/lib/codegen/spec-path.js +0 -101
  241. package/lib/codegen/spec-path.js.map +0 -1
  242. package/lib/codegen/table.d.ts +0 -5
  243. package/lib/codegen/table.d.ts.map +0 -1
  244. package/lib/codegen/table.js +0 -249
  245. package/lib/codegen/table.js.map +0 -1
  246. package/lib/config.js.map +0 -1
  247. package/lib/crypto.js.map +0 -1
  248. package/lib/debug.js.map +0 -1
  249. package/lib/error-category.js.map +0 -1
  250. package/lib/errors.js.map +0 -1
  251. package/lib/graphql.js.map +0 -1
  252. package/lib/graphql.types.js.map +0 -1
  253. package/lib/index.js.map +0 -1
  254. package/lib/json-patch.d.ts +0 -58
  255. package/lib/json-patch.d.ts.map +0 -1
  256. package/lib/json-patch.js +0 -227
  257. package/lib/json-patch.js.map +0 -1
  258. package/lib/pagination.js.map +0 -1
  259. package/lib/protocol-http.js.map +0 -1
  260. package/lib/protocol-rest.js.map +0 -1
  261. package/lib/query.js.map +0 -1
  262. package/lib/response-validation-strict.js.map +0 -1
  263. package/lib/response-validation.js.map +0 -1
  264. package/lib/retry-after.js.map +0 -1
  265. package/lib/retry.js.map +0 -1
  266. package/lib/schema-lite-impl.js.map +0 -1
  267. package/lib/schema-lite-typed.js.map +0 -1
  268. package/lib/schema-lite.js.map +0 -1
  269. package/lib/schema.js.map +0 -1
  270. package/lib/testing.d.ts +0 -40
  271. package/lib/testing.d.ts.map +0 -1
  272. package/lib/testing.js +0 -42
  273. package/lib/testing.js.map +0 -1
  274. package/lib/trait.js.map +0 -1
  275. package/lib/xml.js.map +0 -1
  276. package/src/codegen/boolean-string-enums.ts +0 -155
  277. package/src/codegen/chunk.ts +0 -147
  278. package/src/codegen/cli.ts +0 -293
  279. package/src/codegen/datafy.ts +0 -874
  280. package/src/codegen/dedupe.ts +0 -173
  281. package/src/codegen/emit.ts +0 -200
  282. package/src/codegen/format.ts +0 -49
  283. package/src/codegen/generated-at.ts +0 -88
  284. package/src/codegen/generator.ts +0 -1229
  285. package/src/codegen/graph.ts +0 -151
  286. package/src/codegen/graphql-client.ts +0 -545
  287. package/src/codegen/graphql.ts +0 -1145
  288. package/src/codegen/latin1.ts +0 -131
  289. package/src/codegen/members.ts +0 -79
  290. package/src/codegen/model-diff.ts +0 -67
  291. package/src/codegen/naming.ts +0 -85
  292. package/src/codegen/openapi-cli.ts +0 -141
  293. package/src/codegen/openapi.ts +0 -1845
  294. package/src/codegen/operations.ts +0 -73
  295. package/src/codegen/pagination.ts +0 -64
  296. package/src/codegen/patch-audit.ts +0 -480
  297. package/src/codegen/patches.ts +0 -581
  298. package/src/codegen/prelude.ts +0 -70
  299. package/src/codegen/privatize.ts +0 -200
  300. package/src/codegen/proto.ts +0 -1092
  301. package/src/codegen/pure.ts +0 -94
  302. package/src/codegen/rewrite-operation-ids.ts +0 -1219
  303. package/src/codegen/spec-path.ts +0 -112
  304. package/src/codegen/table.ts +0 -254
  305. package/src/json-patch.ts +0 -273
  306. package/src/testing.ts +0 -74
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The `com.distilled.telemetry#service` trait's `hosts`: facts for requests
3
+ * to S3-compatible hosts such as Cloudflare R2. Generated code imports this
4
+ * only where a trait has one (S3). See
5
+ * `packages/dev/src/codegen/telemetry-traits.md`.
6
+ */
7
+ import type { RequestHook } from "./telemetry.ts";
8
+
9
+ /** Facts for requests to a host ending in `suffix`. */
10
+ export interface HostRule {
11
+ /** Host suffix, with its leading dot (`.r2.cloudflarestorage.com`). */
12
+ readonly suffix: string;
13
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
14
+ /** Attribute that gets the host label just before the suffix (the account id). */
15
+ readonly hostLabel?: string;
16
+ /** Attribute values copied under a second name: `{ "aws.s3.bucket": "cloudflare.r2.bucket" }`. */
17
+ readonly copy?: Readonly<Record<string, string>>;
18
+ }
19
+
20
+ /**
21
+ * Facts recorded when a request goes to a matching host: an S3-compatible
22
+ * service such as Cloudflare R2 reached through the S3 SDK.
23
+ */
24
+ export const hostRules =
25
+ (rules: ReadonlyArray<HostRule>): RequestHook =>
26
+ (host, span, set) => {
27
+ for (const rule of rules) {
28
+ if (!host.endsWith(rule.suffix)) continue;
29
+ for (const key in rule.attributes) set(key, rule.attributes[key]);
30
+ if (rule.hostLabel !== undefined) {
31
+ const prefix = host.slice(0, host.length - rule.suffix.length);
32
+ if (prefix.length > 0) set(rule.hostLabel, prefix.slice(prefix.lastIndexOf(".") + 1));
33
+ }
34
+ for (const from in rule.copy) {
35
+ const value = span.attributes.get(from);
36
+ if (value !== undefined) set(rule.copy[from]!, value);
37
+ }
38
+ }
39
+ };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * W3C trace context in a Lambda `Invoke`'s `ClientContext` (base64 JSON),
3
+ * under `custom.traceparent`, as `@opentelemetry/instrumentation-aws-sdk`
4
+ * writes it; the invoked function reads it from `context.clientContext`.
5
+ * Generated code imports this only where an operation's `inject` has format
6
+ * `lambdaClientContext`. See `packages/dev/src/codegen/telemetry-traits.md`.
7
+ */
8
+ import type * as Tracer from "effect/Tracer";
9
+ import { traceparent } from "./telemetry-message-context.ts";
10
+
11
+ /** Lambda caps `ClientContext` at 3583 bytes of base64. */
12
+ const MAX_CLIENT_CONTEXT = 3583;
13
+
14
+ const toBase64 = (text: string): string => {
15
+ let binary = "";
16
+ for (const byte of new TextEncoder().encode(text)) binary += String.fromCharCode(byte);
17
+ return btoa(binary);
18
+ };
19
+
20
+ const fromBase64 = (text: string): string =>
21
+ new TextDecoder().decode(Uint8Array.from(atob(text), (c) => c.charCodeAt(0)));
22
+
23
+ /**
24
+ * Add `custom.traceparent` to the input's `member` (a base64 JSON client
25
+ * context). Kept as it was: a `traceparent` already there, a value that is
26
+ * not base64 JSON, and a result over Lambda's size cap.
27
+ */
28
+ export const injectLambdaClientContext =
29
+ (place: { readonly member: string }) =>
30
+ (span: Tracer.Span, input: unknown): unknown => {
31
+ if (input === null || typeof input !== "object") return input;
32
+ const record = input as Record<string, unknown>;
33
+ const current = record[place.member];
34
+ try {
35
+ const parsed =
36
+ typeof current === "string" && current.length > 0 ? JSON.parse(fromBase64(current)) : {};
37
+ if (parsed === null || typeof parsed !== "object") return input;
38
+ if (parsed.custom?.traceparent !== undefined) return input;
39
+ const encoded = toBase64(
40
+ JSON.stringify({ ...parsed, custom: { ...parsed.custom, traceparent: traceparent(span) } }),
41
+ );
42
+ return encoded.length > MAX_CLIENT_CONTEXT ? input : { ...record, [place.member]: encoded };
43
+ } catch {
44
+ return input;
45
+ }
46
+ };
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The `com.distilled.telemetry#operation` trait's `inject` and `extract`
3
+ * (format `awsMessageAttributes`): W3C trace context in SQS and SNS
4
+ * message attributes. Generated code imports this only where a trait has
5
+ * one. See `packages/dev/src/codegen/telemetry-traits.md`.
6
+ */
7
+ import * as Tracer from "effect/Tracer";
8
+ import { parseTraceHeader } from "./telemetry-xray.ts";
9
+ import type { MessageExtract } from "./telemetry.ts";
10
+
11
+ /** W3C `traceparent` of a span. */
12
+ export const traceparent = (span: Tracer.AnySpan): string =>
13
+ `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}`;
14
+
15
+ const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
16
+
17
+ /** The span a W3C `traceparent` names, if it is well formed. */
18
+ export const parseTraceparent = (value: unknown): Tracer.ExternalSpan | undefined => {
19
+ const match = typeof value === "string" ? TRACEPARENT.exec(value) : null;
20
+ if (match === null) return undefined;
21
+ return Tracer.externalSpan({
22
+ traceId: match[1]!,
23
+ spanId: match[2]!,
24
+ sampled: (Number.parseInt(match[3]!, 16) & 1) === 1,
25
+ });
26
+ };
27
+
28
+ /** Where messages sit: `member` of the value, or of every element of its `list` member. */
29
+ export interface MessagePlace {
30
+ readonly member: string;
31
+ readonly list?: string;
32
+ }
33
+
34
+ /** SQS and SNS take at most 10 message attributes. */
35
+ const MAX_MESSAGE_ATTRIBUTES = 10;
36
+
37
+ const withTraceparent = (attributes: unknown, value: string): unknown => {
38
+ const map =
39
+ attributes !== null && typeof attributes === "object"
40
+ ? (attributes as Record<string, unknown>)
41
+ : {};
42
+ if ("traceparent" in map || Object.keys(map).length >= MAX_MESSAGE_ATTRIBUTES) return attributes;
43
+ return { ...map, traceparent: { DataType: "String", StringValue: value } };
44
+ };
45
+
46
+ /**
47
+ * Write the span's `traceparent` into each message's attributes (a map of
48
+ * `{ DataType, StringValue }`, the SQS and SNS shape). Kept: a
49
+ * `traceparent` already there, and a message with 10 attributes. The
50
+ * caller's input object is not changed.
51
+ */
52
+ export const injectAwsMessageAttributes =
53
+ (place: MessagePlace) =>
54
+ (span: Tracer.Span, input: unknown): unknown => {
55
+ if (input === null || typeof input !== "object") return input;
56
+ const record = input as Record<string, unknown>;
57
+ const value = traceparent(span);
58
+ if (place.list === undefined) {
59
+ return { ...record, [place.member]: withTraceparent(record[place.member], value) };
60
+ }
61
+ const entries = record[place.list];
62
+ if (!Array.isArray(entries)) return input;
63
+ return {
64
+ ...record,
65
+ [place.list]: entries.map((entry) =>
66
+ entry !== null && typeof entry === "object"
67
+ ? {
68
+ ...entry,
69
+ [place.member]: withTraceparent(
70
+ (entry as Record<string, unknown>)[place.member],
71
+ value,
72
+ ),
73
+ }
74
+ : entry,
75
+ ),
76
+ };
77
+ };
78
+
79
+ /**
80
+ * Where else a received message can carry trace context, by generated
81
+ * property name (SQS `ReceiveMessage`):
82
+ *
83
+ * envelope the body member; an SNS notification delivered without
84
+ * raw message delivery is JSON whose `MessageAttributes`
85
+ * carry the publisher's `traceparent`
86
+ * system the system-attributes member, whose `AWSTraceHeader` is
87
+ * an X-Ray trace header (set by X-Ray-instrumented
88
+ * producers); `systemRequest` is the input member listing
89
+ * system attributes to return
90
+ */
91
+ export interface MessageExtractPlace extends MessagePlace {
92
+ readonly request?: string;
93
+ /** The message's id member: each link carries it as `messaging.message.id`. */
94
+ readonly messageId?: string;
95
+ readonly envelope?: string;
96
+ readonly system?: string;
97
+ readonly systemRequest?: string;
98
+ }
99
+
100
+ const asksFor = (names: unknown, name: string): boolean =>
101
+ Array.isArray(names) && names.some((n) => n === "All" || n === ".*" || n === name);
102
+
103
+ const askFor = (record: Record<string, unknown>, member: string | undefined, name: string) => {
104
+ if (member === undefined || asksFor(record[member], name)) return record;
105
+ const names = record[member];
106
+ return { ...record, [member]: [...(Array.isArray(names) ? names : []), name] };
107
+ };
108
+
109
+ /** The publisher's `traceparent` in an SNS notification body, if there is one. */
110
+ const envelopeTraceparent = (body: unknown): unknown => {
111
+ // Parse only bodies that can hold one: most messages are not SNS JSON.
112
+ if (typeof body !== "string" || !body.includes('"traceparent"')) return undefined;
113
+ try {
114
+ const parsed = JSON.parse(body);
115
+ return parsed?.Type === "Notification"
116
+ ? parsed.MessageAttributes?.traceparent?.Value
117
+ : undefined;
118
+ } catch {
119
+ return undefined;
120
+ }
121
+ };
122
+
123
+ /**
124
+ * Ask for `traceparent` (and `AWSTraceHeader`) back, unless the input asks
125
+ * for `All` or `.*`, and link the span to every well-formed trace context
126
+ * each message carries: its `traceparent` attribute, else the SNS
127
+ * envelope's, plus its X-Ray `AWSTraceHeader` when that names another span.
128
+ */
129
+ export const extractAwsMessageAttributes = (place: MessageExtractPlace): MessageExtract => ({
130
+ request: (input) => {
131
+ if (input === null || typeof input !== "object") return input;
132
+ let record = askFor(input as Record<string, unknown>, place.request, "traceparent");
133
+ if (place.system !== undefined) record = askFor(record, place.systemRequest, "AWSTraceHeader");
134
+ return record;
135
+ },
136
+ links: (output) => {
137
+ if (output === null || typeof output !== "object") return [];
138
+ const record = output as Record<string, unknown>;
139
+ const holders =
140
+ place.list === undefined
141
+ ? [record]
142
+ : Array.isArray(record[place.list])
143
+ ? (record[place.list] as unknown[])
144
+ : [];
145
+ const links: Tracer.SpanLink[] = [];
146
+ for (const holder of holders) {
147
+ if (holder === null || typeof holder !== "object") continue;
148
+ const message = holder as Record<string, unknown>;
149
+ const id = place.messageId === undefined ? undefined : message[place.messageId];
150
+ const linkAttributes = typeof id === "string" ? { "messaging.message.id": id } : {};
151
+ const attributes = message[place.member] as
152
+ | Record<string, { readonly StringValue?: unknown } | undefined>
153
+ | undefined;
154
+ const span =
155
+ parseTraceparent(attributes?.traceparent?.StringValue) ??
156
+ (place.envelope !== undefined
157
+ ? parseTraceparent(envelopeTraceparent(message[place.envelope]))
158
+ : undefined);
159
+ if (span !== undefined) links.push({ span, attributes: linkAttributes });
160
+ if (place.system !== undefined) {
161
+ const system = message[place.system] as Record<string, unknown> | undefined;
162
+ const xray = parseTraceHeader(system?.AWSTraceHeader);
163
+ if (xray !== undefined && xray.spanId !== span?.spanId) {
164
+ links.push({ span: xray, attributes: linkAttributes });
165
+ }
166
+ }
167
+ }
168
+ return links;
169
+ },
170
+ });
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Client call metrics (opt in): a program that never imports this module
3
+ * never bundles it.
4
+ *
5
+ * ```ts
6
+ * import { TelemetryMetrics } from "@distilled.cloud/core/telemetry-metrics";
7
+ * program.pipe(Effect.provide(TelemetryMetrics.layer));
8
+ * ```
9
+ *
10
+ * Records `rpc.client.call.duration` (semantic conventions v1.44:
11
+ * histogram, seconds) for every operation call, around all its retries,
12
+ * whether or not a span is recorded, with `rpc.system.name`, `rpc.method`
13
+ * and, on failure, `error.type`. Effect's metric exporters
14
+ * (`@effect/opentelemetry`, `effect/observability`) send it on.
15
+ */
16
+ import * as Cause from "effect/Cause";
17
+ import * as Effect from "effect/Effect";
18
+ import * as Exit from "effect/Exit";
19
+ import * as Layer from "effect/Layer";
20
+ import * as Metric from "effect/Metric";
21
+ import { type Measure, Metrics, type OperationInfo, tagOf } from "./telemetry.ts";
22
+
23
+ /** The buckets the RPC and HTTP conventions recommend, in seconds. */
24
+ const BOUNDARIES = [0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10];
25
+
26
+ const duration = /*@__PURE__*/ Metric.histogram("rpc.client.call.duration", {
27
+ description: "Duration of outbound RPC calls.",
28
+ boundaries: BOUNDARIES,
29
+ });
30
+
31
+ /** One histogram per operation and outcome, built once. */
32
+ const byOperation = new WeakMap<OperationInfo, Map<string, Metric.Metric<number, unknown>>>();
33
+
34
+ const metricOf = (info: OperationInfo, errorType: string | undefined) => {
35
+ let byOutcome = byOperation.get(info);
36
+ if (byOutcome === undefined) byOperation.set(info, (byOutcome = new Map()));
37
+ const key = errorType ?? "";
38
+ let metric = byOutcome.get(key);
39
+ if (metric === undefined) {
40
+ const attributes: Record<string, string> = {};
41
+ for (const name of ["rpc.system.name", "rpc.method"]) {
42
+ const value = info.attributes[name];
43
+ if (typeof value === "string") attributes[name] = value;
44
+ }
45
+ if (errorType !== undefined) attributes["error.type"] = errorType;
46
+ metric = Metric.withAttributes(duration, attributes) as Metric.Metric<number, unknown>;
47
+ byOutcome.set(key, metric);
48
+ }
49
+ return metric;
50
+ };
51
+
52
+ const errorTypeOf = (exit: Exit.Exit<unknown, unknown>): string | undefined =>
53
+ Exit.isSuccess(exit) ? undefined : tagOf(Cause.squash(exit.cause));
54
+
55
+ const measure: Measure = (info, effect) =>
56
+ Effect.clockWith((clock) => {
57
+ const start = clock.currentTimeNanosUnsafe();
58
+ return Effect.onExit(effect, (exit) =>
59
+ Metric.update(
60
+ metricOf(info, errorTypeOf(exit)),
61
+ Number(clock.currentTimeNanosUnsafe() - start) / 1e9,
62
+ ),
63
+ );
64
+ });
65
+
66
+ export const TelemetryMetrics = {
67
+ /** Records `rpc.client.call.duration` for every distilled call it is provided to. */
68
+ layer: /*@__PURE__*/ Layer.succeed(Metrics, measure) as Layer.Layer<never>,
69
+ } as const;
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The `com.distilled.telemetry#operation` trait's `nameTemplate`, as a
3
+ * function: generated code imports this only where a trait has one
4
+ * (messaging operations). See `packages/dev/src/codegen/telemetry-traits.md`.
5
+ */
6
+ import type { SpanRename } from "./telemetry.ts";
7
+
8
+ const PLACEHOLDER = /\{([^{}]+)\}/g;
9
+
10
+ /**
11
+ * Span name from `{attribute}` placeholders filled from the call's input
12
+ * attributes (`send {messaging.destination.name}`); undefined (the trait's
13
+ * `name`) when one is missing.
14
+ */
15
+ export const nameTemplate =
16
+ (template: string): SpanRename =>
17
+ (attributes) => {
18
+ let complete = true;
19
+ const name = template.replace(PLACEHOLDER, (_, key: string) => {
20
+ const value = attributes[key];
21
+ if (typeof value === "string" || typeof value === "number") return String(value);
22
+ complete = false;
23
+ return "";
24
+ });
25
+ return complete ? name : undefined;
26
+ };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Operation spans that cover a streamed response (the
3
+ * `com.distilled.telemetry#operation` trait's `stream`). Generated modules
4
+ * import this only for the operations whose trait has it, so other programs
5
+ * never bundle it.
6
+ *
7
+ * The GenAI conventions say a GenAI span ends "when the response is fully
8
+ * received", and the OpenTelemetry AWS SDK instrumentations (JavaScript,
9
+ * Python) end Bedrock `ConverseStream` and `InvokeModelWithResponseStream`
10
+ * spans when the caller has read the stream. Every other operation span,
11
+ * S3 `GetObject` included, ends when the call returns, after the response
12
+ * headers, as those instrumentations and the HTTP client span conventions
13
+ * do: reading an object body is the app's work.
14
+ *
15
+ * With `stream: { member }`, the span ends when the caller has read that
16
+ * output member to its end. An error while reading fails it and sets
17
+ * `error.type`; a caller that stops early (`Stream.take`, an interruption)
18
+ * ends it then, with success. A stream the caller never reads never ends
19
+ * the span, as in those instrumentations: the conventions ask clients not
20
+ * to end a span later, in clean-up. `firstChunk` names the attribute that
21
+ * records the seconds from the span's start to the first item
22
+ * (`gen_ai.response.time_to_first_chunk`).
23
+ */
24
+ import * as Cause from "effect/Cause";
25
+ import * as Clock from "effect/Clock";
26
+ import * as Effect from "effect/Effect";
27
+ import * as Exit from "effect/Exit";
28
+ import * as References from "effect/References";
29
+ import * as Stream from "effect/Stream";
30
+ import { type SpanHold, tagOf } from "./telemetry.ts";
31
+
32
+ export interface StreamRule {
33
+ /** The output member holding the stream (the generated property name). */
34
+ readonly member: string;
35
+ /** Attribute for the seconds from the span's start to the first item. */
36
+ readonly firstChunk?: string;
37
+ }
38
+
39
+ export const holdForStream =
40
+ (rule: StreamRule): SpanHold =>
41
+ (fiber, name, options, debug, inSpan) => {
42
+ const clock = fiber.getRef(Clock.Clock);
43
+ const timing = fiber.getRef(References.TracerTimingEnabled);
44
+ const now = () => (timing ? clock.currentTimeNanosUnsafe() : 0n);
45
+ return Effect.uninterruptibleMask((restore) =>
46
+ Effect.flatMap(Effect.makeSpan(name, options), (span) => {
47
+ const end = (exit: Exit.Exit<unknown, unknown>) => {
48
+ if (span.status._tag !== "Ended") span.end(now(), exit);
49
+ };
50
+ let held = false;
51
+ const body = Effect.map(inSpan(span), (output) => {
52
+ const fields = output as Record<string, unknown> | null;
53
+ const stream = fields?.[rule.member];
54
+ if (!Stream.isStream(stream)) return output;
55
+ held = true;
56
+ let done = false;
57
+ const read = Stream.suspend(() => {
58
+ let items = debug === undefined ? stream : debug.readStream(stream, span, rule.member);
59
+ const attribute = rule.firstChunk;
60
+ if (attribute !== undefined) {
61
+ let first = true;
62
+ items = Stream.map(items, (item) => {
63
+ if (first) {
64
+ first = false;
65
+ span.attribute(attribute, Number(now() - span.status.startTime) / 1e9);
66
+ }
67
+ return item;
68
+ });
69
+ }
70
+ return items;
71
+ });
72
+ const wrapped = Stream.onExit(read, (exit) =>
73
+ Effect.sync(() => {
74
+ if (done) return;
75
+ done = true;
76
+ if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
77
+ span.attribute("error.type", tagOf(Cause.squash(exit.cause)));
78
+ end(exit);
79
+ } else end(Exit.void);
80
+ }),
81
+ );
82
+ return { ...fields, [rule.member]: wrapped } as typeof output;
83
+ });
84
+ return Effect.onExit(restore(body), (exit) =>
85
+ Effect.sync(() => {
86
+ if (!held || Exit.isFailure(exit)) end(exit);
87
+ }),
88
+ );
89
+ }),
90
+ );
91
+ };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * AWS X-Ray trace context, which AWS services read and pass on (the OTel
3
+ * AWS SDK conventions recommend it for AWS calls). Generated code imports
4
+ * this only where the model's `com.distilled.telemetry` traits ask for it:
5
+ * a service's `propagation: "xray"`, an operation's `inject` with format
6
+ * `xrayTraceHeader`. See `packages/dev/src/codegen/telemetry-traits.md`.
7
+ *
8
+ * `Root=1-<8 hex>-<24 hex>;Parent=<16 hex>;Sampled=<0|1>`, from a W3C trace
9
+ * id split after 8 hex digits, as OTel's AWS X-Ray propagator writes it.
10
+ */
11
+ import * as Tracer from "effect/Tracer";
12
+
13
+ export const HEADER = "X-Amzn-Trace-Id";
14
+
15
+ /** The X-Ray trace header of a span. */
16
+ export const traceHeader = (span: Tracer.AnySpan): string =>
17
+ `Root=1-${span.traceId.slice(0, 8)}-${span.traceId.slice(8)};Parent=${span.spanId};Sampled=${
18
+ span.sampled ? 1 : 0
19
+ }`;
20
+
21
+ const ROOT = /(?:^|;)\s*Root=1-([0-9a-f]{8})-([0-9a-f]{24})/;
22
+ const PARENT = /(?:^|;)\s*Parent=([0-9a-f]{16})/;
23
+ const SAMPLED = /(?:^|;)\s*Sampled=([01])/;
24
+
25
+ /** The span an X-Ray trace header names, if it has a root and a parent. */
26
+ export const parseTraceHeader = (value: unknown): Tracer.ExternalSpan | undefined => {
27
+ if (typeof value !== "string") return undefined;
28
+ const root = ROOT.exec(value);
29
+ const parent = PARENT.exec(value);
30
+ if (root === null || parent === null) return undefined;
31
+ return Tracer.externalSpan({
32
+ traceId: root[1]! + root[2]!,
33
+ spanId: parent[1]!,
34
+ sampled: SAMPLED.exec(value)?.[1] !== "0",
35
+ });
36
+ };
37
+
38
+ /** `propagation: "xray"`: the `X-Amzn-Trace-Id` request header. */
39
+ export const propagate = (span: Tracer.AnySpan): readonly [string, string] => [
40
+ HEADER,
41
+ traceHeader(span),
42
+ ];
43
+
44
+ /**
45
+ * Write the span's X-Ray trace header into a string `member` of the input,
46
+ * or of every element of its `list` member (EventBridge `PutEvents`
47
+ * entries' `TraceHeader`). A value the caller set is kept.
48
+ */
49
+ export const injectTraceHeader =
50
+ (place: { readonly member: string; readonly list?: string }) =>
51
+ (span: Tracer.Span, input: unknown): unknown => {
52
+ if (input === null || typeof input !== "object") return input;
53
+ const record = input as Record<string, unknown>;
54
+ const value = traceHeader(span);
55
+ const set = (holder: Record<string, unknown>) =>
56
+ holder[place.member] === undefined ? { ...holder, [place.member]: value } : holder;
57
+ if (place.list === undefined) return set(record);
58
+ const entries = record[place.list];
59
+ if (!Array.isArray(entries)) return input;
60
+ return {
61
+ ...record,
62
+ [place.list]: entries.map((entry) =>
63
+ entry !== null && typeof entry === "object" ? set(entry as Record<string, unknown>) : entry,
64
+ ),
65
+ };
66
+ };