Open History to see the last commit
1import * as Alchemy from "alchemy";
2import * as Axiom from "alchemy/Axiom";
3import * as Output from "alchemy/Output";
4import * as Cause from "effect/Cause";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Redacted from "effect/Redacted";
10import * as Schema from "effect/Schema";
11import * as Tracer from "effect/Tracer";
12import { OtlpExporter, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
13
14import { relayResourceNameForStage } from "./deploymentConfig.ts";
15
16const relayRecentSpansQuery = (dataset: string) =>
17 [
18 `['${dataset}']`,
19 `| where isnotnull(span_id) or isnotnull(trace_id)`,
20 `| extend requestMethod = column_ifexists('attributes.http.request.method', ''), path = column_ifexists('attributes.url.path', ''), endpoint = column_ifexists('attributes.http.route', ''), statusCode = column_ifexists('attributes.http.response.status_code', 0), customAttributes = column_ifexists('attributes.custom', dynamic({}))`,
21 `| extend userId = customAttributes['user']['id']`,
22 `| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId`,
23 `| order by _time desc`,
24 `| limit 200`,
25 ].join("\n");
26
27export const RelayObservability = Effect.gen(function* () {
28 const { stage } = yield* Alchemy.Stack;
29 const traces = yield* Axiom.Dataset("RelayTracesDataset", {
30 name: relayResourceNameForStage("t3-code-relay-traces", stage),
31 kind: "otel:traces:v1",
32 description: "T3 Code relay Worker HTTP request spans.",
33 retentionDays: 30,
34 useRetentionPeriod: true,
35 });
36
37 const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
38 name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
39 description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
40 datasetCapabilities: Output.map(traces.name, (dataset) => ({
41 [dataset]: { ingest: ["create" as const] },
42 })),
43 });
44
45 const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
46 name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
47 description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
48 datasetCapabilities: Output.map(traces.name, (dataset) => ({
49 [dataset]: { ingest: ["create" as const] },
50 })),
51 });
52
53 const clientIngestToken = yield* Axiom.ApiToken("RelayClientAxiomIngestToken", {
54 name: relayResourceNameForStage("t3-code-relay-client-otel-ingest", stage),
55 description: "Owned by Alchemy. Scoped OTLP ingest token for first-party relay client spans.",
56 datasetCapabilities: Output.map(traces.name, (dataset) => ({
57 [dataset]: { ingest: ["create" as const] },
58 })),
59 });
60
61 yield* Axiom.View("RelayRecentSpansView", {
62 name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
63 description: "Recent relay HTTP request spans.",
64 datasets: [traces.name],
65 aplQuery: Output.map(traces.name, relayRecentSpansQuery),
66 });
67
68 return { traces, workerIngestToken, mobileIngestToken, clientIngestToken } as const;
69});
70
71export const withSpanAttributes =
72 (attributes: Record<string, unknown>) =>
73 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
74 Effect.annotateCurrentSpan(attributes).pipe(
75 Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
76 );
77
78const appendEncodedAttributes = (
79 attributes: Record<string, unknown>,
80 prefix: string,
81 value: unknown,
82): void => {
83 if (
84 value === null ||
85 typeof value === "string" ||
86 typeof value === "number" ||
87 typeof value === "boolean" ||
88 typeof value === "bigint" ||
89 Array.isArray(value)
90 ) {
91 attributes[prefix] = value;
92 return;
93 }
94 if (typeof value !== "object") {
95 return;
96 }
97 for (const [key, child] of Object.entries(value)) {
98 appendEncodedAttributes(attributes, `${prefix}.${key}`, child);
99 }
100};
101
102const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {
103 if (typeof error !== "object" || error === null) {
104 return undefined;
105 }
106 const constructor = error.constructor;
107 if (!Schema.isSchema(constructor)) {
108 return undefined;
109 }
110 const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(
111 error,
112 );
113 if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {
114 return undefined;
115 }
116 const tag = Reflect.get(encoded.value, "_tag");
117 if (typeof tag !== "string") {
118 return undefined;
119 }
120
121 const attributes: Record<string, unknown> = {
122 "error.type": tag,
123 };
124 for (const [key, value] of Object.entries(encoded.value)) {
125 if (key !== "_tag") {
126 appendEncodedAttributes(attributes, `error.${key}`, value);
127 }
128 }
129 return attributes;
130};
131
132const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {
133 if (Exit.isSuccess(exit)) {
134 return;
135 }
136 for (const reason of exit.cause.reasons) {
137 const error = Cause.isFailReason(reason)
138 ? reason.error
139 : Cause.isDieReason(reason)
140 ? reason.defect
141 : undefined;
142 const attributes = schemaErrorAttributes(error);
143 if (attributes) {
144 for (const [key, value] of Object.entries(attributes)) {
145 span.attribute(key, value);
146 }
147 return;
148 }
149 }
150};
151
152class RelayTraceSpan implements Tracer.Span {
153 readonly _tag = "Span";
154 private readonly delegate: Tracer.Span;
155
156 constructor(delegate: Tracer.Span) {
157 this.delegate = delegate;
158 }
159
160 get name() {
161 return this.delegate.name;
162 }
163 get spanId() {
164 return this.delegate.spanId;
165 }
166 get traceId() {
167 return this.delegate.traceId;
168 }
169 get parent() {
170 return this.delegate.parent;
171 }
172 get annotations() {
173 return this.delegate.annotations;
174 }
175 get status() {
176 return this.delegate.status;
177 }
178 get attributes() {
179 return this.delegate.attributes;
180 }
181 get links() {
182 return this.delegate.links;
183 }
184 get sampled() {
185 return this.delegate.sampled;
186 }
187 get kind() {
188 return this.delegate.kind;
189 }
190
191 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
192 annotateSchemaError(this.delegate, exit);
193 this.delegate.end(endTime, exit);
194 }
195
196 attribute(key: string, value: unknown): void {
197 this.delegate.attribute(key, value);
198 }
199
200 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
201 this.delegate.event(name, startTime, attributes);
202 }
203
204 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
205 this.delegate.addLinks(links);
206 }
207}
208
209const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>
210 Tracer.make({
211 span: (options) => new RelayTraceSpan(delegate.span(options)),
212 ...(delegate.context ? { context: delegate.context } : {}),
213 });
214
215export const makeRelayTraceLayer = (input: {
216 readonly tracesEndpoint: string;
217 readonly tracesDatasetName: string;
218 readonly ingestToken: Redacted.Redacted<string>;
219}) =>
220 Layer.effect(
221 Tracer.Tracer,
222 OtlpTracer.make({
223 url: input.tracesEndpoint,
224 resource: {
225 serviceName: "t3-code-relay-worker",
226 attributes: {
227 "service.runtime": "cloudflare-worker",
228 "service.component": "relay",
229 },
230 },
231 headers: {
232 Authorization: `Bearer ${Redacted.value(input.ingestToken)}`,
233 "X-Axiom-Dataset": input.tracesDatasetName,
234 },
235 exportInterval: "1 second",
236 }).pipe(Effect.map(withSchemaErrorAttributes)),
237 ).pipe(Layer.provideMerge(OtlpExporter.layerFlusher), Layer.provide(OtlpSerialization.layerJson));