mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-28 16:27:07 +03:00
Show Frigate+ rate limits in the UI
Tell the user Frigate+ is rate limiting requests, and how long to wait when the server said, instead of a generic failure: - submitting a tracked object or false positive (explore and the review dialog), a frame from the player, or a frame from tracking details - validating the API key in Frigate+ settings - the Frigate+ model list in detection model settings and the setup wizard The frame upload from the player also showed failures with a success toast, and since axios rejects on error statuses it never reached that branch at all, so failed uploads showed nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
34658593a7
commit
d4f6a9fd91
@@ -342,4 +342,37 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
|
|||||||
dialog.getByRole("button", { name: "Yes", exact: true }),
|
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a rate limited submission says how long to wait", async ({
|
||||||
|
frigateApp,
|
||||||
|
}) => {
|
||||||
|
await frigateApp.installDefaults({ config: { plus: { enabled: true } } });
|
||||||
|
const page = frigateApp.page;
|
||||||
|
await page.route("**/api/events/*/plus", (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 429,
|
||||||
|
headers: { "Retry-After": "90" },
|
||||||
|
json: { success: false, retry_after: 90 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await frigateApp.goto("/explore?labels=person");
|
||||||
|
|
||||||
|
const firstResult = page.locator("[data-start]").first();
|
||||||
|
await expect(firstResult).toBeVisible({ timeout: 10_000 });
|
||||||
|
await firstResult.click();
|
||||||
|
|
||||||
|
const dialog = page.getByRole("dialog");
|
||||||
|
await dialog.getByRole("button", { name: "Yes", exact: true }).click();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByText(
|
||||||
|
"Frigate+ is rate limiting requests. Try again in 1 minute, 30 seconds.",
|
||||||
|
),
|
||||||
|
).toBeVisible();
|
||||||
|
// the object can be submitted again once the wait is over
|
||||||
|
await expect(
|
||||||
|
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -459,6 +459,36 @@ test.describe("Detection models settings @high", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a Frigate+ rate limit says how long to wait", async ({
|
||||||
|
frigateApp,
|
||||||
|
}) => {
|
||||||
|
await installRoutes(
|
||||||
|
frigateApp.page,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
scene: "default",
|
||||||
|
devices: ["openvino:GPU.0"],
|
||||||
|
path: "plus://abc123",
|
||||||
|
plus: PLUS_MODEL,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
// registered last, so it takes precedence over the models route above
|
||||||
|
await frigateApp.page.route("**/api/plus/models", (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 429,
|
||||||
|
headers: { "Retry-After": "120" },
|
||||||
|
json: { success: false, retry_after: 120 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await openPage(frigateApp);
|
||||||
|
|
||||||
|
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
|
||||||
|
"Frigate+ is rate limiting requests. Try again in 2 minutes.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
||||||
frigateApp,
|
frigateApp,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -327,6 +327,10 @@
|
|||||||
"copyDetails": "Copy details",
|
"copyDetails": "Copy details",
|
||||||
"copyFailed": "Could not copy details to clipboard"
|
"copyFailed": "Could not copy details to clipboard"
|
||||||
},
|
},
|
||||||
|
"plusRateLimited": {
|
||||||
|
"retryIn": "Frigate+ is rate limiting requests. Try again in {{duration}}.",
|
||||||
|
"retryLater": "Frigate+ is rate limiting requests. Try again later."
|
||||||
|
},
|
||||||
"selectItem": "Select {{item}}",
|
"selectItem": "Select {{item}}",
|
||||||
"readTheDocumentation": "Read the documentation",
|
"readTheDocumentation": "Read the documentation",
|
||||||
"information": {
|
"information": {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { Switch } from "@/components/ui/switch";
|
|||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||||
import { describeSupportedDetectors } from "@/utils/plusModels";
|
import { describeSupportedDetectors } from "@/utils/plusModels";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
export type FrigatePlusModel = {
|
export type FrigatePlusModel = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -65,9 +66,14 @@ export function ModelSourcePicker({
|
|||||||
// metadata of whatever model was saved before it
|
// metadata of whatever model was saved before it
|
||||||
const selectedId = plusModelId(path) ?? plus?.id;
|
const selectedId = plusModelId(path) ?? plus?.id;
|
||||||
|
|
||||||
const { data: availableModels, isLoading } = useSWR<
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
Record<string, FrigatePlusModel>
|
const {
|
||||||
>(plusEnabled ? "/plus/models" : null, {
|
data: availableModels,
|
||||||
|
error: modelsError,
|
||||||
|
isLoading,
|
||||||
|
} = useSWR<Record<string, FrigatePlusModel>>(
|
||||||
|
plusEnabled ? "/plus/models" : null,
|
||||||
|
{
|
||||||
fetcher: async (url) => {
|
fetcher: async (url) => {
|
||||||
const res = await axios.get(url, { withCredentials: true });
|
const res = await axios.get(url, { withCredentials: true });
|
||||||
return res.data.reduce(
|
return res.data.reduce(
|
||||||
@@ -78,7 +84,8 @@ export function ModelSourcePicker({
|
|||||||
{},
|
{},
|
||||||
);
|
);
|
||||||
},
|
},
|
||||||
});
|
},
|
||||||
|
);
|
||||||
|
|
||||||
const [showIncompatible, setShowIncompatible] = useState(false);
|
const [showIncompatible, setShowIncompatible] = useState(false);
|
||||||
const showIncompatibleId = useId();
|
const showIncompatibleId = useId();
|
||||||
@@ -101,6 +108,7 @@ export function ModelSourcePicker({
|
|||||||
const isCompatible = (model: FrigatePlusModel) =>
|
const isCompatible = (model: FrigatePlusModel) =>
|
||||||
!detector || model.supportedDetectors.includes(detector);
|
!detector || model.supportedDetectors.includes(detector);
|
||||||
|
|
||||||
|
const rateLimitMessage = getRateLimitMessage(modelsError);
|
||||||
const allEntries = Object.entries(availableModels ?? {});
|
const allEntries = Object.entries(availableModels ?? {});
|
||||||
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
|
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
|
||||||
|
|
||||||
@@ -163,7 +171,8 @@ export function ModelSourcePicker({
|
|||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
{entries.length === 0 ? (
|
{entries.length === 0 ? (
|
||||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
{rateLimitMessage ??
|
||||||
|
t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
entries.map(([id, model]) => (
|
entries.map(([id, model]) => (
|
||||||
@@ -184,6 +193,9 @@ export function ModelSourcePicker({
|
|||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
{rateLimitMessage && (
|
||||||
|
<p className="text-xs text-danger">{rateLimitMessage}</p>
|
||||||
|
)}
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
|
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
|
|||||||
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
|
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
|
||||||
import { Trans, useTranslation } from "react-i18next";
|
import { Trans, useTranslation } from "react-i18next";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import { getTranslatedLabel } from "@/utils/i18n";
|
import { getTranslatedLabel } from "@/utils/i18n";
|
||||||
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
||||||
import { DialogPortal } from "@radix-ui/react-dialog";
|
import { DialogPortal } from "@radix-ui/react-dialog";
|
||||||
@@ -699,6 +700,7 @@ function ObjectDetailsTab({
|
|||||||
"views/faceLibrary",
|
"views/faceLibrary",
|
||||||
"components/dialog",
|
"components/dialog",
|
||||||
]);
|
]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
|
|
||||||
const apiHost = useApiHost();
|
const apiHost = useApiHost();
|
||||||
const hasCustomClassificationModels = useMemo(
|
const hasCustomClassificationModels = useMemo(
|
||||||
@@ -1286,7 +1288,7 @@ function ObjectDetailsTab({
|
|||||||
revalidate: false,
|
revalidate: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch {
|
} catch (error) {
|
||||||
if (displayedIdRef.current === eventId) {
|
if (displayedIdRef.current === eventId) {
|
||||||
setState("reviewing");
|
setState("reviewing");
|
||||||
}
|
}
|
||||||
@@ -1294,12 +1296,13 @@ function ObjectDetailsTab({
|
|||||||
// the toast is not object specific, so it is always shown to avoid
|
// the toast is not object specific, so it is always shown to avoid
|
||||||
// silently dropping a failed submission
|
// silently dropping a failed submission
|
||||||
toast.error(
|
toast.error(
|
||||||
|
getRateLimitMessage(error) ??
|
||||||
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
||||||
{ position: "top-center" },
|
{ position: "top-center" },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[search, mutate, mapSearchResults, isEventsKey, t],
|
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ import { useApiHost } from "@/api";
|
|||||||
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
|
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
|
||||||
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import { VideoResolutionType } from "@/types/live";
|
import { VideoResolutionType } from "@/types/live";
|
||||||
import { VodManifest } from "@/types/playback";
|
import { VodManifest } from "@/types/playback";
|
||||||
|
|
||||||
@@ -934,6 +935,7 @@ function LifecycleIconRow({
|
|||||||
annotationOffset,
|
annotationOffset,
|
||||||
}: LifecycleIconRowProps) {
|
}: LifecycleIconRowProps) {
|
||||||
const { t } = useTranslation(["views/explore", "components/player"]);
|
const { t } = useTranslation(["views/explore", "components/player"]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
const { data: config } = useSWR<FrigateConfig>("config");
|
const { data: config } = useSWR<FrigateConfig>("config");
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
|
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
|
||||||
@@ -1251,8 +1253,9 @@ function LifecycleIconRow({
|
|||||||
position: "top-center",
|
position: "top-center",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch {
|
} catch (error) {
|
||||||
toast.error(
|
toast.error(
|
||||||
|
getRateLimitMessage(error) ??
|
||||||
t("toast.error.submitFrigatePlusFailed", {
|
t("toast.error.submitFrigatePlusFailed", {
|
||||||
ns: "components/player",
|
ns: "components/player",
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { baseUrl } from "@/api/baseUrl";
|
|||||||
import { getTranslatedLabel } from "@/utils/i18n";
|
import { getTranslatedLabel } from "@/utils/i18n";
|
||||||
import useImageLoaded from "@/hooks/use-image-loaded";
|
import useImageLoaded from "@/hooks/use-image-loaded";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
export type FrigatePlusDialogProps = {
|
export type FrigatePlusDialogProps = {
|
||||||
upload?: Event;
|
upload?: Event;
|
||||||
@@ -37,6 +38,7 @@ export function FrigatePlusDialog({
|
|||||||
onEventUploaded,
|
onEventUploaded,
|
||||||
}: FrigatePlusDialogProps) {
|
}: FrigatePlusDialogProps) {
|
||||||
const { t, i18n } = useTranslation(["components/dialog"]);
|
const { t, i18n } = useTranslation(["components/dialog"]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
|
|
||||||
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
||||||
const [state, setState] = useState<SubmissionState>(
|
const [state, setState] = useState<SubmissionState>(
|
||||||
@@ -63,14 +65,15 @@ export function FrigatePlusDialog({
|
|||||||
|
|
||||||
setState("submitted");
|
setState("submitted");
|
||||||
onEventUploaded();
|
onEventUploaded();
|
||||||
} catch {
|
} catch (error) {
|
||||||
setState("reviewing");
|
setState("reviewing");
|
||||||
toast.error(t("explore.plus.review.toast.error"), {
|
toast.error(
|
||||||
position: "top-center",
|
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
|
||||||
});
|
{ position: "top-center" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[upload, onEventUploaded, t],
|
[upload, onEventUploaded, t, getRateLimitMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { ASPECT_VERTICAL_LAYOUT, RecordingPlayerError } from "@/types/record";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
|
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
// Android native hls does not seek correctly
|
// Android native hls does not seek correctly
|
||||||
const USE_NATIVE_HLS = false;
|
const USE_NATIVE_HLS = false;
|
||||||
@@ -109,6 +110,7 @@ export default function HlsVideoPlayer({
|
|||||||
transformedOverlay,
|
transformedOverlay,
|
||||||
}: HlsVideoPlayerProps) {
|
}: HlsVideoPlayerProps) {
|
||||||
const { t } = useTranslation("components/player");
|
const { t } = useTranslation("components/player");
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
const { data: config } = useSWR<FrigateConfig>("config");
|
const { data: config } = useSWR<FrigateConfig>("config");
|
||||||
const isAdmin = useIsAdmin();
|
const isAdmin = useIsAdmin();
|
||||||
|
|
||||||
@@ -525,18 +527,26 @@ export default function HlsVideoPlayer({
|
|||||||
onUploadFrame={async () => {
|
onUploadFrame={async () => {
|
||||||
const frameTime = getVideoTime();
|
const frameTime = getVideoTime();
|
||||||
|
|
||||||
if (frameTime && onUploadFrame) {
|
if (!frameTime || !onUploadFrame) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const resp = await onUploadFrame(frameTime);
|
const resp = await onUploadFrame(frameTime);
|
||||||
|
|
||||||
if (resp && resp.status == 200) {
|
if (resp?.status !== 200) {
|
||||||
|
throw new Error();
|
||||||
|
}
|
||||||
|
|
||||||
toast.success(t("toast.success.submittedFrigatePlus"), {
|
toast.success(t("toast.success.submittedFrigatePlus"), {
|
||||||
position: "top-center",
|
position: "top-center",
|
||||||
});
|
});
|
||||||
} else {
|
} catch (error) {
|
||||||
toast.success(t("toast.error.submitFrigatePlusFailed"), {
|
toast.error(
|
||||||
position: "top-center",
|
getRateLimitMessage(error) ??
|
||||||
});
|
t("toast.error.submitFrigatePlusFailed"),
|
||||||
}
|
{ position: "top-center" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
onSnapshot={onSnapshot ? handleSnapshot : undefined}
|
onSnapshot={onSnapshot ? handleSnapshot : undefined}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||||
import type { DetectionHardware } from "@/types/hardware";
|
import type { DetectionHardware } from "@/types/hardware";
|
||||||
import { recommendedDetectorCount } from "@/utils/detectionHardware";
|
import { recommendedDetectorCount } from "@/utils/detectionHardware";
|
||||||
@@ -79,15 +80,16 @@ export default function SetupDetector({
|
|||||||
|
|
||||||
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
||||||
|
|
||||||
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
plusEnabled && needsModel ? "/plus/models" : null,
|
const { data: plusModels, error: plusModelsError } = useSWR<
|
||||||
{
|
FrigatePlusModel[]
|
||||||
|
>(plusEnabled && needsModel ? "/plus/models" : null, {
|
||||||
fetcher: async (url) => {
|
fetcher: async (url) => {
|
||||||
const res = await axios.get(url, { withCredentials: true });
|
const res = await axios.get(url, { withCredentials: true });
|
||||||
return res.data;
|
return res.data;
|
||||||
},
|
},
|
||||||
},
|
});
|
||||||
);
|
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
|
||||||
const [plusModelId, setPlusModelId] = useState("");
|
const [plusModelId, setPlusModelId] = useState("");
|
||||||
|
|
||||||
const compatiblePlusModels = useMemo(
|
const compatiblePlusModels = useMemo(
|
||||||
@@ -217,6 +219,9 @@ export default function SetupDetector({
|
|||||||
<p>
|
<p>
|
||||||
{t("setupWizard.detector.modelRequired", { name: selected.name })}
|
{t("setupWizard.detector.modelRequired", { name: selected.name })}
|
||||||
</p>
|
</p>
|
||||||
|
{plusEnabled && plusRateLimitMessage && (
|
||||||
|
<p className="text-danger">{plusRateLimitMessage}</p>
|
||||||
|
)}
|
||||||
{plusEnabled ? (
|
{plusEnabled ? (
|
||||||
<Select value={plusModelId} onValueChange={setPlusModelId}>
|
<Select value={plusModelId} onValueChange={setPlusModelId}>
|
||||||
<SelectTrigger className="max-w-xs">
|
<SelectTrigger className="max-w-xs">
|
||||||
|
|||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDateLocale } from "@/hooks/use-date-locale";
|
||||||
|
import { formatSecondsToDuration } from "@/utils/dateUtil";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The wait Frigate+ asked for when a request failed because of its rate limit.
|
||||||
|
*
|
||||||
|
* @returns the seconds to wait, null when rate limited without a known wait,
|
||||||
|
* or undefined when the error is not a rate limit
|
||||||
|
*/
|
||||||
|
export function getPlusRetryAfter(error: unknown): number | null | undefined {
|
||||||
|
if (!axios.isAxiosError(error) || error.response?.status !== 429) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const retryAfter = error.response.data?.retry_after;
|
||||||
|
return typeof retryAfter === "number" ? retryAfter : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Messages telling the user Frigate+ is rate limiting requests. */
|
||||||
|
export function usePlusRateLimit() {
|
||||||
|
const { t } = useTranslation(["common"]);
|
||||||
|
const dateLocale = useDateLocale();
|
||||||
|
|
||||||
|
const formatRateLimit = useCallback(
|
||||||
|
(retryAfter: number | null | undefined) =>
|
||||||
|
retryAfter && retryAfter > 0
|
||||||
|
? t("plusRateLimited.retryIn", {
|
||||||
|
ns: "common",
|
||||||
|
duration: formatSecondsToDuration(retryAfter, dateLocale),
|
||||||
|
})
|
||||||
|
: t("plusRateLimited.retryLater", { ns: "common" }),
|
||||||
|
[t, dateLocale],
|
||||||
|
);
|
||||||
|
|
||||||
|
// undefined when the error is not a rate limit, so callers can fall back
|
||||||
|
// to their own error message
|
||||||
|
const getRateLimitMessage = useCallback(
|
||||||
|
(error: unknown) => {
|
||||||
|
const retryAfter = getPlusRetryAfter(error);
|
||||||
|
return retryAfter === undefined ? undefined : formatRateLimit(retryAfter);
|
||||||
|
},
|
||||||
|
[formatRateLimit],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { formatRateLimit, getRateLimitMessage };
|
||||||
|
}
|
||||||
@@ -20,10 +20,17 @@ import { isReplayCamera } from "@/utils/cameraUtil";
|
|||||||
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
|
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
|
||||||
import { getPrimaryModel } from "@/utils/modelUtil";
|
import { getPrimaryModel } from "@/utils/modelUtil";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
|
type PlusKeyStatus =
|
||||||
|
"valid" | "invalid" | "unreachable" | "rate_limited" | "not_set";
|
||||||
|
|
||||||
type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
|
type PlusValidateResponse = {
|
||||||
|
success: boolean;
|
||||||
|
status: PlusKeyStatus;
|
||||||
|
// seconds until Frigate+ accepts requests again, when rate limited
|
||||||
|
retry_after?: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||||
const { t } = useTranslation("views/settings");
|
const { t } = useTranslation("views/settings");
|
||||||
@@ -34,6 +41,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
|
|
||||||
const [isValidating, setIsValidating] = useState(false);
|
const [isValidating, setIsValidating] = useState(false);
|
||||||
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
|
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
|
||||||
|
const [retryAfter, setRetryAfter] = useState<number | null>(null);
|
||||||
|
const { formatRateLimit } = usePlusRateLimit();
|
||||||
|
|
||||||
const validateKey = useCallback(async () => {
|
const validateKey = useCallback(async () => {
|
||||||
setIsValidating(true);
|
setIsValidating(true);
|
||||||
@@ -41,6 +50,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
try {
|
try {
|
||||||
const response = await axios.post<PlusValidateResponse>("plus/validate");
|
const response = await axios.post<PlusValidateResponse>("plus/validate");
|
||||||
setKeyStatus(response.data.status);
|
setKeyStatus(response.data.status);
|
||||||
|
setRetryAfter(response.data.retry_after ?? null);
|
||||||
} catch {
|
} catch {
|
||||||
setKeyStatus("unreachable");
|
setKeyStatus("unreachable");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -124,7 +134,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{keyStatus === "valid" ? (
|
{keyStatus === "valid" ? (
|
||||||
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
|
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
|
||||||
) : keyStatus === "unreachable" ? (
|
) : keyStatus === "unreachable" ||
|
||||||
|
keyStatus === "rate_limited" ? (
|
||||||
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
|
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
|
||||||
) : (
|
) : (
|
||||||
<XCircle className="size-5 shrink-0 text-red-500" />
|
<XCircle className="size-5 shrink-0 text-red-500" />
|
||||||
@@ -134,6 +145,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
? t("frigatePlus.apiKey.serverValid")
|
? t("frigatePlus.apiKey.serverValid")
|
||||||
: keyStatus === "unreachable"
|
: keyStatus === "unreachable"
|
||||||
? t("frigatePlus.apiKey.serverUnreachable")
|
? t("frigatePlus.apiKey.serverUnreachable")
|
||||||
|
: keyStatus === "rate_limited"
|
||||||
|
? formatRateLimit(retryAfter)
|
||||||
: t("frigatePlus.apiKey.serverInvalid")}
|
: t("frigatePlus.apiKey.serverInvalid")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in New Issue
Block a user