🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(monitors): tRPC router, RBAC scopes, requireFeatureFlag middleware (#13771)
Mark Salpeteraa1545af7427
diff --git a/packages/shared/src/features/monitors/service/helpers.test.ts b/packages/shared/src/features/monitors/service/helpers.test.tsindex 8988443056..366e656a37 100644--- a/packages/shared/src/features/monitors/service/helpers.test.ts+++ b/packages/shared/src/features/monitors/service/helpers.test.ts@@ -8,7 +8,7 @@ import {import { describe, it, expect } from "vitest";import { z } from "zod";-import { InvalidRequestError } from "../../../errors";+import { InvalidRequestError, LangfuseNotFoundError } from "../../../errors";import { singleFilter } from "../../../interfaces/filters";import {MonitorSeveritySchema,@@ -479,13 +479,13 @@ describe("decimalToPrisma", () => {});describe("errorFromPrisma", () => {- it("maps P2025 (row not found) to InvalidRequestError", () => {+ it("maps P2025 (row not found) to LangfuseNotFoundError", () => {const e = new Prisma.PrismaClientKnownRequestError("not found", {code: "P2025",clientVersion: "test",});const mapped = errorFromPrisma("mon_01", "proj_01", e);- expect(mapped).toBeInstanceOf(InvalidRequestError);+ expect(mapped).toBeInstanceOf(LangfuseNotFoundError);expect(mapped.message).toContain("mon_01");expect(mapped.message).toContain("proj_01");});diff --git a/packages/shared/src/features/monitors/service/helpers.ts b/packages/shared/src/features/monitors/service/helpers.tsindex 7d6794f2fe..de90685e12 100644--- a/packages/shared/src/features/monitors/service/helpers.ts+++ b/packages/shared/src/features/monitors/service/helpers.ts@@ -26,7 +26,7 @@ import {MonitorSchema,} from "../types";-import { type MonitorListOrderBy } from "./types";+import { MonitorNotFoundError, type MonitorListOrderBy } from "./types";/** nullableOrderColumns is the list of sortable columns that are nullable. */export const nullableOrderColumns: ReadonlySet<MonitorListOrderBy> = new Set([@@ -310,18 +310,14 @@ export const monitorFromPrisma = (monitor: PrismaMonitor): Monitor =>export const decimalToPrisma = (n: number | null): Prisma.Decimal | null =>n == null ? null : new Prisma.Decimal(n);-/** errorFromPrisma maps a Prisma client error to a caller-facing Error:- * P2025 (row not found) becomes `InvalidRequestError`; anything else passes- * through unchanged. */+/** errorFromPrisma converts a Prisma row-not-found error to MonitorNotFoundError. */export const errorFromPrisma = (id: string,projectId: string,e: unknown,): Error => {if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2025") {- return new InvalidRequestError(- `Monitor ${id} not found in project ${projectId}`,- );+ return new MonitorNotFoundError(id, projectId);}return e as Error;};diff --git a/packages/shared/src/features/monitors/service/service.ts b/packages/shared/src/features/monitors/service/service.tsindex 4f81ffb3cb..a4da66b0e2 100644--- a/packages/shared/src/features/monitors/service/service.ts+++ b/packages/shared/src/features/monitors/service/service.ts@@ -1,4 +1,4 @@-/** service.ts contains the MonitorService */+/** service.ts contains the MonitorService. */import { Prisma, prisma } from "../../../db";import { type Monitor } from "../types";@@ -18,9 +18,13 @@ import {windowToMs,} from "./helpers";import {- type CreateMonitorInput,- type MonitorListInput,- type UpdateMonitorInput,+ type CreateMonitor,+ type DeleteMonitor,+ type GetMonitorById,+ type ListMonitors,+ MonitorNotFoundError,+ type SessionContext,+ type UpdateMonitor,} from "./types";/**@@ -32,10 +36,15 @@ import {** Validation is handled directly by the zod schema found in `service/types`.* Services assume the inputs have been parsed and validated by tRPC or other- * API adapters.+ * API adapters. Project membership and scope checks (RBAC) are enforced by+ * the caller (eg. tRPC middleware); this service trusts the supplied+ * `SessionContext.userId` and `input.projectId`.*/export class MonitorService {- public static async create(input: CreateMonitorInput): Promise<Monitor> {+ public static async create(+ session: SessionContext,+ input: CreateMonitor,+ ): Promise<Monitor> {const filters = sortFiltersCanonically(input.filters);const windowMs = windowToMs(input.window);const cadenceMs = calculateCadence(windowMs);@@ -54,8 +63,8 @@ export class MonitorService {const created = await prisma.monitor.create({data: {projectId: input.projectId,- createdBy: input.createdBy,- updatedBy: input.createdBy,+ createdBy: session.userId,+ updatedBy: session.userId,view: viewToPrisma(input.view),filters,metric: input.metric,@@ -76,7 +85,10 @@ export class MonitorService {return monitorFromPrisma(created);}- public static async update(input: UpdateMonitorInput): Promise<Monitor> {+ public static async update(+ session: SessionContext,+ input: UpdateMonitor,+ ): Promise<Monitor> {const filters = sortFiltersCanonically(input.filters);const windowMs = windowToMs(input.window);const cadenceMs = calculateCadence(windowMs);@@ -98,7 +110,7 @@ export class MonitorService {const updated = await prisma.monitor.update({where: { id: input.id, projectId: input.projectId },data: {- updatedBy: input.updatedBy,+ updatedBy: session.userId,view: viewToPrisma(input.view),filters,metric: input.metric,@@ -123,17 +135,21 @@ export class MonitorService {}public static async getById(- monitorId: string,- projectId: string,- ): Promise<Monitor | null> {+ _session: SessionContext,+ input: GetMonitorById,+ ): Promise<Monitor> {const monitor = await prisma.monitor.findFirst({- where: { id: monitorId, projectId },+ where: { id: input.id, projectId: input.projectId },});- return monitor ? monitorFromPrisma(monitor) : null;+ if (!monitor) {+ throw new MonitorNotFoundError(input.id, input.projectId);+ }+ return monitorFromPrisma(monitor);}public static async list(- input: MonitorListInput,+ _session: SessionContext,+ input: ListMonitors,): Promise<{ monitors: Monitor[]; totalCount: number }> {const skip =input.page && input.limit ? (input.page - 1) * input.limit : undefined;@@ -159,15 +175,15 @@ export class MonitorService {}public static async delete(- monitorId: string,- projectId: string,+ _session: SessionContext,+ input: DeleteMonitor,): Promise<void> {try {await prisma.monitor.delete({- where: { id: monitorId, projectId },+ where: { id: input.id, projectId: input.projectId },});} catch (e) {- throw errorFromPrisma(monitorId, projectId, e);+ throw errorFromPrisma(input.id, input.projectId, e);}}}diff --git a/packages/shared/src/features/monitors/service/types.test.ts b/packages/shared/src/features/monitors/service/types.test.tsindex 76fef1e870..11324c51dd 100644--- a/packages/shared/src/features/monitors/service/types.test.ts+++ b/packages/shared/src/features/monitors/service/types.test.ts@@ -1,16 +1,15 @@import { describe, it, expect } from "vitest";import {- CreateMonitorInputSchema,- MonitorListInputSchema,- UpdateMonitorInputSchema,+ CreateMonitorSchema,+ ListMonitorsSchema,+ UpdateMonitorSchema,} from "./types";-// Minimal valid `CreateMonitorInputSchema` payload. Tests override one field+// Minimal valid `CreateMonitorSchema` payload. Tests override one field// at a time to exercise the refinements wired onto the input schema.const validCreateInput = {projectId: "proj_01",- createdBy: null,view: "observations" as const,filters: [],@@ -31,18 +30,15 @@ const validCreateInput = {const validUpdateInput = {...validCreateInput,id: "mon_01",- updatedBy: null,};-describe("CreateMonitorInputSchema", () => {+describe("CreateMonitorSchema", () => {it("parses a minimal valid input", () => {- expect(CreateMonitorInputSchema.safeParse(validCreateInput).success).toBe(- true,- );+ expect(CreateMonitorSchema.safeParse(validCreateInput).success).toBe(true);});it("rejects warning >= alert for gt (validateThresholdOrder is wired)", () => {- const result = CreateMonitorInputSchema.safeParse({+ const result = CreateMonitorSchema.safeParse({...validCreateInput,thresholdOperator: "gt" as const,alertThreshold: 100,@@ -54,7 +50,7 @@ describe("CreateMonitorInputSchema", () => {it.each(["gt", "gte"] as const)("%s emits a `>` strict-ordering message (not the operator name)",(op) => {- const result = CreateMonitorInputSchema.safeParse({+ const result = CreateMonitorSchema.safeParse({...validCreateInput,thresholdOperator: op,alertThreshold: 100,@@ -74,7 +70,7 @@ describe("CreateMonitorInputSchema", () => {it.each(["lt", "lte"] as const)("%s emits a `<` strict-ordering message (not the operator name)",(op) => {- const result = CreateMonitorInputSchema.safeParse({+ const result = CreateMonitorSchema.safeParse({...validCreateInput,thresholdOperator: op,alertThreshold: 100,@@ -90,7 +86,7 @@ describe("CreateMonitorInputSchema", () => {);it("rejects an unknown measure (validateQuery is wired)", () => {- const result = CreateMonitorInputSchema.safeParse({+ const result = CreateMonitorSchema.safeParse({...validCreateInput,metric: { measure: "bogus_measure", aggregation: "count" as const },});@@ -98,7 +94,7 @@ describe("CreateMonitorInputSchema", () => {});it("rejects status `error-bad-query` on create (scheduler-owned)", () => {- const result = CreateMonitorInputSchema.safeParse({+ const result = CreateMonitorSchema.safeParse({...validCreateInput,status: "error-bad-query",});@@ -106,15 +102,13 @@ describe("CreateMonitorInputSchema", () => {});});-describe("UpdateMonitorInputSchema", () => {+describe("UpdateMonitorSchema", () => {it("parses a minimal valid input", () => {- expect(UpdateMonitorInputSchema.safeParse(validUpdateInput).success).toBe(- true,- );+ expect(UpdateMonitorSchema.safeParse(validUpdateInput).success).toBe(true);});it("rejects warning <= alert for lt (validateThresholdOrder is wired)", () => {- const result = UpdateMonitorInputSchema.safeParse({+ const result = UpdateMonitorSchema.safeParse({...validUpdateInput,thresholdOperator: "lt" as const,alertThreshold: 100,@@ -124,7 +118,7 @@ describe("UpdateMonitorInputSchema", () => {});it("rejects an unknown filter column (validateQuery is wired)", () => {- const result = UpdateMonitorInputSchema.safeParse({+ const result = UpdateMonitorSchema.safeParse({...validUpdateInput,filters: [{@@ -142,7 +136,7 @@ describe("UpdateMonitorInputSchema", () => {// `error-bad-query` is flipped by the scheduler when a monitor's query// fails to evaluate. Callers must not be able to set or clear it// directly — narrowing the input DTO to active/paused enforces that.- const result = UpdateMonitorInputSchema.safeParse({+ const result = UpdateMonitorSchema.safeParse({...validUpdateInput,status: "error-bad-query",});@@ -150,9 +144,9 @@ describe("UpdateMonitorInputSchema", () => {});});-describe("MonitorListInputSchema", () => {+describe("ListMonitorsSchema", () => {it("parses a minimal input with defaults filled in", () => {- const result = MonitorListInputSchema.safeParse({+ const result = ListMonitorsSchema.safeParse({projectId: "proj_01",orderBy: null,});@@ -164,7 +158,7 @@ describe("MonitorListInputSchema", () => {});it("accepts an orderBy + explicit pagination", () => {- const result = MonitorListInputSchema.safeParse({+ const result = ListMonitorsSchema.safeParse({projectId: "proj_01",orderBy: { column: "name", order: "ASC" },page: 2,@@ -182,7 +176,7 @@ describe("MonitorListInputSchema", () => {"createdAt","updatedAt",] as const)("accepts %s as orderBy.column", (column) => {- const result = MonitorListInputSchema.safeParse({+ const result = ListMonitorsSchema.safeParse({projectId: "proj_01",orderBy: { column, order: "DESC" },});@@ -190,7 +184,7 @@ describe("MonitorListInputSchema", () => {});it("rejects an unknown orderBy.column (Prisma would otherwise raise a 500)", () => {- const result = MonitorListInputSchema.safeParse({+ const result = ListMonitorsSchema.safeParse({projectId: "proj_01",orderBy: { column: "bogus", order: "DESC" },});@@ -198,7 +192,7 @@ describe("MonitorListInputSchema", () => {});it("rejects a missing projectId", () => {- const result = MonitorListInputSchema.safeParse({ orderBy: null });+ const result = ListMonitorsSchema.safeParse({ orderBy: null });expect(result.success).toBe(false);});});diff --git a/packages/shared/src/features/monitors/service/types.ts b/packages/shared/src/features/monitors/service/types.tsindex 2b8ced7feb..fc4b5ca7f4 100644--- a/packages/shared/src/features/monitors/service/types.ts+++ b/packages/shared/src/features/monitors/service/types.ts@@ -1,7 +1,7 @@-/** service/types.ts contains the DTO schemas and types for the MonitorService- * — the input contracts for `create`, `update`, and `list`. */+/** service/types.ts contains the DTOs, schemas, and errors for the MonitorService. */import { z } from "zod";+import { LangfuseNotFoundError } from "../../../errors";import { paginationZod } from "../../../utils/zod";import {@@ -11,13 +11,25 @@ import {validateThresholdOrder,} from "../types";-/**- * omitOnWrite are the Monitor fields the service generates or owns. They are- * omitted from every write DTO.- */+/** MonitorNotFoundError is thrown when a monitor row doesn't exist in the project. */+export class MonitorNotFoundError extends LangfuseNotFoundError {+ constructor(monitorId: string, projectId: string) {+ super(`Monitor ${monitorId} not found in project ${projectId}`);+ }+}++/** SessionContext identifies the authenticated caller. */+export const SessionContextSchema = z.object({+ userId: z.string(),+});+export type SessionContext = z.infer<typeof SessionContextSchema>;++/** omitOnWrite are the Monitor fields the service owns and clients can't set. */const omitOnWrite = {createdAt: true,updatedAt: true,+ createdBy: true,+ updatedBy: true,severity: true,severityChangedAt: true,alertedAt: true,@@ -26,38 +38,38 @@ const omitOnWrite = {lastCompletedRunAt: true,} as const;-/**- * CreateMonitorInputSchema is the input contract for `MonitorService.create`.- * The caller supplies `createdBy`; the service mirrors it onto `updatedBy`.- * `status` is narrowed to the caller-settable subset (`error-bad-query` is- * scheduler-owned).- */-export const CreateMonitorInputSchema = MonitorSchema.omit({+/** CreateMonitorSchema is the input for MonitorService.create. */+export const CreateMonitorSchema = MonitorSchema.omit({...omitOnWrite,id: true,- updatedBy: true,}).extend({ status: MonitorWriteStatusSchema.default("active") }).superRefine(validateQuery).superRefine(validateThresholdOrder);-export type CreateMonitorInput = z.infer<typeof CreateMonitorInputSchema>;+export type CreateMonitor = z.infer<typeof CreateMonitorSchema>;-/**- * UpdateMonitorInputSchema is the input contract for `MonitorService.update`.- * The caller supplies `id` (target row) and `updatedBy`; `createdBy` is- * preserved from the existing row. `status` is narrowed to the- * caller-settable subset.- */-export const UpdateMonitorInputSchema = MonitorSchema.omit({- ...omitOnWrite,- createdBy: true,-})+/** UpdateMonitorSchema is the input for MonitorService.update. */+export const UpdateMonitorSchema = MonitorSchema.omit(omitOnWrite).extend({ status: MonitorWriteStatusSchema.default("active") }).superRefine(validateQuery).superRefine(validateThresholdOrder);-export type UpdateMonitorInput = z.infer<typeof UpdateMonitorInputSchema>;+export type UpdateMonitor = z.infer<typeof UpdateMonitorSchema>;++/** GetMonitorByIdSchema is the input for MonitorService.getById. */+export const GetMonitorByIdSchema = z.object({+ projectId: z.string(),+ id: z.string(),+});+export type GetMonitorById = z.infer<typeof GetMonitorByIdSchema>;++/** DeleteMonitorSchema is the input for MonitorService.delete. */+export const DeleteMonitorSchema = z.object({+ projectId: z.string(),+ id: z.string(),+});+export type DeleteMonitor = z.infer<typeof DeleteMonitorSchema>;-/** MonitorListOrderBySchema is the list of fields that we can sort the Monitor collection by. */+/** MonitorListOrderBySchema is the set of columns MonitorService.list can sort by. */export const MonitorListOrderBySchema = z.enum(["name","status",@@ -69,8 +81,8 @@ export const MonitorListOrderBySchema = z.enum([]);export type MonitorListOrderBy = z.infer<typeof MonitorListOrderBySchema>;-/** MonitorListInputSchema is the input contract for `MonitorService.list`. */-export const MonitorListInputSchema = z.object({+/** ListMonitorsSchema is the input for MonitorService.list. */+export const ListMonitorsSchema = z.object({projectId: z.string(),orderBy: z.object({@@ -80,4 +92,4 @@ export const MonitorListInputSchema = z.object({.nullable(),...paginationZod,});-export type MonitorListInput = z.infer<typeof MonitorListInputSchema>;+export type ListMonitors = z.infer<typeof ListMonitorsSchema>;diff --git a/web/AGENTS.md b/web/AGENTS.mdindex cb3d7fb927..c7f37e8ae1 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -157,6 +157,12 @@ signoff of user-visible changes.4. If API contract changed, update Fern source (`../fern/apis/**`) and regenerateoutputs (do not hand-edit `../generated/**`).+### Error handling (tRPC + REST)++1. Throw `BaseError` subclasses (eg `LangfuseNotFoundError`) from handlers and services.+2. Let `BaseError`s bubble up to the tRPC and REST middlewares (eg. don't `try/catch` and rethrow in to `TRPCError` the handler)+3. Extend the `BaseError` or its subclasses in [`packages/shared/src/errors/`](../packages/shared/src/errors/) as needed.+### Add frontend feature1. Prefer `src/features/<feature>/*` for feature-local code.diff --git a/web/src/__tests__/server/monitorService.servertest.ts b/web/src/__tests__/server/monitorService.servertest.tsindex b913f98764..81eae3078f 100644--- a/web/src/__tests__/server/monitorService.servertest.ts+++ b/web/src/__tests__/server/monitorService.servertest.ts@@ -2,36 +2,13 @@ import { v4 as uuidv4 } from "uuid";import {createOrgProjectAndApiKey,MonitorService,+ type SessionContext,} from "@langfuse/shared/src/server";import { prisma } from "@langfuse/shared/src/db";-import { InvalidRequestError } from "@langfuse/shared";+import { LangfuseNotFoundError } from "@langfuse/shared";-const baseCreateInput = (- projectId: string,- createdBy: string | null = null,-) => ({+const baseMonitorInput = (projectId: string) => ({projectId,- createdBy,- view: "observations" as const,- filters: [],- metric: { measure: "count", aggregation: "count" as const },- window: "5m" as const,- thresholdOperator: "gt" as const,- alertThreshold: 100,- warningThreshold: null,- noData: { mode: "SILENT" as const },- renotify: { mode: "OFF" as const },- status: "active" as const,- name: "High error rate",- tags: [],-});--const baseUpdateInput = (- projectId: string,- updatedBy: string | null = null,-) => ({- projectId,- updatedBy,view: "observations" as const,filters: [],metric: { measure: "count", aggregation: "count" as const },@@ -48,28 +25,28 @@ const baseUpdateInput = (describe("MonitorService (integration)", () => {let projectId: string;- let creatorUserId: string;- let editorUserId: string;+ let creator: SessionContext;+ let editor: SessionContext;beforeAll(async () => {const org = await createOrgProjectAndApiKey();projectId = org.projectId;- const creator = await prisma.user.create({+ const creatorUser = await prisma.user.create({data: {id: uuidv4(),email: `monitor-creator-${uuidv4().substring(0, 8)}@test.com`,name: "Creator",},});- const editor = await prisma.user.create({+ const editorUser = await prisma.user.create({data: {id: uuidv4(),email: `monitor-editor-${uuidv4().substring(0, 8)}@test.com`,name: "Editor",},});- creatorUserId = creator.id;- editorUserId = editor.id;+ creator = { userId: creatorUser.id };+ editor = { userId: editorUser.id };});afterEach(async () => {@@ -78,7 +55,10 @@ describe("MonitorService (integration)", () => {describe("create", () => {it("creates a monitor and persists derived fields", async () => {- const created = await MonitorService.create(baseCreateInput(projectId));+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );const row = await prisma.monitor.findUnique({where: { id: created.id },@@ -90,6 +70,8 @@ describe("MonitorService (integration)", () => {expect(row!.schedulerBatchId).toBeGreaterThan(0n);expect(row!.nextRunAt.getTime()).toBeLessThanOrEqual(Date.now());expect(row!.severity).toBe("UNKNOWN");+ expect(row!.createdBy).toBe(creator.userId);+ expect(row!.updatedBy).toBe(creator.userId);});it("canonicalizes filter order so permutations share the same schedulerBatchId", async () => {@@ -106,12 +88,12 @@ describe("MonitorService (integration)", () => {type: "string" as const,};- const first = await MonitorService.create({- ...baseCreateInput(projectId),+ const first = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),filters: [filterA, filterB],});- const second = await MonitorService.create({- ...baseCreateInput(projectId),+ const second = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),filters: [filterB, filterA],});@@ -126,8 +108,14 @@ describe("MonitorService (integration)", () => {const otherOrg = await createOrgProjectAndApiKey();const otherProject = otherOrg.projectId;- const here = await MonitorService.create(baseCreateInput(projectId));- const there = await MonitorService.create(baseCreateInput(otherProject));+ const here = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ const there = await MonitorService.create(+ creator,+ baseMonitorInput(otherProject),+ );const rows = await prisma.monitor.findMany({where: { id: { in: [here.id, there.id] } },@@ -143,7 +131,8 @@ describe("MonitorService (integration)", () => {describe("update", () => {it("updates user-editable fields and preserves worker-owned lifecycle state", async () => {const created = await MonitorService.create(- baseCreateInput(projectId, creatorUserId),+ creator,+ baseMonitorInput(projectId),);// Simulate the worker writing lifecycle state between create and update.@@ -157,8 +146,8 @@ describe("MonitorService (integration)", () => {},});- const updated = await MonitorService.update({- ...baseUpdateInput(projectId, editorUserId),+ const updated = await MonitorService.update(editor, {+ ...baseMonitorInput(projectId),id: created.id,name: "Renamed",});@@ -172,41 +161,54 @@ describe("MonitorService (integration)", () => {const row = await prisma.monitor.findUnique({where: { id: created.id },});- expect(row!.createdBy).toBe(creatorUserId);- expect(row!.updatedBy).toBe(editorUserId);+ expect(row!.createdBy).toBe(creator.userId);+ expect(row!.updatedBy).toBe(editor.userId);});- it("throws InvalidRequestError when the monitor does not exist", async () => {+ it("throws LangfuseNotFoundError when the monitor does not exist", async () => {await expect(- MonitorService.update({- ...baseUpdateInput(projectId),+ MonitorService.update(editor, {+ ...baseMonitorInput(projectId),id: "mon_missing",}),- ).rejects.toBeInstanceOf(InvalidRequestError);+ ).rejects.toBeInstanceOf(LangfuseNotFoundError);});});describe("getById / list / delete", () => {it("returns the monitor by id within the project", async () => {- const created = await MonitorService.create(baseCreateInput(projectId));- const fetched = await MonitorService.getById(created.id, projectId);- expect(fetched?.id).toBe(created.id);+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ const fetched = await MonitorService.getById(creator, {+ projectId,+ id: created.id,+ });+ expect(fetched.id).toBe(created.id);});- it("returns null when fetching from a different project", async () => {- const created = await MonitorService.create(baseCreateInput(projectId));- const fetched = await MonitorService.getById(created.id, "other_project");- expect(fetched).toBeNull();+ it("throws LangfuseNotFoundError when fetching from a different project", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ await expect(+ MonitorService.getById(creator, {+ projectId: "other_project",+ id: created.id,+ }),+ ).rejects.toBeInstanceOf(LangfuseNotFoundError);});it("paginates list results", async () => {for (let i = 0; i < 3; i++) {- await MonitorService.create({- ...baseCreateInput(projectId),+ await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),name: `M${i}`,});}- const page = await MonitorService.list({+ const page = await MonitorService.list(creator, {projectId,orderBy: null,limit: 2,@@ -216,11 +218,15 @@ describe("MonitorService (integration)", () => {expect(page.monitors).toHaveLength(2);});- it("deletes a monitor", async () => {- const created = await MonitorService.create(baseCreateInput(projectId));- await MonitorService.delete(created.id, projectId);- const fetched = await MonitorService.getById(created.id, projectId);- expect(fetched).toBeNull();+ it("deletes a monitor and getById then throws LangfuseNotFoundError", async () => {+ const created = await MonitorService.create(+ creator,+ baseMonitorInput(projectId),+ );+ await MonitorService.delete(creator, { projectId, id: created.id });+ await expect(+ MonitorService.getById(creator, { projectId, id: created.id }),+ ).rejects.toBeInstanceOf(LangfuseNotFoundError);});it.each(["name", "status", "severity", "createdAt", "updatedAt"] as const)(@@ -230,8 +236,8 @@ describe("MonitorService (integration)", () => {// non-nullable columns. If it doesn't, this throws// PrismaClientValidationError at runtime and we need to gate `nulls`// on the nullable subset instead.- await MonitorService.create(baseCreateInput(projectId));- const result = await MonitorService.list({+ await MonitorService.create(creator, baseMonitorInput(projectId));+ const result = await MonitorService.list(creator, {projectId,orderBy: { column, order: "ASC" },page: 1,@@ -248,16 +254,16 @@ describe("MonitorService (integration)", () => {column === "alertedAt" ? "alertedAt" : "severityChangedAt";// Three monitors: one never-touched (NULL), one older, one newer.- const neverTouched = await MonitorService.create({- ...baseCreateInput(projectId),+ const neverTouched = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),name: "never",});- const older = await MonitorService.create({- ...baseCreateInput(projectId),+ const older = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),name: "older",});- const newer = await MonitorService.create({- ...baseCreateInput(projectId),+ const newer = await MonitorService.create(creator, {+ ...baseMonitorInput(projectId),name: "newer",});@@ -270,7 +276,7 @@ describe("MonitorService (integration)", () => {data: { [dbColumn]: new Date("2026-06-01T00:00:00.000Z") },});- const desc = await MonitorService.list({+ const desc = await MonitorService.list(creator, {projectId,orderBy: { column, order: "DESC" },page: 1,@@ -282,7 +288,7 @@ describe("MonitorService (integration)", () => {neverTouched.id,]);- const asc = await MonitorService.list({+ const asc = await MonitorService.list(creator, {projectId,orderBy: { column, order: "ASC" },page: 1,diff --git a/web/src/__tests__/server/monitors.servertest.ts b/web/src/__tests__/server/monitors.servertest.tsnew file mode 100644index 0000000000..26f834ec7b--- /dev/null+++ b/web/src/__tests__/server/monitors.servertest.ts@@ -0,0 +1,298 @@+import { appRouter } from "@/src/server/api/root";+import { createInnerTRPCContext } from "@/src/server/api/trpc";+import { prisma } from "@langfuse/shared/src/db";+import { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import type { Session } from "next-auth";+import { v4 } from "uuid";+import { type Role } from "@langfuse/shared/src/db";++type RoleName = keyof typeof Role;++const orgIds: string[] = [];++const buildSession = (params: {+ userId: string;+ orgId: string;+ orgName: string;+ projectId: string;+ projectName: string;+ projectRole: RoleName;+ monitorsFlag?: boolean;+ admin?: boolean;+ enableExperimentalFeatures?: boolean;+}): Session => ({+ expires: "1",+ user: {+ id: params.userId,+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: params.orgId,+ name: params.orgName,+ role: "OWNER",+ plan: "cloud:hobby",+ cloudConfig: undefined,+ metadata: {},+ projects: [+ {+ id: params.projectId,+ role: params.projectRole,+ retentionDays: 30,+ deletedAt: null,+ name: params.projectName,+ metadata: {},+ },+ ],+ },+ ],+ featureFlags: {+ inAppAgent: false,+ templateFlag: false,+ excludeClickhouseRead: false,+ v4BetaToggleVisible: false,+ observationEvals: false,+ experimentsV4Enabled: false,+ monitors: params.monitorsFlag ?? true,+ },+ admin: params.admin ?? false,+ },+ environment: {+ enableExperimentalFeatures: params.enableExperimentalFeatures ?? false,+ selfHostedInstancePlan: "cloud:hobby",+ },+});++const prepare = async (overrides?: {+ projectRole?: RoleName;+ monitorsFlag?: boolean;+ admin?: boolean;+ enableExperimentalFeatures?: boolean;+}) => {+ const { project, org } = await createOrgProjectAndApiKey();+ orgIds.push(org.id);+ const user = await prisma.user.create({+ data: {+ id: v4(),+ email: `monitor-user-${v4().substring(0, 8)}@test.com`,+ name: "Monitor User",+ },+ });++ const session = buildSession({+ userId: user.id,+ orgId: org.id,+ orgName: org.name,+ projectId: project.id,+ projectName: project.name,+ projectRole: overrides?.projectRole ?? "ADMIN",+ monitorsFlag: overrides?.monitorsFlag,+ admin: overrides?.admin,+ enableExperimentalFeatures: overrides?.enableExperimentalFeatures,+ });++ const ctx = createInnerTRPCContext({ session, headers: {} });+ const caller = appRouter.createCaller({ ...ctx, prisma });++ return { project, org, session, caller };+};++const validMonitorInput = (projectId: string) => ({+ projectId,+ view: "observations" as const,+ filters: [],+ metric: { measure: "count", aggregation: "count" as const },+ window: "5m" as const,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },+ status: "active" as const,+ name: "High error rate",+ tags: [],+});++describe("monitors trpc", () => {+ afterAll(async () => {+ if (orgIds.length > 0) {+ await prisma.organization.deleteMany({ where: { id: { in: orgIds } } });+ }+ });++ describe("create / get / all", () => {+ it("creates a monitor and round-trips through get + all", async () => {+ const { project, caller } = await prepare();++ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ expect(created.id).toBeDefined();+ expect(created.name).toBe("High error rate");+ expect(created.projectId).toBe(project.id);++ const fetched = await caller.monitors.get({+ projectId: project.id,+ id: created.id,+ });+ expect(fetched.id).toBe(created.id);++ const list = await caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ });+ expect(list.totalCount).toBe(1);+ expect(list.monitors.map((m) => m.id)).toContain(created.id);+ });++ it("returns ERROR_BAD_QUERY monitors verbatim (scheduler-owned status survives a read)", async () => {+ const { project, caller } = await prepare();++ // Simulate the worker flagging a previously-valid monitor as bad after+ // its underlying measure was removed. The API can't write this status+ // directly, but reads must surface it so the UI can show the failure.+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ await prisma.monitor.update({+ where: { id: created.id },+ data: { status: "ERROR_BAD_QUERY" },+ });++ const fetched = await caller.monitors.get({+ projectId: project.id,+ id: created.id,+ });+ expect(fetched.status).toBe("error-bad-query");+ });+ });++ describe("RBAC", () => {+ it("rejects monitors.create from VIEWER role with FORBIDDEN", async () => {+ const { project, caller } = await prepare({ projectRole: "VIEWER" });++ await expect(+ caller.monitors.create(validMonitorInput(project.id)),+ ).rejects.toThrow(/access/i);+ });++ it("allows monitors.create from MEMBER role (monitors:CUD)", async () => {+ const { project, caller } = await prepare({ projectRole: "MEMBER" });++ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ expect(created.id).toBeDefined();+ });++ it("allows monitors.all from VIEWER role (read-only scope)", async () => {+ const { project, caller } = await prepare({ projectRole: "VIEWER" });++ const list = await caller.monitors.all({+ projectId: project.id,+ orderBy: null,+ });+ expect(list.totalCount).toBe(0);+ });+ });++ describe("validation", () => {+ it("rejects warning >= alert ordering for gt operator", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.monitors.create({+ ...validMonitorInput(project.id),+ thresholdOperator: "gt",+ alertThreshold: 100,+ warningThreshold: 100,+ }),+ ).rejects.toThrow();+ });++ it("rejects an unknown measure", async () => {+ const { project, caller } = await prepare();++ await expect(+ caller.monitors.create({+ ...validMonitorInput(project.id),+ metric: { measure: "bogus_measure", aggregation: "count" },+ }),+ ).rejects.toThrow();+ });+ });++ describe("feature flag gating", () => {+ it("rejects monitors.create when the flag is off, user is not admin, experimental is off", async () => {+ const { project, caller } = await prepare({ monitorsFlag: false });+ await expect(+ caller.monitors.create(validMonitorInput(project.id)),+ ).rejects.toThrow(/monitors/i);+ });++ it("allows monitors.create when admin (overrides flag)", async () => {+ const { project, caller } = await prepare({+ monitorsFlag: false,+ admin: true,+ });+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ expect(created.id).toBeDefined();+ });++ it("allows monitors.create when enableExperimentalFeatures is true (overrides flag)", async () => {+ const { project, caller } = await prepare({+ monitorsFlag: false,+ enableExperimentalFeatures: true,+ });+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );+ expect(created.id).toBeDefined();+ });++ it("rejects monitors.all when the flag is off", async () => {+ const { project, caller } = await prepare({ monitorsFlag: false });+ await expect(+ caller.monitors.all({ projectId: project.id, orderBy: null }),+ ).rejects.toThrow(/monitors/i);+ });+ });++ describe("update / delete", () => {+ it("updates a monitor and surfaces NOT_FOUND on missing id", async () => {+ const { project, caller } = await prepare();+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );++ const updated = await caller.monitors.update({+ ...validMonitorInput(project.id),+ id: created.id,+ name: "Renamed monitor",+ });+ expect(updated.name).toBe("Renamed monitor");++ await expect(+ caller.monitors.update({+ ...validMonitorInput(project.id),+ id: `mon_missing_${v4()}`,+ }),+ ).rejects.toThrow(/not found/i);+ });++ it("deletes a monitor and 404s on subsequent get", async () => {+ const { project, caller } = await prepare();+ const created = await caller.monitors.create(+ validMonitorInput(project.id),+ );++ await caller.monitors.delete({ projectId: project.id, id: created.id });++ await expect(+ caller.monitors.get({ projectId: project.id, id: created.id }),+ ).rejects.toThrow(/not found/i);+ });+ });+});diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex d7a6d7280c..af4e940658 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -5,4 +5,5 @@ export const availableFlags = ["v4BetaToggleVisible","observationEvals","experimentsV4Enabled",+ "monitors",] as const;diff --git a/web/src/features/rbac/constants/projectAccessRights.ts b/web/src/features/rbac/constants/projectAccessRights.tsindex 3d432b61a9..5cc4cd8971 100644--- a/web/src/features/rbac/constants/projectAccessRights.ts+++ b/web/src/features/rbac/constants/projectAccessRights.ts@@ -77,6 +77,9 @@ export const projectScopes = ["automations:CUD","automations:read",++ "monitors:read",+ "monitors:CUD",] as const;// type string of all Resource:Action, e.g. "members:read"@@ -136,6 +139,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"TableViewPresets:read","automations:CUD","automations:read",+ "monitors:read",+ "monitors:CUD",],ADMIN: ["project:read",@@ -189,6 +194,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"TableViewPresets:read","automations:CUD","automations:read",+ "monitors:read",+ "monitors:CUD",],MEMBER: ["project:read",@@ -229,6 +236,8 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"TableViewPresets:CUD","TableViewPresets:read","automations:read",+ "monitors:read",+ "monitors:CUD",],VIEWER: ["project:read",@@ -247,6 +256,7 @@ export const projectRoleAccessRights: Record<Role, ProjectScope[]> = {"dashboards:read","TableViewPresets:read","automations:read",+ "monitors:read",],NONE: [],};diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex b4e5964d95..310df0fd72 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -48,6 +48,7 @@ import { cloudStatusRouter } from "@/src/features/cloud-status-notification/servimport { dashboardWidgetRouter } from "./routers/dashboardWidgets";import { TableViewPresetsRouter } from "@/src/server/api/routers/tableViewPresets";import { automationsRouter } from "@/src/features/automations/server/router";+import { monitorsRouter } from "@/src/server/api/routers/monitors";import { defaultEvalModelRouter } from "@/src/features/evals/server/defaultEvalModelRouter";import { slackRouter } from "@/src/features/slack/server/router";import { plainRouter } from "@/src/features/support-chat/trpc/plainRouter";@@ -113,6 +114,7 @@ export const appRouter = createTRPCRouter({dashboardWidgets: dashboardWidgetRouter,TableViewPresets: TableViewPresetsRouter,automations: automationsRouter,+ monitors: monitorsRouter,slack: slackRouter,plainRouter: plainRouter,surveys: surveysRouter,diff --git a/web/src/server/api/routers/monitors.ts b/web/src/server/api/routers/monitors.tsnew file mode 100644index 0000000000..fd0bd994c6--- /dev/null+++ b/web/src/server/api/routers/monitors.ts@@ -0,0 +1,83 @@+import {+ createTRPCRouter,+ protectedProjectProcedure,+ requireFeatureFlag,+} from "@/src/server/api/trpc";+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";+import {+ CreateMonitorSchema,+ DeleteMonitorSchema,+ GetMonitorByIdSchema,+ ListMonitorsSchema,+ MonitorService,+ type SessionContext,+ UpdateMonitorSchema,+} from "@langfuse/shared/src/server";++/** monitorsProcedure protects every monitors route behind the `monitors` flag. */+const monitorsProcedure = protectedProjectProcedure.use(+ requireFeatureFlag("monitors"),+);++/** sessionContextFromCtx adapts a tRPC session into a MonitorService SessionContext. */+const sessionContextFromCtx = (ctx: {+ session: { user: { id: string } };+}): SessionContext => ({ userId: ctx.session.user.id });++export const monitorsRouter = createTRPCRouter({+ create: monitorsProcedure+ .input(CreateMonitorSchema)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:CUD",+ });+ return MonitorService.create(sessionContextFromCtx(ctx), input);+ }),++ update: monitorsProcedure+ .input(UpdateMonitorSchema)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:CUD",+ });+ return MonitorService.update(sessionContextFromCtx(ctx), input);+ }),++ delete: monitorsProcedure+ .input(DeleteMonitorSchema)+ .mutation(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:CUD",+ });+ await MonitorService.delete(sessionContextFromCtx(ctx), input);+ return { success: true as const };+ }),++ get: monitorsProcedure+ .input(GetMonitorByIdSchema)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:read",+ });+ return MonitorService.getById(sessionContextFromCtx(ctx), input);+ }),++ all: monitorsProcedure+ .input(ListMonitorsSchema)+ .query(async ({ ctx, input }) => {+ throwIfNoProjectAccess({+ session: ctx.session,+ projectId: input.projectId,+ scope: "monitors:read",+ });+ return MonitorService.list(sessionContextFromCtx(ctx), input);+ }),+});diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.tsindex 8e475078cd..f4819f32de 100644--- a/web/src/server/api/trpc.ts+++ b/web/src/server/api/trpc.ts@@ -94,6 +94,7 @@ import {import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";import { env } from "@/src/env.mjs";import { BaseError, parseIO } from "@langfuse/shared";+import { type Flag } from "@/src/features/feature-flags/types";setUpSuperjson();@@ -368,6 +369,23 @@ export const protectedProjectProcedure = withOtelTracingProcedure.use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);+/** requireFeatureFlag gates a procedure behind a server-side feature flag. */+export const requireFeatureFlag = (flag: Flag) =>+ t.middleware(({ ctx, next }) => {+ const session = ctx.session;+ const enabled =+ (session?.user?.featureFlags?.[flag] ?? false) ||+ (session?.user?.admin ?? false) ||+ (session?.environment?.enableExperimentalFeatures ?? false);+ if (!enabled) {+ throw new TRPCError({+ code: "FORBIDDEN",+ message: `Feature "${flag}" is not enabled for this user`,+ });+ }+ return next();+ });+export const protectedProjectProcedureWithoutTracing = t.procedure.use(withErrorHandling).use(enforceUserIsAuthedAndProjectMember);