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>
This commit is contained in:
frigate-agents[bot]
2026-11-23 23:18:29 +00:00
co-authored by Claude Opus 5.5
parent f6d2a1a15e
commit 34658593a7
6 changed files with 147 additions and 6 deletions
+6 -2
View File
@@ -40,6 +40,7 @@ from frigate.api.defs.request.app_body import (
MediaSyncBody, MediaSyncBody,
) )
from frigate.api.defs.tags import Tags 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 import FrigateConfig, GenAIConfig, GenAIProviderEnum
from frigate.config.camera.updater import ( from frigate.config.camera.updater import (
CameraConfigUpdateEnum, CameraConfigUpdateEnum,
@@ -54,7 +55,7 @@ from frigate.jobs.media_sync import (
start_media_sync_job, start_media_sync_job,
) )
from frigate.models import Event, Timeline 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.stats.prometheus import get_metrics, update_metrics
from frigate.types import JobStatusTypesEnum from frigate.types import JobStatusTypesEnum
from frigate.util.builtin import ( from frigate.util.builtin import (
@@ -1654,7 +1655,10 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
status_code=400, 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"]: if not models["list"]:
return JSONResponse( return JSONResponse(
+8
View File
@@ -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.response.generic_response import GenericResponse
from frigate.api.defs.tags import Tags 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.comms.event_metadata_updater import EventMetadataTypeEnum
from frigate.config.classification import ObjectClassificationType from frigate.config.classification import ObjectClassificationType
from frigate.const import CLIPS_DIR from frigate.const import CLIPS_DIR
from frigate.embeddings import EmbeddingsContext from frigate.embeddings import EmbeddingsContext
from frigate.models import Event, ReviewSegment, Timeline, Trigger from frigate.models import Event, ReviewSegment, Timeline, Trigger
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObject from frigate.track.object_processing import TrackedObject
from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image from frigate.util.file import get_event_thumbnail_bytes, load_event_snapshot_image
from frigate.util.path import get_trigger_thumbnail_path, safe_join 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( plus_id = await asyncio.to_thread(
request.app.frigate_config.plus_api.upload_image, image, event.camera 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: except Exception as ex:
logger.exception(ex) logger.exception(ex)
return JSONResponse( return JSONResponse(
@@ -1160,6 +1164,8 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
box, box,
event.label, event.label,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading annotation, unsupported label provided." message = "Error uploading annotation, unsupported label provided."
logger.error(message) logger.error(message)
@@ -1256,6 +1262,8 @@ async def false_positive(request: Request, event_id: str):
event.model_type, event.model_type,
event.detector_type, event.detector_type,
) )
except PlusRateLimitError as err:
return plus_rate_limited_response(err)
except ValueError: except ValueError:
message = "Error uploading false positive, unsupported label provided." message = "Error uploading false positive, unsupported label provided."
logger.error(message) logger.error(message)
+8 -3
View File
@@ -36,6 +36,7 @@ from frigate.api.defs.query.media_query_parameters import (
MediaMjpegFeedQueryParams, MediaMjpegFeedQueryParams,
) )
from frigate.api.defs.tags import Tags 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.camera.state import CameraState
from frigate.config import FrigateConfig from frigate.config import FrigateConfig
from frigate.config.camera.snapshots import SnapshotsConfig 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.models import Event, Previews, Recordings, Regions, ReviewSegment
from frigate.output.preview import get_most_recent_preview_frame from frigate.output.preview import get_most_recent_preview_frame
from frigate.plus import PlusRateLimitError
from frigate.track.object_processing import TrackedObjectProcessor from frigate.track.object_processing import TrackedObjectProcessor
from frigate.util.ffmpeg import terminate_ffmpeg_stream from frigate.util.ffmpeg import terminate_ffmpeg_stream
from frigate.util.file import ( 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) nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
await asyncio.to_thread( try:
request.app.frigate_config.plus_api.upload_image, nd, camera_name 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( return JSONResponse(
content={ content={
+31
View File
@@ -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,
)
+20
View File
@@ -14,6 +14,7 @@ from fastapi import Request
from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user from frigate.api.auth import get_allowed_cameras_for_filter, get_current_user
from frigate.const import MAX_SEGMENT_DURATION from frigate.const import MAX_SEGMENT_DURATION
from frigate.models import Event, Recordings from frigate.models import Event, Recordings
from frigate.plus import PlusRateLimitError
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -2144,3 +2145,22 @@ class TestHttpMedia(BaseTestHttp):
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
upload.assert_called_once_with("frame", "front_door") 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")
+74 -1
View File
@@ -3,8 +3,10 @@
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
import numpy as np
from frigate.models import Event 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 from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
@@ -55,5 +57,76 @@ class TestHttpPlusValidate(BaseTestHttp):
self.assertEqual(response.status_code, 403) 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__": if __name__ == "__main__":
unittest.main(verbosity=2) unittest.main(verbosity=2)