Skip to content

feat: add UniFi Protect API (protect feature) - #78

Merged
JudahZF merged 4 commits into
mainfrom
t3code/plan-unifi-protect-support
Jul 24, 2026
Merged

JudahZF merged 4 commits into
mainfrom
t3code/plan-unifi-protect-support

Conversation

@JudahZF

@JudahZF JudahZF commented Jul 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds support for the official UniFi Protect Integration API (Protect >= 5.3) behind a new opt-in protect cargo feature, with the existing Network API moving behind a unifi feature that remains in default.

  • New ProtectClient targeting /proxy/protect/integration/v1 with the same X-API-Key auth as the Network client: cameras (list/get/patch), binary JPEG snapshots, RTSPS stream get/create/delete, lights, sensors, chimes, viewers, NVR, and meta/info.
  • Live WebSocket subscriptions — subscribe_events() and subscribe_device_updates() return typed futures::Streams over {"type", "item"} envelopes. No auto-reconnect by design (the API has no replay cursor); the reconnect idiom is documented.
  • Shared HTTP transport (src/transport.rs) extracted from UnifiClient so both clients share request/deserialize behavior.
  • First [features] table: default = ["unifi"]; shared core (Error, Endpoint trait, common models) stays ungated. CI now tests the feature matrix.
  • BREAKING: Error is now #[non_exhaustive] and gained a WebSocket(String) variant (declared via BREAKING CHANGE footer → release-plz will cut 2.0.0).
  • Tests: serde round-trips from captured payloads, wiremock HTTP mocks (headers, PATCH bodies, binary snapshot bytes), and a local tungstenite server for stream behavior.
  • New examples/protect-events/ package; README Protect section.

Needs live-console verification (non-blocking)

  • GET /nvrs response shape (modeled as a single object)
  • RTSPS DELETE param placement (implemented as ?qualities= query params)

Test plan

  • cargo build / test / clippy / fmt --check across default, --no-default-features, --no-default-features --features protect, --all-features
  • cargo test --doc --all-features (23 doctests)
  • examples/protect-events builds

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added optional UniFi Protect Integration API support.
    • Added access to cameras, snapshots, RTSPS streams, lights, sensors, chimes, viewers, NVR information, and application metadata.
    • Added typed live event and device update subscriptions over WebSockets.
    • Added secure and local self-signed certificate connection options.
  • Documentation
    • Added setup instructions, usage examples, Cargo feature guidance, and live event behavior details.
  • Testing
    • Expanded coverage across supported feature combinations and Protect API functionality.

- New ProtectClient for the official Protect Integration API
  (/proxy/protect/integration/v1, X-API-Key auth): cameras, lights,
  sensors, chimes, viewers, NVR, binary JPEG snapshots, and RTSPS
  stream management
- Live WebSocket event subscriptions (subscribe/events and
  subscribe/devices) exposed as typed futures::Stream
- First [features] table: default = ["unifi"], protect is opt-in;
  shared core (Error, Endpoint trait, common models, transport) stays
  ungated
- Extracted shared HTTP transport used by both clients
- wiremock + local-WS + serde round-trip tests; CI feature matrix;
  protect-events example package

BREAKING CHANGE: Error is now #[non_exhaustive] and gained a
WebSocket variant.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings July 24, 2026 17:04
@coderabbitai

coderabbitai Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@JudahZF, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 37 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: af858942-b2a0-4ad3-ab84-4203ff9e5610

📥 Commits

Reviewing files that changed from the base of the PR and between fad4065 and 6e346f7.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • examples/protect-events/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (14)
  • Cargo.toml
  • README.md
  • examples/protect-events/src/main.rs
  • src/error.rs
  • src/protect/api/cameras.rs
  • src/protect/api/chimes.rs
  • src/protect/api/lights.rs
  • src/protect/api/mod.rs
  • src/protect/api/sensors.rs
  • src/protect/api/viewers.rs
  • src/protect/client.rs
  • src/protect/ws.rs
  • src/transport.rs
  • tests/protect_client.rs
📝 Walkthrough

Walkthrough

Changes

The crate now supports optional UniFi Protect REST and WebSocket APIs through a protect feature, while existing UniFi functionality is gated behind unifi. The change adds typed Protect models, endpoints, client methods, shared HTTP transport, WebSocket subscriptions, documentation, examples, and feature-matrix CI tests.

UniFi feature surface

Layer / File(s) Summary
Feature flags and public API surface
.github/workflows/ci.yml, Cargo.toml, src/lib.rs, src/api/*, src/models/mod.rs, README.md, examples/protect-events/Cargo.toml, tests/*
Defines unifi and protect features, gates existing APIs and tests, exposes Protect modules, documents usage, and adds feature-combination CI coverage.
Shared HTTP transport and UniFi client wiring
src/transport.rs, src/client.rs
Centralizes HTTP client construction, endpoint execution, authentication, query/body handling, response parsing, and status errors for UniFi and Protect clients.

Protect integration

Layer / File(s) Summary
Protect data contracts and event payloads
src/protect/models/*, src/protect/mod.rs
Adds typed camera, light, sensor, chime, viewer, NVR, metadata, timestamp, patch, device update, and WebSocket message models.
Protect REST endpoints and client operations
src/protect/api/*, src/protect/client.rs, tests/protect_client.rs, tests/protect_types.rs
Adds typed endpoint definitions and ProtectClient methods for resources, snapshots, metadata, RTSPS streams, and partial updates, with integration and serialization tests.
Protect WebSocket subscriptions
src/protect/ws.rs, src/error.rs, tests/protect_events.rs, tests/protect_ws.rs
Adds authenticated event and device-update streams with typed deserialization, parse-error recovery, WebSocket error reporting, and termination handling.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant ProtectClient
  participant ProtectEndpoint
  participant ProtectTransport
  participant ProtectAPI
  ProtectClient->>ProtectEndpoint: construct typed endpoint
  ProtectClient->>ProtectTransport: execute endpoint with API key
  ProtectTransport->>ProtectAPI: send authenticated REST request
  ProtectAPI-->>ProtectTransport: return JSON or binary response
  ProtectTransport-->>ProtectClient: deserialize typed result
Loading

Possibly related PRs

  • JudahZF/rustifi#32 — Both PRs modify CI build and test invocations.
  • JudahZF/rustifi#48 — The transport refactor and feature-gated API surface build on the endpoint and response infrastructure from that PR.

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding UniFi Protect API support behind the protect feature.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch t3code/plan-unifi-protect-support

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds opt-in UniFi Protect API support while preserving the existing Network API as the default feature.

  • Introduces ProtectClient endpoints for Protect devices, snapshots, RTSPS streams, NVR metadata, and live WebSocket subscriptions.
  • Extracts shared HTTP request handling into a transport module.
  • Adds Cargo feature gating, feature-matrix CI coverage, documentation, examples, and Protect-specific tests.

Confidence Score: 5/5

The pull request appears safe to merge because no blocking failure eligible for this follow-up review remains.

No blocking failure remains.

Important Files Changed

Filename Overview
src/protect/client.rs Adds the primary Protect REST client and convenience methods for device, snapshot, stream, and metadata operations.
src/protect/ws.rs Adds typed event and device-update WebSocket streams with explicit termination and parse-error behavior.
src/transport.rs Centralizes HTTP client construction, endpoint execution, status handling, and JSON response parsing.
src/client.rs Refactors the existing Network client to use the shared transport without changing its public request flow.
Cargo.toml Introduces the default unifi feature and opt-in protect feature with TLS and WebSocket dependencies.
src/lib.rs Applies feature gates to Network and Protect modules and public exports.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
    App[Application] -->|unifi feature| UC[UnifiClient]
    App -->|protect feature| PC[ProtectClient]
    UC --> HT[Shared HTTP transport]
    PC --> HT
    PC --> WS[Typed WebSocket streams]
    HT --> Network[UniFi Network API]
    HT --> Protect[Protect Integration API]
    WS --> Protect
Loading

Reviews (4): Last reviewed commit: "fix: track protect-events example main.r..." | Re-trigger Greptile

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds an opt-in UniFi Protect Integration API client (ProtectClient) behind a new protect cargo feature, while moving existing UniFi Network functionality behind a unifi feature (still enabled by default). This expands the crate to support both controller APIs with a shared HTTP transport layer and updated CI coverage for the feature matrix.

Changes:

  • Introduces ProtectClient (REST + WebSocket subscriptions) plus Protect models/endpoints under src/protect/*.
  • Extracts shared HTTP request/deserialize logic into src/transport.rs and refactors UnifiClient to use it.
  • Adds feature gating (unifi/protect), updates docs/tests, and expands CI to test multiple feature combinations.

Reviewed changes

Copilot reviewed 40 out of 42 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
tests/types.rs Gates UniFi Network-related tests behind unifi feature.
tests/types_extended.rs Gates UniFi Network-related tests behind unifi feature.
tests/stats_tests.rs Gates UniFi Network-related tests behind unifi feature.
tests/response_tests.rs Gates UniFi Network-related tests behind unifi feature.
tests/pagination_tests.rs Gates UniFi Network-related tests behind unifi feature.
tests/device_tests.rs Gates UniFi Network-related tests behind unifi feature.
tests/protect_ws.rs Adds Protect WebSocket subscription tests (feature-gated).
tests/protect_types.rs Adds serde-focused Protect model tests (feature-gated).
tests/protect_events.rs Adds typed WebSocket envelope/event parsing tests (feature-gated).
tests/protect_client.rs Adds wiremock-based tests for Protect REST endpoints (feature-gated).
src/transport.rs New shared HTTP transport for endpoint execution/deserialization.
src/protect/ws.rs Adds typed WebSocket stream implementation and subscribe helpers.
src/protect/models/viewer.rs Adds Protect Viewer model + patch type.
src/protect/models/sensor.rs Adds Protect Sensor models + patch types.
src/protect/models/nvr.rs Adds Protect NVR and meta info models.
src/protect/models/mod.rs Exposes Protect models via a central module re-export.
src/protect/models/light.rs Adds Protect Light model + patch type.
src/protect/models/event.rs Adds WebSocket envelope/action/event/device-update models.
src/protect/models/common.rs Adds common Protect enums and a millisecond timestamp type.
src/protect/models/chime.rs Adds Protect Chime model + patch type.
src/protect/models/camera.rs Adds Protect Camera model + patch + RTSPS stream models.
src/protect/mod.rs Adds Protect module entrypoint and prelude exports.
src/protect/client.rs Implements ProtectClient REST methods and snapshot helper.
src/protect/api/viewers.rs Adds Protect Viewer endpoints (get/list/patch).
src/protect/api/sensors.rs Adds Protect Sensor endpoints (get/list/patch).
src/protect/api/nvr.rs Adds Protect NVR endpoint.
src/protect/api/mod.rs Adds Protect API module wiring.
src/protect/api/meta.rs Adds Protect meta/info endpoint.
src/protect/api/lights.rs Adds Protect Light endpoints (get/list/patch).
src/protect/api/chimes.rs Adds Protect Chime endpoints (get/list/patch).
src/protect/api/cameras.rs Adds Protect Camera endpoints + RTSPS stream management.
src/models/mod.rs Gates UniFi Network models behind unifi feature.
src/lib.rs Adds feature-gated module exports for unifi and protect and transport.
src/error.rs Makes Error non-exhaustive and adds WebSocket variant.
src/client.rs Refactors UnifiClient to use shared transport + shared HTTP client builder.
src/api/mod.rs Gates UniFi Network API modules behind unifi feature (keeps endpoint core).
README.md Documents feature flags and adds Protect usage examples.
examples/protect-events/Cargo.toml Adds a Protect events example crate.
examples/protect-events/Cargo.lock Adds lockfile for the new example crate.
Cargo.toml Adds unifi/protect features and optional WS/TLS deps; adds wiremock dev-dep.
Cargo.lock Updates lockfile for new dependencies/features.
.github/workflows/ci.yml Expands CI to test --no-default-features, protect, and --all-features.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/protect/ws.rs Resolved
The Stream impl for TypedWsStream<T> only produces T via
deserialization and never stores or pins it, so the T: Unpin
bound was unnecessary. Use PhantomData<fn() -> T> so the stream
stays Unpin and Send regardless of T.

Addresses Copilot review comment on PR #78.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (14)
src/protect/models/event.rs (1)

39-49: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use TimestampMillis for event timestamps.

TimestampMillis exists specifically for Protect event milliseconds, but these fields expose bare i64s. This loses unit safety and makes seconds and milliseconds interchangeable.

Proposed fix
-use super::common::ModelKey;
+use super::common::{ModelKey, TimestampMillis};
...
-    pub start: i64,
+    pub start: TimestampMillis,
...
-    pub end: Option<i64>,
+    pub end: Option<TimestampMillis>,

As per coding guidelines, "Use strong typing with structs; avoid primitive obsession."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/models/event.rs` around lines 39 - 49, Replace the bare i64
timestamp types in the event model’s start and end fields with the existing
TimestampMillis type, preserving end’s optionality and serde defaults. Update
the Event struct fields only; leave device and smart_detect_types unchanged.

Source: Coding guidelines

src/protect/models/camera.rs (1)

1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Place external imports before internal modules.

  • src/protect/models/camera.rs#L1-L3: move the serde import above super and crate imports.
  • src/protect/models/chime.rs#L1-L3: move the serde import above super and crate imports.
  • src/protect/models/event.rs#L1-L2: move the serde import above the super import.
  • src/protect/models/light.rs#L1-L3: move the serde import above super and crate imports.
  • src/protect/models/nvr.rs#L1-L3: move the serde import above super and crate imports.
  • src/protect/models/sensor.rs#L1-L3: move the serde import above super and crate imports.
  • src/protect/models/viewer.rs#L1-L3: move the serde import above super and crate imports.

As per coding guidelines, "Group imports by external crates first, then internal modules."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/models/camera.rs` around lines 1 - 3, Reorder imports so the
external serde import precedes internal imports in src/protect/models/camera.rs
(lines 1-3), src/protect/models/chime.rs (lines 1-3),
src/protect/models/event.rs (lines 1-2), src/protect/models/light.rs (lines
1-3), src/protect/models/nvr.rs (lines 1-3), src/protect/models/sensor.rs (lines
1-3), and src/protect/models/viewer.rs (lines 1-3); keep super and crate imports
grouped after serde without changing the imported symbols.

Source: Coding guidelines

src/protect/models/mod.rs (1)

1-8: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the remaining public API.

  • src/protect/models/mod.rs#L1-L8: add module-level docs for the public Protect model modules.
  • src/protect/models/common.rs#L38-L45: document TimestampMillis::as_millis and TimestampMillis::as_secs, including their precision semantics.
  • src/protect/models/camera.rs#L197-L205: document RtspsQuality::as_str and its API-value mapping.

As per coding guidelines, "Document public API with proper doc comments."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/models/mod.rs` around lines 1 - 8, Document the public Protect
model modules declared in src/protect/models/mod.rs. Also add doc comments to
TimestampMillis::as_millis and TimestampMillis::as_secs in
src/protect/models/common.rs describing their precision semantics, and to
RtspsQuality::as_str in src/protect/models/camera.rs describing its API-value
mapping.

Source: Coding guidelines

src/protect/api/mod.rs (1)

1-7: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Document the public module exports.

Add doc comments describing each exported API module. As per coding guidelines, “Document public API with proper doc comments.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/api/mod.rs` around lines 1 - 7, Add proper Rust doc comments for
each public module export in the API module declaration: cameras, chimes,
lights, meta, nvr, sensors, and viewers. Briefly describe the purpose of each
module while preserving the existing module exports and visibility.

Source: Coding guidelines

src/protect/api/cameras.rs (1)

1-3: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Group external imports before crate-local imports.

  • src/protect/api/cameras.rs#L1-L3: move serde_json::Value above crate imports.
  • src/protect/api/chimes.rs#L1-L3: move serde_json::Value above crate imports.
  • src/protect/api/sensors.rs#L1-L3: move serde_json::Value above crate imports.

As per coding guidelines, “Group imports by external crates first, then internal modules.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/api/cameras.rs` around lines 1 - 3, Reorder the imports so the
external serde_json::Value import precedes crate-local imports in
src/protect/api/cameras.rs lines 1-3, src/protect/api/chimes.rs lines 1-3, and
src/protect/api/sensors.rs lines 1-3; make no other changes.

Source: Coding guidelines

tests/protect_ws.rs (1)

15-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the WebSocket handshake path and API key.

The server accepts any handshake, so these tests still pass if the client targets the wrong Protect endpoint or omits X-API-Key. Capture the handshake request and assert the expected path and header.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/protect_ws.rs` around lines 15 - 21, Update the test server handshake
handling around tokio_tungstenite::accept_async to capture and inspect the
incoming WebSocket HTTP request before accepting it. Assert that the request
uses the expected Protect endpoint path and includes the expected X-API-Key
header, while preserving the existing frame-sending and close behavior.
src/protect/ws.rs (1)

66-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Unnecessary Unpin bound on T.

T only appears in PhantomData<T> and as an owned field inside the returned WsMessage<T>; it's never pinned. The Unpin bound on T in the Stream impl is not needed for correctness.

♻️ Suggested relaxation
-impl<T> Stream for TypedWsStream<T>
-where
-    T: for<'a> serde::Deserialize<'a> + Unpin,
-{
+impl<T> Stream for TypedWsStream<T>
+where
+    T: for<'a> serde::Deserialize<'a>,
+{
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/ws.rs` around lines 66 - 69, Remove the unnecessary Unpin bound
from T in the Stream implementation for TypedWsStream<T>, while retaining the
Deserialize bound and existing stream behavior.
src/protect/client.rs (2)

128-150: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

snapshot() re-implements auth-header + error-mapping logic instead of reusing transport.

This duplicates the header construction and non-success error mapping already centralized in transport::execute_endpoint. If auth handling changes there (e.g. additional headers), this path can silently drift out of sync.

Consider extracting a small transport helper (e.g. build_authenticated_request(http, url, method, api_key)) that both execute_endpoint and snapshot() can call, keeping the binary-body handling local to this method.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/client.rs` around lines 128 - 150, Refactor snapshot() to reuse
the centralized transport authentication and request-error handling, preferably
by extracting a shared authenticated-request helper used by both
execute_endpoint and snapshot(). Keep snapshot()’s binary response-body handling
local while removing its duplicated API-key header construction and non-success
status mapping.

1-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Import grouping violates "external crates first, then internal modules" across all new Protect files. Every new file in this cohort lists crate::... imports before external crates (reqwest, serde_json, futures/tokio_tungstenite), the opposite of the stated convention.

  • src/protect/client.rs#L1-L19: move use reqwest::Client; above the crate::... imports.
  • src/protect/api/lights.rs#L1-L3: move use serde_json::Value; above the crate::... imports.
  • src/protect/api/viewers.rs#L1-L3: move use serde_json::Value; above the crate::... imports.
  • src/protect/ws.rs#L24-L35: regroup futures, std::*, and tokio_tungstenite imports before the crate::... imports.

As per coding guidelines, "Group imports by external crates first, then internal modules."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/client.rs` around lines 1 - 19, Regroup imports so external
crates precede internal modules: in src/protect/client.rs#L1-L19 move
reqwest::Client above crate imports; in src/protect/api/lights.rs#L1-L3 and
src/protect/api/viewers.rs#L1-L3 move serde_json::Value above crate imports; and
in src/protect/ws.rs#L24-L35 place futures, std::*, and tokio_tungstenite
imports before crate imports.

Source: Coding guidelines

src/protect/api/lights.rs (1)

10-70: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated Get/GetSingle/Patch endpoint boilerplate across resource files. lights.rs and viewers.rs (and the same pattern in cameras.rs, chimes.rs, sensors.rs) repeat near-identical GetX/GetXs/PatchX structs, each overriding build_path() and leaving the PATH constant's {id} placeholder unused/misleading.

  • src/protect/api/lights.rs#L10-L70: extract a small macro (or generic builder) generating the GetX/GetXs/PatchX endpoint trio from a resource name, eliminating the repeated build_path() overrides and the stale PATH literal.
  • src/protect/api/viewers.rs#L10-L70: apply the same macro/generic here instead of the hand-written duplicate.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/protect/api/lights.rs` around lines 10 - 70, Extract a shared macro or
generic builder for the GetX/GetXs/PatchX endpoint trio, generating
resource-specific types, methods, response types, and request bodies without
per-endpoint build_path overrides or unused "{id}" PATH literals. Apply it to
the endpoint definitions in src/protect/api/lights.rs lines 10-70 and
src/protect/api/viewers.rs lines 10-70; both sites require replacement of the
duplicated hand-written boilerplate.
.github/workflows/ci.yml (1)

55-57: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Build the standalone Protect example in CI.

The commands in Line 55-57 target the root package and may not compile examples/protect-events/Cargo.toml. Add an explicit cargo check --manifest-path examples/protect-events/Cargo.toml, or verify that the example is included as a workspace member.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ci.yml around lines 55 - 57, Update the CI Rust command
sequence near the existing cargo build and test steps to explicitly run cargo
check with examples/protect-events/Cargo.toml as its manifest, unless that
example is already verified as a workspace member. Ensure CI compiles the
standalone Protect example in addition to the current root-package checks and
tests.
src/client.rs (1)

1-4: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import order: internal modules precede the external reqwest crate.

See consolidated comment (shared with src/transport.rs).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/client.rs` around lines 1 - 4, Reorder the imports in src/client.rs so
the internal crate modules (Endpoint, Result, and transport) appear before the
external reqwest::Client import, matching the project’s import-order convention.

Source: Coding guidelines

src/transport.rs (2)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import grouping violates the repo's import-ordering guideline in both changed files. Internal crate::* imports are listed before the external reqwest import; the guideline requires external crates first, then internal modules.

  • src/transport.rs#L3-5: reorder to use reqwest::Client; first, then the crate::api::endpoint/crate::error imports.
  • src/client.rs#L1-4: reorder to use reqwest::Client; first, then the crate::api::endpoint/crate::error/crate::transport imports.

As per coding guidelines, "Group imports by external crates first, then internal modules."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/transport.rs` at line 1, Reorder imports in the transport module and the
client module so the external reqwest::Client import appears before all internal
crate imports. Preserve the existing imported symbols and group the
crate::api::endpoint, crate::error, and crate::transport imports together
afterward.

Source: Coding guidelines


3-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Import order: internal modules precede the external reqwest crate.

See consolidated comment (shared with src/client.rs).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/transport.rs` around lines 3 - 5, Reorder the imports in the transport
module so the internal crate imports, including Endpoint, HttpMethod, and
Result, remain before the external reqwest::Client import, matching the
project’s import-order convention.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@README.md`:
- Around line 99-118: Update the Live events example’s reconnect loop around
client.subscribe_events().await so initial WebSocket subscription failures are
handled without returning from the example. Log the subscription error, sleep
for the existing 5-second interval, and continue retrying; preserve the current
stream-processing and disconnect-retry behavior.

In `@src/protect/api/cameras.rs`:
- Around line 36-38: Centralize URL path-segment encoding and apply it to every
resource ID interpolation in build_path methods: src/protect/api/cameras.rs
lines 36-38, 63-65, 92-94, 119-121, and 151-153; src/protect/api/chimes.rs lines
36-38 and 63-65; and src/protect/api/sensors.rs lines 36-38 and 63-65. Ensure
camera_id, chime_id, and sensor_id each remain a single safely encoded path
segment rather than being formatted directly into routes.

In `@src/transport.rs`:
- Around line 70-87: Update the non-success response branch in the transport
request flow to read and retain the response body before constructing the error,
then include that body alongside the status-derived error details in
crate::error::Error::Request. Preserve the existing success-path parsing and
error behavior, while ensuring API-provided diagnostic content is available to
both UnifiClient and ProtectClient callers.

---

Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 55-57: Update the CI Rust command sequence near the existing cargo
build and test steps to explicitly run cargo check with
examples/protect-events/Cargo.toml as its manifest, unless that example is
already verified as a workspace member. Ensure CI compiles the standalone
Protect example in addition to the current root-package checks and tests.

In `@src/client.rs`:
- Around line 1-4: Reorder the imports in src/client.rs so the internal crate
modules (Endpoint, Result, and transport) appear before the external
reqwest::Client import, matching the project’s import-order convention.

In `@src/protect/api/cameras.rs`:
- Around line 1-3: Reorder the imports so the external serde_json::Value import
precedes crate-local imports in src/protect/api/cameras.rs lines 1-3,
src/protect/api/chimes.rs lines 1-3, and src/protect/api/sensors.rs lines 1-3;
make no other changes.

In `@src/protect/api/lights.rs`:
- Around line 10-70: Extract a shared macro or generic builder for the
GetX/GetXs/PatchX endpoint trio, generating resource-specific types, methods,
response types, and request bodies without per-endpoint build_path overrides or
unused "{id}" PATH literals. Apply it to the endpoint definitions in
src/protect/api/lights.rs lines 10-70 and src/protect/api/viewers.rs lines
10-70; both sites require replacement of the duplicated hand-written
boilerplate.

In `@src/protect/api/mod.rs`:
- Around line 1-7: Add proper Rust doc comments for each public module export in
the API module declaration: cameras, chimes, lights, meta, nvr, sensors, and
viewers. Briefly describe the purpose of each module while preserving the
existing module exports and visibility.

In `@src/protect/client.rs`:
- Around line 128-150: Refactor snapshot() to reuse the centralized transport
authentication and request-error handling, preferably by extracting a shared
authenticated-request helper used by both execute_endpoint and snapshot(). Keep
snapshot()’s binary response-body handling local while removing its duplicated
API-key header construction and non-success status mapping.
- Around line 1-19: Regroup imports so external crates precede internal modules:
in src/protect/client.rs#L1-L19 move reqwest::Client above crate imports; in
src/protect/api/lights.rs#L1-L3 and src/protect/api/viewers.rs#L1-L3 move
serde_json::Value above crate imports; and in src/protect/ws.rs#L24-L35 place
futures, std::*, and tokio_tungstenite imports before crate imports.

In `@src/protect/models/camera.rs`:
- Around line 1-3: Reorder imports so the external serde import precedes
internal imports in src/protect/models/camera.rs (lines 1-3),
src/protect/models/chime.rs (lines 1-3), src/protect/models/event.rs (lines
1-2), src/protect/models/light.rs (lines 1-3), src/protect/models/nvr.rs (lines
1-3), src/protect/models/sensor.rs (lines 1-3), and src/protect/models/viewer.rs
(lines 1-3); keep super and crate imports grouped after serde without changing
the imported symbols.

In `@src/protect/models/event.rs`:
- Around line 39-49: Replace the bare i64 timestamp types in the event model’s
start and end fields with the existing TimestampMillis type, preserving end’s
optionality and serde defaults. Update the Event struct fields only; leave
device and smart_detect_types unchanged.

In `@src/protect/models/mod.rs`:
- Around line 1-8: Document the public Protect model modules declared in
src/protect/models/mod.rs. Also add doc comments to TimestampMillis::as_millis
and TimestampMillis::as_secs in src/protect/models/common.rs describing their
precision semantics, and to RtspsQuality::as_str in src/protect/models/camera.rs
describing its API-value mapping.

In `@src/protect/ws.rs`:
- Around line 66-69: Remove the unnecessary Unpin bound from T in the Stream
implementation for TypedWsStream<T>, while retaining the Deserialize bound and
existing stream behavior.

In `@src/transport.rs`:
- Line 1: Reorder imports in the transport module and the client module so the
external reqwest::Client import appears before all internal crate imports.
Preserve the existing imported symbols and group the crate::api::endpoint,
crate::error, and crate::transport imports together afterward.
- Around line 3-5: Reorder the imports in the transport module so the internal
crate imports, including Endpoint, HttpMethod, and Result, remain before the
external reqwest::Client import, matching the project’s import-order convention.

In `@tests/protect_ws.rs`:
- Around line 15-21: Update the test server handshake handling around
tokio_tungstenite::accept_async to capture and inspect the incoming WebSocket
HTTP request before accepting it. Assert that the request uses the expected
Protect endpoint path and includes the expected X-API-Key header, while
preserving the existing frame-sending and close behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 3507f822-59dd-463a-bd93-83835e72d679

📥 Commits

Reviewing files that changed from the base of the PR and between c4f9ec4 and fad4065.

⛔ Files ignored due to path filters (2)
  • Cargo.lock is excluded by !**/*.lock
  • examples/protect-events/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (40)
  • .github/workflows/ci.yml
  • Cargo.toml
  • README.md
  • examples/protect-events/Cargo.toml
  • src/api/mod.rs
  • src/client.rs
  • src/error.rs
  • src/lib.rs
  • src/models/mod.rs
  • src/protect/api/cameras.rs
  • src/protect/api/chimes.rs
  • src/protect/api/lights.rs
  • src/protect/api/meta.rs
  • src/protect/api/mod.rs
  • src/protect/api/nvr.rs
  • src/protect/api/sensors.rs
  • src/protect/api/viewers.rs
  • src/protect/client.rs
  • src/protect/mod.rs
  • src/protect/models/camera.rs
  • src/protect/models/chime.rs
  • src/protect/models/common.rs
  • src/protect/models/event.rs
  • src/protect/models/light.rs
  • src/protect/models/mod.rs
  • src/protect/models/nvr.rs
  • src/protect/models/sensor.rs
  • src/protect/models/viewer.rs
  • src/protect/ws.rs
  • src/transport.rs
  • tests/device_tests.rs
  • tests/pagination_tests.rs
  • tests/protect_client.rs
  • tests/protect_events.rs
  • tests/protect_types.rs
  • tests/protect_ws.rs
  • tests/response_tests.rs
  • tests/stats_tests.rs
  • tests/types.rs
  • tests/types_extended.rs

Comment thread README.md Resolved
Comment thread src/protect/api/cameras.rs Resolved
Comment thread src/transport.rs Resolved
- Percent-encode resource IDs used as URL path segments so an ID
  cannot alter the requested route or query (CodeRabbit)
- Preserve error response bodies in a new Error::Api variant instead
  of discarding them via error_for_status (CodeRabbit)
- Handle initial WebSocket subscription failures in the reconnect
  loops in README and the protect-events example (CodeRabbit)
- Regression tests for both client behaviors

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f709377e23

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread examples/protect-events/Cargo.toml Resolved
Comment thread README.md Resolved
The root .gitignore has a blanket main.rs entry, which silently
excluded the example's entrypoint from the previous commits.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@JudahZF
JudahZF merged commit c1fcf2f into main Jul 24, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants