Shaked Tayeb
Shaked Tayeb

Reputation: 112

Trpc nextjs problems on build when implenting promethus

I am runing a classic nextjs with t3 stack and trpc, when i am implemnting prom using prom-client and trpc middleware everything runing locally .

when i run npm run build all the custom metric does not update any more.

my file structure is /lib/metric/prom.ts

import {register, Counter, Histogram} from 'prom-client';// dynamic?

export  const httpRequestCounter = new Counter({
    name: 'http_requests_total',
    help: 'Total number of HTTP requests',
    labelNames: ['method', 'procedure', 'status_code'],
  });

export const responseTimeHistogram = new Histogram({
    name: 'http_response_time_seconds',
    help: 'Response time in seconds',
    labelNames: ['method', 'procedure'],
  });


register.registerMetric(httpRequestCounter);
register.registerMetric(responseTimeHistogram);


/api/metrics/route.ts

/* eslint-disable */
// @ts-ignore
import { NextResponse } from 'next/server';
import {register} from 'prom-client'
// import dynamic from 'next/dynamic';
//
// @ts-ignore
// const metrics: {register: {contentType: string, metrics: () => {}} } = dynamic(() => import('@/lib/metrics/promethus'), { ssr: false });

import metrics from '@/lib/metrics/promethus'

export async function GET() {
  try {
    const data = await register?.metrics();
    return new NextResponse(data, {
      status: 200,
      headers: { 'Content-Type': register.contentType },
    });
  } catch (error) {
    console.error('Error generating metrics:', error);
    return new NextResponse('Unable to generate metrics', { status: 500 });
  }
}
export const dynamic ='force-dynamic'

/server/api/trpc.ts <-middleware here .

const metricsMiddleware = t.middleware(async ({ path, type, next }) => {
  const endTimer = responseTimeHistogram.startTimer({
    method: type,
    procedure: path,
  });

  // todo: fix servers the thest again might ahve solution
  try {
    const result = await next();

    console.log(' am i here???')
    // Map tRPC result to an HTTP status code
    let statusCode = '200';
    if (!result.ok) {
      // Map specific tRPC error codes to HTTP status codes if needed
      statusCode = '500';
    }

    console.log('before requests')
    httpRequestCounter.inc({
      method: type,
      procedure: path,
      status_code: statusCode,
    });

    console.log("after request")
    return result;
  } catch (error) {
    // Handle unexpected errors
   httpRequestCounter.inc({
      method: type,
      procedure: path,
      status_code: '500',
    });

    throw error;
  } finally {
    endTimer();
  }
});

any direction will be appreciated.

I tried to implement as detailed above, i tried singleton patterns and whatnot but nothing seemed to work, i tried preventing the pap from static loading the prom file, i expected the metric reporting to work same as on local dev but i just cant get it to work.

Upvotes: 0

Views: 32

Answers (0)

Related Questions