From 34658593a793bd0e28e2aa832c056913d3fd250e Mon Sep 17 00:00:00 2001 From: "frigate-agents[bot]" <356735177+frigate-agents[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:44:14 +0000 Subject: [PATCH] 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 --- frigate/api/app.py | 8 ++- frigate/api/event.py | 8 +++ frigate/api/media.py | 11 +++- frigate/api/plus_util.py | 31 ++++++++++ frigate/test/http_api/test_http_media.py | 20 +++++++ frigate/test/http_api/test_http_plus.py | 75 +++++++++++++++++++++++- 6 files changed, 147 insertions(+), 6 deletions(-) create mode 100644 frigate/api/plus_util.py diff --git a/frigate/api/app.py b/frigate/api/app.py index b57e3ad8c0..5486b5a360 100644 --- a/frigate/api/app.py +++ b/frigate/api/app.py @@ -40,6 +40,7 @@ from frigate.api.defs.request.app_body import ( MediaSyncBody, ) from frigate.api.defs.tags import Tags +from frigate.api.plus_util import plus_rate_limited_response from frigate.config import FrigateConfig, GenAIConfig, GenAIProviderEnum from frigate.config.camera.updater import ( CameraConfigUpdateEnum, @@ -54,7 +55,7 @@ from frigate.jobs.media_sync import ( start_media_sync_job, ) from frigate.models import Event, Timeline -from frigate.plus import PlusKeyStatus, load_plus_model_info +from frigate.plus import PlusKeyStatus, PlusRateLimitError, load_plus_model_info from frigate.stats.prometheus import get_metrics, update_metrics from frigate.types import JobStatusTypesEnum from frigate.util.builtin import ( @@ -1654,7 +1655,10 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False): status_code=400, ) - models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models() + try: + models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models() + except PlusRateLimitError as err: + return plus_rate_limited_response(err) if not models["list"]: return JSONResponse( diff --git a/frigate/api/event.py b/frigate/api/event.py index 011c6b887b..78ea890d6f 100644 --- a/frigate/api/event.py +++ b/frigate/api/event.py @@ -53,11 +53,13 @@ from frigate.api.defs.response.event_response import ( ) from frigate.api.defs.response.generic_response import GenericResponse from frigate.api.defs.tags import Tags +from frigate.api.plus_util import plus_rate_limited_response from frigate.comms.event_metadata_updater import EventMetadataTypeEnum from frigate.config.classification import ObjectClassificationType from frigate.const import CLIPS_DIR from frigate.embeddings import EmbeddingsContext from frigate.models import Event, ReviewSegment, Timeline, Trigger +from frigate.plus import PlusRateLimitError from frigate.track.object_processing import TrackedObject from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image from frigate.util.path import get_trigger_thumbnail_path, safe_join @@ -1139,6 +1141,8 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N plus_id = await asyncio.to_thread( request.app.frigate_config.plus_api.upload_image, image, event.camera ) + except PlusRateLimitError as err: + return plus_rate_limited_response(err) except Exception as ex: logger.exception(ex) return JSONResponse( @@ -1160,6 +1164,8 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N box, event.label, ) + except PlusRateLimitError as err: + return plus_rate_limited_response(err) except ValueError: message = "Error uploading annotation, unsupported label provided." logger.error(message) @@ -1256,6 +1262,8 @@ async def false_positive(request: Request, event_id: str): event.model_type, event.detector_type, ) + except PlusRateLimitError as err: + return plus_rate_limited_response(err) except ValueError: message = "Error uploading false positive, unsupported label provided." logger.error(message) diff --git a/frigate/api/media.py b/frigate/api/media.py index bc0257cafc..6bd54af78e 100644 --- a/frigate/api/media.py +++ b/frigate/api/media.py @@ -36,6 +36,7 @@ from frigate.api.defs.query.media_query_parameters import ( MediaMjpegFeedQueryParams, ) from frigate.api.defs.tags import Tags +from frigate.api.plus_util import plus_rate_limited_response from frigate.camera.state import CameraState from frigate.config import FrigateConfig from frigate.config.camera.snapshots import SnapshotsConfig @@ -48,6 +49,7 @@ from frigate.const import ( ) from frigate.models import Event, Previews, Recordings, Regions, ReviewSegment from frigate.output.preview import get_most_recent_preview_frame +from frigate.plus import PlusRateLimitError from frigate.track.object_processing import TrackedObjectProcessor from frigate.util.ffmpeg import terminate_ffmpeg_stream from frigate.util.file import ( @@ -476,9 +478,12 @@ async def submit_recording_snapshot_to_plus( ) nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR) - await asyncio.to_thread( - request.app.frigate_config.plus_api.upload_image, nd, camera_name - ) + try: + await asyncio.to_thread( + request.app.frigate_config.plus_api.upload_image, nd, camera_name + ) + except PlusRateLimitError as err: + return plus_rate_limited_response(err) return JSONResponse( content={ diff --git a/frigate/api/plus_util.py b/frigate/api/plus_util.py new file mode 100644 index 0000000000..cdcc9067dc --- /dev/null +++ b/frigate/api/plus_util.py @@ -0,0 +1,31 @@ +"""Shared responses for endpoints that call Frigate+.""" + +from fastapi.responses import JSONResponse + +from frigate.plus import PlusRateLimitError + + +def plus_rate_limited_response(err: PlusRateLimitError) -> JSONResponse: + """Tell the client Frigate+ is rate limiting requests and how long to wait. + + Args: + err: The rate limit raised by the Frigate+ client + + Returns: + A 429 response with the wait in retry_after (and the Retry-After + header) when Frigate+ provided one + """ + headers = None + + if err.retry_after is not None: + headers = {"Retry-After": str(err.retry_after)} + + return JSONResponse( + content={ + "success": False, + "message": "Frigate+ is rate limiting requests, try again later", + "retry_after": err.retry_after, + }, + status_code=429, + headers=headers, + ) diff --git a/frigate/test/http_api/test_http_media.py b/frigate/test/http_api/test_http_media.py index 59ae5e2f70..0b989c3306 100644 --- a/frigate/test/http_api/test_http_media.py +++ b/frigate/test/http_api/test_http_media.py @@ -14,6 +14,7 @@ from fastapi import Request from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user from frigate.const import MAX_SEGMENT_DURATION from frigate.models import Event, Recordings +from frigate.plus import PlusRateLimitError from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp @@ -2144,3 +2145,22 @@ class TestHttpMedia(BaseTestHttp): self.assertEqual(response.status_code, 200) upload.assert_called_once_with("frame", "front_door") + + def test_plus_snapshot_rate_limited(self): + self._insert_recording("snapshot", 1000, 1010) + + with ( + AuthTestClient(self.app) as client, + patch("frigate.api.media.get_image_from_recording", return_value=b"png"), + patch("frigate.api.media.cv2.imdecode", return_value="frame"), + patch.object( + self.app.frigate_config.plus_api, + "upload_image", + side_effect=PlusRateLimitError(60), + ), + ): + response = client.post("/front_door/plus/1005") + + self.assertEqual(response.status_code, 429) + self.assertEqual(response.json()["retry_after"], 60) + self.assertEqual(response.headers["Retry-After"], "60") diff --git a/frigate/test/http_api/test_http_plus.py b/frigate/test/http_api/test_http_plus.py index 31f23c114e..eb40f22511 100644 --- a/frigate/test/http_api/test_http_plus.py +++ b/frigate/test/http_api/test_http_plus.py @@ -3,8 +3,10 @@ import unittest from unittest.mock import patch +import numpy as np + from frigate.models import Event -from frigate.plus import PlusKeyStatus +from frigate.plus import PlusKeyStatus, PlusRateLimitError from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp @@ -55,5 +57,76 @@ class TestHttpPlusValidate(BaseTestHttp): self.assertEqual(response.status_code, 403) +class TestHttpPlusRateLimit(BaseTestHttp): + """A Frigate+ rate limit reaches the client as a 429 with the wait.""" + + def setUp(self): + super().setUp([Event]) + self.app = self.create_app() + self.plus_api = self.app.frigate_config.plus_api + patcher = patch.object(self.plus_api, "is_active", return_value=True) + patcher.start() + self.addCleanup(patcher.stop) + + def _assert_rate_limited(self, response, retry_after: int | None) -> None: + self.assertEqual(response.status_code, 429) + self.assertEqual(response.json()["retry_after"], retry_after) + self.assertFalse(response.json()["success"]) + self.assertEqual( + response.headers.get("Retry-After"), + None if retry_after is None else str(retry_after), + ) + + def test_listing_models(self): + for retry_after in (30, None): + with ( + self.subTest(retry_after=retry_after), + patch.object( + self.plus_api, + "get_models", + side_effect=PlusRateLimitError(retry_after), + ), + AuthTestClient(self.app) as client, + ): + self._assert_rate_limited(client.get("/plus/models"), retry_after) + + def test_submitting_an_event(self): + self.insert_mock_event("event", data={"box": [0, 0, 1, 1]}) + + with ( + patch( + "frigate.api.event.load_event_snapshot_image", + return_value=(np.ones((10, 10, 3), np.uint8), True), + ), + patch.object( + self.plus_api, "upload_image", side_effect=PlusRateLimitError(30) + ), + AuthTestClient(self.app) as client, + ): + response = client.post("/events/event/plus", json={}) + + self._assert_rate_limited(response, 30) + self.assertIsNone(Event.get(Event.id == "event").plus_id) + + def test_submitting_a_false_positive(self): + self.insert_mock_event( + "event", data={"box": [0, 0, 1, 1], "region": [0, 0, 1, 1], "score": 0.9} + ) + Event.update(plus_id="plus").where(Event.id == "event").execute() + + with ( + patch.object( + self.plus_api, + "add_false_positive", + side_effect=PlusRateLimitError(45), + ), + AuthTestClient(self.app) as client, + ): + response = client.put("/events/event/false_positive") + + self._assert_rate_limited(response, 45) + self.assertFalse(Event.get(Event.id == "event").false_positive) + + if __name__ == "__main__": unittest.main(verbosity=2)