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 Option from "effect/Option";
8import * as Schema from "effect/Schema";
9import * as Tracer from "effect/Tracer";
10
11import { relayResourceNameForStage } from "./deploymentConfig.ts";
12import { RelayMonitoring } from "./monitoring.ts";
13
14const relayRecentSpansQuery = (dataset: string) =>
15 [
16 `['${dataset}']`,
17 `| where isnotnull(span_id) or isnotnull(trace_id)`,
18 `| 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({}))`,
19 `| extend userId = customAttributes['user']['id']`,
20 `| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId`,
21 `| order by _time desc`,
22 `| limit 200`,
23 ].join("\n");
24
25export const RelayObservability = Effect.gen(function* () {
26 const { stage } = yield* Alchemy.Stack;
27 const traces = yield* Axiom.Dataset("RelayTracesDataset", {
28 name: relayResourceNameForStage("t3-code-relay-traces", stage),
29 kind: "otel:traces:v1",
30 description: "T3 Code relay Worker HTTP request spans.",
31 retentionDays: 30,
32 useRetentionPeriod: true,
33 });
34
35 const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
36 name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
37 description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
38 datasetCapabilities: Output.map(traces.name, (dataset) => ({
39 [dataset]: { ingest: ["create" as const] },
40 })),
41 });
42
43 const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
44 name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
45 description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
46 datasetCapabilities: Output.map(traces.name, (dataset) => ({
47 [dataset]: { ingest: ["create" as const] },
48 })),
49 });
50
51 const clientIngestToken = yield* Axiom.ApiToken("RelayClientAxiomIngestToken", {
52 name: relayResourceNameForStage("t3-code-relay-client-otel-ingest", stage),
53 description: "Owned by Alchemy. Scoped OTLP ingest token for first-party relay client spans.",
54 datasetCapabilities: Output.map(traces.name, (dataset) => ({
55 [dataset]: { ingest: ["create" as const] },
56 })),
57 });
58
59 yield* Axiom.View("RelayRecentSpansView", {
60 name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
61 description: "Recent relay HTTP request spans.",
62 datasets: [traces.name],
63 aplQuery: Output.map(traces.name, relayRecentSpansQuery),
64 });
65
66 yield* RelayMonitoring(traces);
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 withSchemaErrorSpanAttributes = <A, E, R>(
216 effect: Effect.Effect<A, E, R>,
217): Effect.Effect<A, E, R> =>
218 Effect.flatMap(Effect.tracer, (tracer) =>
219 effect.pipe(Effect.withTracer(withSchemaErrorAttributes(tracer))),
220 );