Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - one sha256 inside a synchronous Output.map.
2import * as NodeCrypto from "node:crypto";
3
4import * as Alchemy from "alchemy";
5import * as Axiom from "@alchemy.run/axiom";
6import * as Cloudflare from "@alchemy.run/cloudflare";
7import * as Output from "alchemy/Output";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Option from "effect/Option";
12import * as Redacted from "effect/Redacted";
13import * as Schema from "effect/Schema";
14import * as Tracer from "effect/Tracer";
15
16import { relayResourceNameForStage } from "./deploymentConfig.ts";
17import { MobileMonitoring } from "./mobileTelemetry/monitoring.ts";
18import { RelayMonitoring } from "./monitoring.ts";
19
20const relayRecentSpansQuery = (dataset: string) =>
21 [
22 `['${dataset}']`,
23 `| where isnotnull(span_id) or isnotnull(trace_id)`,
24 `| 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({}))`,
25 `| extend userId = customAttributes['user']['id']`,
26 `| project _time, name, trace_id, span_id, duration, requestMethod, path, statusCode, endpoint, userId`,
27 `| order by _time desc`,
28 `| limit 200`,
29 ].join("\n");
30
31export const RelayObservability = Effect.gen(function* () {
32 const { stage } = yield* Alchemy.Stack;
33 const traces = yield* Axiom.Dataset("RelayTracesDataset", {
34 name: relayResourceNameForStage("t3-code-relay-traces", stage),
35 kind: "otel:traces:v1",
36 description: "T3 Code relay Worker HTTP request spans.",
37 // Spans carry user ids; this keeps them inside the 30 days we promise for deleting account data.
38 retentionDays: 28,
39 useRetentionPeriod: true,
40 });
41
42 const workerIngestToken = yield* Axiom.ApiToken("RelayWorkerAxiomIngestToken", {
43 name: relayResourceNameForStage("t3-code-relay-otel-ingest", stage),
44 description: "Owned by Alchemy. Scoped OTLP ingest token for relay HTTP spans.",
45 datasetCapabilities: Output.map(traces.name, (dataset) => ({
46 [dataset]: { ingest: ["create" as const] },
47 })),
48 });
49
50 const mobileIngestToken = yield* Axiom.ApiToken("RelayMobileAxiomIngestToken", {
51 name: relayResourceNameForStage("t3-code-mobile-otel-ingest", stage),
52 description: "Owned by Alchemy. Scoped OTLP ingest token for T3 Code mobile spans.",
53 datasetCapabilities: Output.map(traces.name, (dataset) => ({
54 [dataset]: { ingest: ["create" as const] },
55 })),
56 });
57
58 const clientIngestToken = yield* Axiom.ApiToken("RelayClientAxiomIngestToken", {
59 name: relayResourceNameForStage("t3-code-relay-client-otel-ingest", stage),
60 description: "Owned by Alchemy. Scoped OTLP ingest token for first-party relay client spans.",
61 datasetCapabilities: Output.map(traces.name, (dataset) => ({
62 [dataset]: { ingest: ["create" as const] },
63 })),
64 });
65
66 // expo-observe data, forwarded by src/mobileTelemetry. Mobile spans share the traces dataset.
67 const mobileLogs = yield* Axiom.Dataset("MobileLogsDataset", {
68 name: relayResourceNameForStage("t3-code-mobile-logs", stage),
69 kind: "otel:logs:v1",
70 description: "T3 Code mobile app errors, crashes, and log events from expo-observe.",
71 retentionDays: 30,
72 useRetentionPeriod: true,
73 });
74 const mobileMetrics = yield* Axiom.Dataset("MobileMetricsDataset", {
75 name: relayResourceNameForStage("t3-code-mobile-metrics", stage),
76 kind: "otel:metrics:v1",
77 description: "T3 Code mobile app startup and update metrics from expo-observe.",
78 retentionDays: 30,
79 useRetentionPeriod: true,
80 });
81 const mobileTelemetryIngestToken = yield* Axiom.ApiToken("MobileTelemetryAxiomIngestToken", {
82 name: relayResourceNameForStage("t3-code-mobile-telemetry-ingest", stage),
83 description: "Owned by Alchemy. Scoped ingest token the relay forwards mobile telemetry with.",
84 datasetCapabilities: Output.map(
85 Output.all(traces.name, mobileLogs.name, mobileMetrics.name),
86 (datasets) =>
87 Object.fromEntries(datasets.map((dataset) => [dataset, { ingest: ["create" as const] }])),
88 ),
89 });
90
91 const mobileSourceMaps = yield* Cloudflare.R2.Bucket("MobileSourceMapsBucket", {
92 name: mobileSourceMapsBucketName(stage),
93 // R2 refuses to delete a non-empty bucket, which would half tear down every non-prod stage.
94 forceDestroy: stage !== "prod",
95 });
96
97 yield* Axiom.View("RelayRecentSpansView", {
98 name: relayResourceNameForStage("t3-code-relay-recent-spans", stage),
99 description: "Recent relay HTTP request spans.",
100 datasets: [traces.name],
101 aplQuery: Output.map(traces.name, relayRecentSpansQuery),
102 });
103
104 yield* RelayMonitoring(traces);
105 yield* MobileMonitoring(mobileLogs, traces);
106
107 return {
108 traces,
109 workerIngestToken,
110 mobileIngestToken,
111 clientIngestToken,
112 mobileLogs,
113 mobileMetrics,
114 mobileTelemetryIngestToken,
115 mobileSourceMaps,
116 } as const;
117});
118
119const mobileSourceMapsBucketName = (stage: string) =>
120 relayResourceNameForStage("t3-code-mobile-sourcemaps", stage);
121
122/**
123 * Write-only S3 credentials for the source maps bucket: the `MOBILE_SOURCEMAPS_R2` secret.
124 * R2's S3 access key id is the API token's id and the secret the SHA-256 of its value.
125 */
126export const MobileSourceMapsUploadCredentials = Effect.gen(function* () {
127 const { stage } = yield* Alchemy.Stack;
128 const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment;
129 const bucketName = mobileSourceMapsBucketName(stage);
130 const token = yield* Cloudflare.ApiToken.AccountApiToken("MobileSourceMapsUploadToken", {
131 name: relayResourceNameForStage("t3-code-mobile-sourcemaps-upload", stage),
132 policies: [
133 {
134 effect: "allow",
135 permissionGroups: ["Workers R2 Storage Bucket Item Write"],
136 resources: { [`com.cloudflare.edge.r2.bucket.${accountId}_default_${bucketName}`]: "*" },
137 },
138 ],
139 });
140 return Output.map(Output.all(token.tokenId, token.value), ([tokenId, value]) =>
141 Redacted.make(
142 JSON.stringify({
143 endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
144 bucketName,
145 accessKeyId: tokenId,
146 secretAccessKey: NodeCrypto.createHash("sha256")
147 .update(Redacted.value(value))
148 .digest("hex"),
149 }),
150 ),
151 );
152});
153
154export const withSpanAttributes =
155 (attributes: Record<string, unknown>) =>
156 <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
157 Effect.annotateCurrentSpan(attributes).pipe(
158 Effect.andThen(effect.pipe(Effect.annotateSpans(attributes))),
159 );
160
161const appendEncodedAttributes = (
162 attributes: Record<string, unknown>,
163 prefix: string,
164 value: unknown,
165): void => {
166 if (
167 value === null ||
168 typeof value === "string" ||
169 typeof value === "number" ||
170 typeof value === "boolean" ||
171 typeof value === "bigint" ||
172 Array.isArray(value)
173 ) {
174 attributes[prefix] = value;
175 return;
176 }
177 if (typeof value !== "object") {
178 return;
179 }
180 for (const [key, child] of Object.entries(value)) {
181 appendEncodedAttributes(attributes, `${prefix}.${key}`, child);
182 }
183};
184
185const schemaErrorAttributes = (error: unknown): Record<string, unknown> | undefined => {
186 if (typeof error !== "object" || error === null) {
187 return undefined;
188 }
189 const constructor = error.constructor;
190 if (!Schema.isSchema(constructor)) {
191 return undefined;
192 }
193 const encoded = Schema.encodeUnknownOption(constructor as unknown as Schema.Encoder<unknown>)(
194 error,
195 );
196 if (Option.isNone(encoded) || typeof encoded.value !== "object" || encoded.value === null) {
197 return undefined;
198 }
199 const tag = Reflect.get(encoded.value, "_tag");
200 if (typeof tag !== "string") {
201 return undefined;
202 }
203
204 const attributes: Record<string, unknown> = {
205 "error.type": tag,
206 };
207 for (const [key, value] of Object.entries(encoded.value)) {
208 if (key !== "_tag") {
209 appendEncodedAttributes(attributes, `error.${key}`, value);
210 }
211 }
212 return attributes;
213};
214
215const annotateSchemaError = (span: Tracer.Span, exit: Exit.Exit<unknown, unknown>): void => {
216 if (Exit.isSuccess(exit)) {
217 return;
218 }
219 for (const reason of exit.cause.reasons) {
220 const error = Cause.isFailReason(reason)
221 ? reason.error
222 : Cause.isDieReason(reason)
223 ? reason.defect
224 : undefined;
225 const attributes = schemaErrorAttributes(error);
226 if (attributes) {
227 for (const [key, value] of Object.entries(attributes)) {
228 span.attribute(key, value);
229 }
230 return;
231 }
232 }
233};
234
235class RelayTraceSpan implements Tracer.Span {
236 readonly _tag = "Span";
237 private readonly delegate: Tracer.Span;
238
239 constructor(delegate: Tracer.Span) {
240 this.delegate = delegate;
241 }
242
243 get name() {
244 return this.delegate.name;
245 }
246 get spanId() {
247 return this.delegate.spanId;
248 }
249 get traceId() {
250 return this.delegate.traceId;
251 }
252 get parent() {
253 return this.delegate.parent;
254 }
255 get annotations() {
256 return this.delegate.annotations;
257 }
258 get status() {
259 return this.delegate.status;
260 }
261 get attributes() {
262 return this.delegate.attributes;
263 }
264 get links() {
265 return this.delegate.links;
266 }
267 get sampled() {
268 return this.delegate.sampled;
269 }
270 get kind() {
271 return this.delegate.kind;
272 }
273
274 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
275 annotateSchemaError(this.delegate, exit);
276 this.delegate.end(endTime, exit);
277 }
278
279 attribute(key: string, value: unknown): void {
280 this.delegate.attribute(key, value);
281 }
282
283 event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
284 this.delegate.event(name, startTime, attributes);
285 }
286
287 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
288 this.delegate.addLinks(links);
289 }
290}
291
292const withSchemaErrorAttributes = (delegate: Tracer.Tracer): Tracer.Tracer =>
293 Tracer.make({
294 span: (options) => new RelayTraceSpan(delegate.span(options)),
295 ...(delegate.context ? { context: delegate.context } : {}),
296 });
297
298export const withSchemaErrorSpanAttributes = <A, E, R>(
299 effect: Effect.Effect<A, E, R>,
300): Effect.Effect<A, E, R> =>
301 Effect.flatMap(Effect.tracer, (tracer) =>
302 effect.pipe(Effect.withTracer(withSchemaErrorAttributes(tracer))),
303 );