All files / src/app/api/federated route.ts

93.75% Statements 15/16
55.55% Branches 5/9
100% Functions 1/1
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46              2x     10x 10x         10x 10x   5x       5x 5x       10x 5x               4x 4x     1x 1x      
import { type NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { userToParticipantId } from "@/lib/odrl-engine";
import { activePermitHeaders } from "@/lib/permit-gate";
import { NEO4J_PROXY_URL, callerHeaders, loadTestHeaders } from "@/lib/proxy";
import { speColdStartGate } from "@/lib/spe-power";
 
export const dynamic = "force-dynamic";
 
export async function GET(request: NextRequest) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  // The statistics ask every SPE workspace. A stopped one is started (when
  // the caller may) and the caller is told to come back (ADR-072), rather
  // than waiting for a workspace that is not there.
  const coldStart = await speColdStartGate(auth.session.roles);
  if (coldStart) return coldStart;
 
  try {
    // The proxy records every request it serves as a TransferEvent, the
    // access log behind /admin/audit. Without this header the entry says
    // "unknown" instead of who asked (issue #205).
    const { session } = auth;
    const participantId = userToParticipantId(
      session.user.email ?? session.user.name ?? session.user.id,
      session.roles,
    );
    const permitHeaders = await activePermitHeaders(participantId);
    const resp = await fetch(`${NEO4J_PROXY_URL}/federated/stats`, {
      headers: {
        "X-Participant": participantId,
        ...permitHeaders,
        ...loadTestHeaders(request),
        ...callerHeaders(session),
      },
    });
    const data = await resp.json();
    return NextResponse.json(data);
  } catch (err: unknown) {
    const message =
      err instanceof Error ? err.message : "Federated stats proxy error";
    return NextResponse.json({ error: message }, { status: 502 });
  }
}