Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: add own sentry instrumentation on ingestion (#2897)

Max Deichmann52a3276495dc
diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.ts
index 6eafae5332..5f47b3a024 100644
--- a/web/src/pages/api/public/ingestion.ts
+++ b/web/src/pages/api/public/ingestion.ts
@@ -68,98 +68,117 @@ export default async function handler(
res: NextApiResponse,
) {
try {
- await runMiddleware(req, res, cors);
-
- if (req.method !== "POST") throw new MethodNotAllowedError();
-
- // CHECK AUTH FOR ALL EVENTS
- const authCheck = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
-
- if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
-
- const batchType = z.object({
- batch: z.array(z.unknown()),
- metadata: jsonSchema.nullish(),
- });
-
- const parsedSchema = batchType.safeParse(req.body);
+ return Sentry.startSpan(
+ {
+ name: "POST /api/public/ingestion",
+ forceTransaction: true,
+ op: "http.server",
+ },
+ async (span) => {
+ const startTime = Date.now();
+ let endTime = undefined;
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "POST") throw new MethodNotAllowedError();
+
+ // CHECK AUTH FOR ALL EVENTS
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
+
+ if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);
+
+ const batchType = z.object({
+ batch: z.array(z.unknown()),
+ metadata: jsonSchema.nullish(),
+ });
- Sentry.metrics.increment(
- "ingestion_event",
- parsedSchema.success ? parsedSchema.data.batch.length : 0,
- );
+ const parsedSchema = batchType.safeParse(req.body);
- await gaugePrismaStats();
+ Sentry.metrics.increment(
+ "ingestion_event",
+ parsedSchema.success ? parsedSchema.data.batch.length : 0,
+ );
- if (!parsedSchema.success) {
- console.log("Invalid request data", parsedSchema.error);
- return res.status(400).json({
- message: "Invalid request data",
- errors: parsedSchema.error.issues.map((issue) => issue.message),
- });
- }
+ await gaugePrismaStats();
- const validationErrors: { id: string; error: unknown }[] = [];
-
- const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
- parsedSchema.data.batch.map((event) => {
- const parsed = ingestionEvent.safeParse(event);
- if (!parsed.success) {
- validationErrors.push({
- id:
- typeof event === "object" && event && "id" in event
- ? typeof event.id === "string"
- ? event.id
- : "unknown"
- : "unknown",
- error: new InvalidRequestError(parsed.error.message),
+ if (!parsedSchema.success) {
+ console.log("Invalid request data", parsedSchema.error);
+ return res.status(400).json({
+ message: "Invalid request data",
+ errors: parsedSchema.error.issues.map((issue) => issue.message),
});
- return undefined;
- } else {
- return parsed.data;
}
- });
- const filteredBatch: z.infer<typeof ingestionEvent>[] =
- batch.filter(isNotNullOrUndefined);
- await telemetry();
-
- const sortedBatch = sortBatch(filteredBatch);
+ const validationErrors: { id: string; error: unknown }[] = [];
+
+ const batch: (z.infer<typeof ingestionEvent> | undefined)[] =
+ parsedSchema.data.batch.map((event) => {
+ const parsed = ingestionEvent.safeParse(event);
+ if (!parsed.success) {
+ validationErrors.push({
+ id:
+ typeof event === "object" && event && "id" in event
+ ? typeof event.id === "string"
+ ? event.id
+ : "unknown"
+ : "unknown",
+ error: new InvalidRequestError(parsed.error.message),
+ });
+ return undefined;
+ } else {
+ return parsed.data;
+ }
+ });
+ const filteredBatch: z.infer<typeof ingestionEvent>[] =
+ batch.filter(isNotNullOrUndefined);
+
+ await telemetry();
+
+ const sortedBatch = sortBatch(filteredBatch);
+
+ if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true") {
+ // this function MUST NOT return but send the HTTP response directly
+ console.log("Returning http response early");
+ handleBatchResult(
+ validationErrors, // we are not sending additional server errors to the client in case of early return
+ sortedBatch.map((event) => ({ id: event.id, result: event })),
+ res,
+ );
+ Sentry.captureEvent({
+ message: "Returning http response early",
+ });
+ endTime = Date.now();
+ }
- if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "true") {
- // this function MUST NOT return but send the HTTP response directly
- console.log("Returning http response early");
- handleBatchResult(
- validationErrors, // we are not sending additional server errors to the client in case of early return
- sortedBatch.map((event) => ({ id: event.id, result: event })),
- res,
- );
- }
+ const result = await handleBatch(
+ sortedBatch,
+ parsedSchema.data.metadata,
+ req,
+ authCheck,
+ );
- const result = await handleBatch(
- sortedBatch,
- parsedSchema.data.metadata,
- req,
- authCheck,
- );
+ // send out REST requests to worker for all trace types
+ await sendToWorkerIfEnvironmentConfigured(
+ result.results,
+ authCheck.scope.projectId,
+ );
- // send out REST requests to worker for all trace types
- await sendToWorkerIfEnvironmentConfigured(
- result.results,
- authCheck.scope.projectId,
+ // in case we did not return early, we return the result here
+ if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "false") {
+ handleBatchResult(
+ [...validationErrors, ...result.errors],
+ result.results,
+ res,
+ );
+ }
+ span.setAttributes({
+ duration: (endTime ?? Date.now()) - startTime,
+ async_duration: Date.now() - startTime,
+ });
+ },
);
-
- // in case we did not return early, we return the result here
- if (env.LANGFUSE_ASYNC_INGESTION_PROCESSING === "false") {
- handleBatchResult(
- [...validationErrors, ...result.errors],
- result.results,
- res,
- );
- }
} catch (error: unknown) {
if (!(error instanceof UnauthorizedError)) {
console.error("error_handling_ingestion_event", error);