mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 06:17:12 +03:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8934b19484 |
+6
-16
@@ -40,7 +40,6 @@ 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,
|
||||
@@ -55,7 +54,7 @@ from frigate.jobs.media_sync import (
|
||||
start_media_sync_job,
|
||||
)
|
||||
from frigate.models import Event, Timeline
|
||||
from frigate.plus import PlusKeyStatus, PlusRateLimitError, load_plus_model_info
|
||||
from frigate.plus import PlusKeyStatus, load_plus_model_info
|
||||
from frigate.stats.prometheus import get_metrics, update_metrics
|
||||
from frigate.types import JobStatusTypesEnum
|
||||
from frigate.util.builtin import (
|
||||
@@ -1655,10 +1654,7 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
||||
status_code=400,
|
||||
)
|
||||
|
||||
try:
|
||||
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
|
||||
except PlusRateLimitError as err:
|
||||
return plus_rate_limited_response(err)
|
||||
models: dict[Any, Any] = request.app.frigate_config.plus_api.get_models()
|
||||
|
||||
if not models["list"]:
|
||||
return JSONResponse(
|
||||
@@ -1698,17 +1694,11 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
||||
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
||||
async def validate_plus_key(request: Request):
|
||||
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
||||
plus_api = request.app.frigate_config.plus_api
|
||||
status = await plus_api.validate_key()
|
||||
content: dict[str, Any] = {
|
||||
"success": status == PlusKeyStatus.valid,
|
||||
"status": status.value,
|
||||
}
|
||||
status = await request.app.frigate_config.plus_api.validate_key()
|
||||
|
||||
if status == PlusKeyStatus.rate_limited:
|
||||
content["retry_after"] = plus_api.rate_limit_remaining()
|
||||
|
||||
return JSONResponse(content=content)
|
||||
return JSONResponse(
|
||||
content={"success": status == PlusKeyStatus.valid, "status": status.value}
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
|
||||
@@ -41,6 +41,9 @@ def swap_runtime_config(app: FastAPI, config: FrigateConfig) -> None:
|
||||
"""
|
||||
app.frigate_config = config
|
||||
|
||||
if app.replay_manager is not None:
|
||||
app.replay_manager.update_config(config)
|
||||
|
||||
if app.config_holder is not None:
|
||||
app.config_holder.set(config)
|
||||
|
||||
|
||||
@@ -53,13 +53,11 @@ 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
|
||||
@@ -1141,8 +1139,6 @@ 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(
|
||||
@@ -1164,8 +1160,6 @@ 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)
|
||||
@@ -1262,8 +1256,6 @@ 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)
|
||||
|
||||
@@ -88,7 +88,7 @@ def create_fastapi_app(
|
||||
logger.info("FastAPI started")
|
||||
asyncio.create_task(
|
||||
debug_replay_auto_stop_watchdog(
|
||||
replay_manager, frigate_config, config_publisher
|
||||
replay_manager, lambda: app.frigate_config, config_publisher
|
||||
)
|
||||
)
|
||||
yield
|
||||
|
||||
@@ -36,7 +36,6 @@ 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
|
||||
@@ -49,7 +48,6 @@ 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 (
|
||||
@@ -478,12 +476,9 @@ async def submit_recording_snapshot_to_plus(
|
||||
)
|
||||
|
||||
nd = cv2.imdecode(np.frombuffer(image_data, dtype=np.int8), cv2.IMREAD_COLOR)
|
||||
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)
|
||||
await asyncio.to_thread(
|
||||
request.app.frigate_config.plus_api.upload_image, nd, camera_name
|
||||
)
|
||||
|
||||
return JSONResponse(
|
||||
content={
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
"""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,
|
||||
)
|
||||
+31
-14
@@ -11,10 +11,11 @@ import os
|
||||
import shutil
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
|
||||
from ruamel.yaml import YAML
|
||||
|
||||
from frigate.config import FrigateConfig
|
||||
from frigate.config import CameraConfig, FrigateConfig
|
||||
from frigate.config.camera.updater import (
|
||||
CameraConfigUpdateEnum,
|
||||
CameraConfigUpdatePublisher,
|
||||
@@ -61,6 +62,7 @@ class DebugReplayManager:
|
||||
self.start_ts: float | None = None
|
||||
self.end_ts: float | None = None
|
||||
self.session_started_at: float | None = None
|
||||
self._published_camera: CameraConfig | None = None
|
||||
self._job_state_publisher = JobStatePublisher()
|
||||
|
||||
@property
|
||||
@@ -109,6 +111,13 @@ class DebugReplayManager:
|
||||
self.start_ts = None
|
||||
self.end_ts = None
|
||||
self.session_started_at = None
|
||||
self._published_camera = None
|
||||
|
||||
def update_config(self, config: FrigateConfig) -> None:
|
||||
"""Carry the published replay camera into a newly swapped-in config."""
|
||||
with self._lock:
|
||||
if self._published_camera is not None and self.replay_camera_name:
|
||||
config.cameras[self.replay_camera_name] = self._published_camera
|
||||
|
||||
def publish_camera(
|
||||
self,
|
||||
@@ -117,10 +126,11 @@ class DebugReplayManager:
|
||||
clip_path: str,
|
||||
frigate_config: FrigateConfig,
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> None:
|
||||
) -> bool:
|
||||
"""Build the in-memory replay camera config and publish the add event.
|
||||
|
||||
Called by the job runner during the starting_camera phase.
|
||||
Called by the job runner during the starting_camera phase. Returns
|
||||
False without publishing if the session was stopped meanwhile.
|
||||
"""
|
||||
source_config = frigate_config.cameras[source_camera]
|
||||
camera_dict = self._build_camera_config_dict(
|
||||
@@ -140,12 +150,21 @@ class DebugReplayManager:
|
||||
new_config = FrigateConfig.parse_object(config_data)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to validate replay camera config: {e}") from e
|
||||
frigate_config.cameras[replay_name] = new_config.cameras[replay_name]
|
||||
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||
new_config.cameras[replay_name],
|
||||
)
|
||||
camera_config = new_config.cameras[replay_name]
|
||||
|
||||
with self._lock:
|
||||
if self.replay_camera_name != replay_name:
|
||||
return False
|
||||
|
||||
frigate_config.cameras[replay_name] = camera_config
|
||||
self._published_camera = camera_config
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.add, replay_name),
|
||||
camera_config,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def stop(
|
||||
self,
|
||||
@@ -167,12 +186,10 @@ class DebugReplayManager:
|
||||
replay_name = self.replay_camera_name
|
||||
source_camera = self.source_camera
|
||||
|
||||
# Only publish remove if the camera was actually added to the live
|
||||
# config (i.e. the runner reached the starting_camera phase).
|
||||
if replay_name is not None and replay_name in frigate_config.cameras:
|
||||
if replay_name is not None and self._published_camera is not None:
|
||||
config_publisher.publish_update(
|
||||
CameraConfigUpdateTopic(CameraConfigUpdateEnum.remove, replay_name),
|
||||
frigate_config.cameras[replay_name],
|
||||
self._published_camera,
|
||||
)
|
||||
frigate_config.cameras.pop(replay_name, None)
|
||||
|
||||
@@ -362,7 +379,7 @@ def cleanup_replay_cameras() -> None:
|
||||
|
||||
async def debug_replay_auto_stop_watchdog(
|
||||
manager: DebugReplayManager,
|
||||
frigate_config: FrigateConfig,
|
||||
get_config: Callable[[], FrigateConfig],
|
||||
config_publisher: CameraConfigUpdatePublisher,
|
||||
) -> None:
|
||||
"""Auto-stop debug replay sessions that exceed MAX_SESSION_DURATION_SECONDS.
|
||||
@@ -384,7 +401,7 @@ async def debug_replay_auto_stop_watchdog(
|
||||
replay_name = manager.replay_camera_name
|
||||
await asyncio.to_thread(
|
||||
manager.stop,
|
||||
frigate_config=frigate_config,
|
||||
frigate_config=get_config(),
|
||||
config_publisher=config_publisher,
|
||||
)
|
||||
logger.info(
|
||||
|
||||
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
from pydantic.fields import PrivateAttr
|
||||
|
||||
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
|
||||
from frigate.plus import PlusApi, PlusRateLimitError, load_plus_model_info
|
||||
from frigate.plus import PlusApi, load_plus_model_info
|
||||
from frigate.util.builtin import generate_color_palette, load_labels
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -52,16 +52,6 @@ DEFAULT_SCENE = "default"
|
||||
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
|
||||
|
||||
|
||||
def _rate_limited_message(model_id: str, err: PlusRateLimitError) -> str:
|
||||
"""Explain a rate limited Frigate+ model download, with the wait if known."""
|
||||
message = f"Frigate+ is rate limiting requests, unable to download model {model_id}"
|
||||
|
||||
if err.retry_after is not None:
|
||||
return f"{message}. Try again in {err.retry_after} seconds"
|
||||
|
||||
return f"{message}. Try again later"
|
||||
|
||||
|
||||
class ModelConfig(BaseModel):
|
||||
scene: str = Field(
|
||||
default=DEFAULT_SCENE,
|
||||
@@ -203,16 +193,6 @@ class ModelConfig(BaseModel):
|
||||
raise ValueError(
|
||||
f"Unable to connect to Frigate+ to download model {model_id}"
|
||||
) from e
|
||||
except PlusRateLimitError as e:
|
||||
raise ValueError(_rate_limited_message(model_id, e)) from e
|
||||
|
||||
# an error body written here would be mistaken for the model on
|
||||
# every later start, since only the file's existence is checked
|
||||
if not r.ok:
|
||||
raise ValueError(
|
||||
f"Unable to download model {model_id} from Frigate+ "
|
||||
f"(HTTP {r.status_code})"
|
||||
)
|
||||
|
||||
with open(self.path, "wb") as f:
|
||||
f.write(r.content)
|
||||
@@ -225,8 +205,6 @@ class ModelConfig(BaseModel):
|
||||
raise ValueError(
|
||||
f"Unable to connect to Frigate+ to download model info for {model_id}"
|
||||
) from e
|
||||
except PlusRateLimitError as e:
|
||||
raise ValueError(_rate_limited_message(model_id, e)) from e
|
||||
|
||||
with open(model_info_path, "w") as f:
|
||||
json.dump(model_info, f)
|
||||
|
||||
@@ -376,13 +376,16 @@ class DebugReplayJobRunner(threading.Thread):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
self.replay_manager.publish_camera(
|
||||
if not self.replay_manager.publish_camera(
|
||||
source_camera=self.job.source_camera,
|
||||
replay_name=replay_name,
|
||||
clip_path=clip_path,
|
||||
frigate_config=self.frigate_config,
|
||||
config_publisher=self.config_publisher,
|
||||
)
|
||||
):
|
||||
self._finalize_cancelled(clip_path)
|
||||
return
|
||||
|
||||
self.replay_manager.mark_session_ready(clip_path)
|
||||
|
||||
self.job.status = JobStatusTypesEnum.success
|
||||
|
||||
@@ -487,6 +487,9 @@ def get_export_job_manager(config: FrigateConfig) -> ExportJobManager:
|
||||
with _job_manager_lock:
|
||||
if _job_manager is None:
|
||||
_job_manager = ExportJobManager(config, _get_max_concurrent(config))
|
||||
|
||||
# callers pass the live config, which a save replaces
|
||||
_job_manager.config = config
|
||||
_job_manager.ensure_started()
|
||||
return _job_manager
|
||||
|
||||
|
||||
+14
-10
@@ -789,16 +789,16 @@ class BirdsEyeFrameManager:
|
||||
force_update = True
|
||||
else:
|
||||
return False, False
|
||||
else:
|
||||
# update the last active frame for the camera
|
||||
camera_state["current_frame"] = frame.copy()
|
||||
camera_state["current_frame_time"] = frame_time
|
||||
modes = camera_config.birdseye.modes
|
||||
|
||||
# update the last active frame for the camera
|
||||
camera_state["current_frame"] = frame.copy()
|
||||
camera_state["current_frame_time"] = frame_time
|
||||
modes = camera_config.birdseye.modes
|
||||
if self.camera_threshold_active(modes, activity):
|
||||
camera_state["last_active_frame"] = frame_time
|
||||
|
||||
if self.camera_threshold_active(modes, activity):
|
||||
camera_state["last_active_frame"] = frame_time
|
||||
|
||||
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
||||
camera_state["live_active"] = self.camera_live_active(modes, activity)
|
||||
|
||||
# monotonic so a backward wall clock step can't freeze the output
|
||||
now = time.monotonic()
|
||||
@@ -865,7 +865,10 @@ class Birdseye:
|
||||
(1.0 / self.idle_fps) if self.idle_fps > 0 else None
|
||||
)
|
||||
|
||||
if config.birdseye.restream:
|
||||
# restream changes need a restart, so the buffer exists only if it did at init
|
||||
self.restream = config.birdseye.restream
|
||||
|
||||
if self.restream:
|
||||
self.birdseye_buffer: Any = self.frame_manager.create(
|
||||
"birdseye",
|
||||
self.birdseye_manager.yuv_shape[0] * self.birdseye_manager.yuv_shape[1],
|
||||
@@ -877,7 +880,7 @@ class Birdseye:
|
||||
def __send_new_frame(self) -> None:
|
||||
frame_bytes = self.birdseye_manager.frame.tobytes()
|
||||
|
||||
if self.config.birdseye.restream:
|
||||
if self.restream:
|
||||
self.birdseye_buffer[:] = frame_bytes
|
||||
|
||||
try:
|
||||
@@ -954,6 +957,7 @@ class Birdseye:
|
||||
>= self._idle_interval
|
||||
):
|
||||
self.__send_new_frame()
|
||||
self.birdseye_manager.last_output_time = now
|
||||
|
||||
def stop(self) -> None:
|
||||
self.review_subscriber.stop()
|
||||
|
||||
+14
-121
@@ -1,11 +1,8 @@
|
||||
import datetime
|
||||
import email.utils
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import Any, TypeGuard
|
||||
@@ -31,7 +28,6 @@ class PlusKeyStatus(str, Enum):
|
||||
valid = "valid"
|
||||
invalid = "invalid"
|
||||
unreachable = "unreachable"
|
||||
rate_limited = "rate_limited"
|
||||
not_set = "not_set"
|
||||
|
||||
|
||||
@@ -74,51 +70,6 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
|
||||
return add_hailo_alias(model_info)
|
||||
|
||||
|
||||
class PlusRateLimitError(Exception):
|
||||
"""Frigate+ rejected a request because too many requests were made."""
|
||||
|
||||
def __init__(self, retry_after: int | None) -> None:
|
||||
self.retry_after = retry_after
|
||||
super().__init__(
|
||||
f"Rate limited by Frigate+, retry in {retry_after} seconds"
|
||||
if retry_after is not None
|
||||
else "Rate limited by Frigate+"
|
||||
)
|
||||
|
||||
|
||||
def parse_retry_after(value: str | None) -> int | None:
|
||||
"""Read the number of seconds to wait from a Retry-After header.
|
||||
|
||||
The header (RFC 9110 section 10.2.3) is either a number of seconds or an
|
||||
HTTP date to retry after.
|
||||
|
||||
Args:
|
||||
value: The raw header value
|
||||
|
||||
Returns:
|
||||
Whole seconds to wait, or None when the header is missing or invalid
|
||||
"""
|
||||
if not value:
|
||||
return None
|
||||
|
||||
value = value.strip()
|
||||
|
||||
if value.isdigit():
|
||||
return int(value)
|
||||
|
||||
try:
|
||||
retry_at = email.utils.parsedate_to_datetime(value)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
# HTTP dates are always GMT, but "-0000" parses as a naive datetime
|
||||
if retry_at.tzinfo is None:
|
||||
retry_at = retry_at.replace(tzinfo=datetime.UTC)
|
||||
|
||||
remaining = (retry_at - datetime.datetime.now(datetime.UTC)).total_seconds()
|
||||
return max(0, math.ceil(remaining))
|
||||
|
||||
|
||||
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
|
||||
if image.shape[1] >= image.shape[0]:
|
||||
width = min(max_dim, image.shape[1])
|
||||
@@ -177,54 +128,14 @@ class PlusApi:
|
||||
|
||||
self._is_active: bool = self.key is not None
|
||||
self._token_data: dict = {}
|
||||
# when Frigate+ last asked us to back off, requests are refused locally
|
||||
# until this time instead of being sent to the server again
|
||||
self._rate_limited_until: float | None = None
|
||||
|
||||
# Retry connection failures so a network that comes up late at startup
|
||||
# doesn't fail the Frigate+ model download. Retry-After is not honored
|
||||
# here, since urllib3 would block the calling thread for as long as the
|
||||
# server asks; a 429 is raised to the caller as PlusRateLimitError.
|
||||
# doesn't fail the Frigate+ model download
|
||||
self._session = requests.Session()
|
||||
self._session.mount(
|
||||
self.host,
|
||||
HTTPAdapter(
|
||||
max_retries=Retry(
|
||||
connect=5, backoff_factor=1, respect_retry_after_header=False
|
||||
)
|
||||
),
|
||||
self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
|
||||
)
|
||||
|
||||
def rate_limit_remaining(self) -> int | None:
|
||||
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
|
||||
if self._rate_limited_until is None:
|
||||
return None
|
||||
|
||||
remaining = math.ceil(self._rate_limited_until - time.time())
|
||||
return remaining if remaining > 0 else None
|
||||
|
||||
def _note_rate_limit(self, retry_after: int | None) -> None:
|
||||
"""Remember how long Frigate+ asked us to wait."""
|
||||
logger.warning(
|
||||
"Frigate+ rate limit reached, retry after %s seconds",
|
||||
retry_after if retry_after is not None else "unknown",
|
||||
)
|
||||
|
||||
if retry_after is not None:
|
||||
self._rate_limited_until = time.time() + retry_after
|
||||
|
||||
def _raise_if_rate_limited(self) -> None:
|
||||
remaining = self.rate_limit_remaining()
|
||||
|
||||
if remaining is not None:
|
||||
raise PlusRateLimitError(remaining)
|
||||
|
||||
def _check_rate_limit(self, r: Response) -> None:
|
||||
if r.status_code == 429:
|
||||
retry_after = parse_retry_after(r.headers.get("Retry-After"))
|
||||
self._note_rate_limit(retry_after)
|
||||
raise PlusRateLimitError(retry_after)
|
||||
|
||||
def _refresh_token_if_needed(self) -> None:
|
||||
if (
|
||||
self._token_data.get("expires") is None
|
||||
@@ -234,12 +145,10 @@ class PlusApi:
|
||||
raise Exception(
|
||||
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
|
||||
)
|
||||
self._raise_if_rate_limited()
|
||||
parts = self.key.split(":")
|
||||
r = self._session.get(
|
||||
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
|
||||
)
|
||||
self._check_rate_limit(r)
|
||||
if not r.ok:
|
||||
raise Exception(f"Unable to refresh API token: {r.text}")
|
||||
self._token_data = r.json()
|
||||
@@ -248,30 +157,24 @@ class PlusApi:
|
||||
self._refresh_token_if_needed()
|
||||
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
|
||||
|
||||
def _request(self, method: str, path: str, data: dict | None = None) -> Response:
|
||||
"""Make an authenticated Frigate+ request.
|
||||
def _get(self, path: str) -> Response:
|
||||
return self._session.get(
|
||||
f"{self.host}/v1/{path}", headers=self._get_authorization_header()
|
||||
)
|
||||
|
||||
Raises:
|
||||
PlusRateLimitError: Frigate+ is rate limiting requests
|
||||
"""
|
||||
self._raise_if_rate_limited()
|
||||
r = self._session.request(
|
||||
method,
|
||||
def _post(self, path: str, data: dict) -> Response:
|
||||
return self._session.post(
|
||||
f"{self.host}/v1/{path}",
|
||||
headers=self._get_authorization_header(),
|
||||
json=data,
|
||||
)
|
||||
self._check_rate_limit(r)
|
||||
return r
|
||||
|
||||
def _get(self, path: str) -> Response:
|
||||
return self._request("GET", path)
|
||||
|
||||
def _post(self, path: str, data: dict) -> Response:
|
||||
return self._request("POST", path, data)
|
||||
|
||||
def _put(self, path: str, data: dict) -> Response:
|
||||
return self._request("PUT", path, data)
|
||||
return self._session.put(
|
||||
f"{self.host}/v1/{path}",
|
||||
headers=self._get_authorization_header(),
|
||||
json=data,
|
||||
)
|
||||
|
||||
def is_active(self) -> bool:
|
||||
return self._is_active
|
||||
@@ -284,16 +187,11 @@ class PlusApi:
|
||||
result reflects the key's current state rather than a cached token.
|
||||
|
||||
Returns:
|
||||
The key's status as reported by the Frigate+ server. When it is
|
||||
rate_limited, rate_limit_remaining() gives the wait if known.
|
||||
The key's status as reported by the Frigate+ server
|
||||
"""
|
||||
if self.key is None:
|
||||
return PlusKeyStatus.not_set
|
||||
|
||||
# asking again before the wait is over would only be refused again
|
||||
if self.rate_limit_remaining() is not None:
|
||||
return PlusKeyStatus.rate_limited
|
||||
|
||||
key_id, _, secret = self.key.partition(":")
|
||||
|
||||
# Use a single request with a timeout instead of the retrying session,
|
||||
@@ -309,7 +207,6 @@ class PlusApi:
|
||||
auth=aiohttp.BasicAuth(key_id, secret),
|
||||
) as r:
|
||||
status = r.status
|
||||
retry_after = parse_retry_after(r.headers.get("Retry-After"))
|
||||
token_data = await r.json(content_type=None) if r.ok else None
|
||||
except (aiohttp.ClientError, TimeoutError) as err:
|
||||
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
||||
@@ -321,10 +218,6 @@ class PlusApi:
|
||||
if status in (401, 403):
|
||||
return PlusKeyStatus.invalid
|
||||
|
||||
if status == 429:
|
||||
self._note_rate_limit(retry_after)
|
||||
return PlusKeyStatus.rate_limited
|
||||
|
||||
if status >= 400:
|
||||
logger.warning(
|
||||
"Unexpected response validating Frigate+ API key: %s", status
|
||||
|
||||
@@ -14,7 +14,6 @@ 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
|
||||
|
||||
|
||||
@@ -2145,22 +2144,3 @@ 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")
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from frigate.models import Event
|
||||
from frigate.plus import PlusKeyStatus, PlusRateLimitError
|
||||
from frigate.plus import PlusKeyStatus
|
||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||
|
||||
|
||||
@@ -14,13 +12,11 @@ class TestHttpPlusValidate(BaseTestHttp):
|
||||
def setUp(self):
|
||||
super().setUp([Event])
|
||||
|
||||
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict:
|
||||
def _validate(self, status: PlusKeyStatus) -> dict:
|
||||
app = self.create_app()
|
||||
plus_api = app.frigate_config.plus_api
|
||||
|
||||
with (
|
||||
patch.object(plus_api, "validate_key", return_value=status),
|
||||
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
|
||||
with patch.object(
|
||||
app.frigate_config.plus_api, "validate_key", return_value=status
|
||||
):
|
||||
with AuthTestClient(app) as client:
|
||||
response = client.post("/plus/validate")
|
||||
@@ -39,12 +35,6 @@ class TestHttpPlusValidate(BaseTestHttp):
|
||||
{"success": False, "status": "invalid"},
|
||||
)
|
||||
|
||||
def test_a_rate_limited_key_includes_the_wait(self):
|
||||
self.assertEqual(
|
||||
self._validate(PlusKeyStatus.rate_limited, 90),
|
||||
{"success": False, "status": "rate_limited", "retry_after": 90},
|
||||
)
|
||||
|
||||
def test_viewers_cannot_validate(self):
|
||||
app = self.create_app()
|
||||
|
||||
@@ -57,76 +47,5 @@ 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)
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
import multiprocessing as mp
|
||||
import unittest
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
import numpy as np
|
||||
|
||||
from frigate.config import (
|
||||
BirdseyeModeEnum,
|
||||
@@ -607,6 +609,72 @@ class TestBirdseyeModePayload(unittest.TestCase):
|
||||
assert birdseye_modes_from_mqtt_payload(payload) is None
|
||||
|
||||
|
||||
class TestBirdseyeRuntimeToggles(unittest.TestCase):
|
||||
"""Runtime config changes must not crash or overdrive Birdseye."""
|
||||
|
||||
def setUp(self):
|
||||
config = {
|
||||
"mqtt": {"enabled": False},
|
||||
"birdseye": {"enabled": True, "modes": ["continuous"]},
|
||||
"cameras": {
|
||||
"front": {
|
||||
"ffmpeg": {
|
||||
"inputs": [
|
||||
{"path": "rtsp://10.0.0.1:554/video", "roles": ["detect"]}
|
||||
]
|
||||
},
|
||||
"detect": {"height": 1080, "width": 1920, "fps": 5},
|
||||
}
|
||||
},
|
||||
}
|
||||
self.config = FrigateConfig(**config)
|
||||
self.manager = BirdsEyeFrameManager(self.config, mp.Event())
|
||||
self.frame = np.zeros((1620, 1920), np.uint8)
|
||||
self.activity = BirdseyeActivity(
|
||||
has_object=True, has_motion=True, severity=None
|
||||
)
|
||||
|
||||
def test_disabled_camera_forces_one_update_only(self):
|
||||
self.manager.update("front", self.activity, 1000.0, self.frame)
|
||||
self.config.cameras["front"].birdseye.enabled = False
|
||||
|
||||
changed, _ = self.manager.update("front", self.activity, 1000.2, self.frame)
|
||||
assert changed
|
||||
|
||||
changed, _ = self.manager.update("front", self.activity, 1000.4, self.frame)
|
||||
assert not changed
|
||||
|
||||
def test_enabling_restream_at_runtime_does_not_write_missing_buffer(self):
|
||||
birdseye = Birdseye.__new__(Birdseye)
|
||||
birdseye.restream = False
|
||||
birdseye.config = self.config
|
||||
birdseye.birdseye_manager = self.manager
|
||||
birdseye.input = Mock()
|
||||
self.config.birdseye.restream = True
|
||||
|
||||
birdseye._Birdseye__send_new_frame()
|
||||
|
||||
birdseye.input.put_nowait.assert_called_once()
|
||||
|
||||
def test_idle_heartbeat_waits_a_full_interval_between_sends(self):
|
||||
birdseye = Birdseye.__new__(Birdseye)
|
||||
birdseye.review_severity = {}
|
||||
birdseye.birdseye_manager = Mock()
|
||||
birdseye.birdseye_manager.update.return_value = (False, False)
|
||||
birdseye.birdseye_manager.camera_layout = []
|
||||
birdseye.birdseye_manager.last_output_time = 0.0
|
||||
birdseye._idle_interval = 0.2
|
||||
|
||||
with (
|
||||
patch.object(Birdseye, "_Birdseye__send_new_frame") as send,
|
||||
patch("frigate.output.birdseye.time.monotonic", side_effect=[10.0, 10.1]),
|
||||
):
|
||||
birdseye.write_data("front", [], [], 1.0, Mock())
|
||||
birdseye.write_data("front", [], [], 1.1, Mock())
|
||||
|
||||
assert send.call_count == 1
|
||||
|
||||
|
||||
class TestBirdseyeReviewSeverity(unittest.TestCase):
|
||||
"""Test that review updates drive the per-camera severity map."""
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from copy import deepcopy
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import patch
|
||||
|
||||
import numpy as np
|
||||
import requests
|
||||
@@ -14,7 +14,6 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
|
||||
from frigate.const import MODEL_CACHE_DIR
|
||||
from frigate.detectors import DetectorTypeEnum
|
||||
from frigate.detectors.device import build_detector_config, runner_names
|
||||
from frigate.plus import PlusRateLimitError
|
||||
from frigate.util.builtin import deep_merge
|
||||
from frigate.util.config import resolve_ffmpeg_path
|
||||
|
||||
@@ -1638,51 +1637,6 @@ class TestConfig(unittest.TestCase):
|
||||
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
|
||||
FrigateConfig(**config)
|
||||
|
||||
def _plus_model_config(self, model_id: str) -> dict:
|
||||
return {
|
||||
"mqtt": {"host": "mqtt"},
|
||||
"models": [{"path": f"plus://{model_id}", "devices": ["cpu"]}],
|
||||
"cameras": {
|
||||
"back": {
|
||||
"ffmpeg": {
|
||||
"inputs": [
|
||||
{
|
||||
"path": "rtsp://10.0.0.1:554/video",
|
||||
"roles": ["detect"],
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@patch("frigate.detectors.detector_config.requests.get")
|
||||
@patch(
|
||||
"frigate.plus.PlusApi.get_model_download_url",
|
||||
return_value="https://download.invalid/model",
|
||||
)
|
||||
def test_plus_model_error_response_is_not_saved(self, _, download):
|
||||
model_id = "error_response_model"
|
||||
model_path = os.path.join(MODEL_CACHE_DIR, model_id)
|
||||
download.return_value = MagicMock(ok=False, status_code=429, content=b"busy")
|
||||
|
||||
with self.assertRaisesRegex(ValidationError, r"HTTP 429"):
|
||||
FrigateConfig(**self._plus_model_config(model_id))
|
||||
|
||||
self.assertFalse(os.path.exists(model_path))
|
||||
|
||||
def test_plus_rate_limit_is_validation_error(self):
|
||||
for retry_after, message in ((45, "Try again in 45 seconds"), (None, "later")):
|
||||
with (
|
||||
self.subTest(retry_after=retry_after),
|
||||
patch(
|
||||
"frigate.plus.PlusApi.get_model_download_url",
|
||||
side_effect=PlusRateLimitError(retry_after),
|
||||
),
|
||||
self.assertRaisesRegex(ValidationError, f"rate limiting.*{message}"),
|
||||
):
|
||||
FrigateConfig(**self._plus_model_config("rate_limited_model"))
|
||||
|
||||
def test_fails_on_invalid_role(self):
|
||||
config = {
|
||||
"mqtt": {"host": "mqtt"},
|
||||
|
||||
@@ -24,6 +24,7 @@ class TestSwapRuntimeConfig(unittest.TestCase):
|
||||
|
||||
self.assertIs(app.frigate_config, config)
|
||||
app.genai_manager.update_config.assert_called_once_with(config)
|
||||
app.replay_manager.update_config.assert_called_once_with(config)
|
||||
app.profile_manager.update_config.assert_called_once_with(config)
|
||||
self.assertIs(app.stats_emitter.config, config)
|
||||
app.stats_emitter.hardware_stats.set_config.assert_called_once_with(config)
|
||||
|
||||
@@ -101,6 +101,7 @@ class TestDebugReplayManagerStop(unittest.TestCase):
|
||||
manager.mark_session_ready("/tmp/replay/_replay_front.mp4")
|
||||
|
||||
camera_config = MagicMock()
|
||||
manager._published_camera = camera_config
|
||||
frigate_config = MagicMock()
|
||||
frigate_config.cameras = {"_replay_front": camera_config}
|
||||
publisher = MagicMock()
|
||||
@@ -169,6 +170,7 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
|
||||
source_config = MagicMock()
|
||||
new_camera_config = MagicMock()
|
||||
@@ -246,5 +248,103 @@ class TestDebugReplayManagerPublishCamera(unittest.TestCase):
|
||||
publisher.publish_update.assert_not_called()
|
||||
|
||||
|
||||
class TestDebugReplayManagerLifecycle(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
patcher = patch("frigate.debug_replay.JobStatePublisher")
|
||||
patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
def _publish(self, manager, frigate_config, publisher) -> bool:
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
parsed = MagicMock()
|
||||
parsed.cameras = {"_replay_front": MagicMock(name="replay_camera")}
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
DebugReplayManager,
|
||||
"_build_camera_config_dict",
|
||||
return_value={"enabled": True},
|
||||
),
|
||||
patch("frigate.debug_replay.find_config_file", return_value="/cfg.yml"),
|
||||
patch("frigate.debug_replay.YAML") as yaml_cls,
|
||||
patch(
|
||||
"frigate.debug_replay.FrigateConfig.parse_object",
|
||||
return_value=parsed,
|
||||
),
|
||||
patch("builtins.open", unittest.mock.mock_open(read_data="cameras:\n")),
|
||||
):
|
||||
yaml_cls.return_value.load.return_value = {"cameras": {}}
|
||||
return manager.publish_camera(
|
||||
source_camera="front",
|
||||
replay_name="_replay_front",
|
||||
clip_path="/tmp/clip.mp4",
|
||||
frigate_config=frigate_config,
|
||||
config_publisher=publisher,
|
||||
)
|
||||
|
||||
def _config(self, name: str) -> MagicMock:
|
||||
config = MagicMock(name=name)
|
||||
config.cameras = {"front": MagicMock()}
|
||||
return config
|
||||
|
||||
def _stop(self, manager, frigate_config, publisher) -> None:
|
||||
with (
|
||||
patch.object(manager, "_cleanup_db"),
|
||||
patch.object(manager, "_cleanup_files"),
|
||||
patch("frigate.debug_replay.cancel_debug_replay_job", return_value=False),
|
||||
):
|
||||
manager.stop(frigate_config=frigate_config, config_publisher=publisher)
|
||||
|
||||
def test_publish_after_stop_is_skipped(self) -> None:
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
config = self._config("live")
|
||||
publisher = MagicMock()
|
||||
|
||||
self._stop(manager, config, publisher)
|
||||
|
||||
self.assertFalse(self._publish(manager, config, publisher))
|
||||
self.assertNotIn("_replay_front", config.cameras)
|
||||
publisher.publish_update.assert_not_called()
|
||||
|
||||
def test_config_swap_keeps_replay_camera_and_stop_removes_it(self) -> None:
|
||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
boot = self._config("boot")
|
||||
publisher = MagicMock()
|
||||
self.assertTrue(self._publish(manager, boot, publisher))
|
||||
|
||||
swapped = self._config("swapped")
|
||||
manager.update_config(swapped)
|
||||
self.assertIn("_replay_front", swapped.cameras)
|
||||
|
||||
self._stop(manager, swapped, publisher)
|
||||
|
||||
topic = publisher.publish_update.call_args.args[0]
|
||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
||||
self.assertNotIn("_replay_front", swapped.cameras)
|
||||
|
||||
def test_stop_with_stale_config_still_publishes_remove(self) -> None:
|
||||
from frigate.config.camera.updater import CameraConfigUpdateEnum
|
||||
from frigate.debug_replay import DebugReplayManager
|
||||
|
||||
manager = DebugReplayManager()
|
||||
manager.mark_starting("front", "_replay_front", 100.0, 200.0)
|
||||
live = self._config("live")
|
||||
publisher = MagicMock()
|
||||
self.assertTrue(self._publish(manager, live, publisher))
|
||||
|
||||
self._stop(manager, self._config("stale"), publisher)
|
||||
|
||||
topic = publisher.publish_update.call_args.args[0]
|
||||
self.assertEqual(topic.update_type, CameraConfigUpdateEnum.remove)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -302,7 +302,7 @@ class TestRunnerHappyPath(unittest.TestCase):
|
||||
patch.object(
|
||||
self.manager,
|
||||
"publish_camera",
|
||||
side_effect=lambda *a, **kw: captured.append("published"),
|
||||
side_effect=lambda *a, **kw: captured.append("published") or True,
|
||||
),
|
||||
patch("os.path.exists", return_value=True),
|
||||
patch("os.makedirs"),
|
||||
|
||||
@@ -221,6 +221,24 @@ class TestFfmpegProgressParsing(unittest.TestCase):
|
||||
assert any(abs(p - (30 / 90 * 100)) < 0.01 for p in encoding_percents)
|
||||
|
||||
|
||||
class TestExportJobManagerConfig(unittest.TestCase):
|
||||
def test_manager_follows_the_config_passed_by_callers(self) -> None:
|
||||
import frigate.jobs.export as export_jobs
|
||||
|
||||
boot = MagicMock(name="boot")
|
||||
swapped = MagicMock(name="swapped")
|
||||
|
||||
with (
|
||||
patch.object(export_jobs, "_job_manager", None),
|
||||
patch.object(export_jobs.ExportJobManager, "ensure_started"),
|
||||
patch.object(export_jobs, "_get_max_concurrent", return_value=1),
|
||||
):
|
||||
export_jobs.get_export_job_manager(boot)
|
||||
manager = export_jobs.get_export_job_manager(swapped)
|
||||
|
||||
self.assertIs(manager.config, swapped)
|
||||
|
||||
|
||||
class TestBroadcastAggregation(unittest.TestCase):
|
||||
"""Verify ExportJobManager broadcast payload shape and throttling."""
|
||||
|
||||
|
||||
+4
-178
@@ -1,14 +1,9 @@
|
||||
"""Tests for Frigate+ model metadata."""
|
||||
|
||||
import asyncio
|
||||
import datetime
|
||||
import email.utils
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
@@ -16,16 +11,7 @@ import aiohttp
|
||||
from aiohttp import web
|
||||
from aiohttp.test_utils import TestServer
|
||||
|
||||
from frigate.const import PLUS_ENV_VAR
|
||||
from frigate.plus import (
|
||||
PlusApi,
|
||||
PlusKeyStatus,
|
||||
PlusRateLimitError,
|
||||
load_plus_model_info,
|
||||
parse_retry_after,
|
||||
)
|
||||
|
||||
TEST_PLUS_KEY = f"{'a' * 8}-{'b' * 4}-{'c' * 4}-{'d' * 4}-{'e' * 12}:{'f' * 40}"
|
||||
from frigate.plus import PlusApi, PlusKeyStatus, load_plus_model_info
|
||||
|
||||
|
||||
class TestHailoAlias(unittest.TestCase):
|
||||
@@ -113,26 +99,18 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
||||
api.host = host
|
||||
api.key = key
|
||||
api._token_data = dict(self.CACHED_TOKEN)
|
||||
api._rate_limited_until = None
|
||||
return api
|
||||
|
||||
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
||||
api = self._api(await self._serve(handler))
|
||||
return await api.validate_key(), api
|
||||
|
||||
def _replies(
|
||||
self,
|
||||
status: int = 200,
|
||||
body: object = None,
|
||||
text: str | None = None,
|
||||
headers: dict[str, str] | None = None,
|
||||
):
|
||||
def _replies(self, status: int = 200, body: object = None, text: str | None = None):
|
||||
async def handler(request: web.Request) -> web.Response:
|
||||
self.auth = request.headers.get("Authorization")
|
||||
self.requests_seen = getattr(self, "requests_seen", 0) + 1
|
||||
if text is not None:
|
||||
return web.Response(status=status, text=text, headers=headers)
|
||||
return web.json_response(body, status=status, headers=headers)
|
||||
return web.Response(status=status, text=text)
|
||||
return web.json_response(body, status=status)
|
||||
|
||||
return handler
|
||||
|
||||
@@ -156,25 +134,6 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
||||
|
||||
self.assertEqual(status, PlusKeyStatus.unreachable)
|
||||
|
||||
async def test_a_rate_limited_key_is_not_reported_as_invalid(self):
|
||||
api = self._api(
|
||||
await self._serve(self._replies(429, {}, headers={"Retry-After": "120"}))
|
||||
)
|
||||
|
||||
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
||||
self.assertAlmostEqual(api.rate_limit_remaining(), 120, delta=1)
|
||||
self.assertEqual(api._token_data, self.CACHED_TOKEN)
|
||||
|
||||
# validating again during the wait doesn't ask the server
|
||||
self.assertEqual(await api.validate_key(), PlusKeyStatus.rate_limited)
|
||||
self.assertEqual(self.requests_seen, 1)
|
||||
|
||||
async def test_a_rate_limit_without_retry_after(self):
|
||||
status, api = await self._validate(self._replies(429, {}))
|
||||
|
||||
self.assertEqual(status, PlusKeyStatus.rate_limited)
|
||||
self.assertIsNone(api.rate_limit_remaining())
|
||||
|
||||
async def test_unusable_replies_keep_the_cached_token(self):
|
||||
# a successful reply without a usable token must not replace one that
|
||||
# later Frigate+ requests depend on
|
||||
@@ -253,138 +212,5 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
||||
self.assertEqual(requests_seen, [])
|
||||
|
||||
|
||||
class TestParseRetryAfter(unittest.TestCase):
|
||||
def test_delay_seconds(self):
|
||||
self.assertEqual(parse_retry_after("120"), 120)
|
||||
self.assertEqual(parse_retry_after(" 0 "), 0)
|
||||
|
||||
def test_an_http_date(self):
|
||||
retry_at = datetime.datetime.now(datetime.UTC) + datetime.timedelta(seconds=90)
|
||||
header = email.utils.format_datetime(retry_at, usegmt=True)
|
||||
|
||||
self.assertAlmostEqual(parse_retry_after(header), 90, delta=2)
|
||||
|
||||
def test_a_date_in_the_past_is_no_wait(self):
|
||||
self.assertEqual(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), 0)
|
||||
|
||||
def test_missing_or_invalid_values(self):
|
||||
for value in (None, "", "soon", "-5", "1.5"):
|
||||
with self.subTest(value=value):
|
||||
self.assertIsNone(parse_retry_after(value))
|
||||
|
||||
|
||||
class TestRateLimit(unittest.TestCase):
|
||||
"""A 429 from Frigate+ is raised at once instead of blocking on Retry-After."""
|
||||
|
||||
def setUp(self):
|
||||
self.hits: list[str] = []
|
||||
self.status = 429
|
||||
self.headers: dict[str, str] = {"Retry-After": "30"}
|
||||
test = self
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def _reply(self):
|
||||
test.hits.append(f"{self.command} {self.path}")
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.rfile.read(length)
|
||||
|
||||
if self.path == "/v1/auth/token":
|
||||
status, body = (
|
||||
200,
|
||||
json.dumps({"accessToken": "t", "expires": time.time() + 3600}),
|
||||
)
|
||||
headers = {}
|
||||
else:
|
||||
status, body, headers = test.status, "{}", test.headers
|
||||
|
||||
self.send_response(status)
|
||||
for name, value in headers.items():
|
||||
self.send_header(name, value)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body.encode())
|
||||
|
||||
do_GET = do_PUT = do_POST = _reply
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
|
||||
host = f"http://127.0.0.1:{server.server_port}"
|
||||
with (
|
||||
patch("frigate.plus.PLUS_API_HOST", host),
|
||||
patch.dict(os.environ, {PLUS_ENV_VAR: TEST_PLUS_KEY}),
|
||||
):
|
||||
self.api = PlusApi()
|
||||
|
||||
def _api_hits(self) -> list[str]:
|
||||
return [hit for hit in self.hits if hit != "GET /v1/auth/token"]
|
||||
|
||||
def test_a_429_is_raised_without_retrying(self):
|
||||
for call in (
|
||||
lambda: self.api.get_models(),
|
||||
lambda: self.api.add_annotation("img", [0, 0, 1, 1], "person"),
|
||||
lambda: self.api._post("image/create", {}),
|
||||
):
|
||||
with self.subTest(call=call):
|
||||
self.hits.clear()
|
||||
self.api._rate_limited_until = None
|
||||
start = time.monotonic()
|
||||
|
||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
||||
call()
|
||||
|
||||
self.assertEqual(ctx.exception.retry_after, 30)
|
||||
self.assertEqual(len(self._api_hits()), 1)
|
||||
self.assertLess(time.monotonic() - start, 5)
|
||||
|
||||
def test_requests_are_refused_locally_until_retry_after_passes(self):
|
||||
with self.assertRaises(PlusRateLimitError):
|
||||
self.api.get_models()
|
||||
|
||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 30, delta=1)
|
||||
self.hits.clear()
|
||||
|
||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
||||
self.api.get_model_info("abc")
|
||||
|
||||
self.assertAlmostEqual(ctx.exception.retry_after, 30, delta=1)
|
||||
self.assertEqual(self.hits, [])
|
||||
|
||||
# once the wait has passed, requests go to the server again
|
||||
self.api._rate_limited_until = time.time() - 1
|
||||
self.status = 200
|
||||
|
||||
self.assertEqual(self.api.get_model_info("abc"), {})
|
||||
self.assertIsNone(self.api.rate_limit_remaining())
|
||||
|
||||
def test_a_429_without_retry_after_is_not_remembered(self):
|
||||
self.headers = {}
|
||||
|
||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
||||
self.api.get_models()
|
||||
|
||||
self.assertIsNone(ctx.exception.retry_after)
|
||||
self.assertIsNone(self.api.rate_limit_remaining())
|
||||
|
||||
def test_a_rate_limited_token_refresh(self):
|
||||
self.api._token_data = {}
|
||||
|
||||
with patch.object(
|
||||
self.api._session,
|
||||
"get",
|
||||
return_value=MagicMock(status_code=429, headers={"Retry-After": "60"}),
|
||||
):
|
||||
with self.assertRaises(PlusRateLimitError) as ctx:
|
||||
self.api.get_models()
|
||||
|
||||
self.assertEqual(ctx.exception.retry_after, 60)
|
||||
self.assertAlmostEqual(self.api.rate_limit_remaining(), 60, delta=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
|
||||
@@ -342,37 +342,4 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
|
||||
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||
).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,36 +459,6 @@ 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 ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
|
||||
@@ -327,10 +327,6 @@
|
||||
"copyDetails": "Copy details",
|
||||
"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}}",
|
||||
"readTheDocumentation": "Read the documentation",
|
||||
"information": {
|
||||
|
||||
@@ -14,7 +14,6 @@ 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;
|
||||
@@ -66,26 +65,20 @@ export function ModelSourcePicker({
|
||||
// metadata of whatever model was saved before it
|
||||
const selectedId = plusModelId(path) ?? plus?.id;
|
||||
|
||||
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 { 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 [showIncompatible, setShowIncompatible] = useState(false);
|
||||
const showIncompatibleId = useId();
|
||||
@@ -108,7 +101,6 @@ 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));
|
||||
|
||||
@@ -171,8 +163,7 @@ export function ModelSourcePicker({
|
||||
<SelectGroup>
|
||||
{entries.length === 0 ? (
|
||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||
{rateLimitMessage ??
|
||||
t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||
</div>
|
||||
) : (
|
||||
entries.map(([id, model]) => (
|
||||
@@ -193,9 +184,6 @@ 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,7 +87,6 @@ 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";
|
||||
@@ -700,7 +699,6 @@ function ObjectDetailsTab({
|
||||
"views/faceLibrary",
|
||||
"components/dialog",
|
||||
]);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
|
||||
const apiHost = useApiHost();
|
||||
const hasCustomClassificationModels = useMemo(
|
||||
@@ -1288,7 +1286,7 @@ function ObjectDetailsTab({
|
||||
revalidate: false,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
if (displayedIdRef.current === eventId) {
|
||||
setState("reviewing");
|
||||
}
|
||||
@@ -1296,13 +1294,12 @@ function ObjectDetailsTab({
|
||||
// the toast is not object specific, so it is always shown to avoid
|
||||
// silently dropping a failed submission
|
||||
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" },
|
||||
);
|
||||
}
|
||||
},
|
||||
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
|
||||
[search, mutate, mapSearchResults, isEventsKey, t],
|
||||
);
|
||||
|
||||
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
@@ -54,7 +54,6 @@ 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";
|
||||
|
||||
@@ -935,7 +934,6 @@ 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);
|
||||
@@ -1253,12 +1251,11 @@ function LifecycleIconRow({
|
||||
position: "top-center",
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
} catch {
|
||||
toast.error(
|
||||
getRateLimitMessage(error) ??
|
||||
t("toast.error.submitFrigatePlusFailed", {
|
||||
ns: "components/player",
|
||||
}),
|
||||
t("toast.error.submitFrigatePlusFailed", {
|
||||
ns: "components/player",
|
||||
}),
|
||||
{
|
||||
position: "top-center",
|
||||
},
|
||||
|
||||
@@ -22,7 +22,6 @@ 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;
|
||||
@@ -38,7 +37,6 @@ export function FrigatePlusDialog({
|
||||
onEventUploaded,
|
||||
}: FrigatePlusDialogProps) {
|
||||
const { t, i18n } = useTranslation(["components/dialog"]);
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
|
||||
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
||||
const [state, setState] = useState<SubmissionState>(
|
||||
@@ -65,15 +63,14 @@ export function FrigatePlusDialog({
|
||||
|
||||
setState("submitted");
|
||||
onEventUploaded();
|
||||
} catch (error) {
|
||||
} catch {
|
||||
setState("reviewing");
|
||||
toast.error(
|
||||
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
|
||||
{ position: "top-center" },
|
||||
);
|
||||
toast.error(t("explore.plus.review.toast.error"), {
|
||||
position: "top-center",
|
||||
});
|
||||
}
|
||||
},
|
||||
[upload, onEventUploaded, t, getRateLimitMessage],
|
||||
[upload, onEventUploaded, t],
|
||||
);
|
||||
|
||||
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
||||
|
||||
@@ -22,7 +22,6 @@ 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;
|
||||
@@ -110,7 +109,6 @@ export default function HlsVideoPlayer({
|
||||
transformedOverlay,
|
||||
}: HlsVideoPlayerProps) {
|
||||
const { t } = useTranslation("components/player");
|
||||
const { getRateLimitMessage } = usePlusRateLimit();
|
||||
const { data: config } = useSWR<FrigateConfig>("config");
|
||||
const isAdmin = useIsAdmin();
|
||||
|
||||
@@ -527,26 +525,18 @@ export default function HlsVideoPlayer({
|
||||
onUploadFrame={async () => {
|
||||
const frameTime = getVideoTime();
|
||||
|
||||
if (!frameTime || !onUploadFrame) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (frameTime && onUploadFrame) {
|
||||
const resp = await onUploadFrame(frameTime);
|
||||
|
||||
if (resp?.status !== 200) {
|
||||
throw new Error();
|
||||
if (resp && resp.status == 200) {
|
||||
toast.success(t("toast.success.submittedFrigatePlus"), {
|
||||
position: "top-center",
|
||||
});
|
||||
} else {
|
||||
toast.success(t("toast.error.submitFrigatePlusFailed"), {
|
||||
position: "top-center",
|
||||
});
|
||||
}
|
||||
|
||||
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,7 +10,6 @@ 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";
|
||||
@@ -80,16 +79,15 @@ export default function SetupDetector({
|
||||
|
||||
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
||||
|
||||
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 { data: plusModels } = 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(
|
||||
@@ -219,9 +217,6 @@ 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">
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
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 };
|
||||
}
|
||||
@@ -16,7 +16,8 @@ export function processCameraName(userInput: string): {
|
||||
} {
|
||||
const normalizedInput = userInput.replace(/\s+/g, "_").toLowerCase();
|
||||
|
||||
if (isValidId(normalizedInput)) {
|
||||
// debug replay owns this prefix and deletes data for cameras that use it
|
||||
if (isValidId(normalizedInput) && !isReplayCamera(normalizedInput)) {
|
||||
return {
|
||||
finalCameraName: normalizedInput,
|
||||
friendlyName: userInput.includes(" ") ? userInput : undefined,
|
||||
|
||||
@@ -20,17 +20,10 @@ 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" | "rate_limited" | "not_set";
|
||||
type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
|
||||
|
||||
type PlusValidateResponse = {
|
||||
success: boolean;
|
||||
status: PlusKeyStatus;
|
||||
// seconds until Frigate+ accepts requests again, when rate limited
|
||||
retry_after?: number | null;
|
||||
};
|
||||
type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
|
||||
|
||||
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
const { t } = useTranslation("views/settings");
|
||||
@@ -41,8 +34,6 @@ 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);
|
||||
@@ -50,7 +41,6 @@ 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 {
|
||||
@@ -134,8 +124,7 @@ 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 === "rate_limited" ? (
|
||||
) : keyStatus === "unreachable" ? (
|
||||
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
|
||||
) : (
|
||||
<XCircle className="size-5 shrink-0 text-red-500" />
|
||||
@@ -145,9 +134,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||
? t("frigatePlus.apiKey.serverValid")
|
||||
: keyStatus === "unreachable"
|
||||
? t("frigatePlus.apiKey.serverUnreachable")
|
||||
: keyStatus === "rate_limited"
|
||||
? formatRateLimit(retryAfter)
|
||||
: t("frigatePlus.apiKey.serverInvalid")}
|
||||
: t("frigatePlus.apiKey.serverInvalid")}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user