mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 22:37:08 +03:00
Plus rate limit handling (#25075)
* Raise a rate limit error when Frigate+ returns 429 The shared session's urllib3 Retry honored Retry-After by default, so a 429 on a GET or PUT blocked the calling thread for up to ten times the requested wait (and fell back to exponential backoff for Retry-After: 0) before failing with a generic error. Stop honoring Retry-After in urllib3 and raise PlusRateLimitError with the parsed wait instead. Retry-After is parsed as either delay-seconds or an HTTP date per RFC 9110. While the wait is in effect, further requests are refused locally rather than sent to Frigate+ again. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Don't save a failed Frigate+ model download as the model The model download never checked the response status, so an error body (a 429 from the download host, for example) was written to the model cache. Only the file's existence is checked on later starts, so the error page was loaded as the model from then on. Raise a config error instead of writing the file, and explain a Frigate+ rate limit at startup with how long to wait when it is known. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Report a rate limited Frigate+ key validation A 429 while validating the API key was reported as "unreachable". Add a rate_limited status that records the Retry-After wait, skip asking the server again while that wait is in effect, and include the remaining seconds in the /plus/validate response. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Return 429 from the API when Frigate+ is rate limiting Submitting an event, frame, or false positive reported a rate limit as a generic 400 upload error, and listing models failed with a 500. Return a 429 with the wait in retry_after and the Retry-After header so the UI can tell the user how long to wait. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * 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> * Let a failed Frigate+ annotation be retried send_to_plus saved plus_id as soon as the image uploaded, so when the annotation then failed (a rate limit, for example) every retry was refused with "Already submitted to plus" and the image stayed without its annotation. Keep the uploaded image id in the event's data until the annotation succeeds, and only then set plus_id. A retry reuses that image instead of uploading it again, and since plus_id is still unset the UI already offers the retry. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the longest Frigate+ wait when replies overlap Requests to Frigate+ run on several threads. When two were refused at once, a reply with a shorter Retry-After that was handled last replaced the longer wait, so requests were sent again before Frigate+ allowed it. Only move the deadline later, under a lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Include days in Frigate+ rate limit waits formatSecondsToDuration only formats hours, minutes and seconds, so a wait of a day or more lost its days: 90000 seconds read as "1 hour". Format the wait from whole days down instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Keep the Frigate+ rate limit lock out of the client The config holds the Frigate+ client and is pickled to start worker processes from the forkserver. The lock added to PlusApi can't be pickled, so worker startup failed with "cannot pickle '_thread.lock' object", with or without a Frigate+ key. Use a module level lock instead. Rate limit state is per process, so one lock per process is all that's needed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: frigate-agents[bot] <356735177+frigate-agents[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
frigate-agents[bot] <356735177+frigate-agents[bot]@users.noreply.github.com>
Claude Opus 5.5
parent
f45fae1ef5
commit
2b4b1fdb8e
@@ -14,6 +14,7 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||
import { describeSupportedDetectors } from "@/utils/plusModels";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
|
||||
export type FrigatePlusModel = {
|
||||
id: string;
|
||||
@@ -65,20 +66,26 @@ export function ModelSourcePicker({
|
||||
// metadata of whatever model was saved before it
|
||||
const selectedId = plusModelId(path) ?? plus?.id;
|
||||
|
||||
const { data: availableModels, isLoading } = useSWR<
|
||||
Record<string, FrigatePlusModel>
|
||||
>(plusEnabled ? "/plus/models" : null, {
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data.reduce(
|
||||
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
|
||||
obj[model.id] = model;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
const {
|
||||
data: availableModels,
|
||||
error: modelsError,
|
||||
isLoading,
|
||||
} = useSWR<Record<string, FrigatePlusModel>>(
|
||||
plusEnabled ? "/plus/models" : null,
|
||||
{
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data.reduce(
|
||||
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
|
||||
obj[model.id] = model;
|
||||
return obj;
|
||||
},
|
||||
{},
|
||||
);
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
|
||||
const [showIncompatible, setShowIncompatible] = useState(false);
|
||||
const showIncompatibleId = useId();
|
||||
@@ -101,6 +108,7 @@ export function ModelSourcePicker({
|
||||
const isCompatible = (model: FrigatePlusModel) =>
|
||||
!detector || model.supportedDetectors.includes(detector);
|
||||
|
||||
const rateLimitMessage = getRateLimitMessage(modelsError);
|
||||
const allEntries = Object.entries(availableModels ?? {});
|
||||
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
|
||||
|
||||
@@ -163,7 +171,8 @@ export function ModelSourcePicker({
|
||||
<SelectGroup>
|
||||
{entries.length === 0 ? (
|
||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
{rateLimitMessage ??
|
||||
t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
</div>
|
||||
) : (
|
||||
entries.map(([id, model]) => (
|
||||
@@ -184,6 +193,9 @@ export function ModelSourcePicker({
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{rateLimitMessage && (
|
||||
<p className="text-xs text-danger">{rateLimitMessage}</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
|
||||
</p>
|
||||
|
||||
@@ -87,6 +87,7 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
|
||||
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
|
||||
import { Trans, useTranslation } from "react-i18next";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
import { getTranslatedLabel } from "@/utils/i18n";
|
||||
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
||||
import { DialogPortal } from "@radix-ui/react-dialog";
|
||||
@@ -699,6 +700,7 @@ function ObjectDetailsTab({
|
||||
"views/faceLibrary",
|
||||
"components/dialog",
|
||||
]);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
|
||||
const apiHost = useApiHost();
|
||||
const hasCustomClassificationModels = useMemo(
|
||||
@@ -1286,7 +1288,7 @@ function ObjectDetailsTab({
|
||||
revalidate: false,
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (displayedIdRef.current === eventId) {
|
||||
setState("reviewing");
|
||||
}
|
||||
@@ -1294,12 +1296,13 @@ function ObjectDetailsTab({
|
||||
// the toast is not object specific, so it is always shown to avoid
|
||||
// silently dropping a failed submission
|
||||
toast.error(
|
||||
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
||||
getRateLimitMessage(error) ??
|
||||
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
}
|
||||
},
|
||||
[search, mutate, mapSearchResults, isEventsKey, t],
|
||||
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
|
||||
);
|
||||
|
||||
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
@@ -54,6 +54,7 @@ import { useApiHost } from "@/api";
|
||||
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
|
||||
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
import { VideoResolutionType } from "@/types/live";
|
||||
import { VodManifest } from "@/types/playback";
|
||||
|
||||
@@ -934,6 +935,7 @@ function LifecycleIconRow({
|
||||
annotationOffset,
|
||||
}: LifecycleIconRowProps) {
|
||||
const { t } = useTranslation(["views/explore", "components/player"]);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
|
||||
@@ -1251,11 +1253,12 @@ function LifecycleIconRow({
|
||||
position: "top-center",
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
t("toast.error.submitFrigatePlusFailed", {
|
||||
ns: "components/player",
|
||||
}),
|
||||
getRateLimitMessage(error) ??
|
||||
t("toast.error.submitFrigatePlusFailed", {
|
||||
ns: "components/player",
|
||||
}),
|
||||
{
|
||||
position: "top-center",
|
||||
},
|
||||
|
||||
@@ -22,6 +22,7 @@ import { baseUrl } from "@/api/baseUrl";
|
||||
import { getTranslatedLabel } from "@/utils/i18n";
|
||||
import useImageLoaded from "@/hooks/use-image-loaded";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
|
||||
export type FrigatePlusDialogProps = {
|
||||
upload?: Event;
|
||||
@@ -37,6 +38,7 @@ export function FrigatePlusDialog({
|
||||
onEventUploaded,
|
||||
}: FrigatePlusDialogProps) {
|
||||
const { t, i18n } = useTranslation(["components/dialog"]);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
|
||||
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
||||
const [state, setState] = useState<SubmissionState>(
|
||||
@@ -63,14 +65,15 @@ export function FrigatePlusDialog({
|
||||
|
||||
setState("submitted");
|
||||
onEventUploaded();
|
||||
} catch {
|
||||
} catch (error) {
|
||||
setState("reviewing");
|
||||
toast.error(t("explore.plus.review.toast.error"), {
|
||||
position: "top-center",
|
||||
});
|
||||
toast.error(
|
||||
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
}
|
||||
},
|
||||
[upload, onEventUploaded, t],
|
||||
[upload, onEventUploaded, t, getRateLimitMessage],
|
||||
);
|
||||
|
||||
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
||||
|
||||
@@ -22,6 +22,7 @@ import { ASPECT_VERTICAL_LAYOUT, RecordingPlayerError } from "@/types/record";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
|
||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
|
||||
// Android native hls does not seek correctly
|
||||
const USE_NATIVE_HLS = false;
|
||||
@@ -109,6 +110,7 @@ export default function HlsVideoPlayer({
|
||||
transformedOverlay,
|
||||
}: HlsVideoPlayerProps) {
|
||||
const { t } = useTranslation("components/player");
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const isAdmin = useIsAdmin();
|
||||
|
||||
@@ -525,18 +527,26 @@ export default function HlsVideoPlayer({
|
||||
onUploadFrame={async () => {
|
||||
const frameTime = getVideoTime();
|
||||
|
||||
if (frameTime && onUploadFrame) {
|
||||
if (!frameTime || !onUploadFrame) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await onUploadFrame(frameTime);
|
||||
|
||||
if (resp && resp.status == 200) {
|
||||
toast.success(t("toast.success.submittedFrigatePlus"), {
|
||||
position: "top-center",
|
||||
});
|
||||
} else {
|
||||
toast.success(t("toast.error.submitFrigatePlusFailed"), {
|
||||
position: "top-center",
|
||||
});
|
||||
if (resp?.status !== 200) {
|
||||
throw new Error();
|
||||
}
|
||||
|
||||
toast.success(t("toast.success.submittedFrigatePlus"), {
|
||||
position: "top-center",
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error(
|
||||
getRateLimitMessage(error) ??
|
||||
t("toast.error.submitFrigatePlusFailed"),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
}
|
||||
}}
|
||||
onSnapshot={onSnapshot ? handleSnapshot : undefined}
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||
import type { DetectionHardware } from "@/types/hardware";
|
||||
import { recommendedDetectorCount } from "@/utils/detectionHardware";
|
||||
@@ -79,15 +80,16 @@ export default function SetupDetector({
|
||||
|
||||
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
||||
|
||||
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
|
||||
plusEnabled && needsModel ? "/plus/models" : null,
|
||||
{
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data;
|
||||
},
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
const { data: plusModels, error: plusModelsError } = useSWR<
|
||||
FrigatePlusModel[]
|
||||
>(plusEnabled && needsModel ? "/plus/models" : null, {
|
||||
fetcher: async (url) => {
|
||||
const res = await axios.get(url, { withCredentials: true });
|
||||
return res.data;
|
||||
},
|
||||
);
|
||||
});
|
||||
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
|
||||
const [plusModelId, setPlusModelId] = useState("");
|
||||
|
||||
const compatiblePlusModels = useMemo(
|
||||
@@ -217,6 +219,9 @@ export default function SetupDetector({
|
||||
<p>
|
||||
{t("setupWizard.detector.modelRequired", { name: selected.name })}
|
||||
</p>
|
||||
{plusEnabled && plusRateLimitMessage && (
|
||||
<p className="text-danger">{plusRateLimitMessage}</p>
|
||||
)}
|
||||
{plusEnabled ? (
|
||||
<Select value={plusModelId} onValueChange={setPlusModelId}>
|
||||
<SelectTrigger className="max-w-xs">
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import axios from "axios";
|
||||
import { formatDuration, Locale } from "date-fns";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDateLocale } from "@/hooks/use-date-locale";
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* A wait in seconds as a readable duration, such as "1 day, 1 hour".
|
||||
*
|
||||
* Waits can last days, so the days are kept rather than folded away or
|
||||
* turned into calendar months.
|
||||
*/
|
||||
export function formatPlusWait(seconds: number, locale?: Locale): string {
|
||||
const total = Math.ceil(seconds);
|
||||
|
||||
return formatDuration(
|
||||
{
|
||||
days: Math.floor(total / 86400),
|
||||
hours: Math.floor((total % 86400) / 3600),
|
||||
minutes: Math.floor((total % 3600) / 60),
|
||||
seconds: total % 60,
|
||||
},
|
||||
{ delimiter: ", ", locale },
|
||||
);
|
||||
}
|
||||
|
||||
/** 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: formatPlusWait(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 { getPrimaryModel } from "@/utils/modelUtil";
|
||||
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) {
|
||||
const { t } = useTranslation("views/settings");
|
||||
@@ -34,6 +41,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
|
||||
const [isValidating, setIsValidating] = useState(false);
|
||||
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
|
||||
const [retryAfter, setRetryAfter] = useState<number | null>(null);
|
||||
const { formatRateLimit } = usePlusRateLimit();
|
||||
|
||||
const validateKey = useCallback(async () => {
|
||||
setIsValidating(true);
|
||||
@@ -41,6 +50,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
try {
|
||||
const response = await axios.post<PlusValidateResponse>("plus/validate");
|
||||
setKeyStatus(response.data.status);
|
||||
setRetryAfter(response.data.retry_after ?? null);
|
||||
} catch {
|
||||
setKeyStatus("unreachable");
|
||||
} finally {
|
||||
@@ -124,7 +134,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
<div className="flex items-center gap-2">
|
||||
{keyStatus === "valid" ? (
|
||||
<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" />
|
||||
) : (
|
||||
<XCircle className="size-5 shrink-0 text-red-500" />
|
||||
@@ -134,7 +145,9 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
? t("frigatePlus.apiKey.serverValid")
|
||||
: keyStatus === "unreachable"
|
||||
? t("frigatePlus.apiKey.serverUnreachable")
|
||||
: t("frigatePlus.apiKey.serverInvalid")}
|
||||
: keyStatus === "rate_limited"
|
||||
? formatRateLimit(retryAfter)
|
||||
: t("frigatePlus.apiKey.serverInvalid")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user