Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions apps/api/src/telemetry-options.ts
Original file line number Diff line number Diff line change
@@ -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<string> = [
"@maple/backend/errors/McpOAuthProtocolError",
"@maple/backend/TransitionConflictError",
]

export const apiTelemetryOptions: WorkerTelemetryOptions = {
serviceName: "maple-api",
anticipatedErrorIdentifiers: API_ANTICIPATED_ERROR_IDENTIFIERS,
}
64 changes: 55 additions & 9 deletions apps/api/src/worker-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down Expand Up @@ -90,18 +93,18 @@ const stubFetch = (recorded: Array<RecordedRequest>): typeof globalThis.fetch =>
return new Response("{}", { status: 200 })
}) as typeof globalThis.fetch

const serverSpans = (recorded: ReadonlyArray<RecordedRequest>): Array<ExportedSpan> => {
const exportedSpans = (recorded: ReadonlyArray<RecordedRequest>): Array<ExportedSpan> => {
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<RecordedRequest>): Array<ExportedSpan> =>
Arr.filter(exportedSpans(recorded), (span) => span.kind === SERVER_KIND)

const logBodies = (recorded: ReadonlyArray<RecordedRequest>): Array<string> => {
const logRequests = Arr.filter(recorded, (request) => Str.endsWith("/v1/logs")(request.url))
const resources = Arr.flatMap(
Expand Down Expand Up @@ -180,6 +183,15 @@ const renderedServerErrorApp: Effect.Effect<HttpEffect> = 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<HttpEffect> =>
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<HttpEffect> = Effect.succeed(Effect.die(new Error("handler exploded")))

Expand Down Expand Up @@ -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,
Expand All @@ -287,7 +299,13 @@ const event = (
const body = yield* Effect.promise(() => response.text())
yield* Effect.promise(() => new Promise<void>((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", () => {
Expand Down Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion apps/api/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -94,7 +95,7 @@ export default class MapleApi extends Cloudflare.Worker<MapleApi>()(
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),
]),
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -259,6 +259,37 @@ describe("SavedViewsService", () => {
),
)

it.effect("refuses a taken name without a failed database span", () => {
const spans: Array<Tracer.NativeSpan> = []
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* () {
Expand Down
31 changes: 24 additions & 7 deletions packages/backend/src/services/saved-views/SavedViewsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,13 +157,12 @@ export class SavedViewsService extends Context.Service<SavedViewsService, SavedV
const database = yield* Database
const dbExecute = makeDbExecute(database, "SavedViewsService", toPersistenceError)
// The owner's names are unique per explorer: a taken one lands on the index.
const nameTaken = (name: string) =>
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),
)

Expand Down Expand Up @@ -270,6 +269,8 @@ export class SavedViewsService extends Context.Service<SavedViewsService, SavedV
createdAt: now,
updatedAt: now,
})
// A taken name is an answer, not a failed statement: no row comes back.
.onConflictDoNothing()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

onConflictDoNothing on saved-view create is not pinned by any test

F1 · Warning · tests

The duplicate-name tests (SavedViewsService.test.ts:250, :252) only assert the 409 tag, which the removed 23505 mapping produced too. Dropping line 273 or the rename pre-check leaves every test green, so nothing catches the failed DatabaseError span and its error issue coming back.

Add a service test that runs the duplicate create and the rename under a tracer and asserts no finished span carries `error.type` `@maple/backend/platform/DatabaseLive` error, like `McpOAuthService.test.ts:360`.
🤖 Prompt to fix with an AI agent
In `packages/backend/src/services/saved-views/SavedViewsService.ts:273`: `onConflictDoNothing` on saved-view create is not pinned by any test.

The duplicate-name tests (`SavedViewsService.test.ts:250`, `:252`) only assert the 409 tag, which the removed 23505 mapping produced too. Dropping line 273 or the rename pre-check leaves every test green, so nothing catches the failed `DatabaseError` span and its error issue coming back.

Suggested fix: Add a service test that runs the duplicate create and the rename under a tracer and asserts no finished span carries `error.type` `@maple/backend/platform/DatabaseLive` error, like `McpOAuthService.test.ts:360`.

Verify the problem exists at that location before changing it, and keep the fix to those lines.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: new test runs the duplicate create and rename under a tracer and asserts only the SavedViewsService call spans fail. Verified it fails when onConflictDoNothing is removed.

.returning(storedColumns),
)
return Option.some(rows[0])
Expand All @@ -283,9 +284,7 @@ export class SavedViewsService extends Context.Service<SavedViewsService, SavedV
})
}
const row = inserted.value
if (row === undefined) {
return yield* new SavedViewPersistenceError({ message: "Insert returned no row" })
}
if (row === undefined) return yield* nameTaken(input.name)
return yield* Option.match(toView(caller, row), {
onNone: unreadable,
onSome: Effect.succeed,
Expand All @@ -312,6 +311,24 @@ export class SavedViewsService extends Context.Service<SavedViewsService, SavedV
onSome: Effect.succeed,
})
}
// Checked first so a taken name never reaches the index as a failed statement.
const newName = input.name
if (newName !== undefined && newName !== existing.name) {
const clash = yield* dbExecute((db) =>
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(
Expand Down
Loading