API referencePlatform APIEndpoint reference
GUIDE & REFERENCE

/api/v1/tenants/[id]/metrics (management)

Source-derived management endpoint contract, authentication, request validation, responses, and errors.

This is the management service route. Its origin and authentication are described in Platform API overview and Authentication. A path shared by another service is a different endpoint.

PropertyContract
MethodsGET
Path/api/v1/tenants/[id]/metrics
Path parametersid
Query parameters read in routeperiod
Headers read in routeNo additional direct header reads; authentication helpers may read credentials

Authentication and access

Management auth context: validated x-api-key or configured session authentication; trusted gateway integration may select its auth pipeline. Organization/tenant checks are separate.

Request and response definitions

The following named definitions are imported or declared by this route. Optional markers, defaults, bounds, and enum values are shown exactly as implemented. A response type is a source contract, not an example populated with real account data.

MetricsResponse

MetricsResponse = z.object({
  tenant_id: z.string(),
  period: MetricsPeriod,
  timestamp: z.string().datetime(),
  metrics: z.object({
    compute: ComputeMetrics,
    storage: StorageMetrics,
    performance: PerformanceMetrics,
    cognitive: CognitiveMetrics,
  }),
})

Source: minds-ui/apps/api-service/types/monitoring.ts:60.

MetricsResponse

export type MetricsResponse = z.infer<typeof MetricsResponse>

Source: minds-ui/apps/api-service/types/monitoring.ts:72.

apiRequestCounter

apiRequestCounter = new promClient.Counter({
  name: 'api_requests_total',
  help: 'Total number of API requests',
  labelNames: ['method', 'path', 'status', 'tenant_id'],
  registers: [register],
})

Source: minds-ui/apps/api-service/lib/services/prometheus.ts:27.

apiRequestDuration

apiRequestDuration = new promClient.Histogram({
  name: 'api_request_duration_seconds',
  help: 'API request duration in seconds',
  labelNames: ['method', 'path', 'tenant_id'],
  buckets: [0.01, 0.05, 0.1, 0.5, 1, 2, 5],
  registers: [register],
})

Source: minds-ui/apps/api-service/lib/services/prometheus.ts:34.

apiRequestErrors

apiRequestErrors = new promClient.Counter({
  name: 'api_request_errors_total',
  help: 'Total number of API request errors',
  labelNames: ['method', 'path', 'error_type', 'tenant_id'],
  registers: [register],
})

Source: minds-ui/apps/api-service/lib/services/prometheus.ts:42.

RouteContext

interface RouteContext {
  params: Promise<{ id: string }>
}

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:26.

Method behavior

The handler excerpt preserves field validation, response envelopes, cookie changes, and exception branches. Values returned by service helpers retain their named response type above; for passthrough routes, the upstream response is authoritative.

GET

export async function GET(request: NextRequest, context: RouteContext) {
  const requestId = generateRequestId()
  const { id: rawTenantId } = await context.params
  const period = (request.nextUrl.searchParams.get('period') || '1h') as MetricsPeriod
  const pathLabel = '/api/v1/tenants/[id]/metrics'
  const requestLogger = createRequestLogger(request)
  const traceContext = extractTraceContext(request.headers)
  const span = tracer.startSpan('tenant.metrics.fetch', traceContext, {
    'http.method': 'GET',
    'http.route': pathLabel,
    'request.id': requestId,
    'tenant.id': rawTenantId,
    'metrics.period': period,
  })
  const stopTimer = apiRequestDuration.startTimer()
  const startedAt = Date.now()

  let statusCode = 200
  let tenantIdForLog = rawTenantId
  let rateLimitInfo: RateLimitMetadata | undefined

  try {
    const tenantId = validateTenantId(rawTenantId)
    tenantIdForLog = tenantId
    tracer.setSpanAttributes(span.spanId, { 'tenant.id': tenantId })

    requestLogger.info('Fetching tenant metrics', {
      requestId,
      tenantId,
      metadata: { period },
    })

    const authContext = await resolveAuthContext(request)
    const evaluation = await enforceRateLimit({
      context: authContext,
      tenantId,
    })

    rateLimitInfo = {
      ...evaluation.metadata,
      retryAfter: evaluation.retryAfter,
    }

    tracer.setSpanAttributes(span.spanId, {
      'rate.limit.limit': evaluation.metadata?.limit ?? 0,
      'rate.limit.remaining': evaluation.metadata?.remaining ?? 0,
    })

    if (evaluation.blocked) {
      throw new RateLimitExceededError(evaluation.retryAfter ?? 60)
    }

    const metrics = await getTenantMetrics(tenantId)

    tenantOperations.inc({ tenant_id: tenantId, operation_type: 'metrics_read' })
    tracer.addSpanEvent(span.spanId, 'metrics.fetched', { 'tenant.id': tenantId })

    requestLogger.info('Tenant metrics fetched', {
      requestId,
      tenantId,
      metadata: { period },
    })

    const response = apiSuccess<MetricsResponse>(metrics)
    return withRequestMetadata(response, requestId, rateLimitInfo)
  } catch (error) {
    const normalizedError =
      error instanceof ApiError
        ? error
        : new ApiError(500, 'INTERNAL_ERROR', 'Failed to get metrics')

    statusCode = normalizedError.statusCode

    apiRequestErrors.inc({
      method: 'GET',
      path: pathLabel,
      tenant_id: tenantIdForLog,
      error_type: normalizedError.code,
    })

    tracer.recordError(span.spanId, normalizedError)

    requestLogger.error('Failed to fetch tenant metrics', {
      requestId,
      tenantId: tenantIdForLog,
      error: normalizedError,
      metadata: { period },
    })

    const response = apiError(normalizedError, requestId)
    return withRequestMetadata(response, requestId, rateLimitInfo)
  } finally {
    stopTimer({
      method: 'GET',
      path: pathLabel,
      tenant_id: tenantIdForLog,
    })

    apiRequestCounter.inc({
      method: 'GET',
      path: pathLabel,
      tenant_id: tenantIdForLog,
    })

    const durationMs = Date.now() - startedAt
    requestLogger.logResponse('GET', pathLabel, statusCode, durationMs, {
      requestId,
      tenantId: tenantIdForLog,
      metadata: { period, rateLimit: rateLimitInfo },
    })

    tracer.setSpanAttributes(span.spanId, {
      'http.status_code': statusCode,
      'tenant.id': tenantIdForLog,
      'metrics.period': period,
    })

    tracer.endSpan(span.spanId)
  }
}

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:30.

Response and error branches

Literal HTTP statuses in the route: 500. Shared management error classes are defined in Errors and responses.

new RateLimitExceededError(evaluation.retryAfter ?? 60)

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:79.

apiSuccess<MetricsResponse>(metrics)

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:93.

new ApiError(500, 'INTERNAL_ERROR', 'Failed to get metrics')

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:99.

tracer.recordError(span.spanId, normalizedError)

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:110.

apiError(normalizedError, requestId)

Source: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts:119.

Service dependencies

  • minds-ui/apps/api-service/lib/api-response.ts
  • minds-ui/apps/api-service/lib/validation.ts
  • minds-ui/apps/api-service/types/monitoring.ts
  • minds-ui/apps/api-service/types/errors.ts
  • minds-ui/apps/api-service/lib/observability/logger.ts
  • minds-ui/apps/api-service/lib/observability/tracer.ts
  • minds-ui/apps/api-service/lib/services/auth-context.ts
  • minds-ui/apps/api-service/lib/services/tenant-service.ts
  • minds-ui/apps/api-service/lib/services/rate-limit.ts
  • minds-ui/apps/api-service/lib/services/prometheus.ts

Evidence

Generated from the local source snapshot on 2026-09-12. This page documents implemented code and does not certify a deployed service, permissions configuration, or successful provider operation.

Source file: minds-ui/apps/api-service/app/api/v1/tenants/[id]/metrics/route.ts. SHA-256: e2ad938ece39559cc84a2ec00117e33511fe000b83939d73fb237b454e91b0d1.

On this page