The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Lambda from "@alchemy.run/aws/Lambda"; |
| 2 | import * as XRay from "@alchemy.run/aws/XRay"; |
| 3 | import * as Duration from "effect/Duration"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 6 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Result from "effect/Result"; |
| 9 | import * as Schedule from "effect/Schedule"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import path from "pathe"; |
| 12 | |
| 13 | const main = path.resolve(import.meta.dirname, "handler.ts"); |
| 14 | |
| 15 | export class XRayTestFunction extends Lambda.Function<Lambda.Function>()("XRayTestFunction") {} |
| 16 | |
| 17 | /** Collapse a typed API call to `"ok"` or its typed error tag. */ |
| 18 | const outcome = <A, E extends { _tag: string }>(effect: Effect.Effect<A, E>) => |
| 19 | Effect.result(effect).pipe( |
| 20 | Effect.map((result) => (Result.isFailure(result) ? result.failure._tag : "ok")), |
| 21 | ); |
| 22 | |
| 23 | export default XRayTestFunction.make( |
| 24 | { |
| 25 | main, |
| 26 | functionUrl: true, |
| 27 | // Active tracing: every sampled invocation of this function produces an |
| 28 | // X-Ray trace whose service name is the function name. |
| 29 | tracing: "Active", |
| 30 | timeout: Duration.seconds(30), |
| 31 | }, |
| 32 | Effect.gen(function* () { |
| 33 | // Event source: subscribe the host to X-Ray insight updates. The deploy |
| 34 | // proves the EventBridge rule + invoke permission wiring. |
| 35 | yield* XRay.consumeInsightEvents({ states: ["ACTIVE"] }, (events) => |
| 36 | Stream.runForEach(events, (event) => |
| 37 | Effect.log(`xray insight: ${event.detail.InsightId} (${event.detail.State})`), |
| 38 | ), |
| 39 | ); |
| 40 | |
| 41 | const getTraceSummaries = yield* XRay.GetTraceSummaries(); |
| 42 | const batchGetTraces = yield* XRay.BatchGetTraces(); |
| 43 | const putTraceSegments = yield* XRay.PutTraceSegments(); |
| 44 | const putTelemetryRecords = yield* XRay.PutTelemetryRecords(); |
| 45 | const getSamplingRules = yield* XRay.GetSamplingRules(); |
| 46 | const getSamplingTargets = yield* XRay.GetSamplingTargets(); |
| 47 | const getSamplingStatisticSummaries = yield* XRay.GetSamplingStatisticSummaries(); |
| 48 | const getServiceGraph = yield* XRay.GetServiceGraph(); |
| 49 | const getTraceGraph = yield* XRay.GetTraceGraph(); |
| 50 | const getTimeSeriesServiceStatistics = yield* XRay.GetTimeSeriesServiceStatistics(); |
| 51 | const getInsight = yield* XRay.GetInsight(); |
| 52 | const getInsightEvents = yield* XRay.GetInsightEvents(); |
| 53 | const getInsightImpactGraph = yield* XRay.GetInsightImpactGraph(); |
| 54 | const getInsightSummaries = yield* XRay.GetInsightSummaries(); |
| 55 | const getTraceSegmentDestination = yield* XRay.GetTraceSegmentDestination(); |
| 56 | const startTraceRetrieval = yield* XRay.StartTraceRetrieval(); |
| 57 | const listRetrievedTraces = yield* XRay.ListRetrievedTraces(); |
| 58 | const getRetrievedTracesGraph = yield* XRay.GetRetrievedTracesGraph(); |
| 59 | const cancelTraceRetrieval = yield* XRay.CancelTraceRetrieval(); |
| 60 | |
| 61 | // X-Ray read APIs have low TPS quotas; the test polls routes while |
| 62 | // sibling suites run, so absorb throttling in the fixture. |
| 63 | const throttleRetry = <A, E extends { _tag: string }>(effect: Effect.Effect<A, E>) => |
| 64 | effect.pipe( |
| 65 | Effect.retry({ |
| 66 | while: (error): boolean => error._tag === "ThrottledException", |
| 67 | schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(5)]), |
| 68 | }), |
| 69 | ); |
| 70 | |
| 71 | return { |
| 72 | fetch: Effect.gen(function* () { |
| 73 | const request = yield* HttpServerRequest; |
| 74 | const url = new URL(request.originalUrl); |
| 75 | const pathname = url.pathname; |
| 76 | const now = yield* Effect.sync(() => Date.now()); |
| 77 | |
| 78 | if (request.method === "GET" && pathname === "/ping") { |
| 79 | const functionName = yield* Effect.sync(() => process.env.AWS_LAMBDA_FUNCTION_NAME); |
| 80 | return yield* HttpServerResponse.json({ ok: true, functionName }); |
| 81 | } |
| 82 | |
| 83 | if (request.method === "GET" && pathname === "/trace-summaries") { |
| 84 | const service = url.searchParams.get("service"); |
| 85 | const result = yield* throttleRetry( |
| 86 | getTraceSummaries({ |
| 87 | StartTime: new Date(now - 10 * 60 * 1000), |
| 88 | EndTime: new Date(now), |
| 89 | FilterExpression: service ? `service("${service}")` : undefined, |
| 90 | }), |
| 91 | ); |
| 92 | return yield* HttpServerResponse.json({ |
| 93 | traceIds: (result.TraceSummaries ?? []).flatMap((summary) => |
| 94 | summary.Id ? [summary.Id] : [], |
| 95 | ), |
| 96 | }); |
| 97 | } |
| 98 | |
| 99 | if (request.method === "GET" && pathname === "/batch-get-traces") { |
| 100 | const ids = url.searchParams.get("ids"); |
| 101 | const result = yield* throttleRetry( |
| 102 | batchGetTraces({ TraceIds: ids ? ids.split(",") : [] }), |
| 103 | ); |
| 104 | return yield* HttpServerResponse.json({ |
| 105 | traces: (result.Traces ?? []).map((trace) => ({ |
| 106 | id: trace.Id, |
| 107 | segments: trace.Segments?.length ?? 0, |
| 108 | })), |
| 109 | unprocessed: result.UnprocessedTraceIds ?? [], |
| 110 | }); |
| 111 | } |
| 112 | |
| 113 | if (request.method === "POST" && pathname === "/put-trace-segments") { |
| 114 | // A well-formed custom segment: epoch-anchored trace id, unique |
| 115 | // segment id, sub-second duration. |
| 116 | const epochHex = Math.floor(now / 1000).toString(16); |
| 117 | const random24 = Array.from({ length: 24 }, () => |
| 118 | Math.floor(Math.random() * 16).toString(16), |
| 119 | ).join(""); |
| 120 | const segmentId = Array.from({ length: 16 }, () => |
| 121 | Math.floor(Math.random() * 16).toString(16), |
| 122 | ).join(""); |
| 123 | const traceId = `1-${epochHex}-${random24}`; |
| 124 | const result = yield* throttleRetry( |
| 125 | putTraceSegments({ |
| 126 | TraceSegmentDocuments: [ |
| 127 | JSON.stringify({ |
| 128 | name: "alchemy-xray-binding-test", |
| 129 | id: segmentId, |
| 130 | trace_id: traceId, |
| 131 | start_time: now / 1000 - 0.5, |
| 132 | end_time: now / 1000, |
| 133 | }), |
| 134 | ], |
| 135 | }), |
| 136 | ); |
| 137 | return yield* HttpServerResponse.json({ |
| 138 | traceId, |
| 139 | unprocessed: result.UnprocessedTraceSegments ?? [], |
| 140 | }); |
| 141 | } |
| 142 | |
| 143 | if (request.method === "POST" && pathname === "/telemetry") { |
| 144 | yield* throttleRetry( |
| 145 | putTelemetryRecords({ |
| 146 | TelemetryRecords: [ |
| 147 | { |
| 148 | Timestamp: new Date(now), |
| 149 | SegmentsReceivedCount: 1, |
| 150 | SegmentsSentCount: 1, |
| 151 | }, |
| 152 | ], |
| 153 | }), |
| 154 | ); |
| 155 | return yield* HttpServerResponse.json({ ok: true }); |
| 156 | } |
| 157 | |
| 158 | if (request.method === "GET" && pathname === "/sampling") { |
| 159 | const rules = yield* throttleRetry(getSamplingRules()); |
| 160 | const summaries = yield* throttleRetry(getSamplingStatisticSummaries()); |
| 161 | // Report sampling statistics for the built-in Default rule — the |
| 162 | // real sampler protocol handshake. |
| 163 | const clientId = Array.from({ length: 24 }, () => |
| 164 | Math.floor(Math.random() * 16).toString(16), |
| 165 | ).join(""); |
| 166 | const targets = yield* Effect.result( |
| 167 | getSamplingTargets({ |
| 168 | SamplingStatisticsDocuments: [ |
| 169 | { |
| 170 | RuleName: "Default", |
| 171 | ClientID: clientId, |
| 172 | Timestamp: new Date(now), |
| 173 | RequestCount: 1, |
| 174 | SampledCount: 1, |
| 175 | }, |
| 176 | ], |
| 177 | }), |
| 178 | ); |
| 179 | return yield* HttpServerResponse.json({ |
| 180 | ruleNames: (rules.SamplingRuleRecords ?? []).flatMap((record) => |
| 181 | record.SamplingRule?.RuleName ? [record.SamplingRule.RuleName] : [], |
| 182 | ), |
| 183 | statisticSummaries: (summaries.SamplingStatisticSummaries ?? []).length, |
| 184 | targets: Result.isSuccess(targets) |
| 185 | ? { |
| 186 | outcome: "ok", |
| 187 | documents: (targets.success.SamplingTargetDocuments ?? []).length, |
| 188 | } |
| 189 | : { outcome: targets.failure._tag, documents: null }, |
| 190 | }); |
| 191 | } |
| 192 | |
| 193 | if (request.method === "GET" && pathname === "/service-graph") { |
| 194 | const graph = yield* Effect.result( |
| 195 | throttleRetry( |
| 196 | getServiceGraph({ |
| 197 | StartTime: new Date(now - 10 * 60 * 1000), |
| 198 | EndTime: new Date(now), |
| 199 | }), |
| 200 | ), |
| 201 | ); |
| 202 | return yield* HttpServerResponse.json( |
| 203 | Result.isSuccess(graph) |
| 204 | ? { services: (graph.success.Services ?? []).length, error: null } |
| 205 | : { services: null, error: graph.failure._tag }, |
| 206 | ); |
| 207 | } |
| 208 | |
| 209 | if (request.method === "GET" && pathname === "/trace-graph") { |
| 210 | const ids = url.searchParams.get("ids"); |
| 211 | const graph = yield* Effect.result( |
| 212 | throttleRetry(getTraceGraph({ TraceIds: ids ? ids.split(",") : [] })), |
| 213 | ); |
| 214 | return yield* HttpServerResponse.json( |
| 215 | Result.isSuccess(graph) |
| 216 | ? { services: (graph.success.Services ?? []).length, error: null } |
| 217 | : { services: null, error: graph.failure._tag }, |
| 218 | ); |
| 219 | } |
| 220 | |
| 221 | if (request.method === "GET" && pathname === "/time-series") { |
| 222 | const service = url.searchParams.get("service"); |
| 223 | const stats = yield* Effect.result( |
| 224 | getTimeSeriesServiceStatistics({ |
| 225 | StartTime: new Date(now - 10 * 60 * 1000), |
| 226 | EndTime: new Date(now), |
| 227 | EntitySelectorExpression: service ? `service("${service}")` : undefined, |
| 228 | Period: 60, |
| 229 | }), |
| 230 | ); |
| 231 | return yield* HttpServerResponse.json( |
| 232 | Result.isSuccess(stats) |
| 233 | ? { |
| 234 | points: (stats.success.TimeSeriesServiceStatistics ?? []).length, |
| 235 | error: null, |
| 236 | } |
| 237 | : { points: null, error: stats.failure._tag }, |
| 238 | ); |
| 239 | } |
| 240 | |
| 241 | if (request.method === "GET" && pathname === "/insight-summaries") { |
| 242 | // The group may not have insights enabled — report either the |
| 243 | // summary count or the API's typed error tag. |
| 244 | const group = url.searchParams.get("group") ?? "Default"; |
| 245 | const result = yield* Effect.result( |
| 246 | throttleRetry( |
| 247 | getInsightSummaries({ |
| 248 | GroupName: group, |
| 249 | StartTime: new Date(now - 24 * 60 * 60 * 1000), |
| 250 | EndTime: new Date(now), |
| 251 | }), |
| 252 | ), |
| 253 | ); |
| 254 | return yield* HttpServerResponse.json( |
| 255 | Result.isSuccess(result) |
| 256 | ? { |
| 257 | insights: (result.success.InsightSummaries ?? []).length, |
| 258 | error: null, |
| 259 | } |
| 260 | : { insights: null, error: result.failure._tag }, |
| 261 | ); |
| 262 | } |
| 263 | |
| 264 | if (request.method === "GET" && pathname === "/insight") { |
| 265 | // No insight can be provisioned on demand — prove each binding's |
| 266 | // IAM grant by observing the API's typed validation error for a |
| 267 | // syntactically-plausible but nonexistent insight id (an IAM |
| 268 | // failure would surface as AccessDeniedException instead). |
| 269 | const insightId = url.searchParams.get("id") ?? "00000000-0000-0000-0000-000000000000"; |
| 270 | return yield* HttpServerResponse.json({ |
| 271 | getInsight: yield* outcome(getInsight({ InsightId: insightId })), |
| 272 | getInsightEvents: yield* outcome(getInsightEvents({ InsightId: insightId })), |
| 273 | getInsightImpactGraph: yield* outcome( |
| 274 | getInsightImpactGraph({ |
| 275 | InsightId: insightId, |
| 276 | StartTime: new Date(now - 60 * 60 * 1000), |
| 277 | EndTime: new Date(now), |
| 278 | }), |
| 279 | ), |
| 280 | }); |
| 281 | } |
| 282 | |
| 283 | if (request.method === "GET" && pathname === "/trace-retrieval") { |
| 284 | // Transaction Search requires a CloudWatch Logs trace destination; |
| 285 | // on the default X-Ray destination the retrieval ops answer with |
| 286 | // typed errors — either way each call proves its IAM grant. |
| 287 | const destination = yield* throttleRetry(getTraceSegmentDestination()); |
| 288 | const epochHex = Math.floor(now / 1000).toString(16); |
| 289 | const start = yield* Effect.result( |
| 290 | startTraceRetrieval({ |
| 291 | TraceIds: [`1-${epochHex}-abcdef0123456789abcdef01`], |
| 292 | StartTime: new Date(now - 60 * 60 * 1000), |
| 293 | EndTime: new Date(now), |
| 294 | }), |
| 295 | ); |
| 296 | const retrievalToken = Result.isSuccess(start) ? start.success.RetrievalToken : undefined; |
| 297 | const bogusToken = retrievalToken ?? "alchemy-nonexistent-token"; |
| 298 | return yield* HttpServerResponse.json({ |
| 299 | destination: destination.Destination, |
| 300 | startTraceRetrieval: Result.isFailure(start) ? start.failure._tag : "ok", |
| 301 | listRetrievedTraces: yield* outcome( |
| 302 | listRetrievedTraces({ RetrievalToken: bogusToken }), |
| 303 | ), |
| 304 | getRetrievedTracesGraph: yield* outcome( |
| 305 | getRetrievedTracesGraph({ RetrievalToken: bogusToken }), |
| 306 | ), |
| 307 | cancelTraceRetrieval: yield* outcome( |
| 308 | cancelTraceRetrieval({ RetrievalToken: bogusToken }), |
| 309 | ), |
| 310 | }); |
| 311 | } |
| 312 | |
| 313 | return yield* HttpServerResponse.json( |
| 314 | { error: "Not found", method: request.method, pathname }, |
| 315 | { status: 404 }, |
| 316 | ); |
| 317 | }).pipe(Effect.orDie), |
| 318 | }; |
| 319 | }).pipe( |
| 320 | Effect.provide( |
| 321 | Layer.mergeAll( |
| 322 | Lambda.EventSource, |
| 323 | XRay.GetTraceSummariesHttp, |
| 324 | XRay.BatchGetTracesHttp, |
| 325 | XRay.PutTraceSegmentsHttp, |
| 326 | XRay.PutTelemetryRecordsHttp, |
| 327 | XRay.GetSamplingRulesHttp, |
| 328 | XRay.GetSamplingTargetsHttp, |
| 329 | XRay.GetSamplingStatisticSummariesHttp, |
| 330 | XRay.GetServiceGraphHttp, |
| 331 | XRay.GetTraceGraphHttp, |
| 332 | XRay.GetTimeSeriesServiceStatisticsHttp, |
| 333 | XRay.GetInsightHttp, |
| 334 | XRay.GetInsightEventsHttp, |
| 335 | XRay.GetInsightImpactGraphHttp, |
| 336 | XRay.GetInsightSummariesHttp, |
| 337 | XRay.GetTraceSegmentDestinationHttp, |
| 338 | XRay.StartTraceRetrievalHttp, |
| 339 | XRay.ListRetrievedTracesHttp, |
| 340 | XRay.GetRetrievedTracesGraphHttp, |
| 341 | XRay.CancelTraceRetrievalHttp, |
| 342 | ), |
| 343 | ), |
| 344 | ), |
| 345 | ); |