mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-24 22:37:08 +03:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
87b7412dee | ||
|
|
bcd64d96a6 | ||
|
|
0798d3f247 | ||
|
|
2b4b1fdb8e |
+49
-26
@@ -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 (
|
||||||
@@ -73,7 +74,7 @@ from frigate.util.config import (
|
|||||||
find_config_file,
|
find_config_file,
|
||||||
redact_credential,
|
redact_credential,
|
||||||
)
|
)
|
||||||
from frigate.util.env import substitute_frigate_vars
|
from frigate.util.env import candidate_env_vars, substitute_frigate_vars
|
||||||
from frigate.util.live_streams import (
|
from frigate.util.live_streams import (
|
||||||
generated_transcode_streams,
|
generated_transcode_streams,
|
||||||
sync_transcode_streams,
|
sync_transcode_streams,
|
||||||
@@ -588,14 +589,18 @@ def config_raw():
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _go2rtc_config(raw_config: str) -> dict[str, Any]:
|
def _go2rtc_config(raw_config: str) -> tuple[dict[str, Any], Any]:
|
||||||
"""Load the go2rtc section with the same loader Frigate and go2rtc startup use.
|
"""Load the go2rtc section and environment_vars with the same loader Frigate
|
||||||
|
and go2rtc startup use.
|
||||||
|
|
||||||
Raises ruamel.yaml.YAMLError when the config cannot be parsed.
|
Raises ruamel.yaml.YAMLError when the config cannot be parsed.
|
||||||
"""
|
"""
|
||||||
loaded = ruamel.yaml.YAML().load(raw_config)
|
loaded = ruamel.yaml.YAML().load(raw_config)
|
||||||
go2rtc = loaded.get("go2rtc") if isinstance(loaded, dict) else None
|
if not isinstance(loaded, dict):
|
||||||
return go2rtc if isinstance(go2rtc, dict) else {}
|
return {}, None
|
||||||
|
|
||||||
|
go2rtc = loaded.get("go2rtc")
|
||||||
|
return go2rtc if isinstance(go2rtc, dict) else {}, loaded.get("environment_vars")
|
||||||
|
|
||||||
|
|
||||||
def _restricted_go2rtc_response(
|
def _restricted_go2rtc_response(
|
||||||
@@ -607,7 +612,7 @@ def _restricted_go2rtc_response(
|
|||||||
otherwise load them from the saved config on the next restart.
|
otherwise load them from the saved config on the next restart.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
new_go2rtc = _go2rtc_config(new_raw_config)
|
new_go2rtc, new_env_vars = _go2rtc_config(new_raw_config)
|
||||||
except ruamel.yaml.YAMLError:
|
except ruamel.yaml.YAMLError:
|
||||||
logger.warning("Rejected config change that could not be parsed")
|
logger.warning("Rejected config change that could not be parsed")
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -616,13 +621,13 @@ def _restricted_go2rtc_response(
|
|||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
old_go2rtc = _go2rtc_config(old_raw_config)
|
old_go2rtc, _ = _go2rtc_config(old_raw_config)
|
||||||
except ruamel.yaml.YAMLError:
|
except ruamel.yaml.YAMLError:
|
||||||
# with no readable saved config, every source is treated as new
|
# with no readable saved config, every source is treated as new
|
||||||
old_go2rtc = {}
|
old_go2rtc = {}
|
||||||
|
|
||||||
issues = find_restricted_go2rtc_stream_changes(
|
issues = find_restricted_go2rtc_stream_changes(
|
||||||
old_go2rtc.get("streams"), new_go2rtc.get("streams")
|
old_go2rtc.get("streams"), new_go2rtc.get("streams"), new_env_vars
|
||||||
)
|
)
|
||||||
exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc)
|
exec_keys = find_restricted_go2rtc_exec_changes(old_go2rtc, new_go2rtc)
|
||||||
if not issues and not exec_keys:
|
if not issues and not exec_keys:
|
||||||
@@ -786,16 +791,20 @@ def config_save(save_option: str, body: Any = Body(media_type="text/plain")):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None:
|
def _restore_masked_camera_paths(
|
||||||
|
config_data: dict, saved: dict, shown_env_vars: dict[str, str]
|
||||||
|
) -> str | None:
|
||||||
"""Substitute incoming masked camera paths with the saved ones.
|
"""Substitute incoming masked camera paths with the saved ones.
|
||||||
|
|
||||||
The /config response masks ffmpeg input credentials, so the settings UI
|
The /config response masks ffmpeg input credentials, so the settings UI
|
||||||
sends the masked path back when sibling fields (e.g. hwaccel_args) are
|
sends the masked path back when sibling fields (e.g. hwaccel_args) are
|
||||||
edited. Each masked path is matched to the saved input that masks to the
|
edited. Each masked path is matched to the saved input that masks to the
|
||||||
same value, with roles breaking a tie, so deleting or reordering inputs
|
same value, with roles breaking a tie, so deleting or reordering inputs
|
||||||
keeps each path's own credentials. The saved path is restored as written,
|
keeps each path's own credentials. Saved paths resolve with
|
||||||
keeping any {FRIGATE_*} placeholder. Mutates `config_data` in place and
|
`shown_env_vars`, the block the running config and /config used. The saved
|
||||||
returns an error message when a masked path has no single match.
|
path is restored as written, keeping any {FRIGATE_*} placeholder. Mutates
|
||||||
|
`config_data` in place and returns an error message when a masked path has
|
||||||
|
no single match.
|
||||||
"""
|
"""
|
||||||
cameras = config_data.get("cameras")
|
cameras = config_data.get("cameras")
|
||||||
if not isinstance(cameras, dict):
|
if not isinstance(cameras, dict):
|
||||||
@@ -831,11 +840,13 @@ def _restore_masked_camera_paths(config_data: dict, saved: dict) -> str | None:
|
|||||||
path = input_obj.get("path")
|
path = input_obj.get("path")
|
||||||
if not isinstance(path, str) or not is_masked_camera_path(path):
|
if not isinstance(path, str) or not is_masked_camera_path(path):
|
||||||
continue
|
continue
|
||||||
candidates = [
|
with candidate_env_vars(shown_env_vars):
|
||||||
inp
|
candidates = [
|
||||||
for inp in saved_inputs
|
inp
|
||||||
if clean_camera_user_pass(_resolve_frigate_vars(inp["path"])) == path
|
for inp in saved_inputs
|
||||||
]
|
if clean_camera_user_pass(_resolve_frigate_vars(inp["path"]))
|
||||||
|
== path
|
||||||
|
]
|
||||||
if len({inp["path"] for inp in candidates}) > 1:
|
if len({inp["path"] for inp in candidates}) > 1:
|
||||||
candidates = [
|
candidates = [
|
||||||
inp
|
inp
|
||||||
@@ -879,14 +890,14 @@ def _saved_config_from_memory(config: FrigateConfig) -> dict[str, Any]:
|
|||||||
|
|
||||||
|
|
||||||
def _config_data_to_updates(
|
def _config_data_to_updates(
|
||||||
config_data: dict, saved: dict[str, Any]
|
config_data: dict, saved: dict[str, Any], running: FrigateConfig
|
||||||
) -> tuple[dict[str, Any], str | None]:
|
) -> tuple[dict[str, Any], str | None]:
|
||||||
"""Flatten a /config/set payload after restoring masked credentials.
|
"""Flatten a /config/set payload after restoring masked credentials.
|
||||||
|
|
||||||
`saved` is the config the masked values were taken from. Returns the flat
|
`saved` is the config the masked values were taken from. Returns the flat
|
||||||
updates, or an error message when a masked value can't be restored.
|
updates, or an error message when a masked value can't be restored.
|
||||||
"""
|
"""
|
||||||
error = _restore_masked_camera_paths(config_data, saved)
|
error = _restore_masked_camera_paths(config_data, saved, running.environment_vars)
|
||||||
if error:
|
if error:
|
||||||
return {}, error
|
return {}, error
|
||||||
|
|
||||||
@@ -940,7 +951,9 @@ def _config_set_in_memory(request: Request, body: AppConfigSetBody) -> JSONRespo
|
|||||||
updates = {}
|
updates = {}
|
||||||
if body.config_data:
|
if body.config_data:
|
||||||
updates, error = _config_data_to_updates(
|
updates, error = _config_data_to_updates(
|
||||||
body.config_data, _saved_config_from_memory(request.app.frigate_config)
|
body.config_data,
|
||||||
|
_saved_config_from_memory(request.app.frigate_config),
|
||||||
|
request.app.frigate_config,
|
||||||
)
|
)
|
||||||
if error:
|
if error:
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -1121,6 +1134,7 @@ def config_set(request: Request, body: AppConfigSetBody):
|
|||||||
updates, error = _config_data_to_updates(
|
updates, error = _config_data_to_updates(
|
||||||
body.config_data,
|
body.config_data,
|
||||||
saved_config if isinstance(saved_config, dict) else {},
|
saved_config if isinstance(saved_config, dict) else {},
|
||||||
|
request.app.frigate_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
if error:
|
if error:
|
||||||
@@ -1665,7 +1679,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(
|
||||||
@@ -1705,11 +1722,17 @@ def plusModels(request: Request, filterByCurrentModelDetector: bool = False):
|
|||||||
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
@router.post("/plus/validate", dependencies=[Depends(require_role(["admin"]))])
|
||||||
async def validate_plus_key(request: Request):
|
async def validate_plus_key(request: Request):
|
||||||
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
"""Validate the configured Frigate+ API key with the Frigate+ server."""
|
||||||
status = await request.app.frigate_config.plus_api.validate_key()
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
return JSONResponse(
|
if status == PlusKeyStatus.rate_limited:
|
||||||
content={"success": status == PlusKeyStatus.valid, "status": status.value}
|
content["retry_after"] = plus_api.rate_limit_remaining()
|
||||||
)
|
|
||||||
|
return JSONResponse(content=content)
|
||||||
|
|
||||||
|
|
||||||
@router.get(
|
@router.get(
|
||||||
|
|||||||
+61
-35
@@ -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
|
||||||
@@ -67,6 +69,9 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
router = APIRouter(tags=[Tags.events])
|
router = APIRouter(tags=[Tags.events])
|
||||||
|
|
||||||
|
# event.data key holding a Frigate+ image id until its annotation is uploaded
|
||||||
|
PLUS_PENDING_ID_KEY = "plus_pending_id"
|
||||||
|
|
||||||
|
|
||||||
def _build_attribute_filter_clause(attributes: str):
|
def _build_attribute_filter_clause(attributes: str):
|
||||||
filtered_attributes = [
|
filtered_attributes = [
|
||||||
@@ -1112,43 +1117,55 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
content=({"success": False, "message": message}), status_code=400
|
content=({"success": False, "message": message}), status_code=400
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
# an image uploaded by an earlier attempt whose annotation failed, so a
|
||||||
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
|
# retry finishes that submission instead of uploading the image again
|
||||||
except Exception:
|
plus_id = event.data.get(PLUS_PENDING_ID_KEY)
|
||||||
logger.error(f"Unable to load clean snapshot for event: {event.id}")
|
|
||||||
return JSONResponse(
|
|
||||||
content=(
|
|
||||||
{"success": False, "message": "Unable to load clean snapshot for event"}
|
|
||||||
),
|
|
||||||
status_code=400,
|
|
||||||
)
|
|
||||||
|
|
||||||
if not is_clean_snapshot or image is None or image.size == 0:
|
if plus_id is None:
|
||||||
logger.error(f"Unable to find clean snapshot for event: {event.id}")
|
try:
|
||||||
return JSONResponse(
|
image, is_clean_snapshot = load_event_snapshot_image(event, clean_only=True)
|
||||||
content=(
|
except Exception:
|
||||||
{
|
logger.error(f"Unable to load clean snapshot for event: {event.id}")
|
||||||
"success": False,
|
return JSONResponse(
|
||||||
"message": "Unable to find clean snapshot for event",
|
content=(
|
||||||
}
|
{
|
||||||
),
|
"success": False,
|
||||||
status_code=400,
|
"message": "Unable to load clean snapshot for event",
|
||||||
)
|
}
|
||||||
|
),
|
||||||
|
status_code=400,
|
||||||
|
)
|
||||||
|
|
||||||
try:
|
if not is_clean_snapshot or image is None or image.size == 0:
|
||||||
plus_id = await asyncio.to_thread(
|
logger.error(f"Unable to find clean snapshot for event: {event.id}")
|
||||||
request.app.frigate_config.plus_api.upload_image, image, event.camera
|
return JSONResponse(
|
||||||
)
|
content=(
|
||||||
except Exception as ex:
|
{
|
||||||
logger.exception(ex)
|
"success": False,
|
||||||
return JSONResponse(
|
"message": "Unable to find clean snapshot for event",
|
||||||
content=({"success": False, "message": "Error uploading image"}),
|
}
|
||||||
status_code=400,
|
),
|
||||||
)
|
status_code=400,
|
||||||
|
)
|
||||||
|
|
||||||
# store image id in the database
|
try:
|
||||||
event.plus_id = plus_id
|
plus_id = await asyncio.to_thread(
|
||||||
event.save()
|
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(
|
||||||
|
content=({"success": False, "message": "Error uploading image"}),
|
||||||
|
status_code=400,
|
||||||
|
)
|
||||||
|
|
||||||
|
if include_annotation is not None:
|
||||||
|
# the image isn't marked submitted until its annotation is, or a
|
||||||
|
# failed annotation could never be retried
|
||||||
|
event.data[PLUS_PENDING_ID_KEY] = plus_id
|
||||||
|
event.save()
|
||||||
|
|
||||||
if include_annotation is not None:
|
if include_annotation is not None:
|
||||||
box = event.data["box"]
|
box = event.data["box"]
|
||||||
@@ -1156,10 +1173,12 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
try:
|
try:
|
||||||
await asyncio.to_thread(
|
await asyncio.to_thread(
|
||||||
request.app.frigate_config.plus_api.add_annotation,
|
request.app.frigate_config.plus_api.add_annotation,
|
||||||
event.plus_id,
|
plus_id,
|
||||||
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)
|
||||||
@@ -1174,6 +1193,11 @@ async def send_to_plus(request: Request, event_id: str, body: SubmitPlusBody = N
|
|||||||
status_code=400,
|
status_code=400,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# store image id in the database
|
||||||
|
event.plus_id = plus_id
|
||||||
|
event.data.pop(PLUS_PENDING_ID_KEY, None)
|
||||||
|
event.save()
|
||||||
|
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
content=({"success": True, "plus_id": plus_id}), status_code=200
|
content=({"success": True, "plus_id": plus_id}), status_code=200
|
||||||
)
|
)
|
||||||
@@ -1256,6 +1280,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)
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -51,6 +52,7 @@ from frigate.output.preview import (
|
|||||||
get_most_recent_preview_frame,
|
get_most_recent_preview_frame,
|
||||||
is_camera_preview_frame,
|
is_camera_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 (
|
||||||
@@ -479,9 +481,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={
|
||||||
|
|||||||
@@ -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,
|
||||||
|
)
|
||||||
@@ -4,6 +4,7 @@ import io
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
from collections.abc import Mapping
|
||||||
from typing import Any, Self
|
from typing import Any, Self
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
@@ -34,7 +35,7 @@ from frigate.util.config import (
|
|||||||
get_relative_coordinates,
|
get_relative_coordinates,
|
||||||
migrate_frigate_config,
|
migrate_frigate_config,
|
||||||
)
|
)
|
||||||
from frigate.util.env import EnvVars, reload_sources
|
from frigate.util.env import EnvVars, candidate_env_vars, reload_sources
|
||||||
from frigate.util.image import create_mask
|
from frigate.util.image import create_mask
|
||||||
from frigate.util.live_streams import (
|
from frigate.util.live_streams import (
|
||||||
default_transcode_source,
|
default_transcode_source,
|
||||||
@@ -1566,6 +1567,12 @@ class FrigateConfig(FrigateBaseModel):
|
|||||||
def parse_object(
|
def parse_object(
|
||||||
cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False
|
cls, obj: Any, *, plus_api: PlusApi | None = None, install: bool = False
|
||||||
):
|
):
|
||||||
return cls.model_validate(
|
context = {"plus_api": plus_api, "install": install}
|
||||||
obj, context={"plus_api": plus_api, "install": install}
|
|
||||||
)
|
if install:
|
||||||
|
return cls.model_validate(obj, context=context)
|
||||||
|
|
||||||
|
# a candidate config resolves placeholders against its own block
|
||||||
|
env_vars = obj.get("environment_vars") if isinstance(obj, Mapping) else None
|
||||||
|
with candidate_env_vars(env_vars):
|
||||||
|
return cls.model_validate(obj, context=context)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from pydantic import BaseModel, ConfigDict, Field
|
|||||||
from pydantic.fields import PrivateAttr
|
from pydantic.fields import PrivateAttr
|
||||||
|
|
||||||
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
|
from frigate.const import DEFAULT_ATTRIBUTE_LABEL_MAP, MODEL_CACHE_DIR
|
||||||
from frigate.plus import PlusApi, load_plus_model_info
|
from frigate.plus import PlusApi, PlusRateLimitError, load_plus_model_info
|
||||||
from frigate.util.builtin import generate_color_palette, load_labels
|
from frigate.util.builtin import generate_color_palette, load_labels
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -52,6 +52,16 @@ DEFAULT_SCENE = "default"
|
|||||||
SCENE_PATTERN = r"^[A-Za-z0-9_-]+$"
|
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):
|
class ModelConfig(BaseModel):
|
||||||
scene: str = Field(
|
scene: str = Field(
|
||||||
default=DEFAULT_SCENE,
|
default=DEFAULT_SCENE,
|
||||||
@@ -193,6 +203,16 @@ class ModelConfig(BaseModel):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Unable to connect to Frigate+ to download model {model_id}"
|
f"Unable to connect to Frigate+ to download model {model_id}"
|
||||||
) from e
|
) 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:
|
with open(self.path, "wb") as f:
|
||||||
f.write(r.content)
|
f.write(r.content)
|
||||||
@@ -205,6 +225,8 @@ class ModelConfig(BaseModel):
|
|||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"Unable to connect to Frigate+ to download model info for {model_id}"
|
f"Unable to connect to Frigate+ to download model info for {model_id}"
|
||||||
) from e
|
) from e
|
||||||
|
except PlusRateLimitError as e:
|
||||||
|
raise ValueError(_rate_limited_message(model_id, e)) from e
|
||||||
|
|
||||||
with open(model_info_path, "w") as f:
|
with open(model_info_path, "w") as f:
|
||||||
json.dump(model_info, f)
|
json.dump(model_info, f)
|
||||||
|
|||||||
+137
-16
@@ -1,8 +1,12 @@
|
|||||||
import datetime
|
import datetime
|
||||||
|
import email.utils
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
|
import math
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, TypeGuard
|
from typing import Any, TypeGuard
|
||||||
@@ -21,6 +25,11 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
PLUS_VALIDATE_TIMEOUT = 10
|
PLUS_VALIDATE_TIMEOUT = 10
|
||||||
|
|
||||||
|
# Requests run on several threads, and a reply that arrives late must not
|
||||||
|
# shorten a wait recorded from another one. The lock is kept out of PlusApi
|
||||||
|
# because the client is pickled with the config to start worker processes.
|
||||||
|
_rate_limit_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
class PlusKeyStatus(str, Enum):
|
class PlusKeyStatus(str, Enum):
|
||||||
"""Result of validating a Frigate+ API key with the server."""
|
"""Result of validating a Frigate+ API key with the server."""
|
||||||
@@ -28,6 +37,7 @@ class PlusKeyStatus(str, Enum):
|
|||||||
valid = "valid"
|
valid = "valid"
|
||||||
invalid = "invalid"
|
invalid = "invalid"
|
||||||
unreachable = "unreachable"
|
unreachable = "unreachable"
|
||||||
|
rate_limited = "rate_limited"
|
||||||
not_set = "not_set"
|
not_set = "not_set"
|
||||||
|
|
||||||
|
|
||||||
@@ -70,6 +80,51 @@ def load_plus_model_info(model_id: str) -> dict[str, Any] | None:
|
|||||||
return add_hailo_alias(model_info)
|
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:
|
def get_jpg_bytes(image: ndarray, max_dim: int, quality: int) -> bytes:
|
||||||
if image.shape[1] >= image.shape[0]:
|
if image.shape[1] >= image.shape[0]:
|
||||||
width = min(max_dim, image.shape[1])
|
width = min(max_dim, image.shape[1])
|
||||||
@@ -128,14 +183,62 @@ class PlusApi:
|
|||||||
|
|
||||||
self._is_active: bool = self.key is not None
|
self._is_active: bool = self.key is not None
|
||||||
self._token_data: dict = {}
|
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
|
# Retry connection failures so a network that comes up late at startup
|
||||||
# doesn't fail the Frigate+ model download
|
# 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.
|
||||||
self._session = requests.Session()
|
self._session = requests.Session()
|
||||||
self._session.mount(
|
self._session.mount(
|
||||||
self.host, HTTPAdapter(max_retries=Retry(connect=5, backoff_factor=1))
|
self.host,
|
||||||
|
HTTPAdapter(
|
||||||
|
max_retries=Retry(
|
||||||
|
connect=5, backoff_factor=1, respect_retry_after_header=False
|
||||||
|
)
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def rate_limit_remaining(self) -> int | None:
|
||||||
|
"""Seconds until Frigate+ accepts requests again, or None if not limited."""
|
||||||
|
rate_limited_until = self._rate_limited_until
|
||||||
|
|
||||||
|
if rate_limited_until is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
remaining = math.ceil(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 None:
|
||||||
|
return
|
||||||
|
|
||||||
|
until = time.time() + retry_after
|
||||||
|
|
||||||
|
with _rate_limit_lock:
|
||||||
|
if self._rate_limited_until is None or until > self._rate_limited_until:
|
||||||
|
self._rate_limited_until = until
|
||||||
|
|
||||||
|
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:
|
def _refresh_token_if_needed(self) -> None:
|
||||||
if (
|
if (
|
||||||
self._token_data.get("expires") is None
|
self._token_data.get("expires") is None
|
||||||
@@ -145,10 +248,12 @@ class PlusApi:
|
|||||||
raise Exception(
|
raise Exception(
|
||||||
"Plus API key not set. See https://docs.frigate.video/integrations/plus#set-your-api-key"
|
"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(":")
|
parts = self.key.split(":")
|
||||||
r = self._session.get(
|
r = self._session.get(
|
||||||
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
|
f"{self.host}/v1/auth/token", auth=(parts[0], parts[1])
|
||||||
)
|
)
|
||||||
|
self._check_rate_limit(r)
|
||||||
if not r.ok:
|
if not r.ok:
|
||||||
raise Exception(f"Unable to refresh API token: {r.text}")
|
raise Exception(f"Unable to refresh API token: {r.text}")
|
||||||
self._token_data = r.json()
|
self._token_data = r.json()
|
||||||
@@ -157,24 +262,30 @@ class PlusApi:
|
|||||||
self._refresh_token_if_needed()
|
self._refresh_token_if_needed()
|
||||||
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
|
return {"authorization": f"Bearer {self._token_data.get('accessToken')}"}
|
||||||
|
|
||||||
def _get(self, path: str) -> Response:
|
def _request(self, method: str, path: str, data: dict | None = None) -> Response:
|
||||||
return self._session.get(
|
"""Make an authenticated Frigate+ request.
|
||||||
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,
|
||||||
|
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:
|
def _post(self, path: str, data: dict) -> Response:
|
||||||
return self._session.post(
|
return self._request("POST", path, data)
|
||||||
f"{self.host}/v1/{path}",
|
|
||||||
headers=self._get_authorization_header(),
|
|
||||||
json=data,
|
|
||||||
)
|
|
||||||
|
|
||||||
def _put(self, path: str, data: dict) -> Response:
|
def _put(self, path: str, data: dict) -> Response:
|
||||||
return self._session.put(
|
return self._request("PUT", path, data)
|
||||||
f"{self.host}/v1/{path}",
|
|
||||||
headers=self._get_authorization_header(),
|
|
||||||
json=data,
|
|
||||||
)
|
|
||||||
|
|
||||||
def is_active(self) -> bool:
|
def is_active(self) -> bool:
|
||||||
return self._is_active
|
return self._is_active
|
||||||
@@ -187,11 +298,16 @@ class PlusApi:
|
|||||||
result reflects the key's current state rather than a cached token.
|
result reflects the key's current state rather than a cached token.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The key's status as reported by the Frigate+ server
|
The key's status as reported by the Frigate+ server. When it is
|
||||||
|
rate_limited, rate_limit_remaining() gives the wait if known.
|
||||||
"""
|
"""
|
||||||
if self.key is None:
|
if self.key is None:
|
||||||
return PlusKeyStatus.not_set
|
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(":")
|
key_id, _, secret = self.key.partition(":")
|
||||||
|
|
||||||
# Use a single request with a timeout instead of the retrying session,
|
# Use a single request with a timeout instead of the retrying session,
|
||||||
@@ -207,6 +323,7 @@ class PlusApi:
|
|||||||
auth=aiohttp.BasicAuth(key_id, secret),
|
auth=aiohttp.BasicAuth(key_id, secret),
|
||||||
) as r:
|
) as r:
|
||||||
status = r.status
|
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
|
token_data = await r.json(content_type=None) if r.ok else None
|
||||||
except (aiohttp.ClientError, TimeoutError) as err:
|
except (aiohttp.ClientError, TimeoutError) as err:
|
||||||
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
logger.warning("Unable to reach Frigate+ to validate API key: %s", err)
|
||||||
@@ -218,6 +335,10 @@ class PlusApi:
|
|||||||
if status in (401, 403):
|
if status in (401, 403):
|
||||||
return PlusKeyStatus.invalid
|
return PlusKeyStatus.invalid
|
||||||
|
|
||||||
|
if status == 429:
|
||||||
|
self._note_rate_limit(retry_after)
|
||||||
|
return PlusKeyStatus.rate_limited
|
||||||
|
|
||||||
if status >= 400:
|
if status >= 400:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Unexpected response validating Frigate+ API key: %s", status
|
"Unexpected response validating Frigate+ API key: %s", status
|
||||||
|
|||||||
@@ -10,7 +10,13 @@ import ruamel.yaml
|
|||||||
|
|
||||||
from frigate.models import Event, Recordings, ReviewSegment
|
from frigate.models import Event, Recordings, ReviewSegment
|
||||||
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
from frigate.test.http_api.base_http_test import AuthTestClient, BaseTestHttp
|
||||||
from frigate.util.env import _CONTAINER_ENV, FRIGATE_ENV_VARS, reload_sources
|
from frigate.util.env import (
|
||||||
|
_CONFIG_ENV_VARS,
|
||||||
|
_CONTAINER_ENV,
|
||||||
|
FRIGATE_ENV_VARS,
|
||||||
|
apply_config_env_vars,
|
||||||
|
reload_sources,
|
||||||
|
)
|
||||||
|
|
||||||
# shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced
|
# shape of the source in GHSA-qjjw-3v66-279f, with the payload replaced
|
||||||
_INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
_INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
||||||
@@ -18,6 +24,8 @@ _INJECTED_SRC = "ffmpeg:#input='-f''h264''-i''data:placeholder''-c''copy'"
|
|||||||
# an unrestricted ffmpeg: source the operator already has in the file on disk
|
# an unrestricted ffmpeg: source the operator already has in the file on disk
|
||||||
_EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn"
|
_EXISTING_SRC = "ffmpeg:rtsp://10.0.0.1:554/video#raw=-vn"
|
||||||
|
|
||||||
|
_PLACEHOLDER_SRC = "ffmpeg:rtsp://10.0.0.1:554/{FRIGATE_CAM_PATH}"
|
||||||
|
|
||||||
_CONFIG = {
|
_CONFIG = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
"go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}},
|
"go2rtc": {"streams": {"front_door": [_EXISTING_SRC]}},
|
||||||
@@ -111,6 +119,28 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
|
|||||||
headers={"Content-Type": "text/plain"},
|
headers={"Content-Type": "text/plain"},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def _save(self, config: dict):
|
||||||
|
with AuthTestClient(self.app) as client:
|
||||||
|
return client.post(
|
||||||
|
"/config/save?save_option=saveonly",
|
||||||
|
content=_dump(config),
|
||||||
|
headers={"Content-Type": "text/plain"},
|
||||||
|
)
|
||||||
|
|
||||||
|
def _start_with_placeholder_source(self) -> dict:
|
||||||
|
"""Write and install a config whose stream reads FRIGATE_CAM_PATH from
|
||||||
|
environment_vars, as if Frigate had started with it."""
|
||||||
|
config = copy.deepcopy(_CONFIG)
|
||||||
|
config["environment_vars"] = {"FRIGATE_CAM_PATH": "video"}
|
||||||
|
config["go2rtc"]["streams"]["front_door"].append(_PLACEHOLDER_SRC)
|
||||||
|
with open(self.config_path, "w") as f:
|
||||||
|
f.write(_dump(config))
|
||||||
|
|
||||||
|
apply_config_env_vars(config["environment_vars"])
|
||||||
|
self.addCleanup(reload_sources, warn=False)
|
||||||
|
self.addCleanup(_CONFIG_ENV_VARS.clear)
|
||||||
|
return config
|
||||||
|
|
||||||
# --- config/set ---
|
# --- config/set ---
|
||||||
|
|
||||||
def test_set_rejects_injected_ffmpeg_source(self):
|
def test_set_rejects_injected_ffmpeg_source(self):
|
||||||
@@ -255,6 +285,52 @@ class TestConfigGo2rtcStreamRestrictions(BaseTestHttp):
|
|||||||
assert resp.status_code == 200, resp.text
|
assert resp.status_code == 200, resp.text
|
||||||
assert src in self._read_config()
|
assert src in self._read_config()
|
||||||
|
|
||||||
|
def test_save_rejects_changed_env_var_in_existing_source(self):
|
||||||
|
config = self._start_with_placeholder_source()
|
||||||
|
before = self._read_config()
|
||||||
|
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video#raw=-vn"
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "Restricted go2rtc stream source" in resp.json()["message"]
|
||||||
|
assert self._read_config() == before
|
||||||
|
|
||||||
|
def test_save_allows_safe_env_var_change_in_existing_source(self):
|
||||||
|
config = self._start_with_placeholder_source()
|
||||||
|
config["environment_vars"]["FRIGATE_CAM_PATH"] = "video2"
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
|
||||||
|
def test_save_resubmitting_placeholder_source_allowed(self):
|
||||||
|
config = self._start_with_placeholder_source()
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
|
||||||
|
def test_save_rejects_removed_env_var_in_existing_source(self):
|
||||||
|
config = self._start_with_placeholder_source()
|
||||||
|
before = self._read_config()
|
||||||
|
del config["environment_vars"]
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert self._read_config() == before
|
||||||
|
|
||||||
|
def test_save_allows_env_var_added_with_its_source(self):
|
||||||
|
config = copy.deepcopy(_CONFIG)
|
||||||
|
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video"}
|
||||||
|
config["go2rtc"]["streams"]["new_stream"] = (
|
||||||
|
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
|
||||||
|
)
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 200, resp.text
|
||||||
|
|
||||||
|
def test_save_rejects_unsafe_env_var_added_with_its_source(self):
|
||||||
|
config = copy.deepcopy(_CONFIG)
|
||||||
|
config["environment_vars"] = {"FRIGATE_NEW_PATH": "video#raw=-vn"}
|
||||||
|
config["go2rtc"]["streams"]["new_stream"] = (
|
||||||
|
"ffmpeg:rtsp://10.0.0.2:554/{FRIGATE_NEW_PATH}"
|
||||||
|
)
|
||||||
|
resp = self._save(config)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
|
||||||
# --- go2rtc ffmpeg and ngrok options ---
|
# --- go2rtc ffmpeg and ngrok options ---
|
||||||
|
|
||||||
def test_save_rejects_ffmpeg_bin_override(self):
|
def test_save_rejects_ffmpeg_bin_override(self):
|
||||||
|
|||||||
@@ -624,6 +624,96 @@ class TestConfigSetWildcardPropagation(BaseTestHttp):
|
|||||||
finally:
|
finally:
|
||||||
os.unlink(config_path)
|
os.unlink(config_path)
|
||||||
|
|
||||||
|
@patch.dict("frigate.util.env._CONFIG_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
|
||||||
|
@patch.dict("frigate.util.env.FRIGATE_ENV_VARS", {"FRIGATE_CAM_HOST": "10.0.0.1"})
|
||||||
|
@patch("frigate.api.app.find_config_file")
|
||||||
|
def test_masked_path_matches_after_saved_env_var_swap(self, mock_find_config):
|
||||||
|
"""A no-restart update swaps in a config resolved with the saved
|
||||||
|
environment_vars, so /config shows the saved value until a restart."""
|
||||||
|
path = "rtsp://admin:pw@{FRIGATE_CAM_HOST}:554/live"
|
||||||
|
self._set_inputs([(path, "detect")])
|
||||||
|
self.minimal_config["environment_vars"] = {"FRIGATE_CAM_HOST": "10.0.0.2"}
|
||||||
|
config_path = self._write_config_file()
|
||||||
|
mock_find_config.return_value = config_path
|
||||||
|
|
||||||
|
try:
|
||||||
|
app, _ = self._create_app_with_publisher()
|
||||||
|
|
||||||
|
with AuthTestClient(app) as client:
|
||||||
|
resp = self._save(
|
||||||
|
client, {"cameras": {"front_door": {"detect": {"fps": 6}}}}
|
||||||
|
)
|
||||||
|
self.assertEqual(resp.status_code, 200, resp.text)
|
||||||
|
|
||||||
|
camera = client.get("/config").json()["cameras"]["front_door"]
|
||||||
|
inputs = camera["ffmpeg"]["inputs"]
|
||||||
|
self.assertIn("10.0.0.2", inputs[0]["path"])
|
||||||
|
|
||||||
|
resp = self._save(
|
||||||
|
client,
|
||||||
|
{
|
||||||
|
"cameras": {
|
||||||
|
"front_door": {
|
||||||
|
"ffmpeg": {"inputs": inputs},
|
||||||
|
"detect": {"fps": 7},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
self.assertEqual(resp.status_code, 200, resp.text)
|
||||||
|
|
||||||
|
_, saved = self._read_config_file(config_path)
|
||||||
|
self.assertEqual(
|
||||||
|
saved["cameras"]["front_door"]["ffmpeg"]["inputs"][0]["path"], path
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
os.unlink(config_path)
|
||||||
|
|
||||||
|
@patch.dict(
|
||||||
|
"frigate.util.env._CONFIG_ENV_VARS",
|
||||||
|
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
|
||||||
|
)
|
||||||
|
@patch.dict(
|
||||||
|
"frigate.util.env.FRIGATE_ENV_VARS",
|
||||||
|
{"FRIGATE_HOST_A": "10.0.0.1", "FRIGATE_HOST_B": "10.0.0.2"},
|
||||||
|
)
|
||||||
|
@patch("frigate.api.app.find_config_file")
|
||||||
|
def test_masked_paths_match_running_env_vars(self, mock_find_config):
|
||||||
|
"""A saved but not yet applied environment_vars change must not make
|
||||||
|
one input's masked path match another's."""
|
||||||
|
path_a = "rtsp://admin:pw@{FRIGATE_HOST_A}:554/live"
|
||||||
|
path_b = "rtsp://admin:pw@{FRIGATE_HOST_B}:554/live"
|
||||||
|
self._set_inputs([(path_a, "detect"), (path_b, "record")])
|
||||||
|
self.minimal_config["environment_vars"] = {
|
||||||
|
"FRIGATE_HOST_A": "10.0.0.1",
|
||||||
|
"FRIGATE_HOST_B": "10.0.0.2",
|
||||||
|
}
|
||||||
|
app, _ = self._create_app_with_publisher()
|
||||||
|
|
||||||
|
self.minimal_config["environment_vars"]["FRIGATE_HOST_A"] = "10.0.0.2"
|
||||||
|
config_path = self._write_config_file()
|
||||||
|
mock_find_config.return_value = config_path
|
||||||
|
|
||||||
|
try:
|
||||||
|
with AuthTestClient(app) as client:
|
||||||
|
camera = client.get("/config").json()["cameras"]["front_door"]
|
||||||
|
inputs = camera["ffmpeg"]["inputs"]
|
||||||
|
inputs[0]["roles"], inputs[1]["roles"] = ["record"], ["detect"]
|
||||||
|
|
||||||
|
resp = self._save(
|
||||||
|
client, {"cameras": {"front_door": {"ffmpeg": {"inputs": inputs}}}}
|
||||||
|
)
|
||||||
|
self.assertEqual(resp.status_code, 200, resp.text)
|
||||||
|
|
||||||
|
_, saved = self._read_config_file(config_path)
|
||||||
|
saved_inputs = saved["cameras"]["front_door"]["ffmpeg"]["inputs"]
|
||||||
|
self.assertEqual(
|
||||||
|
[(inp["path"], inp["roles"]) for inp in saved_inputs],
|
||||||
|
[(path_a, ["record"]), (path_b, ["detect"])],
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
os.unlink(config_path)
|
||||||
|
|
||||||
@patch("frigate.api.app.find_config_file")
|
@patch("frigate.api.app.find_config_file")
|
||||||
def test_over_masked_path_round_trips(self, mock_find_config):
|
def test_over_masked_path_round_trips(self, mock_find_config):
|
||||||
path = "rtsp://10.0.0.1:554/live?x=a@b"
|
path = "rtsp://10.0.0.1:554/live?x=a@b"
|
||||||
|
|||||||
@@ -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")
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|
||||||
@@ -12,11 +14,13 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
def setUp(self):
|
def setUp(self):
|
||||||
super().setUp([Event])
|
super().setUp([Event])
|
||||||
|
|
||||||
def _validate(self, status: PlusKeyStatus) -> dict:
|
def _validate(self, status: PlusKeyStatus, retry_after: int | None = None) -> dict:
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
|
plus_api = app.frigate_config.plus_api
|
||||||
|
|
||||||
with patch.object(
|
with (
|
||||||
app.frigate_config.plus_api, "validate_key", return_value=status
|
patch.object(plus_api, "validate_key", return_value=status),
|
||||||
|
patch.object(plus_api, "rate_limit_remaining", return_value=retry_after),
|
||||||
):
|
):
|
||||||
with AuthTestClient(app) as client:
|
with AuthTestClient(app) as client:
|
||||||
response = client.post("/plus/validate")
|
response = client.post("/plus/validate")
|
||||||
@@ -35,6 +39,12 @@ class TestHttpPlusValidate(BaseTestHttp):
|
|||||||
{"success": False, "status": "invalid"},
|
{"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):
|
def test_viewers_cannot_validate(self):
|
||||||
app = self.create_app()
|
app = self.create_app()
|
||||||
|
|
||||||
@@ -47,5 +57,111 @@ 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_a_rate_limited_annotation_can_be_retried(self):
|
||||||
|
self.insert_mock_event("event", data={"box": [0, 0, 1, 1]})
|
||||||
|
snapshot = patch(
|
||||||
|
"frigate.api.event.load_event_snapshot_image",
|
||||||
|
return_value=(np.ones((10, 10, 3), np.uint8), True),
|
||||||
|
)
|
||||||
|
|
||||||
|
with (
|
||||||
|
snapshot,
|
||||||
|
patch.object(self.plus_api, "upload_image", return_value="img") as upload,
|
||||||
|
patch.object(
|
||||||
|
self.plus_api,
|
||||||
|
"add_annotation",
|
||||||
|
side_effect=[PlusRateLimitError(30), None],
|
||||||
|
) as annotate,
|
||||||
|
AuthTestClient(self.app) as client,
|
||||||
|
):
|
||||||
|
first = client.post("/events/event/plus", json={"include_annotation": 1})
|
||||||
|
# the image isn't marked submitted while its annotation is missing
|
||||||
|
self.assertIsNone(Event.get(Event.id == "event").plus_id)
|
||||||
|
|
||||||
|
retry = client.post("/events/event/plus", json={"include_annotation": 1})
|
||||||
|
|
||||||
|
self._assert_rate_limited(first, 30)
|
||||||
|
self.assertEqual(retry.status_code, 200)
|
||||||
|
self.assertEqual(retry.json()["plus_id"], "img")
|
||||||
|
upload.assert_called_once()
|
||||||
|
self.assertEqual(
|
||||||
|
[call.args[0] for call in annotate.call_args_list], ["img", "img"]
|
||||||
|
)
|
||||||
|
|
||||||
|
event = Event.get(Event.id == "event")
|
||||||
|
self.assertEqual(event.plus_id, "img")
|
||||||
|
self.assertNotIn("plus_pending_id", event.data)
|
||||||
|
|
||||||
|
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)
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import pickle
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from unittest.mock import patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import requests
|
import requests
|
||||||
@@ -14,6 +15,7 @@ from frigate.config import BirdseyeModeEnum, FrigateConfig, RetainModeEnum
|
|||||||
from frigate.const import MODEL_CACHE_DIR
|
from frigate.const import MODEL_CACHE_DIR
|
||||||
from frigate.detectors import DetectorTypeEnum
|
from frigate.detectors import DetectorTypeEnum
|
||||||
from frigate.detectors.device import build_detector_config, runner_names
|
from frigate.detectors.device import build_detector_config, runner_names
|
||||||
|
from frigate.plus import PlusApi, PlusRateLimitError
|
||||||
from frigate.util.builtin import deep_merge
|
from frigate.util.builtin import deep_merge
|
||||||
from frigate.util.config import resolve_ffmpeg_path
|
from frigate.util.config import resolve_ffmpeg_path
|
||||||
|
|
||||||
@@ -1637,6 +1639,60 @@ class TestConfig(unittest.TestCase):
|
|||||||
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
|
with self.assertRaisesRegex(ValidationError, "Unable to connect to Frigate+"):
|
||||||
FrigateConfig(**config)
|
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_config_can_be_sent_to_a_worker_process(self):
|
||||||
|
# worker processes start from the forkserver, which pickles the config
|
||||||
|
# along with the Frigate+ client it holds
|
||||||
|
frigate_config = FrigateConfig(**self.minimal)
|
||||||
|
|
||||||
|
copy = pickle.loads(pickle.dumps(frigate_config))
|
||||||
|
|
||||||
|
self.assertIsInstance(copy.plus_api, PlusApi)
|
||||||
|
|
||||||
|
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):
|
def test_fails_on_invalid_role(self):
|
||||||
config = {
|
config = {
|
||||||
"mqtt": {"host": "mqtt"},
|
"mqtt": {"host": "mqtt"},
|
||||||
|
|||||||
@@ -518,11 +518,47 @@ class TestSecretsReload(unittest.TestCase):
|
|||||||
"""
|
"""
|
||||||
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "from_config"})
|
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "from_config"})
|
||||||
config = FrigateConfig.parse_yaml(
|
config = FrigateConfig.parse_yaml(
|
||||||
|
"environment_vars:\n FRIGATE_MQTT_HOST: from_config\n"
|
||||||
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
||||||
)
|
)
|
||||||
self.assertEqual(config.mqtt.host, "from_config")
|
self.assertEqual(config.mqtt.host, "from_config")
|
||||||
self.assertEqual(env._CONFIG_ENV_VARS["FRIGATE_MQTT_HOST"], "from_config")
|
self.assertEqual(env._CONFIG_ENV_VARS["FRIGATE_MQTT_HOST"], "from_config")
|
||||||
|
|
||||||
|
def test_candidate_env_var_resolves_before_install(self):
|
||||||
|
"""A non-install parse resolves against the candidate's own block, so
|
||||||
|
an entry can be added and referenced in the same save."""
|
||||||
|
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"})
|
||||||
|
config = FrigateConfig.parse_yaml(
|
||||||
|
"environment_vars:\n FRIGATE_MQTT_HOST: candidate\n"
|
||||||
|
" FRIGATE_MQTT_USER: added\n"
|
||||||
|
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\n'
|
||||||
|
' user: "{FRIGATE_MQTT_USER}"\n password: secret\ncameras: {}\n'
|
||||||
|
)
|
||||||
|
self.assertEqual(config.mqtt.host, "candidate")
|
||||||
|
self.assertEqual(config.mqtt.user, "added")
|
||||||
|
self.assertEqual(env._CONFIG_ENV_VARS, {"FRIGATE_MQTT_HOST": "running"})
|
||||||
|
self.assertNotIn("FRIGATE_MQTT_USER", os.environ)
|
||||||
|
|
||||||
|
def test_removed_candidate_env_var_fails_validation(self):
|
||||||
|
"""Removing an entry that is still referenced fails now, not at the
|
||||||
|
next start."""
|
||||||
|
env.apply_config_env_vars({"FRIGATE_MQTT_HOST": "running"})
|
||||||
|
with self.assertRaises(ValidationError):
|
||||||
|
FrigateConfig.parse_yaml(
|
||||||
|
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_candidate_env_var_keeps_lowest_precedence(self):
|
||||||
|
"""secrets.yaml still outranks the candidate's block."""
|
||||||
|
with open(os.path.join(self._dir.name, "secrets.yaml"), "w") as f:
|
||||||
|
f.write("FRIGATE_MQTT_HOST: from_secrets\n")
|
||||||
|
|
||||||
|
config = FrigateConfig.parse_yaml(
|
||||||
|
"environment_vars:\n FRIGATE_MQTT_HOST: candidate\n"
|
||||||
|
'mqtt:\n host: "{FRIGATE_MQTT_HOST}"\ncameras: {}\n'
|
||||||
|
)
|
||||||
|
self.assertEqual(config.mqtt.host, "from_secrets")
|
||||||
|
|
||||||
|
|
||||||
class TestSourceRobustness(unittest.TestCase):
|
class TestSourceRobustness(unittest.TestCase):
|
||||||
"""Reload behavior, bad input, and the os.environ export."""
|
"""Reload behavior, bad input, and the os.environ export."""
|
||||||
|
|||||||
+218
-4
@@ -1,9 +1,15 @@
|
|||||||
"""Tests for Frigate+ model metadata."""
|
"""Tests for Frigate+ model metadata."""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import datetime
|
||||||
|
import email.utils
|
||||||
|
import http.server
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import pickle
|
||||||
import tempfile
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
from unittest.mock import MagicMock, patch
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
@@ -11,7 +17,16 @@ import aiohttp
|
|||||||
from aiohttp import web
|
from aiohttp import web
|
||||||
from aiohttp.test_utils import TestServer
|
from aiohttp.test_utils import TestServer
|
||||||
|
|
||||||
from frigate.plus import PlusApi, PlusKeyStatus, load_plus_model_info
|
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}"
|
||||||
|
|
||||||
|
|
||||||
class TestHailoAlias(unittest.TestCase):
|
class TestHailoAlias(unittest.TestCase):
|
||||||
@@ -99,18 +114,26 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
api.host = host
|
api.host = host
|
||||||
api.key = key
|
api.key = key
|
||||||
api._token_data = dict(self.CACHED_TOKEN)
|
api._token_data = dict(self.CACHED_TOKEN)
|
||||||
|
api._rate_limited_until = None
|
||||||
return api
|
return api
|
||||||
|
|
||||||
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
async def _validate(self, handler) -> tuple[PlusKeyStatus, PlusApi]:
|
||||||
api = self._api(await self._serve(handler))
|
api = self._api(await self._serve(handler))
|
||||||
return await api.validate_key(), api
|
return await api.validate_key(), api
|
||||||
|
|
||||||
def _replies(self, status: int = 200, body: object = None, text: str | None = None):
|
def _replies(
|
||||||
|
self,
|
||||||
|
status: int = 200,
|
||||||
|
body: object = None,
|
||||||
|
text: str | None = None,
|
||||||
|
headers: dict[str, str] | None = None,
|
||||||
|
):
|
||||||
async def handler(request: web.Request) -> web.Response:
|
async def handler(request: web.Request) -> web.Response:
|
||||||
self.auth = request.headers.get("Authorization")
|
self.auth = request.headers.get("Authorization")
|
||||||
|
self.requests_seen = getattr(self, "requests_seen", 0) + 1
|
||||||
if text is not None:
|
if text is not None:
|
||||||
return web.Response(status=status, text=text)
|
return web.Response(status=status, text=text, headers=headers)
|
||||||
return web.json_response(body, status=status)
|
return web.json_response(body, status=status, headers=headers)
|
||||||
|
|
||||||
return handler
|
return handler
|
||||||
|
|
||||||
@@ -134,6 +157,25 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
|
|
||||||
self.assertEqual(status, PlusKeyStatus.unreachable)
|
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):
|
async def test_unusable_replies_keep_the_cached_token(self):
|
||||||
# a successful reply without a usable token must not replace one that
|
# a successful reply without a usable token must not replace one that
|
||||||
# later Frigate+ requests depend on
|
# later Frigate+ requests depend on
|
||||||
@@ -212,5 +254,177 @@ class TestValidateKey(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertEqual(requests_seen, [])
|
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_shorter_wait_arriving_later_keeps_the_longer_one(self):
|
||||||
|
# two requests in flight are both refused, and the reply with the
|
||||||
|
# longer wait is handled first
|
||||||
|
self.api._note_rate_limit(120)
|
||||||
|
self.api._note_rate_limit(10)
|
||||||
|
|
||||||
|
self.assertAlmostEqual(self.api.rate_limit_remaining(), 120, delta=1)
|
||||||
|
|
||||||
|
# a longer wait still extends it
|
||||||
|
self.api._note_rate_limit(300)
|
||||||
|
|
||||||
|
self.assertAlmostEqual(self.api.rate_limit_remaining(), 300, delta=1)
|
||||||
|
|
||||||
|
def test_concurrent_replies_keep_the_longest_wait(self):
|
||||||
|
waits = list(range(1, 201))
|
||||||
|
threads = [
|
||||||
|
threading.Thread(target=self.api._note_rate_limit, args=(wait,))
|
||||||
|
for wait in waits
|
||||||
|
]
|
||||||
|
|
||||||
|
with patch("frigate.plus.logger"):
|
||||||
|
for thread in threads:
|
||||||
|
thread.start()
|
||||||
|
for thread in threads:
|
||||||
|
thread.join()
|
||||||
|
|
||||||
|
self.assertAlmostEqual(self.api.rate_limit_remaining(), max(waits), delta=1)
|
||||||
|
|
||||||
|
def test_the_client_can_be_sent_to_a_worker_process(self):
|
||||||
|
# worker processes start from the forkserver, which pickles the
|
||||||
|
# config and the Frigate+ client it holds
|
||||||
|
self.api._note_rate_limit(60)
|
||||||
|
|
||||||
|
copy = pickle.loads(pickle.dumps(self.api))
|
||||||
|
|
||||||
|
self.assertAlmostEqual(copy.rate_limit_remaining(), 60, delta=1)
|
||||||
|
copy._note_rate_limit(120)
|
||||||
|
self.assertAlmostEqual(copy.rate_limit_remaining(), 120, delta=1)
|
||||||
|
|
||||||
|
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__":
|
if __name__ == "__main__":
|
||||||
unittest.main(verbosity=2)
|
unittest.main(verbosity=2)
|
||||||
|
|||||||
+40
-4
@@ -3,7 +3,9 @@
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from collections.abc import Mapping
|
from collections.abc import Iterator, Mapping
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from contextvars import ContextVar
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
|
||||||
@@ -246,6 +248,35 @@ def apply_config_env_vars(values: Mapping[str, object]) -> None:
|
|||||||
reload_sources(warn=False)
|
reload_sources(warn=False)
|
||||||
|
|
||||||
|
|
||||||
|
_CANDIDATE_ENV_VARS: ContextVar[dict[str, str] | None] = ContextVar(
|
||||||
|
"candidate_env_vars", default=None
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def candidate_env_vars(values: object) -> Iterator[None]:
|
||||||
|
"""Resolve placeholders against a candidate config's environment_vars.
|
||||||
|
|
||||||
|
Its FRIGATE_ keys replace the installed block at the same lowest
|
||||||
|
precedence. Nothing is installed or exported to os.environ.
|
||||||
|
"""
|
||||||
|
merged = {
|
||||||
|
str(key): str(value)
|
||||||
|
for key, value in (values.items() if isinstance(values, Mapping) else ())
|
||||||
|
if str(key).startswith("FRIGATE_")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, source in _SOURCES:
|
||||||
|
if source is not _CONFIG_ENV_VARS:
|
||||||
|
merged.update(source)
|
||||||
|
|
||||||
|
token = _CANDIDATE_ENV_VARS.set(merged)
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
_CANDIDATE_ENV_VARS.reset(token)
|
||||||
|
|
||||||
|
|
||||||
# Matches a FRIGATE_* identifier following an opening brace.
|
# Matches a FRIGATE_* identifier following an opening brace.
|
||||||
_FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+")
|
_FRIGATE_IDENT_RE = re.compile(r"FRIGATE_[A-Za-z0-9_]+")
|
||||||
|
|
||||||
@@ -258,7 +289,8 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
(e.g. ffmpeg `%{localtime\\:...}` expressions) untouched:
|
(e.g. ffmpeg `%{localtime\\:...}` expressions) untouched:
|
||||||
|
|
||||||
* `{{` and `}}` collapse to literal `{` / `}` (the documented escape).
|
* `{{` and `}}` collapse to literal `{` / `}` (the documented escape).
|
||||||
* `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`; an unknown name
|
* `{FRIGATE_NAME}` is replaced from `FRIGATE_ENV_VARS`, or from the
|
||||||
|
sources set by `candidate_env_vars`; an unknown name
|
||||||
raises `UnknownVariableError` to preserve the existing "Invalid
|
raises `UnknownVariableError` to preserve the existing "Invalid
|
||||||
substitution" error path.
|
substitution" error path.
|
||||||
* A `{` that begins `{FRIGATE_` but is not a well-formed
|
* A `{` that begins `{FRIGATE_` but is not a well-formed
|
||||||
@@ -268,6 +300,10 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
error.
|
error.
|
||||||
* Any other `{` or `}` is treated as a literal and passed through.
|
* Any other `{` or `}` is treated as a literal and passed through.
|
||||||
"""
|
"""
|
||||||
|
env_vars = _CANDIDATE_ENV_VARS.get()
|
||||||
|
if env_vars is None:
|
||||||
|
env_vars = FRIGATE_ENV_VARS
|
||||||
|
|
||||||
out: list[str] = []
|
out: list[str] = []
|
||||||
i = 0
|
i = 0
|
||||||
n = len(value)
|
n = len(value)
|
||||||
@@ -288,12 +324,12 @@ def substitute_frigate_vars(value: str) -> str:
|
|||||||
and value[ident_match.end()] == "}"
|
and value[ident_match.end()] == "}"
|
||||||
):
|
):
|
||||||
key = ident_match.group(0)
|
key = ident_match.group(0)
|
||||||
if key not in FRIGATE_ENV_VARS:
|
if key not in env_vars:
|
||||||
raise UnknownVariableError(
|
raise UnknownVariableError(
|
||||||
f"{key} is not defined in the environment, "
|
f"{key} is not defined in the environment, "
|
||||||
"secrets.yaml, or the environment_vars config"
|
"secrets.yaml, or the environment_vars config"
|
||||||
)
|
)
|
||||||
out.append(FRIGATE_ENV_VARS[key])
|
out.append(env_vars[key])
|
||||||
i = ident_match.end() + 1
|
i = ident_match.end() + 1
|
||||||
continue
|
continue
|
||||||
# Looks like a FRIGATE placeholder but is malformed
|
# Looks like a FRIGATE placeholder but is malformed
|
||||||
|
|||||||
+31
-14
@@ -30,7 +30,11 @@ from frigate.const import (
|
|||||||
SHM_FRAMES_VAR,
|
SHM_FRAMES_VAR,
|
||||||
)
|
)
|
||||||
from frigate.util.builtin import clean_camera_user_pass, escape_special_characters
|
from frigate.util.builtin import clean_camera_user_pass, escape_special_characters
|
||||||
from frigate.util.env import UnknownVariableError, substitute_frigate_vars
|
from frigate.util.env import (
|
||||||
|
UnknownVariableError,
|
||||||
|
candidate_env_vars,
|
||||||
|
substitute_frigate_vars,
|
||||||
|
)
|
||||||
from frigate.util.live_streams import is_valid_go2rtc_stream_name
|
from frigate.util.live_streams import is_valid_go2rtc_stream_name
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -1228,16 +1232,27 @@ class Go2rtcStreamIssue(str, Enum):
|
|||||||
invalid_name = "invalid_name"
|
invalid_name = "invalid_name"
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_running_frigate_vars(source: str) -> str | None:
|
||||||
|
try:
|
||||||
|
return substitute_frigate_vars(source)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def find_restricted_go2rtc_stream_changes(
|
def find_restricted_go2rtc_stream_changes(
|
||||||
old_streams: dict[str, Any] | None, new_streams: dict[str, Any] | None
|
old_streams: dict[str, Any] | None,
|
||||||
|
new_streams: dict[str, Any] | None,
|
||||||
|
new_env_vars: object,
|
||||||
) -> dict[str, Go2rtcStreamIssue]:
|
) -> dict[str, Go2rtcStreamIssue]:
|
||||||
"""Return the go2rtc streams with new sources that must be rejected.
|
"""Return the go2rtc streams with new sources that must be rejected.
|
||||||
|
|
||||||
Used when the config is changed through the API. A source that is already
|
Used when the config is changed through the API. Every source must resolve
|
||||||
in the saved config for the same stream is left alone, so streams the
|
its {FRIGATE_*} placeholders against the new config's environment_vars. A
|
||||||
operator configured on disk keep working; any other source must resolve
|
source that is already in the saved config for the same stream and
|
||||||
its {FRIGATE_*} placeholders and pass `is_restricted_go2rtc_api_source`.
|
resolves to the same value as it does now is left alone, so streams the
|
||||||
New stream names must pass `is_valid_go2rtc_stream_name`.
|
operator configured on disk keep working; any other source must pass
|
||||||
|
`is_restricted_go2rtc_api_source`. New stream names must pass
|
||||||
|
`is_valid_go2rtc_stream_name`.
|
||||||
"""
|
"""
|
||||||
old_streams = old_streams if isinstance(old_streams, dict) else {}
|
old_streams = old_streams if isinstance(old_streams, dict) else {}
|
||||||
new_streams = new_streams if isinstance(new_streams, dict) else {}
|
new_streams = new_streams if isinstance(new_streams, dict) else {}
|
||||||
@@ -1251,20 +1266,17 @@ def find_restricted_go2rtc_stream_changes(
|
|||||||
existing = _go2rtc_stream_sources(old_streams.get(name))
|
existing = _go2rtc_stream_sources(old_streams.get(name))
|
||||||
|
|
||||||
for source in _go2rtc_stream_sources(stream):
|
for source in _go2rtc_stream_sources(stream):
|
||||||
if source in existing:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if not isinstance(source, str):
|
if not isinstance(source, str):
|
||||||
# the map form is only usable with arbitrary exec enabled
|
# the map form is only usable with arbitrary exec enabled
|
||||||
if is_go2rtc_arbitrary_exec_allowed():
|
if source in existing or is_go2rtc_arbitrary_exec_allowed():
|
||||||
continue
|
continue
|
||||||
issues[name] = Go2rtcStreamIssue.restricted
|
issues[name] = Go2rtcStreamIssue.restricted
|
||||||
break
|
break
|
||||||
|
|
||||||
# only sources whose placeholders resolve here are accepted, so the
|
# the resolved value checked below is what go2rtc loads at startup
|
||||||
# resolved value checked below is what go2rtc loads at startup
|
|
||||||
try:
|
try:
|
||||||
resolved_source = substitute_frigate_vars(source)
|
with candidate_env_vars(new_env_vars):
|
||||||
|
resolved_source = substitute_frigate_vars(source)
|
||||||
except UnknownVariableError:
|
except UnknownVariableError:
|
||||||
issues[name] = Go2rtcStreamIssue.unknown_variable
|
issues[name] = Go2rtcStreamIssue.unknown_variable
|
||||||
break
|
break
|
||||||
@@ -1272,6 +1284,11 @@ def find_restricted_go2rtc_stream_changes(
|
|||||||
issues[name] = Go2rtcStreamIssue.invalid_placeholder
|
issues[name] = Go2rtcStreamIssue.invalid_placeholder
|
||||||
break
|
break
|
||||||
|
|
||||||
|
if source in existing and resolved_source == (
|
||||||
|
_resolve_running_frigate_vars(source)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
if is_restricted_go2rtc_api_source(
|
if is_restricted_go2rtc_api_source(
|
||||||
source
|
source
|
||||||
) or is_restricted_go2rtc_api_source(resolved_source):
|
) or is_restricted_go2rtc_api_source(resolved_source):
|
||||||
|
|||||||
@@ -342,4 +342,37 @@ test.describe("Explore — Frigate+ submission (desktop) @high", () => {
|
|||||||
dialog.getByRole("button", { name: "Yes", exact: true }),
|
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||||
).toBeVisible();
|
).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a rate limited submission says how long to wait", async ({
|
||||||
|
frigateApp,
|
||||||
|
}) => {
|
||||||
|
await frigateApp.installDefaults({ config: { plus: { enabled: true } } });
|
||||||
|
const page = frigateApp.page;
|
||||||
|
await page.route("**/api/events/*/plus", (route) =>
|
||||||
|
route.fulfill({
|
||||||
|
status: 429,
|
||||||
|
headers: { "Retry-After": "90" },
|
||||||
|
json: { success: false, retry_after: 90 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
await frigateApp.goto("/explore?labels=person");
|
||||||
|
|
||||||
|
const firstResult = page.locator("[data-start]").first();
|
||||||
|
await expect(firstResult).toBeVisible({ timeout: 10_000 });
|
||||||
|
await firstResult.click();
|
||||||
|
|
||||||
|
const dialog = page.getByRole("dialog");
|
||||||
|
await dialog.getByRole("button", { name: "Yes", exact: true }).click();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
page.getByText(
|
||||||
|
"Frigate+ is rate limiting requests. Try again in 1 minute, 30 seconds.",
|
||||||
|
),
|
||||||
|
).toBeVisible();
|
||||||
|
// the object can be submitted again once the wait is over
|
||||||
|
await expect(
|
||||||
|
dialog.getByRole("button", { name: "Yes", exact: true }),
|
||||||
|
).toBeVisible();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -459,6 +459,36 @@ test.describe("Detection models settings @high", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a Frigate+ rate limit says how long to wait, including days", 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": "90000" },
|
||||||
|
json: { success: false, retry_after: 90000 },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await openPage(frigateApp);
|
||||||
|
|
||||||
|
await expect(frigateApp.page.locator("#pageRoot")).toContainText(
|
||||||
|
"Frigate+ is rate limiting requests. Try again in 1 day, 1 hour.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
test("picking a Frigate+ model stays on the tab and saves a plus path", async ({
|
||||||
frigateApp,
|
frigateApp,
|
||||||
}) => {
|
}) => {
|
||||||
|
|||||||
@@ -327,6 +327,10 @@
|
|||||||
"copyDetails": "Copy details",
|
"copyDetails": "Copy details",
|
||||||
"copyFailed": "Could not copy details to clipboard"
|
"copyFailed": "Could not copy details to clipboard"
|
||||||
},
|
},
|
||||||
|
"plusRateLimited": {
|
||||||
|
"retryIn": "Frigate+ is rate limiting requests. Try again in {{duration}}.",
|
||||||
|
"retryLater": "Frigate+ is rate limiting requests. Try again later."
|
||||||
|
},
|
||||||
"selectItem": "Select {{item}}",
|
"selectItem": "Select {{item}}",
|
||||||
"readTheDocumentation": "Read the documentation",
|
"readTheDocumentation": "Read the documentation",
|
||||||
"information": {
|
"information": {
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { Switch } from "@/components/ui/switch";
|
|||||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||||
import { describeSupportedDetectors } from "@/utils/plusModels";
|
import { describeSupportedDetectors } from "@/utils/plusModels";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
export type FrigatePlusModel = {
|
export type FrigatePlusModel = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -65,20 +66,26 @@ export function ModelSourcePicker({
|
|||||||
// metadata of whatever model was saved before it
|
// metadata of whatever model was saved before it
|
||||||
const selectedId = plusModelId(path) ?? plus?.id;
|
const selectedId = plusModelId(path) ?? plus?.id;
|
||||||
|
|
||||||
const { data: availableModels, isLoading } = useSWR<
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
Record<string, FrigatePlusModel>
|
const {
|
||||||
>(plusEnabled ? "/plus/models" : null, {
|
data: availableModels,
|
||||||
fetcher: async (url) => {
|
error: modelsError,
|
||||||
const res = await axios.get(url, { withCredentials: true });
|
isLoading,
|
||||||
return res.data.reduce(
|
} = useSWR<Record<string, FrigatePlusModel>>(
|
||||||
(obj: Record<string, FrigatePlusModel>, model: FrigatePlusModel) => {
|
plusEnabled ? "/plus/models" : null,
|
||||||
obj[model.id] = model;
|
{
|
||||||
return obj;
|
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 [showIncompatible, setShowIncompatible] = useState(false);
|
||||||
const showIncompatibleId = useId();
|
const showIncompatibleId = useId();
|
||||||
@@ -101,6 +108,7 @@ export function ModelSourcePicker({
|
|||||||
const isCompatible = (model: FrigatePlusModel) =>
|
const isCompatible = (model: FrigatePlusModel) =>
|
||||||
!detector || model.supportedDetectors.includes(detector);
|
!detector || model.supportedDetectors.includes(detector);
|
||||||
|
|
||||||
|
const rateLimitMessage = getRateLimitMessage(modelsError);
|
||||||
const allEntries = Object.entries(availableModels ?? {});
|
const allEntries = Object.entries(availableModels ?? {});
|
||||||
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
|
const hasIncompatible = allEntries.some(([, model]) => !isCompatible(model));
|
||||||
|
|
||||||
@@ -163,7 +171,8 @@ export function ModelSourcePicker({
|
|||||||
<SelectGroup>
|
<SelectGroup>
|
||||||
{entries.length === 0 ? (
|
{entries.length === 0 ? (
|
||||||
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
<div className="px-4 py-3 text-center text-sm text-muted-foreground">
|
||||||
{t("frigatePlus.modelInfo.noModelsAvailable")}
|
{rateLimitMessage ??
|
||||||
|
t("frigatePlus.modelInfo.noModelsAvailable")}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
entries.map(([id, model]) => (
|
entries.map(([id, model]) => (
|
||||||
@@ -184,6 +193,9 @@ export function ModelSourcePicker({
|
|||||||
</SelectGroup>
|
</SelectGroup>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
{rateLimitMessage && (
|
||||||
|
<p className="text-xs text-danger">{rateLimitMessage}</p>
|
||||||
|
)}
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
|
<Trans ns="views/settings">frigatePlus.modelInfo.modelSelect</Trans>
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -87,6 +87,7 @@ import TextEntryDialog from "@/components/overlay/dialog/TextEntryDialog";
|
|||||||
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
|
import AttributeSelectDialog from "@/components/overlay/dialog/AttributeSelectDialog";
|
||||||
import { Trans, useTranslation } from "react-i18next";
|
import { Trans, useTranslation } from "react-i18next";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import { getTranslatedLabel } from "@/utils/i18n";
|
import { getTranslatedLabel } from "@/utils/i18n";
|
||||||
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
import { CameraNameLabel } from "@/components/camera/FriendlyNameLabel";
|
||||||
import { DialogPortal } from "@radix-ui/react-dialog";
|
import { DialogPortal } from "@radix-ui/react-dialog";
|
||||||
@@ -699,6 +700,7 @@ function ObjectDetailsTab({
|
|||||||
"views/faceLibrary",
|
"views/faceLibrary",
|
||||||
"components/dialog",
|
"components/dialog",
|
||||||
]);
|
]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
|
|
||||||
const apiHost = useApiHost();
|
const apiHost = useApiHost();
|
||||||
const hasCustomClassificationModels = useMemo(
|
const hasCustomClassificationModels = useMemo(
|
||||||
@@ -1286,7 +1288,7 @@ function ObjectDetailsTab({
|
|||||||
revalidate: false,
|
revalidate: false,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch {
|
} catch (error) {
|
||||||
if (displayedIdRef.current === eventId) {
|
if (displayedIdRef.current === eventId) {
|
||||||
setState("reviewing");
|
setState("reviewing");
|
||||||
}
|
}
|
||||||
@@ -1294,12 +1296,13 @@ function ObjectDetailsTab({
|
|||||||
// the toast is not object specific, so it is always shown to avoid
|
// the toast is not object specific, so it is always shown to avoid
|
||||||
// silently dropping a failed submission
|
// silently dropping a failed submission
|
||||||
toast.error(
|
toast.error(
|
||||||
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
getRateLimitMessage(error) ??
|
||||||
|
t("explore.plus.review.toast.error", { ns: "components/dialog" }),
|
||||||
{ position: "top-center" },
|
{ position: "top-center" },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[search, mutate, mapSearchResults, isEventsKey, t],
|
[search, mutate, mapSearchResults, isEventsKey, t, getRateLimitMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
const popoverContainerRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ import { useApiHost } from "@/api";
|
|||||||
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
|
import ImageLoadingIndicator from "@/components/indicators/ImageLoadingIndicator";
|
||||||
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
import ObjectTrackOverlay from "../ObjectTrackOverlay";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import { VideoResolutionType } from "@/types/live";
|
import { VideoResolutionType } from "@/types/live";
|
||||||
import { VodManifest } from "@/types/playback";
|
import { VodManifest } from "@/types/playback";
|
||||||
|
|
||||||
@@ -934,6 +935,7 @@ function LifecycleIconRow({
|
|||||||
annotationOffset,
|
annotationOffset,
|
||||||
}: LifecycleIconRowProps) {
|
}: LifecycleIconRowProps) {
|
||||||
const { t } = useTranslation(["views/explore", "components/player"]);
|
const { t } = useTranslation(["views/explore", "components/player"]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
const { data: config } = useSWR<FrigateConfig>("config");
|
const { data: config } = useSWR<FrigateConfig>("config");
|
||||||
const [isOpen, setIsOpen] = useState(false);
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
|
const [showAdvancedScores, setShowAdvancedScores] = useState(false);
|
||||||
@@ -1251,11 +1253,12 @@ function LifecycleIconRow({
|
|||||||
position: "top-center",
|
position: "top-center",
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
} catch {
|
} catch (error) {
|
||||||
toast.error(
|
toast.error(
|
||||||
t("toast.error.submitFrigatePlusFailed", {
|
getRateLimitMessage(error) ??
|
||||||
ns: "components/player",
|
t("toast.error.submitFrigatePlusFailed", {
|
||||||
}),
|
ns: "components/player",
|
||||||
|
}),
|
||||||
{
|
{
|
||||||
position: "top-center",
|
position: "top-center",
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { baseUrl } from "@/api/baseUrl";
|
|||||||
import { getTranslatedLabel } from "@/utils/i18n";
|
import { getTranslatedLabel } from "@/utils/i18n";
|
||||||
import useImageLoaded from "@/hooks/use-image-loaded";
|
import useImageLoaded from "@/hooks/use-image-loaded";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
export type FrigatePlusDialogProps = {
|
export type FrigatePlusDialogProps = {
|
||||||
upload?: Event;
|
upload?: Event;
|
||||||
@@ -37,6 +38,7 @@ export function FrigatePlusDialog({
|
|||||||
onEventUploaded,
|
onEventUploaded,
|
||||||
}: FrigatePlusDialogProps) {
|
}: FrigatePlusDialogProps) {
|
||||||
const { t, i18n } = useTranslation(["components/dialog"]);
|
const { t, i18n } = useTranslation(["components/dialog"]);
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
|
|
||||||
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
type SubmissionState = "reviewing" | "uploading" | "submitted";
|
||||||
const [state, setState] = useState<SubmissionState>(
|
const [state, setState] = useState<SubmissionState>(
|
||||||
@@ -63,14 +65,15 @@ export function FrigatePlusDialog({
|
|||||||
|
|
||||||
setState("submitted");
|
setState("submitted");
|
||||||
onEventUploaded();
|
onEventUploaded();
|
||||||
} catch {
|
} catch (error) {
|
||||||
setState("reviewing");
|
setState("reviewing");
|
||||||
toast.error(t("explore.plus.review.toast.error"), {
|
toast.error(
|
||||||
position: "top-center",
|
getRateLimitMessage(error) ?? t("explore.plus.review.toast.error"),
|
||||||
});
|
{ position: "top-center" },
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[upload, onEventUploaded, t],
|
[upload, onEventUploaded, t, getRateLimitMessage],
|
||||||
);
|
);
|
||||||
|
|
||||||
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
const [imgRef, imgLoaded, onImgLoad] = useImageLoaded();
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import { ASPECT_VERTICAL_LAYOUT, RecordingPlayerError } from "@/types/record";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
|
import ObjectTrackOverlay from "@/components/overlay/ObjectTrackOverlay";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
// Android native hls does not seek correctly
|
// Android native hls does not seek correctly
|
||||||
const USE_NATIVE_HLS = false;
|
const USE_NATIVE_HLS = false;
|
||||||
@@ -109,6 +110,7 @@ export default function HlsVideoPlayer({
|
|||||||
transformedOverlay,
|
transformedOverlay,
|
||||||
}: HlsVideoPlayerProps) {
|
}: HlsVideoPlayerProps) {
|
||||||
const { t } = useTranslation("components/player");
|
const { t } = useTranslation("components/player");
|
||||||
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
const { data: config } = useSWR<FrigateConfig>("config");
|
const { data: config } = useSWR<FrigateConfig>("config");
|
||||||
const isAdmin = useIsAdmin();
|
const isAdmin = useIsAdmin();
|
||||||
|
|
||||||
@@ -525,18 +527,26 @@ export default function HlsVideoPlayer({
|
|||||||
onUploadFrame={async () => {
|
onUploadFrame={async () => {
|
||||||
const frameTime = getVideoTime();
|
const frameTime = getVideoTime();
|
||||||
|
|
||||||
if (frameTime && onUploadFrame) {
|
if (!frameTime || !onUploadFrame) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
const resp = await onUploadFrame(frameTime);
|
const resp = await onUploadFrame(frameTime);
|
||||||
|
|
||||||
if (resp && resp.status == 200) {
|
if (resp?.status !== 200) {
|
||||||
toast.success(t("toast.success.submittedFrigatePlus"), {
|
throw new Error();
|
||||||
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}
|
onSnapshot={onSnapshot ? handleSnapshot : undefined}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from "@/components/ui/select";
|
} from "@/components/ui/select";
|
||||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
import type { FrigateConfig } from "@/types/frigateConfig";
|
import type { FrigateConfig } from "@/types/frigateConfig";
|
||||||
import type { DetectionHardware } from "@/types/hardware";
|
import type { DetectionHardware } from "@/types/hardware";
|
||||||
import { recommendedDetectorCount } from "@/utils/detectionHardware";
|
import { recommendedDetectorCount } from "@/utils/detectionHardware";
|
||||||
@@ -79,15 +80,16 @@ export default function SetupDetector({
|
|||||||
|
|
||||||
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
const needsModel = MODEL_REQUIRED_DETECTORS.includes(selected.detector);
|
||||||
|
|
||||||
const { data: plusModels } = useSWR<FrigatePlusModel[]>(
|
const { getRateLimitMessage } = usePlusRateLimit();
|
||||||
plusEnabled && needsModel ? "/plus/models" : null,
|
const { data: plusModels, error: plusModelsError } = useSWR<
|
||||||
{
|
FrigatePlusModel[]
|
||||||
fetcher: async (url) => {
|
>(plusEnabled && needsModel ? "/plus/models" : null, {
|
||||||
const res = await axios.get(url, { withCredentials: true });
|
fetcher: async (url) => {
|
||||||
return res.data;
|
const res = await axios.get(url, { withCredentials: true });
|
||||||
},
|
return res.data;
|
||||||
},
|
},
|
||||||
);
|
});
|
||||||
|
const plusRateLimitMessage = getRateLimitMessage(plusModelsError);
|
||||||
const [plusModelId, setPlusModelId] = useState("");
|
const [plusModelId, setPlusModelId] = useState("");
|
||||||
|
|
||||||
const compatiblePlusModels = useMemo(
|
const compatiblePlusModels = useMemo(
|
||||||
@@ -217,6 +219,9 @@ export default function SetupDetector({
|
|||||||
<p>
|
<p>
|
||||||
{t("setupWizard.detector.modelRequired", { name: selected.name })}
|
{t("setupWizard.detector.modelRequired", { name: selected.name })}
|
||||||
</p>
|
</p>
|
||||||
|
{plusEnabled && plusRateLimitMessage && (
|
||||||
|
<p className="text-danger">{plusRateLimitMessage}</p>
|
||||||
|
)}
|
||||||
{plusEnabled ? (
|
{plusEnabled ? (
|
||||||
<Select value={plusModelId} onValueChange={setPlusModelId}>
|
<Select value={plusModelId} onValueChange={setPlusModelId}>
|
||||||
<SelectTrigger className="max-w-xs">
|
<SelectTrigger className="max-w-xs">
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import { formatDuration, Locale } from "date-fns";
|
||||||
|
import { useCallback } from "react";
|
||||||
|
import { useTranslation } from "react-i18next";
|
||||||
|
import { useDateLocale } from "@/hooks/use-date-locale";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The wait Frigate+ asked for when a request failed because of its rate limit.
|
||||||
|
*
|
||||||
|
* @returns the seconds to wait, null when rate limited without a known wait,
|
||||||
|
* or undefined when the error is not a rate limit
|
||||||
|
*/
|
||||||
|
export function getPlusRetryAfter(error: unknown): number | null | undefined {
|
||||||
|
if (!axios.isAxiosError(error) || error.response?.status !== 429) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const retryAfter = error.response.data?.retry_after;
|
||||||
|
return typeof retryAfter === "number" ? retryAfter : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A wait in seconds as a readable duration, such as "1 day, 1 hour".
|
||||||
|
*
|
||||||
|
* Waits can last days, so the days are kept rather than folded away or
|
||||||
|
* turned into calendar months.
|
||||||
|
*/
|
||||||
|
export function formatPlusWait(seconds: number, locale?: Locale): string {
|
||||||
|
const total = Math.ceil(seconds);
|
||||||
|
|
||||||
|
return formatDuration(
|
||||||
|
{
|
||||||
|
days: Math.floor(total / 86400),
|
||||||
|
hours: Math.floor((total % 86400) / 3600),
|
||||||
|
minutes: Math.floor((total % 3600) / 60),
|
||||||
|
seconds: total % 60,
|
||||||
|
},
|
||||||
|
{ delimiter: ", ", locale },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Messages telling the user Frigate+ is rate limiting requests. */
|
||||||
|
export function usePlusRateLimit() {
|
||||||
|
const { t } = useTranslation(["common"]);
|
||||||
|
const dateLocale = useDateLocale();
|
||||||
|
|
||||||
|
const formatRateLimit = useCallback(
|
||||||
|
(retryAfter: number | null | undefined) =>
|
||||||
|
retryAfter && retryAfter > 0
|
||||||
|
? t("plusRateLimited.retryIn", {
|
||||||
|
ns: "common",
|
||||||
|
duration: formatPlusWait(retryAfter, dateLocale),
|
||||||
|
})
|
||||||
|
: t("plusRateLimited.retryLater", { ns: "common" }),
|
||||||
|
[t, dateLocale],
|
||||||
|
);
|
||||||
|
|
||||||
|
// undefined when the error is not a rate limit, so callers can fall back
|
||||||
|
// to their own error message
|
||||||
|
const getRateLimitMessage = useCallback(
|
||||||
|
(error: unknown) => {
|
||||||
|
const retryAfter = getPlusRetryAfter(error);
|
||||||
|
return retryAfter === undefined ? undefined : formatRateLimit(retryAfter);
|
||||||
|
},
|
||||||
|
[formatRateLimit],
|
||||||
|
);
|
||||||
|
|
||||||
|
return { formatRateLimit, getRateLimitMessage };
|
||||||
|
}
|
||||||
@@ -20,10 +20,17 @@ import { isReplayCamera } from "@/utils/cameraUtil";
|
|||||||
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
|
import type { SettingsPageProps } from "@/views/settings/SingleSectionPage";
|
||||||
import { getPrimaryModel } from "@/utils/modelUtil";
|
import { getPrimaryModel } from "@/utils/modelUtil";
|
||||||
import { useIsAdmin } from "@/hooks/use-is-admin";
|
import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||||
|
import { usePlusRateLimit } from "@/hooks/use-plus-rate-limit";
|
||||||
|
|
||||||
type PlusKeyStatus = "valid" | "invalid" | "unreachable" | "not_set";
|
type PlusKeyStatus =
|
||||||
|
"valid" | "invalid" | "unreachable" | "rate_limited" | "not_set";
|
||||||
|
|
||||||
type PlusValidateResponse = { success: boolean; status: PlusKeyStatus };
|
type PlusValidateResponse = {
|
||||||
|
success: boolean;
|
||||||
|
status: PlusKeyStatus;
|
||||||
|
// seconds until Frigate+ accepts requests again, when rate limited
|
||||||
|
retry_after?: number | null;
|
||||||
|
};
|
||||||
|
|
||||||
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
||||||
const { t } = useTranslation("views/settings");
|
const { t } = useTranslation("views/settings");
|
||||||
@@ -34,6 +41,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
|
|
||||||
const [isValidating, setIsValidating] = useState(false);
|
const [isValidating, setIsValidating] = useState(false);
|
||||||
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
|
const [keyStatus, setKeyStatus] = useState<PlusKeyStatus>();
|
||||||
|
const [retryAfter, setRetryAfter] = useState<number | null>(null);
|
||||||
|
const { formatRateLimit } = usePlusRateLimit();
|
||||||
|
|
||||||
const validateKey = useCallback(async () => {
|
const validateKey = useCallback(async () => {
|
||||||
setIsValidating(true);
|
setIsValidating(true);
|
||||||
@@ -41,6 +50,7 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
try {
|
try {
|
||||||
const response = await axios.post<PlusValidateResponse>("plus/validate");
|
const response = await axios.post<PlusValidateResponse>("plus/validate");
|
||||||
setKeyStatus(response.data.status);
|
setKeyStatus(response.data.status);
|
||||||
|
setRetryAfter(response.data.retry_after ?? null);
|
||||||
} catch {
|
} catch {
|
||||||
setKeyStatus("unreachable");
|
setKeyStatus("unreachable");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -124,7 +134,8 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
{keyStatus === "valid" ? (
|
{keyStatus === "valid" ? (
|
||||||
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
|
<CheckCircle2 className="size-5 shrink-0 text-green-500" />
|
||||||
) : keyStatus === "unreachable" ? (
|
) : keyStatus === "unreachable" ||
|
||||||
|
keyStatus === "rate_limited" ? (
|
||||||
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
|
<AlertTriangle className="size-5 shrink-0 text-yellow-500" />
|
||||||
) : (
|
) : (
|
||||||
<XCircle className="size-5 shrink-0 text-red-500" />
|
<XCircle className="size-5 shrink-0 text-red-500" />
|
||||||
@@ -134,7 +145,9 @@ export default function FrigatePlusSettingsView(_props: SettingsPageProps) {
|
|||||||
? t("frigatePlus.apiKey.serverValid")
|
? t("frigatePlus.apiKey.serverValid")
|
||||||
: keyStatus === "unreachable"
|
: keyStatus === "unreachable"
|
||||||
? t("frigatePlus.apiKey.serverUnreachable")
|
? t("frigatePlus.apiKey.serverUnreachable")
|
||||||
: t("frigatePlus.apiKey.serverInvalid")}
|
: keyStatus === "rate_limited"
|
||||||
|
? formatRateLimit(retryAfter)
|
||||||
|
: t("frigatePlus.apiKey.serverInvalid")}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
Reference in New Issue
Block a user