All files / pages/Home HomePage.tsx

100% Statements 18/18
75% Branches 6/8
100% Functions 6/6
100% Lines 18/18

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                              1x                       1x       1x 15x     13x           13x   13x 13x   13x                       13x 1x             1x               13x             15x 9x   6x     1x                   13x                                                                                            
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;
};
 
const hostsEndpoint = "/api/admin/hosts";
 
// 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 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>
        );
      },
    },
  ];
 
  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"
            />
          </>
        )}
      </div>
    </BasicLayout>
  );
}