@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.
- package/LICENSE +201 -0
- package/README.md +33 -0
- package/lib/_bundle/aws.js +2 -0
- package/lib/_bundle/aws.js.map +1 -0
- package/lib/_bundle/base.js +5 -0
- package/lib/_bundle/base.js.map +1 -0
- package/lib/_bundle/graphql.js +3 -0
- package/lib/_bundle/graphql.js.map +1 -0
- package/lib/_bundle/grpc.js +3 -0
- package/lib/_bundle/grpc.js.map +1 -0
- package/lib/_bundle/rest.js +2 -0
- package/lib/_bundle/rest.js.map +1 -0
- package/lib/_bundle/xml.js +4 -0
- package/lib/_bundle/xml.js.map +1 -0
- package/lib/annotations.d.ts +17 -0
- package/lib/annotations.d.ts.map +1 -0
- package/lib/annotations.js +2 -0
- package/lib/annotations.js.map +1 -0
- package/lib/api.d.ts +220 -51
- package/lib/api.d.ts.map +1 -1
- package/lib/api.js +1 -178
- package/lib/category.d.ts +19 -16
- package/lib/category.d.ts.map +1 -1
- package/lib/category.js +1 -280
- package/lib/chunks.d.ts +3 -0
- package/lib/chunks.d.ts.map +1 -0
- package/lib/chunks.js +1 -0
- package/lib/config.d.ts +81 -0
- package/lib/config.d.ts.map +1 -0
- package/lib/config.js +1 -0
- package/lib/crypto.d.ts +76 -0
- package/lib/crypto.d.ts.map +1 -0
- package/lib/crypto.js +1 -0
- package/lib/error-category.d.ts +1 -1
- package/lib/error-category.d.ts.map +1 -1
- package/lib/error-category.js +1 -46
- package/lib/errors.d.ts +99 -74
- package/lib/errors.d.ts.map +1 -1
- package/lib/errors.js +1 -186
- package/lib/graphql.d.ts +420 -0
- package/lib/graphql.d.ts.map +1 -0
- package/lib/graphql.js +1 -0
- package/lib/graphql.types.d.ts +11 -0
- package/lib/graphql.types.d.ts.map +1 -0
- package/lib/graphql.types.js +1 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-http2.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-http2.js +6 -0
- package/lib/grpc-transport-cloudflare-http2.js.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts +7 -0
- package/lib/grpc-transport-cloudflare-sockets.d.ts.map +1 -0
- package/lib/grpc-transport-cloudflare-sockets.js +5 -0
- package/lib/grpc-transport-cloudflare-sockets.js.map +1 -0
- package/lib/grpc-transport-node-http2.d.ts +19 -0
- package/lib/grpc-transport-node-http2.d.ts.map +1 -0
- package/lib/grpc-transport-node-http2.js +2 -0
- package/lib/grpc-transport-node-http2.js.map +1 -0
- package/lib/grpc-transport.d.ts +111 -0
- package/lib/grpc-transport.d.ts.map +1 -0
- package/lib/grpc-transport.js +1 -0
- package/lib/hpack.d.ts +34 -0
- package/lib/hpack.d.ts.map +1 -0
- package/lib/hpack.js +2 -0
- package/lib/hpack.js.map +1 -0
- package/lib/index.d.ts +32 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +17 -0
- package/lib/max-message-bytes.d.ts +42 -0
- package/lib/max-message-bytes.d.ts.map +1 -0
- package/lib/max-message-bytes.js +2 -0
- package/lib/max-message-bytes.js.map +1 -0
- package/lib/ndjson.d.ts +3 -0
- package/lib/ndjson.d.ts.map +1 -0
- package/lib/ndjson.js +2 -0
- package/lib/ndjson.js.map +1 -0
- package/lib/pagination.d.ts +105 -25
- package/lib/pagination.d.ts.map +1 -1
- package/lib/pagination.js +1 -182
- package/lib/plain-values.d.ts +21 -0
- package/lib/plain-values.d.ts.map +1 -0
- package/lib/plain-values.js +2 -0
- package/lib/plain-values.js.map +1 -0
- package/lib/protobuf.d.ts +85 -0
- package/lib/protobuf.d.ts.map +1 -0
- package/lib/protobuf.js +1 -0
- package/lib/protocol-grpc.d.ts +123 -0
- package/lib/protocol-grpc.d.ts.map +1 -0
- package/lib/protocol-grpc.js +1 -0
- package/lib/protocol-http.d.ts +206 -25
- package/lib/protocol-http.d.ts.map +1 -1
- package/lib/protocol-http.js +1 -554
- package/lib/protocol-rest.d.ts +258 -64
- package/lib/protocol-rest.d.ts.map +1 -1
- package/lib/protocol-rest.js +1 -242
- package/lib/protocol.d.ts +113 -0
- package/lib/protocol.d.ts.map +1 -0
- package/lib/protocol.js +0 -0
- package/lib/query.d.ts +29 -0
- package/lib/query.d.ts.map +1 -0
- package/lib/query.js +1 -0
- package/lib/response-validation-strict.d.ts +48 -0
- package/lib/response-validation-strict.d.ts.map +1 -0
- package/lib/response-validation-strict.js +1 -0
- package/lib/response-validation.d.ts +86 -0
- package/lib/response-validation.d.ts.map +1 -0
- package/lib/response-validation.js +1 -0
- package/lib/retry-after.d.ts +4 -4
- package/lib/retry-after.d.ts.map +1 -1
- package/lib/retry-after.js +1 -112
- package/lib/retry-state.d.ts +26 -0
- package/lib/retry-state.d.ts.map +1 -0
- package/lib/retry-state.js +2 -0
- package/lib/retry-state.js.map +1 -0
- package/lib/retry.d.ts +141 -42
- package/lib/retry.d.ts.map +1 -1
- package/lib/retry.js +1 -210
- package/lib/schema-lite-impl.d.ts +179 -0
- package/lib/schema-lite-impl.d.ts.map +1 -0
- package/lib/schema-lite-impl.js +1 -0
- package/lib/schema-lite-typed.d.ts +41 -0
- package/lib/schema-lite-typed.d.ts.map +1 -0
- package/lib/schema-lite-typed.js +1 -0
- package/lib/schema-lite.d.ts +41 -0
- package/lib/schema-lite.d.ts.map +1 -0
- package/lib/schema-lite.js +1 -0
- package/lib/schema.d.ts +21 -7
- package/lib/schema.d.ts.map +1 -1
- package/lib/schema.js +1 -48
- package/lib/sdk-error.d.ts +31 -0
- package/lib/sdk-error.d.ts.map +1 -0
- package/lib/sdk-error.js +1 -0
- package/lib/send.d.ts +37 -0
- package/lib/send.d.ts.map +1 -0
- package/lib/send.js +2 -0
- package/lib/send.js.map +1 -0
- package/lib/sensitive.d.ts +28 -0
- package/lib/sensitive.d.ts.map +1 -0
- package/lib/sensitive.js +2 -0
- package/lib/sensitive.js.map +1 -0
- package/lib/telemetry-debug.d.ts +6 -0
- package/lib/telemetry-debug.d.ts.map +1 -0
- package/lib/telemetry-debug.js +2 -0
- package/lib/telemetry-debug.js.map +1 -0
- package/lib/telemetry-hooks.d.ts +32 -0
- package/lib/telemetry-hooks.d.ts.map +1 -0
- package/lib/telemetry-hooks.js +2 -0
- package/lib/telemetry-hooks.js.map +1 -0
- package/lib/telemetry-host-rules.d.ts +23 -0
- package/lib/telemetry-host-rules.d.ts.map +1 -0
- package/lib/telemetry-host-rules.js +2 -0
- package/lib/telemetry-host-rules.js.map +1 -0
- package/lib/telemetry-lambda-context.d.ts +17 -0
- package/lib/telemetry-lambda-context.d.ts.map +1 -0
- package/lib/telemetry-lambda-context.js +2 -0
- package/lib/telemetry-lambda-context.js.map +1 -0
- package/lib/telemetry-message-context.d.ts +52 -0
- package/lib/telemetry-message-context.d.ts.map +1 -0
- package/lib/telemetry-message-context.js +2 -0
- package/lib/telemetry-message-context.js.map +1 -0
- package/lib/telemetry-metrics.d.ts +6 -0
- package/lib/telemetry-metrics.d.ts.map +1 -0
- package/lib/telemetry-metrics.js +2 -0
- package/lib/telemetry-metrics.js.map +1 -0
- package/lib/telemetry-name-template.d.ts +13 -0
- package/lib/telemetry-name-template.d.ts.map +1 -0
- package/lib/telemetry-name-template.js +2 -0
- package/lib/telemetry-name-template.js.map +1 -0
- package/lib/telemetry-stream.d.ts +11 -0
- package/lib/telemetry-stream.d.ts.map +1 -0
- package/lib/telemetry-stream.js +2 -0
- package/lib/telemetry-stream.js.map +1 -0
- package/lib/telemetry-xray.d.ts +28 -0
- package/lib/telemetry-xray.d.ts.map +1 -0
- package/lib/telemetry-xray.js +2 -0
- package/lib/telemetry-xray.js.map +1 -0
- package/lib/telemetry.d.ts +317 -0
- package/lib/telemetry.d.ts.map +1 -0
- package/lib/telemetry.js +3 -0
- package/lib/telemetry.js.map +1 -0
- package/lib/token-cache.d.ts +31 -0
- package/lib/token-cache.d.ts.map +1 -0
- package/lib/token-cache.js +2 -0
- package/lib/token-cache.js.map +1 -0
- package/lib/trait.d.ts +94 -20
- package/lib/trait.d.ts.map +1 -1
- package/lib/trait.js +1 -107
- package/lib/unknown-error.d.ts +18 -0
- package/lib/unknown-error.d.ts.map +1 -0
- package/lib/unknown-error.js +1 -0
- package/lib/xml.d.ts +44 -0
- package/lib/xml.d.ts.map +1 -0
- package/lib/xml.js +1 -0
- package/package.json +13 -13
- package/src/annotations.ts +53 -0
- package/src/api.ts +1597 -234
- package/src/category.ts +97 -134
- package/src/chunks.ts +30 -0
- package/src/config.ts +261 -0
- package/src/crypto.ts +202 -0
- package/src/error-category.ts +16 -29
- package/src/errors.ts +99 -77
- package/src/graphql.ts +1817 -0
- package/src/graphql.types.ts +120 -0
- package/src/grpc-transport-cloudflare-http2.ts +569 -0
- package/src/grpc-transport-cloudflare-sockets.ts +368 -0
- package/src/grpc-transport-node-http2.ts +307 -0
- package/src/grpc-transport.ts +287 -0
- package/src/hpack.ts +331 -0
- package/src/index.ts +31 -0
- package/src/max-message-bytes.ts +58 -0
- package/src/ndjson.ts +55 -0
- package/src/pagination.ts +379 -94
- package/src/plain-values.ts +70 -0
- package/src/protobuf.ts +1367 -0
- package/src/protocol-grpc.ts +811 -0
- package/src/protocol-http.ts +1045 -371
- package/src/protocol-rest.ts +908 -255
- package/src/protocol.ts +150 -0
- package/src/query.ts +39 -0
- package/src/response-validation-strict.ts +333 -0
- package/src/response-validation.ts +161 -0
- package/src/retry-after.ts +8 -14
- package/src/retry-state.ts +105 -0
- package/src/retry.ts +260 -145
- package/src/schema-lite-impl.ts +621 -0
- package/src/schema-lite-typed.ts +44 -0
- package/src/schema-lite.ts +45 -0
- package/src/schema.ts +259 -15
- package/src/sdk-error.ts +37 -0
- package/src/send.ts +156 -0
- package/src/sensitive.ts +188 -0
- package/src/telemetry-debug.ts +179 -0
- package/src/telemetry-hooks.ts +33 -0
- package/src/telemetry-host-rules.ts +39 -0
- package/src/telemetry-lambda-context.ts +46 -0
- package/src/telemetry-message-context.ts +170 -0
- package/src/telemetry-metrics.ts +69 -0
- package/src/telemetry-name-template.ts +26 -0
- package/src/telemetry-stream.ts +100 -0
- package/src/telemetry-xray.ts +66 -0
- package/src/telemetry.ts +800 -0
- package/src/token-cache.ts +117 -0
- package/src/trait.ts +139 -67
- package/src/unknown-error.ts +38 -0
- package/src/xml.ts +346 -0
- package/lib/api.js.map +0 -1
- package/lib/category.js.map +0 -1
- package/lib/codegen/cli.d.ts +0 -29
- package/lib/codegen/cli.d.ts.map +0 -1
- package/lib/codegen/cli.js +0 -165
- package/lib/codegen/cli.js.map +0 -1
- package/lib/codegen/emit.d.ts +0 -129
- package/lib/codegen/emit.d.ts.map +0 -1
- package/lib/codegen/emit.js +0 -105
- package/lib/codegen/emit.js.map +0 -1
- package/lib/codegen/format.d.ts +0 -23
- package/lib/codegen/format.d.ts.map +0 -1
- package/lib/codegen/format.js +0 -28
- package/lib/codegen/format.js.map +0 -1
- package/lib/codegen/generator.d.ts +0 -334
- package/lib/codegen/generator.d.ts.map +0 -1
- package/lib/codegen/generator.js +0 -691
- package/lib/codegen/generator.js.map +0 -1
- package/lib/codegen/graph.d.ts +0 -36
- package/lib/codegen/graph.d.ts.map +0 -1
- package/lib/codegen/graph.js +0 -136
- package/lib/codegen/graph.js.map +0 -1
- package/lib/codegen/members.d.ts +0 -25
- package/lib/codegen/members.d.ts.map +0 -1
- package/lib/codegen/members.js +0 -55
- package/lib/codegen/members.js.map +0 -1
- package/lib/codegen/naming.d.ts +0 -29
- package/lib/codegen/naming.d.ts.map +0 -1
- package/lib/codegen/naming.js +0 -74
- package/lib/codegen/naming.js.map +0 -1
- package/lib/codegen/openapi-cli.d.ts +0 -38
- package/lib/codegen/openapi-cli.d.ts.map +0 -1
- package/lib/codegen/openapi-cli.js +0 -107
- package/lib/codegen/openapi-cli.js.map +0 -1
- package/lib/codegen/openapi.d.ts +0 -115
- package/lib/codegen/openapi.d.ts.map +0 -1
- package/lib/codegen/openapi.js +0 -1220
- package/lib/codegen/openapi.js.map +0 -1
- package/lib/codegen/operations.d.ts +0 -24
- package/lib/codegen/operations.d.ts.map +0 -1
- package/lib/codegen/operations.js +0 -56
- package/lib/codegen/operations.js.map +0 -1
- package/lib/codegen/pagination.d.ts +0 -39
- package/lib/codegen/pagination.d.ts.map +0 -1
- package/lib/codegen/pagination.js +0 -33
- package/lib/codegen/pagination.js.map +0 -1
- package/lib/codegen/prelude.d.ts +0 -15
- package/lib/codegen/prelude.d.ts.map +0 -1
- package/lib/codegen/prelude.js +0 -60
- package/lib/codegen/prelude.js.map +0 -1
- package/lib/error-category.js.map +0 -1
- package/lib/errors.js.map +0 -1
- package/lib/json-patch.d.ts +0 -44
- package/lib/json-patch.d.ts.map +0 -1
- package/lib/json-patch.js +0 -174
- package/lib/json-patch.js.map +0 -1
- package/lib/pagination.js.map +0 -1
- package/lib/protocol-http.js.map +0 -1
- package/lib/protocol-rest.js.map +0 -1
- package/lib/retry-after.js.map +0 -1
- package/lib/retry.js.map +0 -1
- package/lib/schema.js.map +0 -1
- package/lib/trait.js.map +0 -1
- package/src/codegen/cli.ts +0 -268
- package/src/codegen/emit.ts +0 -207
- package/src/codegen/format.ts +0 -47
- package/src/codegen/generator.ts +0 -1153
- package/src/codegen/graph.ts +0 -151
- package/src/codegen/members.ts +0 -71
- package/src/codegen/naming.ts +0 -86
- package/src/codegen/openapi-cli.ts +0 -166
- package/src/codegen/openapi.ts +0 -1450
- package/src/codegen/operations.ts +0 -76
- package/src/codegen/pagination.ts +0 -71
- package/src/codegen/prelude.ts +0 -70
- package/src/json-patch.ts +0 -222
package/src/sensitive.ts
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secrets in values, logs and error messages: one rule for every SDK.
|
|
3
|
+
*
|
|
4
|
+
* A schema holds a secret when a value it reaches is marked sensitive
|
|
5
|
+
* ({@link sensitiveValueSymbol}: `T.SensitiveValue` in the REST SDKs, the
|
|
6
|
+
* `Sensitive*` schemas in AWS). An operation's input and its output are
|
|
7
|
+
* judged independently, each by its own schema:
|
|
8
|
+
*
|
|
9
|
+
* - its plain form (a serialized request, a response body, the value a
|
|
10
|
+
* parse failure quotes) is {@link REDACTED} whole: {@link redactPlain};
|
|
11
|
+
* - its parsed form shows only the sensitive values as `Redacted`:
|
|
12
|
+
* {@link redactParsed} for logs, {@link wrapSensitive} for decoded output.
|
|
13
|
+
*
|
|
14
|
+
* Imports only `effect/Redacted` and the AST helpers, so a protocol can use
|
|
15
|
+
* it without loading the REST protocol.
|
|
16
|
+
*/
|
|
17
|
+
import * as Redacted from "effect/Redacted";
|
|
18
|
+
import type * as AST from "effect/SchemaAST";
|
|
19
|
+
import { getAnn, getProps, resolveNode } from "./annotations.ts";
|
|
20
|
+
import { isOpaqueValue } from "./plain-values.ts";
|
|
21
|
+
|
|
22
|
+
export const sensitiveValueSymbol = /*@__PURE__*/ Symbol.for(
|
|
23
|
+
"@distilled.cloud/core/sensitive-value",
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
/** What the plain form of a value that can hold a secret is shown as. */
|
|
27
|
+
export const REDACTED = "[REDACTED]";
|
|
28
|
+
|
|
29
|
+
/** Whether `ast` is marked sensitive (through optional, Suspend and encoding wrappers). */
|
|
30
|
+
export const isSensitive = (ast: AST.AST): boolean =>
|
|
31
|
+
getAnn(ast, sensitiveValueSymbol) !== undefined;
|
|
32
|
+
|
|
33
|
+
const holds = /*@__PURE__*/ new WeakMap<AST.AST, boolean>();
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Whether a value of the type `ast` can hold a sensitive value, at any depth:
|
|
37
|
+
* the type itself, members, map values, list elements and union arms.
|
|
38
|
+
*/
|
|
39
|
+
export const holdsSensitive = (ast: AST.AST): boolean => {
|
|
40
|
+
const cached = holds.get(ast);
|
|
41
|
+
if (cached !== undefined) return cached;
|
|
42
|
+
const seen = new Set<AST.AST>();
|
|
43
|
+
const visit = (n: AST.AST): boolean => {
|
|
44
|
+
if (isSensitive(n)) return true;
|
|
45
|
+
const node = resolveNode(n);
|
|
46
|
+
if (seen.has(node)) return false;
|
|
47
|
+
seen.add(node);
|
|
48
|
+
switch (node._tag) {
|
|
49
|
+
case "Union":
|
|
50
|
+
return node.types.some(visit);
|
|
51
|
+
case "Arrays":
|
|
52
|
+
return [...(node.elements ?? []), ...(node.rest ?? [])].some(visit);
|
|
53
|
+
case "Objects":
|
|
54
|
+
return [...(node.propertySignatures ?? []), ...(node.indexSignatures ?? [])].some((m) =>
|
|
55
|
+
visit(m.type),
|
|
56
|
+
);
|
|
57
|
+
default:
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
const result = visit(ast);
|
|
62
|
+
holds.set(ast, result);
|
|
63
|
+
return result;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** `plain`, the plain form of a value of the type `ast`: {@link REDACTED} when it can hold a secret. */
|
|
67
|
+
export const redactPlain = <A>(ast: AST.AST, plain: A): A | typeof REDACTED =>
|
|
68
|
+
holdsSensitive(ast) ? REDACTED : plain;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `value`, a parsed value of the type `ast`, as a log shows it: every
|
|
72
|
+
* sensitive value `Redacted` whole, whatever its type, and the rest as is.
|
|
73
|
+
*/
|
|
74
|
+
export const redactParsed = (ast: AST.AST, value: unknown): unknown =>
|
|
75
|
+
holdsSensitive(ast) ? wrap(ast, value, true) : value;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Walk a decoded (TS-named) value alongside its schema AST, wrapping values
|
|
79
|
+
* marked sensitive (members, map values, list elements) in `Redacted`: a
|
|
80
|
+
* string, or any non-null value of an untyped (`S.Unknown`) schema. A typed
|
|
81
|
+
* struct is walked so its own sensitive members are wrapped and its type
|
|
82
|
+
* stays accurate. Keys the schema doesn't model pass through. A union
|
|
83
|
+
* applies every arm in turn; a map arm skips keys a sibling arm names.
|
|
84
|
+
*/
|
|
85
|
+
export const wrapSensitive = (
|
|
86
|
+
ast: AST.AST,
|
|
87
|
+
value: unknown,
|
|
88
|
+
siblingNames?: ReadonlySet<string>,
|
|
89
|
+
): unknown => wrap(ast, value, false, siblingNames);
|
|
90
|
+
|
|
91
|
+
/** Whether `wrap` wraps `v`, a value of the sensitive type `type`. */
|
|
92
|
+
const isSecretValue = (type: AST.AST, v: unknown, whole: boolean): boolean =>
|
|
93
|
+
whole
|
|
94
|
+
? v !== null && v !== undefined
|
|
95
|
+
: typeof v === "string" || (v !== null && resolveNode(type)._tag === "Unknown");
|
|
96
|
+
|
|
97
|
+
/** The member names of a union's object arms, once per union. */
|
|
98
|
+
const armNames = /*@__PURE__*/ new WeakMap<AST.AST, ReadonlySet<string>>();
|
|
99
|
+
/** A struct's members by name, once per struct. */
|
|
100
|
+
const membersByName = /*@__PURE__*/ new WeakMap<
|
|
101
|
+
AST.AST,
|
|
102
|
+
ReadonlyMap<string, AST.PropertySignature>
|
|
103
|
+
>();
|
|
104
|
+
|
|
105
|
+
const byNameOf = (
|
|
106
|
+
node: AST.AST,
|
|
107
|
+
props: ReadonlyArray<AST.PropertySignature>,
|
|
108
|
+
): ReadonlyMap<string, AST.PropertySignature> => {
|
|
109
|
+
const byName = new Map(props.map((p) => [String(p.name), p]));
|
|
110
|
+
membersByName.set(node, byName);
|
|
111
|
+
return byName;
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* `wrap`, except that a value whose type holds no sensitive value is
|
|
116
|
+
* returned as is: walking it would only copy it.
|
|
117
|
+
*/
|
|
118
|
+
const wrapHolding = (
|
|
119
|
+
ast: AST.AST,
|
|
120
|
+
value: unknown,
|
|
121
|
+
whole: boolean,
|
|
122
|
+
siblingNames?: ReadonlySet<string>,
|
|
123
|
+
): unknown => (holdsSensitive(ast) ? wrap(ast, value, whole, siblingNames) : value);
|
|
124
|
+
|
|
125
|
+
const wrap = (
|
|
126
|
+
ast: AST.AST,
|
|
127
|
+
value: unknown,
|
|
128
|
+
whole: boolean,
|
|
129
|
+
siblingNames?: ReadonlySet<string>,
|
|
130
|
+
): unknown => {
|
|
131
|
+
if (Redacted.isRedacted(value)) return value;
|
|
132
|
+
// The value's own type is sensitive: a response whose whole body is the
|
|
133
|
+
// secret (a bare-payload root).
|
|
134
|
+
if (isSensitive(ast) && isSecretValue(ast, value, whole)) return Redacted.make(value);
|
|
135
|
+
if (value === null || typeof value !== "object" || isOpaqueValue(value)) {
|
|
136
|
+
return value;
|
|
137
|
+
}
|
|
138
|
+
const node = resolveNode(ast);
|
|
139
|
+
if (node._tag === "Union") {
|
|
140
|
+
// Redact every possible sensitive member, including in partial responses.
|
|
141
|
+
let named = armNames.get(node);
|
|
142
|
+
if (named === undefined) {
|
|
143
|
+
named = new Set(
|
|
144
|
+
node.types.flatMap((arm) => {
|
|
145
|
+
const armNode = resolveNode(arm);
|
|
146
|
+
return armNode._tag === "Objects" ? getProps(armNode).map((p) => String(p.name)) : [];
|
|
147
|
+
}),
|
|
148
|
+
);
|
|
149
|
+
armNames.set(node, named);
|
|
150
|
+
}
|
|
151
|
+
return node.types.reduce<unknown>(
|
|
152
|
+
(redacted, arm) => wrapHolding(arm, redacted, whole, named),
|
|
153
|
+
value,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
if (node._tag === "Arrays") {
|
|
157
|
+
if (!Array.isArray(value)) return value;
|
|
158
|
+
const elem = node.rest?.[0];
|
|
159
|
+
if (!elem) return value;
|
|
160
|
+
const sensitive = isSensitive(elem);
|
|
161
|
+
return value.map((v) =>
|
|
162
|
+
sensitive && isSecretValue(elem, v, whole) && !Redacted.isRedacted(v)
|
|
163
|
+
? Redacted.make(v)
|
|
164
|
+
: wrapHolding(elem, v, whole),
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
if (node._tag === "Objects" && !Array.isArray(value)) {
|
|
168
|
+
const props = getProps(node);
|
|
169
|
+
const mapValue = node.indexSignatures?.[0]?.type;
|
|
170
|
+
if (props.length === 0 && mapValue === undefined) return value;
|
|
171
|
+
const byName = membersByName.get(node) ?? byNameOf(node, props);
|
|
172
|
+
// fromEntries keeps a `__proto__` key an entry instead of the prototype.
|
|
173
|
+
return Object.fromEntries(
|
|
174
|
+
Object.entries(value as Record<string, unknown>).flatMap<[string, unknown]>(([k, v]) => {
|
|
175
|
+
if (v === undefined) return [];
|
|
176
|
+
const prop = byName.get(k);
|
|
177
|
+
const type = prop?.type ?? (siblingNames?.has(k) ? undefined : mapValue);
|
|
178
|
+
if (type === undefined) return [[k, v]];
|
|
179
|
+
// Union arms run over each other's output: keep a value one already wrapped.
|
|
180
|
+
if (isSensitive(type) && isSecretValue(type, v, whole)) {
|
|
181
|
+
return [[k, Redacted.isRedacted(v) ? v : Redacted.make(v)]];
|
|
182
|
+
}
|
|
183
|
+
return [[k, wrapHolding(type, v, whole)]];
|
|
184
|
+
}),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
return value;
|
|
188
|
+
};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Debug telemetry: spans for distilled's internals, on top of the operation
|
|
3
|
+
* span every call records. Opt in by providing the layer; a program that
|
|
4
|
+
* never imports this module never bundles it.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { TelemetryDebug } from "@distilled.cloud/core/telemetry-debug";
|
|
8
|
+
* program.pipe(Effect.provide(TelemetryDebug.layer));
|
|
9
|
+
* ```
|
|
10
|
+
*
|
|
11
|
+
* With it, the operation span is the parent of:
|
|
12
|
+
*
|
|
13
|
+
* - one `Attempt` span per try, with Effect's HTTP span under it;
|
|
14
|
+
* - INTERNAL spans at trace level `Debug` for first-call setup,
|
|
15
|
+
* serialize, sign, deserialize, backoff sleeps and the caller's read
|
|
16
|
+
* of a streamed output (`Tracer.MinimumTraceLevel` can drop them);
|
|
17
|
+
*
|
|
18
|
+
* and carries the caller's `code.*` attributes.
|
|
19
|
+
*
|
|
20
|
+
* Every SDK also writes the same `Effect.logDebug` lines for each call,
|
|
21
|
+
* with or without an exporter. They go to the program's logger, so they
|
|
22
|
+
* show when `References.MinimumLogLevel` admits `Debug`, and a logger that
|
|
23
|
+
* reads the current span (an OTel log exporter) links them to the trace:
|
|
24
|
+
*
|
|
25
|
+
* ```
|
|
26
|
+
* DEBUG distilled.operation=0ms: call S3.PutObject
|
|
27
|
+
* distilled.operation: S3.PutObject
|
|
28
|
+
* url.template: /{Bucket}/{Key+}
|
|
29
|
+
* DEBUG distilled.operation=23ms: -> PUT my-bucket.s3.us-east-1.amazonaws.com
|
|
30
|
+
* DEBUG distilled.operation=25ms: <- 200
|
|
31
|
+
* DEBUG distilled.operation=27ms: ok S3.PutObject
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* The `call` line carries the input and the `ok` line the output, each
|
|
35
|
+
* with only its sensitive values `Redacted` (`./sensitive.ts`; input and
|
|
36
|
+
* output judged independently). The lines hold no serialized body and no
|
|
37
|
+
* full URL (a URL can carry a presigned signature or a sensitive label).
|
|
38
|
+
*/
|
|
39
|
+
import * as Cause from "effect/Cause";
|
|
40
|
+
import * as Effect from "effect/Effect";
|
|
41
|
+
import * as Exit from "effect/Exit";
|
|
42
|
+
import * as Layer from "effect/Layer";
|
|
43
|
+
import * as Stream from "effect/Stream";
|
|
44
|
+
import * as Tracer from "effect/Tracer";
|
|
45
|
+
import { redactParsed } from "./sensitive.ts";
|
|
46
|
+
import { Debug, type DebugHooks, OperationSpan, tagOf } from "./telemetry.ts";
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The call's log lines. Every line inside (the HTTP ones included) carries
|
|
50
|
+
* the operation and its URL template, and the exit line its duration. The
|
|
51
|
+
* input and output show only their sensitive values `Redacted`; each is
|
|
52
|
+
* judged by its own schema.
|
|
53
|
+
*/
|
|
54
|
+
const call: DebugHooks["call"] = (info, input, schemas, effect) => {
|
|
55
|
+
const template = info.attributes["url.template"];
|
|
56
|
+
const start =
|
|
57
|
+
schemas === undefined
|
|
58
|
+
? Effect.logDebug(`call ${info.name}`)
|
|
59
|
+
: Effect.logDebug(`call ${info.name}`, redactParsed(schemas.input, input));
|
|
60
|
+
const logged = Effect.flatMap(start, () =>
|
|
61
|
+
Effect.onExit(effect, (exit) =>
|
|
62
|
+
Exit.isSuccess(exit)
|
|
63
|
+
? schemas === undefined
|
|
64
|
+
? Effect.logDebug(`ok ${info.name}`)
|
|
65
|
+
: Effect.logDebug(`ok ${info.name}`, redactParsed(schemas.output, exit.value))
|
|
66
|
+
: Cause.hasInterruptsOnly(exit.cause)
|
|
67
|
+
? Effect.logDebug(`interrupted ${info.name}`)
|
|
68
|
+
: Effect.logDebug(`failed ${info.name}: ${tagOf(Cause.squash(exit.cause))}`),
|
|
69
|
+
),
|
|
70
|
+
);
|
|
71
|
+
return Effect.annotateLogs(Effect.withLogSpan(logged, "distilled.operation"), {
|
|
72
|
+
"distilled.operation": info.name,
|
|
73
|
+
...(typeof template === "string" ? { "url.template": template } : {}),
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
/** The host of `url`, without the path or query (which can carry secrets). */
|
|
78
|
+
const hostOf = (url: string): string => {
|
|
79
|
+
try {
|
|
80
|
+
return new URL(url).host;
|
|
81
|
+
} catch {
|
|
82
|
+
return "";
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** One HTTP exchange: method and host out, status back. */
|
|
87
|
+
const http: DebugHooks["http"] = (request, sent) =>
|
|
88
|
+
Effect.flatMap(Effect.logDebug(`-> ${request.method} ${hostOf(request.url)}`), () =>
|
|
89
|
+
Effect.tap(sent, (response) => Effect.logDebug(`<- ${response.status}`)),
|
|
90
|
+
);
|
|
91
|
+
|
|
92
|
+
const phase: DebugHooks["phase"] = (name, effect, attributes) =>
|
|
93
|
+
Effect.withSpan(effect, name, { level: "Debug", attributes, captureStackTrace: false });
|
|
94
|
+
|
|
95
|
+
const attempt: DebugHooks["attempt"] = (base, n) =>
|
|
96
|
+
Effect.withFiber((fiber) => {
|
|
97
|
+
const call = fiber.getRef(OperationSpan);
|
|
98
|
+
if (call === undefined) return base;
|
|
99
|
+
return Effect.useSpan(
|
|
100
|
+
"Attempt",
|
|
101
|
+
{
|
|
102
|
+
parent: call.span,
|
|
103
|
+
attributes: { "distilled.attempt": n, "http.request.resend_count": n - 1 },
|
|
104
|
+
},
|
|
105
|
+
(span) => {
|
|
106
|
+
call.attempt = span;
|
|
107
|
+
const run = Effect.tapError(base, (error) =>
|
|
108
|
+
Effect.sync(() => span.attribute("error.type", tagOf(error))),
|
|
109
|
+
);
|
|
110
|
+
return Effect.provideService(run, Tracer.ParentSpan, span);
|
|
111
|
+
},
|
|
112
|
+
);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* `distilled.read_stream`: from the caller's first pull on a streamed
|
|
117
|
+
* output member (an S3 object body, a Bedrock event stream) to its end,
|
|
118
|
+
* with the member's name and how many items (and bytes) it carried. It
|
|
119
|
+
* fills the operation span's time after the response headers arrive.
|
|
120
|
+
*/
|
|
121
|
+
const readStream: DebugHooks["readStream"] = (stream, parent, member) =>
|
|
122
|
+
Stream.unwrap(
|
|
123
|
+
Effect.map(
|
|
124
|
+
Effect.makeSpan("distilled.read_stream", {
|
|
125
|
+
parent,
|
|
126
|
+
level: "Debug",
|
|
127
|
+
attributes: { "distilled.stream.member": member },
|
|
128
|
+
}),
|
|
129
|
+
(span) => {
|
|
130
|
+
let items = 0;
|
|
131
|
+
let bytes = 0;
|
|
132
|
+
const counted = Stream.map(stream, (item) => {
|
|
133
|
+
items++;
|
|
134
|
+
if (item instanceof Uint8Array) bytes += item.byteLength;
|
|
135
|
+
return item;
|
|
136
|
+
});
|
|
137
|
+
return Stream.onExit(counted, (exit) =>
|
|
138
|
+
Effect.clockWith((clock) =>
|
|
139
|
+
Effect.sync(() => {
|
|
140
|
+
span.attribute("distilled.stream.items", items);
|
|
141
|
+
if (bytes > 0) span.attribute("distilled.stream.bytes", bytes);
|
|
142
|
+
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {
|
|
143
|
+
span.attribute("error.type", tagOf(Cause.squash(exit.cause)));
|
|
144
|
+
}
|
|
145
|
+
span.end(clock.currentTimeNanosUnsafe(), exit);
|
|
146
|
+
}),
|
|
147
|
+
),
|
|
148
|
+
);
|
|
149
|
+
},
|
|
150
|
+
),
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
const LOCATION = /\(?((?:file:\/\/)?[^\s()]+):(\d+):(\d+)\)?$/;
|
|
154
|
+
|
|
155
|
+
/** OTel `code.*` attributes for the caller's line. */
|
|
156
|
+
const callSite: DebugHooks["callSite"] = (site) => {
|
|
157
|
+
const line = site?.();
|
|
158
|
+
const match = line ? LOCATION.exec(line) : null;
|
|
159
|
+
if (!match) return undefined;
|
|
160
|
+
const fn = /^at (\S+) \(/.exec(line!)?.[1];
|
|
161
|
+
return {
|
|
162
|
+
"code.file.path": match[1],
|
|
163
|
+
"code.line.number": Number(match[2]),
|
|
164
|
+
"code.column.number": Number(match[3]),
|
|
165
|
+
...(fn ? { "code.function.name": fn } : {}),
|
|
166
|
+
};
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
export const TelemetryDebug = {
|
|
170
|
+
/** Turns on debug spans and debug log lines for every distilled call it is provided to. */
|
|
171
|
+
layer: /*@__PURE__*/ Layer.succeed(Debug, {
|
|
172
|
+
phase,
|
|
173
|
+
attempt,
|
|
174
|
+
readStream,
|
|
175
|
+
callSite,
|
|
176
|
+
call,
|
|
177
|
+
http,
|
|
178
|
+
}) as Layer.Layer<never>,
|
|
179
|
+
} as const;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App callbacks on each recorded operation span, for attributes distilled
|
|
3
|
+
* does not record (an app's own ids, a custom request field):
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* import { TelemetryHooks } from "@distilled.cloud/core/telemetry-hooks";
|
|
7
|
+
*
|
|
8
|
+
* program.pipe(
|
|
9
|
+
* Effect.provide(
|
|
10
|
+
* TelemetryHooks.layer({
|
|
11
|
+
* onStart: (span, { method, input }) => {
|
|
12
|
+
* if (method === "S3/PutObject") span.attribute("app.tenant", tenantOf(input));
|
|
13
|
+
* },
|
|
14
|
+
* onEnd: (span, exit) => {},
|
|
15
|
+
* }),
|
|
16
|
+
* ),
|
|
17
|
+
* );
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* `onStart` runs when the span starts, before the request is built, with
|
|
21
|
+
* the operation's span name, its `rpc.method` and the caller's input.
|
|
22
|
+
* `onEnd` runs when the call ends, after every retry. Both run only when a
|
|
23
|
+
* span is recorded (an exporter is installed). A program that never
|
|
24
|
+
* imports this module never bundles it.
|
|
25
|
+
*/
|
|
26
|
+
import * as Layer from "effect/Layer";
|
|
27
|
+
import { Hooks, type SpanHooks } from "./telemetry.ts";
|
|
28
|
+
|
|
29
|
+
export type { SpanHooks };
|
|
30
|
+
|
|
31
|
+
export const TelemetryHooks = {
|
|
32
|
+
layer: (hooks: SpanHooks): Layer.Layer<never> => Layer.succeed(Hooks, hooks),
|
|
33
|
+
} as const;
|
|
@@ -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
|
+
});
|