Skip to content

feat(autoscan): Sonarr/Radarr webhook intake without arr API keys - #353

Merged
Quick104 merged 10 commits into
mainfrom
feat/autoscan-arr-webhook-intake
Jul 9, 2026
Merged

Quick104 merged 10 commits into
mainfrom
feat/autoscan-arr-webhook-intake

Conversation

@Quick104

@Quick104 Quick104 commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Autoscan's Sonarr/Radarr integration is pull-based: sources poll arr /api/v3/history through the silo.autoscan.arr plugin, which requires storing an arr API key in Silo and adds poll latency between an import finishing and the scan starting.

What this does

Adds a webhook delivery mode so Sonarr/Radarr POST import, upgrade, rename, and delete notifications directly to Silo — no arr API key, no plugin install, no SDK change. Polling mode is untouched.

  • Built-in source identity silo.autoscan.arr-webhook, supplied by a composite scan-source lister, so webhook sources need no plugin installation (create-time validation requires an installed capability; piggybacking on the ARR plugin identity would have forced installing a plugin the webhook path never calls).
  • Public endpoint POST /api/v1/autoscan/webhooks/{token}: 32-byte rotatable bearer tokens (SHA-256 lookup, AAD-bound encrypted redisplay), per-IP rate limiting via the existing internal/ratelimit middleware, 256 KiB body cap, and coarse response semantics (404 for any unknown token; 202 for test events, unknown event types, and disabled sources so arr never marks the webhook unhealthy; 500 only when durable acceptance itself fails; actionable deliveries are persisted before 202 and transient ingest failures retry inside Silo).
  • Durable webhook inbox: actionable deliveries are stored before acknowledgement, attempted immediately, and retried by a leased, multi-node-safe task with bounded backoff. Successful retries clear endpoint error state; disabled sources pause rather than discard accepted work.
  • Shared consume pipeline: PollOnce's back half is extracted into consumeSourceChanges (marker semantics preserved verbatim; existing poll tests pass unmodified) and webhook deliveries enter through a new IngestChanges. Deliveries are never single-flight-dropped — unlike polls, they carry no marker window to re-read, so CreateEvent gains a SkipRunningCheck path and the suppressor's atomic claim remains the duplicate-scan guard (season-pack bursts are the normal case, not an anomaly).
  • Host-side parser (internal/autoscan/arrwebhook) with provider auto-inference, rename previous-path extraction and upgrade deletedFiles extraction (reconciled via the existing vanished-path fallback), subtree fallback, dedupe, and fixture coverage for Sonarr/Radarr Download/Rename/FileDelete/Test.
  • Admin UI: webhook sources get a generate/copy/rotate URL section, provider selector, and delivery status; the Add-source dialog offers "Sonarr/Radarr Webhook" with no connection/interval inputs; activity rows badge webhook events with the arr event type. Path rewrites stay editable in both modes (webhook payload paths are arr-side paths).
  • Events record delivery_mode and provider_event_type from day one.
  • Log-hygiene fix found during live testing: the shared request-logger and activity-log middleware recorded raw URLs, persisting webhook bearer tokens (and pre-existing webhook-sync secrets) into logs and activity_log. Both sinks now redact secret path segments.

All /api/v1 changes are additive: new fields, new endpoints, one new delivery_mode column defaulting existing rows to poll.

Design & scope

  • Design spec (four approaches compared; decisions locked): docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md
  • Implementation plan: docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md
  • No existing scope issue covers this feature; happy to link one if the epic mapping is preferred.

Verification

  • GOWORK=off go test ./... — passes except two documented pre-existing flaky packages (jellycompat TestBeginWebOperation*, playback GPU probes), both untouched here.
  • New tests: parser fixtures including upgrade deletedFiles, durable delivery lifecycle and retry leases, service ingest (enqueue parity with polling, burst non-drop, suppression, unresolved/transient semantics), Redis burst parity, webhook-only provider validation, handler status-code matrix (202/400/404/413/500), token-never-logged assertion via a captured slog handler, DB-backed endpoint lifecycle + SkipRunningCheck tests (require SILO_TEST_DATABASE_URL).
  • Web: pnpm run lint completes with no errors (existing warnings remain); format:check and build pass. The 4 failing vitest cases fail identically on main (pre-existing).
  • Verified live on dev: source creation, URL generation, real Sonarr 4.0.15 and Radarr 5.26.2 test deliveries (202), token rotation invalidating the old URL (404), last_received_at bookkeeping, and redacted [redacted] paths in both app logs and activity_log.

Risks / follow-ups

  • The PollOnce refactor is behavior-preserving by test evidence, but it is the highest-risk diff — the marker-advancement decision comments moved intact into consumeSourceChanges.
  • Real import events (non-test) haven't been observed on dev yet; the parser is fixture-verified against the Servarr payload shapes.
  • Operators who tested before this branch's final commit should rotate their webhook URL once (earlier logs recorded raw tokens).

AI-use disclosure

Implemented by Claude Code (Fable 5) from the committed design spec and plan, with human review of the spec decisions and live dev verification. Review follow-ups were implemented and re-verified with OpenAI Codex.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added webhook delivery mode for Autoscan sources, including admin setup to create, rotate, and delete per-source webhook URLs.
    • Implemented public Sonarr/Radarr webhook intake with durable, retryable delivery handling.
    • Updated Autoscan UI to configure delivery mode/provider and display webhook delivery details (provider event type, timestamps/errors).
    • Added a background retry task for pending webhook deliveries.
  • Bug Fixes
    • Improved request and activity logging to redact secret-bearing path parameters.
    • Enhanced webhook handling safeguards: consistent responses for disabled/test/unknown events and safer token error behavior.

Quick104 and others added 9 commits July 9, 2026 10:40
Adds delivery_mode to autoscan_sources, the autoscan_webhook_endpoints
table, and delivery_mode/provider_event_type on autoscan_events.

Co-Authored-By: Claude Fable 5 <[email protected]>
Host-discovered scan-source entry so webhook-mode sources need no
plugin installation; composite lister appends it to plugin discovery.

Co-Authored-By: Claude Fable 5 <[email protected]>
Sources carry delivery_mode; autoscan_webhook_endpoints CRUD with
SHA-256 token lookup and AAD-bound encrypted redisplay; events record
delivery_mode/provider_event_type; CreateEvent gains SkipRunningCheck
so webhook deliveries are never dropped by the poll exclusion.

Co-Authored-By: Claude Fable 5 <[email protected]>
Extracts consumeSourceChanges from PollOnce (marker semantics
preserved, existing poll tests unchanged); PollOnce skips webhook
sources; IngestChanges feeds deliveries through the shared pipeline
without markers and without the running-event exclusion.

Co-Authored-By: Claude Fable 5 <[email protected]>
Host-side arrwebhook package: provider inference, import/rename/delete
path extraction with vanished-path-friendly previous paths, subtree
fallback, exact-path dedupe, and no-op unknown events. Fixture-backed.

Co-Authored-By: Claude Fable 5 <[email protected]>
…management

Public POST /api/v1/autoscan/webhooks/{token} with per-IP rate
limiting, 256KiB body cap, 202-for-noop semantics, and token/body kept
out of logs; admin create/rotate/delete endpoint routes; source
responses carry delivery mode + webhook status/URL; create/update
validate delivery mode against source identity.

Co-Authored-By: Claude Fable 5 <[email protected]>
Webhook sources get a generate/copy/rotate webhook URL section,
provider selector, delivery status, and a connection-free Add-source
flow; activity rows badge webhook deliveries with the arr event type.
Path rewrites stay editable in both modes.

Co-Authored-By: Claude Fable 5 <[email protected]>
The request logger and activity-log middleware recorded raw URLs, so
bearer credentials in secret path segments (autoscan webhook {token},
webhook-sync {secret}) were persisted to app logs and activity_log.
Redact the secret segment via the chi route params in both sinks.

Co-Authored-By: Claude Fable 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds webhook delivery mode for Sonarr/Radarr autoscan sources, including schema, repository, parser, service, HTTP, logging, task, and frontend updates, plus design and rollout docs.

Changes

Autoscan Webhook Intake

Layer / File(s) Summary
Design, plan, and rollout docs
docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md, docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md
Adds the design spec, implementation plan, and rollout/testing notes for webhook delivery mode.
Schema, types, and webhook persistence
migrations/sql/20260709143635_autoscan_webhook_intake.sql, internal/autoscan/types.go, internal/autoscan/repository.go, internal/autoscan/webhook_delivery.go, internal/autoscan/webhook_endpoint.go, internal/autoscan/service.go, internal/autoscan/service_test.go, internal/autoscan/webhook_endpoint_test.go
Adds delivery-mode/event metadata, webhook endpoint and delivery storage, and repository/service support for endpoint lifecycle and queued delivery handling.
Built-in discovery and ARR webhook parsing
internal/autoscan/discovery.go, internal/autoscan/discovery_test.go, internal/api/autoscan_wiring.go, internal/autoscan/arrwebhook/parse.go, internal/autoscan/arrwebhook/parse_test.go, internal/autoscan/arrwebhook/testdata/*
Adds the built-in webhook source identity, composite source listing, and ARR payload parsing into autoscan changes with tests and fixtures.
Shared ingest pipeline and retry task
internal/autoscan/service.go, internal/autoscan/service_ingest_test.go, internal/taskmanager/tasks/autoscan_webhook_retry.go, internal/taskmanager/tasks/autoscan_webhook_retry_test.go, cmd/silo/main.go
Refactors polling into a shared ingest path, adds webhook ingestion and retry processing, and registers the retry task at startup.
Autoscan HTTP handlers, routing, and log redaction
internal/api/handlers/autoscan.go, internal/api/handlers/autoscan_webhook.go, internal/api/handlers/autoscan_test.go, internal/api/handlers/autoscan_webhook_test.go, internal/api/router.go, internal/api/middleware/request_logger.go, internal/activitylog/middleware.go, internal/activitylog/redact_test.go, internal/ratelimit/ratelimit.go, internal/ratelimit/redis.go, internal/ratelimit/redis_test.go
Adds webhook-aware autoscan responses, admin/public webhook endpoints, route wiring, rate-limit support, and secret-path redaction in request logging.
Frontend autoscan types and UI
web/src/api/types.ts, web/src/hooks/queries/useAutoscan.ts, web/src/pages/admin/autoscan/ActivityPanel.tsx, web/src/pages/admin/autoscan/SourcesPanel.tsx, web/src/lib/autoscanLabels.test.ts
Extends frontend autoscan types and mutations, and updates the admin activity and sources panels to create, rotate, display, and label webhook delivery mode.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.47% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding Sonarr/Radarr autoscan webhook intake without arr API keys.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/autoscan-arr-webhook-intake

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

@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: 39408c7257

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread internal/api/handlers/autoscan.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md (1)

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

Signature drift between spec and plan for consumeSourceChanges/ChangeIngest.

The design spec declares consumeSourceChanges returning (consumeResult, error) and ChangeIngest with a DeliveryMode field; this plan declares consumeSourceChanges returning bare error and drops DeliveryMode from ChangeIngest. Worth reconciling one way before Phase 4 implementation so there's a single source of truth.

🤖 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 `@docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md` around
lines 171 - 208, Reconcile the API drift between the plan and the design spec
before implementation: `Service.consumeSourceChanges` should match the agreed
`(consumeResult, error)` contract instead of returning only `error`, and
`ChangeIngest` should include the `DeliveryMode` field if it is part of the
spec. Update the `consumeSourceChanges`, `PollOnce`, and `IngestChanges`
signatures and their callers together so there is one consistent source of truth
for webhook vs poll handling.
🤖 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.

Nitpick comments:
In `@docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md`:
- Around line 171-208: Reconcile the API drift between the plan and the design
spec before implementation: `Service.consumeSourceChanges` should match the
agreed `(consumeResult, error)` contract instead of returning only `error`, and
`ChangeIngest` should include the `DeliveryMode` field if it is part of the
spec. Update the `consumeSourceChanges`, `PollOnce`, and `IngestChanges`
signatures and their callers together so there is one consistent source of truth
for webhook vs poll handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: df3faad2-b9b2-4fbb-89c8-bb42f7fd0b35

📥 Commits

Reviewing files that changed from the base of the PR and between b2b95a3 and 39408c7.

📒 Files selected for processing (37)
  • docs/superpowers/plans/2026-07-09-autoscan-arr-webhook-intake-plan.md
  • docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md
  • internal/activitylog/middleware.go
  • internal/activitylog/redact_test.go
  • internal/api/autoscan_wiring.go
  • internal/api/handlers/autoscan.go
  • internal/api/handlers/autoscan_test.go
  • internal/api/handlers/autoscan_webhook.go
  • internal/api/handlers/autoscan_webhook_test.go
  • internal/api/middleware/request_logger.go
  • internal/api/router.go
  • internal/autoscan/arrwebhook/parse.go
  • internal/autoscan/arrwebhook/parse_test.go
  • internal/autoscan/arrwebhook/testdata/radarr_download.json
  • internal/autoscan/arrwebhook/testdata/radarr_moviefile_delete.json
  • internal/autoscan/arrwebhook/testdata/radarr_rename.json
  • internal/autoscan/arrwebhook/testdata/radarr_test.json
  • internal/autoscan/arrwebhook/testdata/sonarr_download.json
  • internal/autoscan/arrwebhook/testdata/sonarr_episodefile_delete.json
  • internal/autoscan/arrwebhook/testdata/sonarr_rename.json
  • internal/autoscan/arrwebhook/testdata/sonarr_test.json
  • internal/autoscan/arrwebhook/testdata/unknown_event.json
  • internal/autoscan/discovery.go
  • internal/autoscan/discovery_test.go
  • internal/autoscan/repository.go
  • internal/autoscan/service.go
  • internal/autoscan/service_ingest_test.go
  • internal/autoscan/types.go
  • internal/autoscan/webhook_endpoint.go
  • internal/autoscan/webhook_endpoint_test.go
  • internal/ratelimit/ratelimit.go
  • migrations/sql/20260709143635_autoscan_webhook_intake.sql
  • web/src/api/types.ts
  • web/src/hooks/queries/useAutoscan.ts
  • web/src/lib/autoscanLabels.test.ts
  • web/src/pages/admin/autoscan/ActivityPanel.tsx
  • web/src/pages/admin/autoscan/SourcesPanel.tsx

@Quick104

Quick104 commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the review findings in ec20ade0:

  • persist actionable Arr deliveries before returning 202, with leased multi-node retries and bounded backoff inside Silo
  • honor configured burst capacity in the Redis limiter while retaining the minute cap
  • parse upgrade deletedFiles for both Sonarr and Radarr
  • scope webhook_provider validation and canonicalization to webhook-mode sources only

Verification: focused Go tests, focused race tests, migration validation, local-path verification, frontend lint/format/build, and git diff --check pass. The complete Go suite still shows the documented unrelated Jellycompat process-lock and playback GPU-probe flakes. DB-backed lifecycle tests require SILO_TEST_DATABASE_URL and were skipped locally.

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jul 9, 2026
@Quick104
Quick104 merged commit 2b243ab into main Jul 9, 2026
1 check was pending
@Quick104
Quick104 deleted the feat/autoscan-arr-webhook-intake branch July 9, 2026 18:13

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md (1)

313-320: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Restore the /api/v1 admin prefix.

These routes are documented as part of /api/v1/admin/autoscan, but the examples drop /api/v1. That makes the contract inconsistent and will lead to implementation/client mismatches.

Fix the route examples
- POST /admin/autoscan/sources/{id}/webhook
+ POST /api/v1/admin/autoscan/sources/{id}/webhook
...
- POST /admin/autoscan/sources/{id}/webhook/rotate
+ POST /api/v1/admin/autoscan/sources/{id}/webhook/rotate
...
- DELETE /admin/autoscan/sources/{id}/webhook
+ DELETE /api/v1/admin/autoscan/sources/{id}/webhook
🤖 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 `@docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md`
around lines 313 - 320, The webhook route examples are missing the `/api/v1`
admin prefix, which makes the documented contract inconsistent with the rest of
`/api/v1/admin/autoscan`. Update the route examples for the webhook create,
rotate, and delete endpoints to include the full
`/api/v1/admin/autoscan/sources/{id}/webhook` prefix so the spec matches the
intended API shape; use the existing autoscan admin route naming in this spec as
the reference point.
🧹 Nitpick comments (3)
migrations/sql/20260709175720_autoscan_webhook_delivery_queue.sql (1)

3-20: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add an index on source_id.

autoscan_webhook_deliveries will grow with every actionable webhook, and ON DELETE CASCADE from autoscan_sources will be much more expensive without an index on the child FK column.

Add the supporting index
 CREATE INDEX idx_autoscan_webhook_deliveries_due
     ON autoscan_webhook_deliveries (next_attempt_at, id);
+
+CREATE INDEX idx_autoscan_webhook_deliveries_source_id
+    ON autoscan_webhook_deliveries (source_id);
🤖 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 `@migrations/sql/20260709175720_autoscan_webhook_delivery_queue.sql` around
lines 3 - 20, The autoscan_webhook_deliveries table is missing an index on its
foreign key column source_id, which will make deletes from autoscan_sources with
ON DELETE CASCADE increasingly expensive as the table grows. Update the
migration that creates autoscan_webhook_deliveries to also add a supporting
index on source_id, alongside the existing idx_autoscan_webhook_deliveries_due
index, so lookups and cascade deletes can use
autoscan_webhook_deliveries.source_id efficiently.
internal/ratelimit/redis_test.go (1)

16-25: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider adding a zero/negative-burst coverage case.

Both tests configure a positive Burst. Since redis.go isn't in this batch, worth confirming the fallback behavior when Burst is unset (0) is still exercised somewhere, since that's the common case for existing rate-limit configs upgrading to this change.

🤖 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 `@internal/ratelimit/redis_test.go` around lines 16 - 25, Add test coverage for
the fallback when Rate.Burst is unset or non-positive in redisWindowLimits,
since the current Redis window limit tests only cover a positive Burst. Update
or add a test in TestRedisWindowLimitsKeepMinuteOnlyRatesUsable (or a nearby
Redis rate-limit test) to assert the returned second/minute limits still match
the expected minute-only behavior when Burst is 0 or negative, using
redisWindowLimits and Rate as the key symbols to locate the logic.
internal/api/handlers/autoscan.go (1)

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

Duplicate webhook-provider validation/canonicalization block in Create and Update handlers.

The same 8-line block (validate + lowercase/trim webhook_provider) is repeated verbatim in HandleCreateSource and HandleUpdateSource. Extracting it into a shared helper reduces the risk of the two paths drifting on this validation logic.

♻️ Proposed extraction
+func applyWebhookProviderConfig(sourceConfig map[string]string, deliveryMode string) error {
+	if deliveryMode != autoscan.DeliveryModeWebhook {
+		return nil
+	}
+	if err := validateWebhookProvider(sourceConfig); err != nil {
+		return err
+	}
+	if provider, ok := sourceConfig["webhook_provider"]; ok {
+		sourceConfig["webhook_provider"] = strings.ToLower(strings.TrimSpace(provider))
+	}
+	return nil
+}

Then in both handlers:

 	sourceConfig := normalizeSourceConfig(in.SourceConfig)
-	if deliveryMode == autoscan.DeliveryModeWebhook {
-		if err := validateWebhookProvider(sourceConfig); err != nil {
-			writeError(w, http.StatusBadRequest, "bad_request", err.Error())
-			return
-		}
-		if provider, ok := sourceConfig["webhook_provider"]; ok {
-			sourceConfig["webhook_provider"] = strings.ToLower(strings.TrimSpace(provider))
-		}
-	}
+	if err := applyWebhookProviderConfig(sourceConfig, deliveryMode); err != nil {
+		writeError(w, http.StatusBadRequest, "bad_request", err.Error())
+		return
+	}

Also applies to: 720-728

🤖 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 `@internal/api/handlers/autoscan.go` around lines 578 - 586, The
webhook-provider validation and canonicalization logic is duplicated in both
HandleCreateSource and HandleUpdateSource. Extract the shared
validateWebhookProvider plus strings.ToLower/strings.TrimSpace block into a
helper near those handlers, then call that helper from both paths so the webhook
provider handling stays consistent and won’t drift.
🤖 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 `@internal/autoscan/webhook_delivery.go`:
- Line 12: The webhook retry flow currently never stops for permanently failing
deliveries, so add a dead-letter path in the autoscan webhook delivery logic to
prevent infinite rescheduling once attempt_count grows. Update the retry
handling around webhookDeliveryLease and the webhook delivery processing code to
detect exhausted attempts, mark the delivery as dead-lettered or otherwise
terminal, and stop it from remaining eligible in autoscan_webhook_deliveries.
Ensure the relevant delivery dequeue/reschedule logic uses this terminal state
so retries no longer continue indefinitely.

---

Outside diff comments:
In `@docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md`:
- Around line 313-320: The webhook route examples are missing the `/api/v1`
admin prefix, which makes the documented contract inconsistent with the rest of
`/api/v1/admin/autoscan`. Update the route examples for the webhook create,
rotate, and delete endpoints to include the full
`/api/v1/admin/autoscan/sources/{id}/webhook` prefix so the spec matches the
intended API shape; use the existing autoscan admin route naming in this spec as
the reference point.

---

Nitpick comments:
In `@internal/api/handlers/autoscan.go`:
- Around line 578-586: The webhook-provider validation and canonicalization
logic is duplicated in both HandleCreateSource and HandleUpdateSource. Extract
the shared validateWebhookProvider plus strings.ToLower/strings.TrimSpace block
into a helper near those handlers, then call that helper from both paths so the
webhook provider handling stays consistent and won’t drift.

In `@internal/ratelimit/redis_test.go`:
- Around line 16-25: Add test coverage for the fallback when Rate.Burst is unset
or non-positive in redisWindowLimits, since the current Redis window limit tests
only cover a positive Burst. Update or add a test in
TestRedisWindowLimitsKeepMinuteOnlyRatesUsable (or a nearby Redis rate-limit
test) to assert the returned second/minute limits still match the expected
minute-only behavior when Burst is 0 or negative, using redisWindowLimits and
Rate as the key symbols to locate the logic.

In `@migrations/sql/20260709175720_autoscan_webhook_delivery_queue.sql`:
- Around line 3-20: The autoscan_webhook_deliveries table is missing an index on
its foreign key column source_id, which will make deletes from autoscan_sources
with ON DELETE CASCADE increasingly expensive as the table grows. Update the
migration that creates autoscan_webhook_deliveries to also add a supporting
index on source_id, alongside the existing idx_autoscan_webhook_deliveries_due
index, so lookups and cascade deletes can use
autoscan_webhook_deliveries.source_id efficiently.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 76bd6903-4dfa-4aed-90d6-f94065fd08cc

📥 Commits

Reviewing files that changed from the base of the PR and between 39408c7 and ec20ade.

📒 Files selected for processing (20)
  • cmd/silo/main.go
  • docs/superpowers/specs/2026-07-09-autoscan-arr-webhook-intake-design.md
  • internal/api/handlers/autoscan.go
  • internal/api/handlers/autoscan_webhook.go
  • internal/api/handlers/autoscan_webhook_test.go
  • internal/autoscan/arrwebhook/parse.go
  • internal/autoscan/arrwebhook/parse_test.go
  • internal/autoscan/service.go
  • internal/autoscan/service_ingest_test.go
  • internal/autoscan/service_test.go
  • internal/autoscan/types.go
  • internal/autoscan/webhook_delivery.go
  • internal/autoscan/webhook_endpoint.go
  • internal/autoscan/webhook_endpoint_test.go
  • internal/ratelimit/ratelimit.go
  • internal/ratelimit/redis.go
  • internal/ratelimit/redis_test.go
  • internal/taskmanager/tasks/autoscan_webhook_retry.go
  • internal/taskmanager/tasks/autoscan_webhook_retry_test.go
  • migrations/sql/20260709175720_autoscan_webhook_delivery_queue.sql
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/ratelimit/ratelimit.go
  • internal/autoscan/arrwebhook/parse_test.go
  • internal/api/handlers/autoscan_webhook_test.go
  • internal/api/handlers/autoscan_webhook.go
  • internal/autoscan/webhook_endpoint.go
  • internal/autoscan/types.go
  • internal/autoscan/arrwebhook/parse.go
  • internal/autoscan/service.go

"github.com/google/uuid"
)

const webhookDeliveryLease = 5 * time.Minute

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Look for a max-attempts / give-up / dead-letter path around webhook delivery retries.
rg -nP 'AttemptCount|attempt_count|maxAttempt|MaxAttempt|give.?up|dead.?letter' internal/autoscan/service.go internal/taskmanager/tasks/autoscan_webhook_retry.go

Repository: Silo-Server/silo-server

Length of output: 238


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== service.go matches ==\n'
rg -n "webhookRetryDelay|RetryPendingWebhookDeliveries|processWebhookDelivery|AttemptCount|CompleteWebhookDelivery|RetryWebhookDelivery|ErrNotFound" internal/autoscan/service.go

printf '\n== retry task matches ==\n'
rg -n "webhookRetryDelay|AttemptCount|CompleteWebhookDelivery|RetryWebhookDelivery|ErrNotFound|dead.?letter|give.?up|maxAttempt|attempt" internal/taskmanager/tasks/autoscan_webhook_retry.go

printf '\n== relevant service.go slice ==\n'
sed -n '440,540p' internal/autoscan/service.go

printf '\n== relevant autoscan_webhook_retry.go slice ==\n'
sed -n '1,220p' internal/taskmanager/tasks/autoscan_webhook_retry.go

Repository: Silo-Server/silo-server

Length of output: 1161


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== service.go around retry path ==\n'
sed -n '410,510p' internal/autoscan/service.go

printf '\n== full retry task file ==\n'
cat -n internal/taskmanager/tasks/autoscan_webhook_retry.go

Repository: Silo-Server/silo-server

Length of output: 6661


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== webhook delivery store methods ==\n'
rg -n "func .*WebhookDelivery|attempt_count|dead.?letter|give.?up|DeleteWebhookDelivery|RemoveWebhookDelivery|CompleteWebhookDelivery|RetryWebhookDelivery|ClaimWebhookDeliveries" internal/autoscan -g'*.go'

printf '\n== webhook_delivery.go ==\n'
cat -n internal/autoscan/webhook_delivery.go

printf '\n== surrounding store implementation slices ==\n'
sed -n '1,220p' internal/autoscan/webhook_delivery.go

printf '\n== any schema references ==\n'
rg -n "autoscan_webhook_deliveries|attempt_count|locked_by" . -g'*.sql' -g'*.go'

Repository: Silo-Server/silo-server

Length of output: 23513


Add a dead-letter path for webhook retries Permanently failing deliveries are rescheduled forever; once attempt_count rises, nothing ever stops them from staying in autoscan_webhook_deliveries and being retried indefinitely.

🤖 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 `@internal/autoscan/webhook_delivery.go` at line 12, The webhook retry flow
currently never stops for permanently failing deliveries, so add a dead-letter
path in the autoscan webhook delivery logic to prevent infinite rescheduling
once attempt_count grows. Update the retry handling around webhookDeliveryLease
and the webhook delivery processing code to detect exhausted attempts, mark the
delivery as dead-lettered or otherwise terminal, and stop it from remaining
eligible in autoscan_webhook_deliveries. Ensure the relevant delivery
dequeue/reschedule logic uses this terminal state so retries no longer continue
indefinitely.

Quick104 added a commit that referenced this pull request Jul 10, 2026
* docs(autoscan): add arr webhook intake spec and implementation plan

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): add webhook intake schema migration

Adds delivery_mode to autoscan_sources, the autoscan_webhook_endpoints
table, and delivery_mode/provider_event_type on autoscan_events.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): add built-in arr-webhook source identity

Host-discovered scan-source entry so webhook-mode sources need no
plugin installation; composite lister appends it to plugin discovery.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): persist delivery mode, webhook endpoints, event metadata

Sources carry delivery_mode; autoscan_webhook_endpoints CRUD with
SHA-256 token lookup and AAD-bound encrypted redisplay; events record
delivery_mode/provider_event_type; CreateEvent gains SkipRunningCheck
so webhook deliveries are never dropped by the poll exclusion.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): share the consume path and add webhook IngestChanges

Extracts consumeSourceChanges from PollOnce (marker semantics
preserved, existing poll tests unchanged); PollOnce skips webhook
sources; IngestChanges feeds deliveries through the shared pipeline
without markers and without the running-event exclusion.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): add Sonarr/Radarr webhook payload parser

Host-side arrwebhook package: provider inference, import/rename/delete
path extraction with vanished-path-friendly previous paths, subtree
fallback, exact-path dedupe, and no-op unknown events. Fixture-backed.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(autoscan): add public webhook delivery route and admin endpoint management

Public POST /api/v1/autoscan/webhooks/{token} with per-IP rate
limiting, 256KiB body cap, 202-for-noop semantics, and token/body kept
out of logs; admin create/rotate/delete endpoint routes; source
responses carry delivery mode + webhook status/URL; create/update
validate delivery mode against source identity.

Co-Authored-By: Claude Fable 5 <[email protected]>

* feat(web): add webhook delivery mode to Autoscan admin UI

Webhook sources get a generate/copy/rotate webhook URL section,
provider selector, delivery status, and a connection-free Add-source
flow; activity rows badge webhook deliveries with the arr event type.
Path rewrites stay editable in both modes.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(api): redact secret path params from request and activity logs

The request logger and activity-log middleware recorded raw URLs, so
bearer credentials in secret path segments (autoscan webhook {token},
webhook-sync {secret}) were persisted to app logs and activity_log.
Redact the secret segment via the chi route params in both sinks.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix(autoscan): make webhook delivery reliable

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant