All files / src/app/admin/monitoring/traces page.tsx

0% Statements 0/228
100% Branches 0/0
0% Functions 0/1
0% Lines 0/228

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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { clientLogger } from '@/lib/logging/clientLogger';
import { TraceExplorer, type TraceListItem } from '@/components/features/admin/monitoring/TraceExplorer';
import {
  TraceWaterfall,
  type SpanNode,
  type TraceInfo,
  type TraceStats,
} from '@/components/features/admin/monitoring/TraceWaterfall';

interface TracesResponse {
  traces: TraceListItem[];
  pagination: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

interface TraceDetailResponse {
  trace: TraceInfo;
  flatSpans: SpanNode[];
  stats: TraceStats;
}

export default function TracesPage() {
  // List state
  const [traces, setTraces] = useState<TraceListItem[]>([]);
  const [pagination, setPagination] = useState({ page: 1, limit: 20, total: 0, totalPages: 0 });
  const [isLoading, setIsLoading] = useState(true);
  const [searchValue, setSearchValue] = useState('');
  const [statusFilter, setStatusFilter] = useState<'all' | 'ok' | 'error'>('all');

  // Detail state
  const [selectedTraceId, setSelectedTraceId] = useState<string | null>(null);
  const [traceDetail, setTraceDetail] = useState<TraceDetailResponse | null>(null);
  const [isLoadingDetail, setIsLoadingDetail] = useState(false);
  const [selectedSpanId, setSelectedSpanId] = useState<string | undefined>(undefined);

  // Fetch traces list
  const fetchTraces = useCallback(async () => {
    setIsLoading(true);
    try {
      const params = new URLSearchParams({
        page: String(pagination.page),
        limit: String(pagination.limit),
        status: statusFilter,
        sortBy: 'startTime',
        sortOrder: 'desc',
      });
      if (searchValue) {
        params.set('search', searchValue);
      }

      const response = await fetch(`/api/admin/monitoring/traces?${params}`);
      if (!response.ok) throw new Error('Failed to fetch traces');

      const data: TracesResponse = await response.json();
      setTraces(data.traces);
      setPagination(data.pagination);
    } catch (error) {
      clientLogger.error('Failed to fetch traces', error instanceof Error ? error : undefined);
    } finally {
      setIsLoading(false);
    }
  }, [pagination.page, pagination.limit, statusFilter, searchValue]);

  // Fetch trace detail
  const fetchTraceDetail = useCallback(async (traceId: string) => {
    setIsLoadingDetail(true);
    setSelectedSpanId(undefined);
    try {
      const response = await fetch(`/api/admin/monitoring/traces/${traceId}`);
      if (!response.ok) throw new Error('Failed to fetch trace detail');

      const data: TraceDetailResponse = await response.json();
      setTraceDetail(data);
    } catch (error) {
      clientLogger.error('Failed to fetch trace detail', error instanceof Error ? error : undefined);
      setTraceDetail(null);
    } finally {
      setIsLoadingDetail(false);
    }
  }, []);

  // Initial load
  useEffect(() => {
    fetchTraces();
  }, [fetchTraces]);

  // Fetch detail when trace is selected
  useEffect(() => {
    if (selectedTraceId) {
      fetchTraceDetail(selectedTraceId);
    } else {
      setTraceDetail(null);
    }
  }, [selectedTraceId, fetchTraceDetail]);

  // Debounce search
  useEffect(() => {
    const timer = setTimeout(() => {
      fetchTraces();
    }, 300);
    return () => clearTimeout(timer);
  }, [searchValue, statusFilter, fetchTraces]);

  const handleSelectTrace = (traceId: string) => {
    setSelectedTraceId(traceId === selectedTraceId ? null : traceId);
  };

  const handleSearchChange = (value: string) => {
    setSearchValue(value);
    setPagination((p) => ({ ...p, page: 1 }));
  };

  const handleStatusFilterChange = (status: 'all' | 'ok' | 'error') => {
    setStatusFilter(status);
    setPagination((p) => ({ ...p, page: 1 }));
  };

  const handleSelectSpan = (span: SpanNode) => {
    setSelectedSpanId(span.id === selectedSpanId ? undefined : span.id);
  };

  return (
    <div className="p-6 min-h-screen bg-gray-50 dark:bg-gray-900">
      {/* Header */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900 dark:text-white">Trace Explorer</h1>
        <p className="text-gray-500 dark:text-gray-400 mt-1">
          View and analyze distributed traces from your application
        </p>
      </div>

      {/* Main content */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Trace list */}
        <div>
          <TraceExplorer
            traces={traces}
            selectedTraceId={selectedTraceId ?? undefined}
            onSelectTrace={handleSelectTrace}
            isLoading={isLoading}
            searchValue={searchValue}
            onSearchChange={handleSearchChange}
            statusFilter={statusFilter}
            onStatusFilterChange={handleStatusFilterChange}
          />

          {/* Pagination */}
          {pagination.totalPages > 1 && (
            <div className="mt-4 flex items-center justify-between">
              <span className="text-sm text-gray-500 dark:text-gray-400">
                Showing {(pagination.page - 1) * pagination.limit + 1} to{' '}
                {Math.min(pagination.page * pagination.limit, pagination.total)} of{' '}
                {pagination.total} traces
              </span>
              <div className="flex gap-2">
                <button
                  onClick={() => setPagination((p) => ({ ...p, page: p.page - 1 }))}
                  disabled={pagination.page === 1}
                  className="px-3 py-1 text-sm font-medium rounded bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 disabled:opacity-50"
                >
                  Previous
                </button>
                <button
                  onClick={() => setPagination((p) => ({ ...p, page: p.page + 1 }))}
                  disabled={pagination.page === pagination.totalPages}
                  className="px-3 py-1 text-sm font-medium rounded bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 disabled:opacity-50"
                >
                  Next
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Trace detail */}
        <div>
          {selectedTraceId ? (
            traceDetail ? (
              <TraceWaterfall
                trace={traceDetail.trace}
                flatSpans={traceDetail.flatSpans}
                stats={traceDetail.stats}
                isLoading={isLoadingDetail}
                selectedSpanId={selectedSpanId}
                onSelectSpan={handleSelectSpan}
              />
            ) : isLoadingDetail ? (
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-8 text-center">
                <div className="inline-block animate-spin rounded-full h-8 w-8 border-4 border-blue-500 border-t-transparent mb-4" />
                <p className="text-gray-500 dark:text-gray-400">Loading trace details...</p>
              </div>
            ) : (
              <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-8 text-center">
                <p className="text-gray-500 dark:text-gray-400">Failed to load trace details</p>
              </div>
            )
          ) : (
            <div className="bg-white dark:bg-gray-800 rounded-lg shadow p-8 text-center">
              <svg
                className="mx-auto h-12 w-12 text-gray-400"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={1.5}
                  d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                />
              </svg>
              <p className="mt-4 text-gray-500 dark:text-gray-400">
                Select a trace to view its waterfall diagram
              </p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}