diff --git a/apps/api/src/telemetry-options.ts b/apps/api/src/telemetry-options.ts new file mode 100644 index 0000000000..8c73599cf4 --- /dev/null +++ b/apps/api/src/telemetry-options.ts @@ -0,0 +1,17 @@ +import type { WorkerTelemetryOptions } from "@maple/infra/worker-telemetry" + +/** + * Backend errors the api always answers as a 4xx or absorbs, added to the domain's 4xx set so a + * span that fails only with one exports `Ok`: an OAuth client's bad request (rendered as an OAuth + * 400) and a guarded transition that lost its race (remapped to a 409 or caught as a no-op). + * Literals keep the backend classes off the init path; the bridge test holds them to the classes. + */ +export const API_ANTICIPATED_ERROR_IDENTIFIERS: ReadonlyArray = [ + "@maple/backend/errors/McpOAuthProtocolError", + "@maple/backend/TransitionConflictError", +] + +export const apiTelemetryOptions: WorkerTelemetryOptions = { + serviceName: "maple-api", + anticipatedErrorIdentifiers: API_ANTICIPATED_ERROR_IDENTIFIERS, +} diff --git a/apps/api/src/worker-bridge.test.ts b/apps/api/src/worker-bridge.test.ts index 3e364ff76d..de49390153 100644 --- a/apps/api/src/worker-bridge.test.ts +++ b/apps/api/src/worker-bridge.test.ts @@ -4,6 +4,8 @@ import { assert, describe, it } from "@effect/vitest" import * as MapleCloudflareSDK from "@maple-dev/effect-sdk/cloudflare" import { v2WorkerUnavailableDefinition } from "@maple/domain/http/v2-worker-unavailable" import { workerTelemetryConfig } from "@maple/infra/worker-telemetry" +import { McpOAuthProtocolError } from "@maple/backend/services/auth/McpOAuthService" +import { TransitionConflictError } from "@maple/backend/platform/transition-row" import * as Cloudflare from "@alchemy.run/cloudflare" import type { HttpEffect } from "alchemy/Http" import { @@ -27,6 +29,7 @@ import { cachedRecoverable } from "@maple/infra/cached-recoverable" import { recordRenderedFailure } from "@maple/backend/http/rendered-failure" import { runAfterResponse } from "@maple/backend/platform/after-response" import { buildIsolateHandler, makeFetch } from "./worker/http" +import { apiTelemetryOptions } from "./telemetry-options" /** * One request the way alchemy's bridge runs it — `makeRequestHandler` is the @@ -90,18 +93,18 @@ const stubFetch = (recorded: Array): typeof globalThis.fetch => return new Response("{}", { status: 200 }) }) as typeof globalThis.fetch -const serverSpans = (recorded: ReadonlyArray): Array => { +const exportedSpans = (recorded: ReadonlyArray): Array => { const traceRequests = Arr.filter(recorded, (request) => Str.endsWith("/v1/traces")(request.url)) const resources = Arr.flatMap( traceRequests, (request) => decodeExportedTraces(JSON.parse(request.body ?? "{}")).resourceSpans ?? [], ) - const spans = Arr.flatMap(resources, (resource) => - Arr.flatMap(resource.scopeSpans, (scope) => scope.spans), - ) - return Arr.filter(spans, (span) => span.kind === SERVER_KIND) + return Arr.flatMap(resources, (resource) => Arr.flatMap(resource.scopeSpans, (scope) => scope.spans)) } +const serverSpans = (recorded: ReadonlyArray): Array => + Arr.filter(exportedSpans(recorded), (span) => span.kind === SERVER_KIND) + const logBodies = (recorded: ReadonlyArray): Array => { const logRequests = Arr.filter(recorded, (request) => Str.endsWith("/v1/logs")(request.url)) const resources = Arr.flatMap( @@ -180,6 +183,15 @@ const renderedServerErrorApp: Effect.Effect = Effect.succeed( Effect.succeed(HttpServerResponse.text("", { status: 500 })), ) +/** A handler whose inner span fails with `error`, which the route answers as a 4xx. */ +const answeredAs4xx = (error: McpOAuthProtocolError | TransitionConflictError): Effect.Effect => + Effect.succeed( + Effect.fail(error).pipe( + Effect.withSpan("Probe.inner"), + Effect.orElseSucceed(() => HttpServerResponse.text("", { status: 400 })), + ), + ) + /** A graph whose handler dies, so the cause is still live when it leaves the router. */ const dyingApp: Effect.Effect = Effect.succeed(Effect.die(new Error("handler exploded"))) @@ -267,9 +279,9 @@ const event = ( // One tag under two types: the SDK reads its env where the bridge provides the Worker's. const services = yield* Layer.buildWithScope( Layer.mergeAll( - MapleCloudflareSDK.make( - workerTelemetryConfig({ serviceName: "maple-api" }), - ).requestLayer.pipe(Layer.provide(Layer.succeed(MapleCloudflareSDK.WorkerEnvironment, env))), + MapleCloudflareSDK.make(workerTelemetryConfig(apiTelemetryOptions)).requestLayer.pipe( + Layer.provide(Layer.succeed(MapleCloudflareSDK.WorkerEnvironment, env)), + ), Layer.succeed(Cloudflare.WorkerEnvironment, env), ), request, @@ -287,7 +299,13 @@ const event = ( const body = yield* Effect.promise(() => response.text()) yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0))) yield* Scope.close(request, Exit.void) - return { response, body, server: serverSpans(recorded), logs: logBodies(recorded) } + return { + response, + body, + server: serverSpans(recorded), + spans: exportedSpans(recorded), + logs: logBodies(recorded), + } }).pipe(Effect.scoped) describe("the api Worker through alchemy's bridge", () => { @@ -537,6 +555,34 @@ describe("the api Worker through alchemy's bridge", () => { }), ) + it.effect("a backend failure the api answers as a 4xx never exports as an Error span", () => + Effect.forEach( + [ + new McpOAuthProtocolError({ error: "invalid_request", message: "Request body is too large" }), + new TransitionConflictError({ + message: "moved first", + table: "investigations", + id: "inv", + expected: ["diagnosed"], + target: "investigating", + }), + ], + (error) => + Effect.gen(function* () { + const { response, spans } = yield* event("POST", "/register", answeredAs4xx(error)) + assert.strictEqual(response.status, 400) + const inner = Arr.findFirst(spans, (span) => span.name === "Probe.inner") + assert.isTrue(Option.isSome(inner), error._tag) + assert.deepStrictEqual( + Arr.filter(spans, (span) => span.status.code === 2 /* Error */), + [], + error._tag, + ) + }), + { discard: true }, + ), + ) + it.effect("a routed answer is recorded as a server span with its status", () => Effect.gen(function* () { const { response, server } = yield* event("GET", "/nope", notFoundApp) diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 7b641287c2..eb56ac38c1 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -21,6 +21,7 @@ import * as AlchemyTelemetry from "alchemy/Telemetry" import { Effect } from "effect" import { makeVcsSyncIsolateCaches } from "@maple/backend/services/integrations/vcs/vcs-sync-isolate-caches" import { ApiObservabilityLive } from "./http/api-observability" +import { apiTelemetryOptions } from "./telemetry-options" import { resolveWorkerEnv } from "@maple/infra/secret-guard" import { apiConfiguredEnv } from "./resources/env" import { ApiBindingsLive, apiPorts, bindApiClients } from "./worker/bindings" @@ -94,7 +95,7 @@ export default class MapleApi extends Cloudflare.Worker()( IsolateAge.layer, Cloudflare.Workers.CronEventSourceLive, Cloudflare.Queues.EventSourceLive, - WorkerTelemetry({ serviceName: "maple-api" }), + WorkerTelemetry(apiTelemetryOptions), // Read by the bridge's `HttpMiddleware.tracer`; cannot live in the app graph. AlchemyTelemetry.layer(ApiObservabilityLive), ]), diff --git a/packages/backend/src/services/saved-views/SavedViewsService.test.ts b/packages/backend/src/services/saved-views/SavedViewsService.test.ts index 65be4af647..1c60f359e6 100644 --- a/packages/backend/src/services/saved-views/SavedViewsService.test.ts +++ b/packages/backend/src/services/saved-views/SavedViewsService.test.ts @@ -1,5 +1,5 @@ import { afterEach, assert, describe, it } from "@effect/vitest" -import { Array as Arr, Effect, Layer, Order, Schema } from "effect" +import { Array as Arr, Effect, Layer, Order, Result, Schema, String as Str, Tracer } from "effect" import { OrgId, SavedViewId, UserId } from "@maple/domain/http" import { cleanupTestDbs, createTestDb, executeSql, type TestDb } from "@maple/backend/testing/test-pglite" import { SAVED_VIEWS_PER_OWNER_LIMIT, type SavedViewCaller, SavedViewsService } from "./SavedViewsService" @@ -259,6 +259,37 @@ describe("SavedViewsService", () => { ), ) + it.effect("refuses a taken name without a failed database span", () => { + const spans: Array = [] + const tracer = Tracer.make({ + span(options) { + const span = new Tracer.NativeSpan(options) + spans.push(span) + return span + }, + }) + return provide( + Effect.gen(function* () { + const views = yield* SavedViewsService + yield* views.create(ANA, { surface: "logs", name: "Errors", state: errorState }) + const other = yield* views.create(ANA, { surface: "logs", name: "Other", state: errorState }) + yield* Effect.flip(views.create(ANA, { surface: "logs", name: "Errors", state: errorState })) + yield* Effect.flip(views.update(ANA, other.id, { name: "Errors" })) + // Only the service call answering the 409 may fail; a database span failing opens an error issue. + const failures = Arr.filterMap(spans, (span) => + span.status._tag === "Ended" && span.status.exit._tag === "Failure" + ? Result.succeed(span.name) + : Result.failVoid, + ) + assert.isAbove(failures.length, 0) + assert.deepStrictEqual( + Arr.filter(failures, (name) => !Str.startsWith("SavedViewsService.")(name)), + [], + ) + }).pipe(Effect.withTracer(tracer)), + ) + }) + it.effect("stops one person at the per-explorer limit and leaves the other explorers open", () => provide( Effect.gen(function* () { diff --git a/packages/backend/src/services/saved-views/SavedViewsService.ts b/packages/backend/src/services/saved-views/SavedViewsService.ts index 2f814dfef7..9a0673348c 100644 --- a/packages/backend/src/services/saved-views/SavedViewsService.ts +++ b/packages/backend/src/services/saved-views/SavedViewsService.ts @@ -157,13 +157,12 @@ export class SavedViewsService extends Context.Service + new SavedViewNameTakenError({ message: `You already have a view named "${name}"`, name }) const dbExecuteNamed = (name: string) => makeDbExecute(database, "SavedViewsService", (error: DatabaseError) => postgresSqlState(error) === UNIQUE_VIOLATION - ? new SavedViewNameTakenError({ - message: `You already have a view named "${name}"`, - name, - }) + ? nameTaken(name) : toPersistenceError(error), ) @@ -270,6 +269,8 @@ export class SavedViewsService extends Context.Service + db.run( + PG.from(SavedViews) + .select(($) => ({ id: $.id })) + .where(($) => [ + $.orgId.eq(caller.orgId), + $.ownerUserId.eq(caller.userId), + $.surface.eq(existing.surface), + $.name.eq(newName), + ]) + .limit(1), + ), + ) + if (clash.length > 0) return yield* nameTaken(newName) + } const now = yield* Clock.currentTimeMillis const rows = yield* dbExecuteNamed(input.name ?? existing.name)((db) => db.run(