Merge pull request #3469 from fosrl/refactor/batch-status-requests

refactor: batch status histories
This commit is contained in:
Milo Schwartz
2026-07-29 17:27:11 -04:00
committed by GitHub
29 changed files with 1122 additions and 215 deletions
+80 -96
View File
@@ -1,18 +1,20 @@
"use client";
import { useState, useCallback, useEffect } from "react";
import { AxiosResponse } from "axios";
import { useCallback } from "react";
import { GetCertificateResponse } from "@server/routers/certificates/types";
import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { domainQueries } from "@app/lib/queries";
import { durationToMs } from "@app/lib/durationToMs";
type UseCertificateProps = {
orgId: string;
domainId: string;
fullDomain: string;
autoFetch?: boolean;
polling?: boolean;
pollingInterval?: number;
initialCertValue?: GetCertificateResponse | null;
};
type UseCertificateReturn = {
@@ -20,124 +22,106 @@ type UseCertificateReturn = {
certLoading: boolean;
certError: string | null;
refreshing: boolean;
fetchCert: (showLoading?: boolean) => Promise<void>;
fetchCert: () => Promise<void>;
refreshCert: () => Promise<void>;
clearCert: () => void;
// clearCert: () => void;
};
const POLL_JITTER_MS = durationToMs(1, "seconds");
/** A valid cert isn't going anywhere soon, so check on it far less often. */
const VALID_POLL_INTERVAL_MS = durationToMs(30, "seconds");
export function useCertificate({
orgId,
domainId,
fullDomain,
autoFetch = true,
initialCertValue,
polling = false,
pollingInterval = 5000
pollingInterval = durationToMs(5, "seconds")
}: UseCertificateProps): UseCertificateReturn {
const api = createApiClient(useEnvContext());
const queryClient = useQueryClient();
const [cert, setCert] = useState<GetCertificateResponse | null>(null);
const [certLoading, setCertLoading] = useState(false);
const [certError, setCertError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const certQuery = domainQueries.getCertificate({
orgId,
domainId,
domain: fullDomain
});
const fetchCert = useCallback(
async (showLoading = true) => {
if (!orgId || !domainId || !fullDomain) return;
if (showLoading) {
setCertLoading(true);
}
try {
const res = await api.get<
AxiosResponse<GetCertificateResponse>
>(`/org/${orgId}/certificate/${domainId}/${fullDomain}`);
const certData = res.data.data;
if (certData) {
setCertError(null);
setCert(certData);
}
} catch (error: any) {
console.error("Failed to fetch certificate:", error);
setCertError("Failed");
} finally {
if (showLoading) {
setCertLoading(false);
}
}
const { data, isLoading, isError, refetch } = useQuery({
...certQuery,
enabled: Boolean(orgId && domainId && fullDomain),
refetchInterval: (query) => {
if (!polling) return false;
const interval =
query.state.data?.status === "valid"
? VALID_POLL_INTERVAL_MS
: pollingInterval;
// Add a small random offset to each tick. Without it, every row in
// a table would poll at the exact same instant, hitting the server
// in bursts instead of spreading the requests out.
// the requests will be jittered by less or more than 1s
const jitter = (Math.random() * 2 - 1) * POLL_JITTER_MS;
return Math.max(1000, interval + jitter);
},
[api, orgId, domainId, fullDomain]
);
// An explicit `null` is a real answer ("this domain has no certificate")
// and is seeded like any other, so a server-prefetched row doesn't
// refetch on mount. Only an omitted prop leaves the cache empty.
...(initialCertValue !== undefined && { initialData: initialCertValue })
});
const cert = data ?? null;
const restartCert = useMutation({
mutationFn: async (certId: number) => {
await api.post(`/org/${orgId}/certificate/${certId}/restart`, {});
},
onSuccess: () => {
// the backend flips the status asynchronously; reflect it optimistically
setTimeout(() => {
queryClient.setQueryData(certQuery.queryKey, (prev) =>
prev ? { ...prev, status: "pending" } : prev
);
}, 500);
},
onError: (error) => {
console.error("Failed to restart certificate:", error);
}
});
const fetchCert = useCallback(async () => {
await refetch();
}, [refetch]);
const { mutateAsync: restartCertAsync } = restartCert;
const refreshCert = useCallback(async () => {
if (!cert) return;
setRefreshing(true);
setCertError(null);
try {
await api.post(
`/org/${orgId}/certificate/${cert.certId}/restart`,
{}
);
// Update status to pending
setTimeout(() => {
setCert({ ...cert, status: "pending" });
}, 500);
} catch (error: any) {
console.error("Failed to restart certificate:", error);
setCertError("Failed to restart");
} finally {
setRefreshing(false);
await restartCertAsync(cert.certId);
} catch {
// surfaced through certError
}
}, [api, orgId, cert]);
}, [cert, restartCertAsync]);
const clearCert = useCallback(() => {
setCert(null);
setCertError(null);
}, []);
// const clearCert = useCallback(() => {
// queryClient.removeQueries({ queryKey: certQuery.queryKey });
// }, [queryClient, certQuery.queryKey]);
// Auto-fetch on mount if enabled
useEffect(() => {
if (autoFetch && orgId && domainId && fullDomain) {
fetchCert();
}
}, [autoFetch, orgId, domainId, fullDomain, fetchCert]);
useEffect(() => {
if (!polling || !orgId || !domainId || !fullDomain) return;
const POLL_JITTER_MS = 1000;
let cancelled = false;
let timeoutId: ReturnType<typeof setTimeout>;
const scheduleNext = () => {
const jitter = (Math.random() * 2 - 1) * POLL_JITTER_MS;
const delayMs = Math.max(
1000,
Math.round(pollingInterval + jitter)
);
timeoutId = setTimeout(() => {
if (cancelled) return;
void fetchCert(false);
scheduleNext();
}, delayMs);
};
scheduleNext();
return () => {
cancelled = true;
clearTimeout(timeoutId);
};
}, [polling, orgId, domainId, fullDomain, pollingInterval, fetchCert]);
let certError: string | null = null;
if (restartCert.isError) {
certError = "Failed to restart";
} else if (isError) {
certError = "Failed";
}
return {
cert,
certLoading,
certLoading: isLoading,
certError,
refreshing,
refreshing: restartCert.isPending,
fetchCert,
refreshCert,
clearCert
refreshCert
// clearCert
};
}