mirror of
https://github.com/fosrl/pangolin.git
synced 2026-07-30 17:25:43 +02:00
♻️ Batch certificate queries
This commit is contained in:
+73
-106
@@ -1,18 +1,17 @@
|
||||
"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 { useQuery } from "@tanstack/react-query";
|
||||
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;
|
||||
@@ -23,135 +22,103 @@ type UseCertificateReturn = {
|
||||
certLoading: boolean;
|
||||
certError: string | null;
|
||||
refreshing: boolean;
|
||||
fetchCert: (showLoading?: boolean) => Promise<void>;
|
||||
fetchCert: () => Promise<void>;
|
||||
refreshCert: () => Promise<void>;
|
||||
// clearCert: () => void;
|
||||
};
|
||||
|
||||
const POLL_JITTER_MS = durationToMs(1, "seconds");
|
||||
|
||||
export function useCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
fullDomain,
|
||||
initialCertValue = null,
|
||||
autoFetch = true,
|
||||
initialCertValue,
|
||||
polling = false,
|
||||
pollingInterval = 5000
|
||||
}: UseCertificateProps): UseCertificateReturn {
|
||||
const api = createApiClient(useEnvContext());
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// const [cert, setCert] = useState<GetCertificateResponse | null>(
|
||||
// initialCertValue
|
||||
// );
|
||||
// const [certLoading, setCertLoading] = useState(false);
|
||||
const [certError, setCertError] = useState<string | null>(null);
|
||||
const [refreshing, setRefreshing] = useState(false);
|
||||
|
||||
const query = useQuery({
|
||||
...domainQueries.getCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
domain: fullDomain
|
||||
}),
|
||||
initialData: initialCertValue
|
||||
const certQuery = domainQueries.getCertificate({
|
||||
orgId,
|
||||
domainId,
|
||||
domain: fullDomain
|
||||
});
|
||||
|
||||
// const fetchCert = useCallback(
|
||||
// async (showLoading = true) => {
|
||||
// if (!orgId || !domainId || !fullDomain) return;
|
||||
const { data, isLoading, isError, refetch } = useQuery({
|
||||
...certQuery,
|
||||
enabled: Boolean(orgId && domainId && fullDomain),
|
||||
// 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.
|
||||
refetchInterval: polling
|
||||
? () =>
|
||||
Math.max(
|
||||
1000,
|
||||
Math.round(
|
||||
pollingInterval +
|
||||
(Math.random() * 2 - 1) * POLL_JITTER_MS
|
||||
)
|
||||
)
|
||||
: false,
|
||||
// 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 })
|
||||
});
|
||||
|
||||
// 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);
|
||||
// }
|
||||
// }
|
||||
// },
|
||||
// [api, orgId, domainId, fullDomain]
|
||||
// );
|
||||
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: query.data,
|
||||
certLoading: query.isLoading,
|
||||
cert,
|
||||
certLoading: isLoading,
|
||||
certError,
|
||||
refreshing,
|
||||
fetchCert: query.refetch,
|
||||
refreshing: restartCert.isPending,
|
||||
fetchCert,
|
||||
refreshCert
|
||||
// clearCert
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user