Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 15 additions & 9 deletions apps/ensadmin/src/app/mock/indexing-stats/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
"use client";

import { useQuery } from "@tanstack/react-query";
import { getUnixTime } from "date-fns";
import { useEffect, useState } from "react";

import {
type IndexingStatusResponse,
CrossChainIndexingStatusSnapshot,
createRealtimeIndexingStatusProjection,
IndexingStatusResponseOk,
OmnichainIndexingStatusIds,
} from "@ensnode/ensnode-sdk";
Expand All @@ -13,10 +15,7 @@ import { IndexingStats } from "@/components/indexing-status/indexing-stats";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";

import {
indexingStatusResponseError,
indexingStatusResponseOkOmnichain,
} from "../indexing-status-api.mock";
import { indexingStatusResponseOkOmnichain } from "../indexing-status-api.mock";

type LoadingVariant = "Loading" | "Loading Error";
type ResponseOkVariant = keyof typeof indexingStatusResponseOkOmnichain;
Expand All @@ -37,7 +36,7 @@ let loadingTimeoutId: number;

async function fetchMockedIndexingStatus(
selectedVariant: Variant,
): Promise<IndexingStatusResponseOk> {
): Promise<CrossChainIndexingStatusSnapshot> {
// always try clearing loading timeout when performing a mocked fetch
// this way we get a fresh and very long request to observe the loading state
if (loadingTimeoutId) {
Expand All @@ -48,14 +47,19 @@ async function fetchMockedIndexingStatus(
case OmnichainIndexingStatusIds.Unstarted:
case OmnichainIndexingStatusIds.Backfill:
case OmnichainIndexingStatusIds.Following:
case OmnichainIndexingStatusIds.Completed:
return indexingStatusResponseOkOmnichain[selectedVariant] as IndexingStatusResponseOk;
case OmnichainIndexingStatusIds.Completed: {
const response = indexingStatusResponseOkOmnichain[
selectedVariant
] as IndexingStatusResponseOk;

return response.realtimeProjection.snapshot;
}
case "Error ResponseCode":
throw new Error(
"Received Indexing Status response with responseCode other than 'ok' which will not be cached.",
);
case "Loading":
return new Promise<IndexingStatusResponseOk>((_resolve, reject) => {
return new Promise<CrossChainIndexingStatusSnapshot>((_resolve, reject) => {
loadingTimeoutId = +setTimeout(reject, 5 * 60 * 1_000);
});
case "Loading Error":
Expand All @@ -67,10 +71,12 @@ export default function MockIndexingStatusPage() {
const [selectedVariant, setSelectedVariant] = useState<Variant>(
OmnichainIndexingStatusIds.Unstarted,
);
const now = getUnixTime(new Date());

const mockedIndexingStatus = useQuery({
queryKey: ["mock", "useIndexingStatus", selectedVariant],
queryFn: () => fetchMockedIndexingStatus(selectedVariant),
select: (cachedSnapshot) => createRealtimeIndexingStatusProjection(cachedSnapshot, now),
retry: false, // allows loading error to be observed immediately
});

Expand Down
15 changes: 12 additions & 3 deletions apps/ensadmin/src/components/datetime-utils/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,18 @@ export function RelativeTime({
const [relativeTime, setRelativeTime] = useState<string>("");

useEffect(() => {
setRelativeTime(
formatRelativeTime(timestamp, enforcePast, includeSeconds, conciseFormatting, relativeTo),
);
const updateTime = () => {
setRelativeTime(
formatRelativeTime(timestamp, enforcePast, includeSeconds, conciseFormatting, relativeTo),
);
};

updateTime();

if (includeSeconds) {
const interval = setInterval(updateTime, 1000);
return () => clearInterval(interval);
}
}, [timestamp, conciseFormatting, enforcePast, includeSeconds, relativeTo]);

const tooltipTriggerContent = (
Expand Down
20 changes: 9 additions & 11 deletions apps/ensadmin/src/components/indexing-status/indexing-stats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ import {

import { ChainIcon } from "@/components/chains/ChainIcon";
import { ChainName } from "@/components/chains/ChainName";
import { useIndexingStatusWithSwr } from "@/components/indexing-status/use-indexing-status-with-swr";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { formatChainStatus, formatOmnichainIndexingStatus } from "@/lib/indexing-status";
Expand All @@ -34,6 +33,8 @@ import { cn } from "@/lib/utils";
import { BackfillStatus } from "./backfill-status";
import { BlockStats } from "./block-refs";
import { IndexingStatusLoading } from "./indexing-status-loading";
import { ProjectionInfo } from "./projection-info";
import { useIndexingStatusWithSwr } from "./use-indexing-status-with-swr";

interface IndexingStatsForOmnichainStatusSnapshotProps<
OmnichainIndexingStatusSnapshotType extends
Expand Down Expand Up @@ -323,15 +324,18 @@ export function IndexingStatsForSnapshotFollowing({
* UI component for presenting indexing stats UI for specific overall status.
*/
export function IndexingStatsShell({
omnichainStatus,
realtimeProjection,
children,
}: PropsWithChildren<{ omnichainStatus?: OmnichainIndexingStatusId }>) {
}: PropsWithChildren<{ realtimeProjection?: RealtimeIndexingStatusProjection }>) {
const omnichainStatus = realtimeProjection?.snapshot.omnichainSnapshot.omnichainStatus;
return (
<Card className="w-full flex flex-col gap-2">
<CardHeader>
<CardTitle className="flex gap-2 items-center">
<span>Indexing Status</span>

{realtimeProjection && <ProjectionInfo realtimeProjection={realtimeProjection} />}

{omnichainStatus && (
<Badge
className={cn("uppercase text-xs leading-none")}
Expand Down Expand Up @@ -423,7 +427,7 @@ export function IndexingStatsForRealtimeStatusProjection({
<section className="flex flex-col gap-6">
{maybeIndexingTimeline}

<IndexingStatsShell omnichainStatus={omnichainStatusSnapshot.omnichainStatus}>
<IndexingStatsShell realtimeProjection={realtimeProjection}>
{indexingStats}
</IndexingStatsShell>
</section>
Expand All @@ -450,11 +454,5 @@ export function IndexingStats(props: IndexingStatsProps) {
return <IndexingStatusLoading />;
}

const indexingStatus = indexingStatusQuery.data;

return (
<IndexingStatsForRealtimeStatusProjection
realtimeProjection={indexingStatus.realtimeProjection}
/>
);
return <IndexingStatsForRealtimeStatusProjection realtimeProjection={indexingStatusQuery.data} />;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"use client";

import { InfoIcon } from "lucide-react";

import type { RealtimeIndexingStatusProjection } from "@ensnode/ensnode-sdk";

import { RelativeTime } from "@/components/datetime-utils";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";

interface ProjectionInfoProps {
realtimeProjection: RealtimeIndexingStatusProjection;
}

/**
* Displays metadata about the current indexing status projection in a tooltip.
* Shows when the projection was generated, when the snapshot was taken, and worst-case distance.
*/
export function ProjectionInfo({ realtimeProjection }: ProjectionInfoProps) {
const { projectedAt, snapshot, worstCaseDistance } = realtimeProjection;
const { snapshotTime } = snapshot;

return (
<Tooltip delayDuration={300}>
<TooltipTrigger asChild>
<button
type="button"
className="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground h-8 w-8"
aria-label="Indexing Status Metadata"
>
<InfoIcon className="h-4 w-4" />
</button>
</TooltipTrigger>
<TooltipContent
side="right"
className="bg-gray-50 text-sm text-black shadow-md outline-none w-80 p-4"
>
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<div className="font-semibold text-xs text-gray-500 uppercase">
Worst-Case Distance*
</div>
<div className="text-sm">
{worstCaseDistance !== null ? `${worstCaseDistance} seconds` : "N/A"}
</div>
</div>

<div className="text-xs text-gray-600 leading-relaxed">
* as of real-time projection generated just now from indexing status snapshot captured{" "}
<RelativeTime timestamp={snapshotTime} includeSeconds conciseFormatting />.
</div>
</div>
</TooltipContent>
</Tooltip>
);
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,32 @@
"use client";

import { secondsToMilliseconds } from "date-fns";
import { useCallback, useMemo } from "react";

import {
createIndexingStatusQueryOptions,
QueryParameter,
useENSNodeSDKConfig,
type useIndexingStatus,
useNow,
useSwrQuery,
WithSDKConfigParameter,
} from "@ensnode/ensnode-react";
import {
CrossChainIndexingStatusSnapshotOmnichain,
createRealtimeIndexingStatusProjection,
type IndexingStatusRequest,
IndexingStatusResponseCodes,
IndexingStatusResponseOk,
RealtimeIndexingStatusProjection,
} from "@ensnode/ensnode-sdk";

const DEFAULT_REFETCH_INTERVAL = 10 * 1000;
const DEFAULT_REFETCH_INTERVAL = secondsToMilliseconds(10);

const REALTIME_PROJECTION_REFRESH_RATE = secondsToMilliseconds(1);

interface UseIndexingStatusParameters
extends IndexingStatusRequest,
QueryParameter<IndexingStatusResponseOk> {}
QueryParameter<CrossChainIndexingStatusSnapshotOmnichain> {}

/**
* A proxy hook for {@link useIndexingStatus} which applies
Expand All @@ -31,6 +37,7 @@ export function useIndexingStatusWithSwr(
) {
const { config, query = {} } = parameters;
const _config = useENSNodeSDKConfig(config);
const now = useNow(REALTIME_PROJECTION_REFRESH_RATE);

const queryOptions = useMemo(() => createIndexingStatusQueryOptions(_config), [_config]);
const queryKey = useMemo(() => ["swr", ...queryOptions.queryKey], [queryOptions.queryKey]);
Expand All @@ -46,18 +53,35 @@ export function useIndexingStatusWithSwr(
);
}

// successful response to be cached
return response;
// The indexing status snapshot has been fetched and successfully validated for caching.
// Therefore, return it so that query cache for `queryOptions.queryKey` will:
// - Replace the currently cached value (if any) with this new value.
// - Return this non-null value.
return response.realtimeProjection.snapshot;
}),
[queryOptions.queryFn],
);

// Call select function to `createRealtimeIndexingStatusProjection` each time
// `now` is updated.
const select = useCallback(
(
cachedSnapshot: CrossChainIndexingStatusSnapshotOmnichain,
): RealtimeIndexingStatusProjection => {
const realtimeProjection = createRealtimeIndexingStatusProjection(cachedSnapshot, now);

return realtimeProjection;
},
[now],
);

return useSwrQuery({
...queryOptions,
refetchInterval: query.refetchInterval ?? DEFAULT_REFETCH_INTERVAL, // Indexing status changes frequently
...query,
enabled: query.enabled ?? queryOptions.enabled,
queryKey,
queryFn,
select,
});
}
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,9 @@ export function useStatefulRegistrarActions({

let isRegistrarActionsApiSupported = false;

if (
ensNodeConfigQuery.isSuccess &&
indexingStatusQuery.isSuccess &&
indexingStatusQuery.data.responseCode === IndexingStatusResponseCodes.Ok
) {
if (ensNodeConfigQuery.isSuccess && indexingStatusQuery.isSuccess) {
const { ensIndexerPublicConfig } = ensNodeConfigQuery.data;
const { omnichainSnapshot } = indexingStatusQuery.data.realtimeProjection.snapshot;
const { omnichainSnapshot } = indexingStatusQuery.data.snapshot;

isRegistrarActionsApiSupported =
hasEnsIndexerConfigSupport(ensIndexerPublicConfig) &&
Expand Down Expand Up @@ -100,7 +96,7 @@ export function useStatefulRegistrarActions({
} satisfies StatefulFetchRegistrarActionsUnsupported;
}

const { omnichainSnapshot } = indexingStatusQuery.data.realtimeProjection.snapshot;
const { omnichainSnapshot } = indexingStatusQuery.data.snapshot;

// fetching is temporarily not possible due to indexing status being not advanced enough
if (!hasIndexingStatusSupport(omnichainSnapshot.omnichainStatus)) {
Expand Down
3 changes: 2 additions & 1 deletion packages/ensnode-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"vitest": "catalog:"
},
"dependencies": {
"@ensnode/ensnode-sdk": "workspace:*"
"@ensnode/ensnode-sdk": "workspace:*",
"date-fns": "catalog:"
}
}
1 change: 1 addition & 0 deletions packages/ensnode-react/src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export * from "./useENSNodeConfig";
export * from "./useENSNodeSDKConfig";
export * from "./useIndexingStatus";
export * from "./useNow";
export * from "./usePrimaryName";
export * from "./usePrimaryNames";
export * from "./useRecords";
Expand Down
31 changes: 31 additions & 0 deletions packages/ensnode-react/src/hooks/useNow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { getUnixTime } from "date-fns";
import { useEffect, useState } from "react";

/**
* Hook that returns the current Unix timestamp, updated at a specified interval.
*
* @param refreshRate - How often to update the timestamp in milliseconds (default: 1000ms)
* @returns Current Unix timestamp that updates every refreshRate milliseconds
*
* @example
* ```tsx
* // Updates every second
* const now = useNow(1000);
*
* // Updates every 5 seconds
* const now = useNow(5000);
* ```
*/
export function useNow(refreshRate = 1000): number {
const [now, setNow] = useState(() => getUnixTime(new Date()));

useEffect(() => {
const interval = setInterval(() => {
setNow(getUnixTime(new Date()));
}, refreshRate);

return () => clearInterval(interval);
}, [refreshRate]);

return now;
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.