All files / pages/Home HomePage.tsx

100% Statements 30/30
75% Branches 9/12
100% Functions 13/13
100% Lines 30/30

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 230 231                              1x                                         1x 1x       1x 11x     27x           27x   27x 27x   27x                       27x               27x 1x             1x               27x             11x 6x   5x     1x                 27x 2x           1x     1x           27x               16x 16x             16x                                       16x     2x                 27x                                                                                                        
import { useBackend, useBackendMutation } from "main/utils/useBackend";
import BasicLayout from "main/layouts/BasicLayout/BasicLayout";
import OurTable from "main/components/Common/OurTable";
import { Button } from "react-bootstrap";
import { toast } from "react-toastify";
import type { Cell } from "@tanstack/react-table";
import { hasRole, useCurrentUser } from "main/utils/currentUser";
 
type Stats = {
  totalRequests: number;
  cacheHits: number;
  cacheMisses: number;
  hitRatePercentage: number;
};
 
const defaultStats: Stats = {
  totalRequests: 0,
  cacheHits: 0,
  cacheMisses: 0,
  hitRatePercentage: 0,
};
 
export type HostCount = {
  host: string;
  count: number;
};
 
export type CachedEndpoint = {
  id: string;
  requestPath: string;
  hitCount: number;
  responseStatus: number;
  responseBody: string;
  cachedAt: string | null;
};
 
const hostsEndpoint = "/api/admin/hosts";
const cachedEndpointsEndpoint = "/api/admin/endpoints";
 
// A host that hasn't (yet, or successfully) resolved to a hostname still displays as its own
// raw IPv4 address - that's exactly the signal to show a retry button for it.
const looksLikeIpAddress = (host: string): boolean =>
  /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);
 
export default function HomePage(): React.JSX.Element {
  const { data } = useBackend<Stats>(
    ["/api/stats"],
    { method: "GET", url: "/api/stats" },
    // Stryker disable next-line all : don't test default value of empty stats
    defaultStats,
  );
  const stats = data ?? defaultStats;
 
  const currentUser = useCurrentUser();
  const isAdmin = hasRole(currentUser, "ROLE_ADMIN");
 
  const { data: hostCounts } = useBackend<HostCount[]>(
    // Stryker disable next-line ArrayDeclaration: this is the only query using this key in
    // any given test, so an empty key behaves identically in isolation.
    [hostsEndpoint],
    // Stryker disable next-line StringLiteral: axios treats a falsy method as "GET"
    { method: "GET", url: hostsEndpoint },
    // Stryker disable next-line all : don't test default value of empty list
    [],
    false,
    { enabled: isAdmin },
  );
 
  const { data: cachedEndpoints } = useBackend<CachedEndpoint[]>(
    [cachedEndpointsEndpoint],
    { method: "GET", url: cachedEndpointsEndpoint },
    [],
    false,
    { enabled: isAdmin },
  );
 
  const retryMutation = useBackendMutation<string>(
    (ip: string) => ({
      url: `${hostsEndpoint}/resolve`,
      method: "POST",
      params: { ip },
    }),
    {
      onSuccess: () => {
        toast("Requested hostname resolution");
      },
    },
    // Stryker disable next-line ArrayDeclaration: invalidateQueries([]) invalidates every
    // query, which is behaviorally identical here since this is the only active query.
    [hostsEndpoint],
  );
 
  const hostColumns = [
    { header: "Host", accessorKey: "host" },
    { header: "Count", accessorKey: "count" },
    {
      header: "",
      id: "retry",
      cell: ({ cell }: { cell: Cell<HostCount, unknown> }) => {
        if (!looksLikeIpAddress(cell.row.original.host)) {
          return null;
        }
        return (
          <Button
            size="sm"
            onClick={() => retryMutation.mutate(cell.row.original.host)}
            data-testid={`HomePage-hosts-table-cell-row-${cell.row.index}-col-retry-button`}
          >
            Retry
          </Button>
        );
      },
    },
  ];
  const purgeMutation = useBackendMutation<string>(
    (id: string) => ({
      url: `${cachedEndpointsEndpoint}/${id}`,
      method: "DELETE",
    }),
    {
      onSuccess: () => {
        toast.success("Cached response purged");
      },
      onError: () => {
        toast.error("Failed to purge cached response");
      },
    },
    [cachedEndpointsEndpoint],
  );
 
  const cachedEndpointColumns = [
    { header: "Request Path", accessorKey: "requestPath" },
    { header: "Hit Count", accessorKey: "hitCount" },
    { header: "Response Status", accessorKey: "responseStatus" },
    {
      header: "Cached At",
      accessorKey: "cachedAt",
      cell: ({ cell }: { cell: Cell<CachedEndpoint, unknown> }) => {
        const { cachedAt } = cell.row.original;
        return cachedAt ? new Date(cachedAt).toLocaleString() : "Unknown";
      },
    },
    {
      header: "Response Body",
      id: "responseBody",
      cell: ({ cell }: { cell: Cell<CachedEndpoint, unknown> }) => (
        <details>
          <summary>View Response</summary>
          <pre
            style={{
              maxWidth: "400px",
              maxHeight: "200px",
              overflow: "auto",
              whiteSpace: "pre-wrap",
              overflowWrap: "anywhere",
            }}
          >
            {cell.row.original.responseBody}
          </pre>
        </details>
      ),
    },
    {
      header: "",
      id: "purge",
      cell: ({ cell }: { cell: Cell<CachedEndpoint, unknown> }) => (
        <Button
          size="sm"
          variant="danger"
          onClick={() => purgeMutation.mutate(cell.row.original.id)}
          data-testid={`HomePage-cached-table-cell-row-${cell.row.index}-col-purge-button`}
        >
          Purge
        </Button>
      ),
    },
  ];
 
  return (
    <BasicLayout>
      <div className="pt-2">
        <h1>Dining Caching Proxy</h1>
        <table className="table" data-testid="HomePage-stats-table">
          <tbody>
            <tr>
              <th scope="row">Total Requests</th>
              <td data-testid="HomePage-totalRequests">
                {stats.totalRequests}
              </td>
            </tr>
            <tr>
              <th scope="row">Cache Hits</th>
              <td data-testid="HomePage-cacheHits">{stats.cacheHits}</td>
            </tr>
            <tr>
              <th scope="row">Cache Misses</th>
              <td data-testid="HomePage-cacheMisses">{stats.cacheMisses}</td>
            </tr>
            <tr>
              <th scope="row">Hit Rate</th>
              <td data-testid="HomePage-hitRate">
                {stats.hitRatePercentage.toFixed(1)}%
              </td>
            </tr>
          </tbody>
        </table>
 
        {isAdmin && (
          <>
            <h2>Requesting Hosts</h2>
            <OurTable
              // Stryker disable next-line ArrayDeclaration: initialData=[] above guarantees
              // hostCounts is never actually undefined at runtime; this is TypeScript-only
              // defensiveness (the useBackend generic wrapper defeats initialData narrowing).
              data={hostCounts ?? []}
              columns={hostColumns}
              testid="HomePage-hosts-table"
            />
            <h2>Cached Responses</h2>
            <OurTable
              data={cachedEndpoints ?? []}
              columns={cachedEndpointColumns}
              testid="HomePage-cached-table"
            />
          </>
        )}
      </div>
    </BasicLayout>
  );
}