Skip to content

Validate StreamRetryPolicy at processor entry#56

Open
aleksandar-apostolov wants to merge 1 commit intodevelopfrom
fix/retry-processor-validate-policy
Open

Validate StreamRetryPolicy at processor entry#56
aleksandar-apostolov wants to merge 1 commit intodevelopfrom
fix/retry-processor-validate-policy

Conversation

@aleksandar-apostolov
Copy link
Copy Markdown
Collaborator

@aleksandar-apostolov aleksandar-apostolov commented Apr 22, 2026

Goal

Defense-in-depth: validate StreamRetryPolicy invariants at the point of consumption (StreamRetryProcessor.retry()), not just at creation time.

Addresses a review observation from GetStream/stream-video-android#1645 (by @rahul-lohra): the processor's while (attempt <= policy.maxRetries) loop silently skips execution if maxRetries < 1, falling through to a confusing IllegalStateException("Check your policy"). While factory methods already validate via requireValid(), the processor itself should guard against invalid policies as well.

Implementation

  • StreamRetryPolicy.requireValid() — extracted from the private validate() companion extension into an internal member function. Single source of truth for invariant checks, callable from both factory methods and the processor.
  • StreamRetryProcessor.retry() — calls policy.requireValid() at entry. Invalid policies now fail immediately with a clear IllegalArgumentException message instead of silently skipping the retry loop.
  • @IntRange annotations — added to constructor and all factory method parameters for IDE-level early detection.
  • Error message fix"minRetries must be ≥ 0" corrected to "minRetries must be > 0" (the require check is > 0, not >= 0).

Testing

  • Updated StreamRetryProcessorImplTest — the maxRetries = 0 test now expects IllegalArgumentException with message "maxRetries must be" instead of IllegalStateException with "Check your policy".
  • All existing StreamRetryPolicyTest and StreamRetryProcessorImplTest tests pass.

Summary by CodeRabbit

  • Refactor

    • Strengthened retry policy validation to enforce stricter bounds on retry attempt counts and delay-related parameters. Validation errors now provide more detailed messages that include actual parameter values for easier troubleshooting.
  • Chores

    • Updated parameter annotations across retry policy factory methods to improve constraint validation and ensure better configuration reliability.

- Extract requireValid() as internal member on StreamRetryPolicy
- Call policy.requireValid() at the top of StreamRetryProcessor.retry()
- Add @IntRange annotations to constructor and factory method params
- Fix error message: "minRetries must be > 0" (was incorrectly "≥ 0")
- Update test to expect IllegalArgumentException from requireValid()
  instead of IllegalStateException from unreachable fallthrough
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Apr 22, 2026

PR checklist ✅

All required conditions are satisfied:

  • Title length is OK (or ignored by label).
  • At least one pr: label exists.
  • Sections ### Goal, ### Implementation, and ### Testing are filled.

🎉 Great job! This PR is ready for review.

@aleksandar-apostolov aleksandar-apostolov changed the title fix: validate StreamRetryPolicy at processor entry Validate StreamRetryPolicy at processor entry Apr 22, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 22, 2026

Walkthrough

The changes refactor the validation mechanism in StreamRetryPolicy by introducing @IntRange annotations on constructor and factory method parameters to express numeric bounds, replacing the validate() function with an internal requireValid() method that enforces constraints via require(...) statements with updated error messages, and updating dependent test assertions accordingly.

Changes

Cohort / File(s) Summary
Retry Policy Validation Refactoring
stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt
Added @IntRange annotations to all numeric parameters in the private constructor and three factory methods (exponential, linear, fixed). Replaced validate() call chains with also { it.requireValid() }. Introduced internal fun requireValid() that enforces bounds using require(...) statements with descriptive error messages (including actual values). Changed minRetries validation from ≥ 0 to > 0.
Validation Integration & Tests
stream-android-core/src/main/java/io/getstream/android/core/internal/processing/StreamRetryProcessorImpl.kt, stream-android-core/src/test/java/io/getstream/android/core/internal/processing/StreamRetryProcessorImplTest.kt
StreamRetryProcessorImpl.retry(...) now calls policy.requireValid() at the start of execution. Test case updated to expect IllegalArgumentException with message containing "maxRetries must be" instead of IllegalStateException with "Check your policy".

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 With annotations bright and bounds so clear,
@IntRange marks keep errors near,
Validation refactored with grace so fine,
requireValid() ensures all will align!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% 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
Title check ✅ Passed The title 'fix: validate StreamRetryPolicy at processor entry' clearly and concisely describes the main change: adding validation of StreamRetryPolicy at the point of consumption in the processor.
Description check ✅ Passed The pull request description fully covers all required sections: Goal explains the defense-in-depth validation rationale, Implementation details all changes made, Testing describes test updates, and Checklist is included (though items unchecked).
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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 fix/retry-processor-validate-policy

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

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)
stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt (1)

32-38: ⚠️ Potential issue | 🟡 Minor

Update the KDoc to match the new minRetries > 0 invariant.

The docs still say minRetries ≥ 0 and that 0 disables retries, but the annotations and requireValid() now reject 0.

📝 Proposed KDoc update
- * * `minRetries ≥ 0`
+ * * `minRetries > 0`
  * * `maxRetries ≥ minRetries`
  * * `0 ≤ minBackoffMills ≤ maxBackoffMills`
  *
- * `@param` minRetries Minimum number of retry attempts (not counting the original call). Set to `0`
- *   to disable retries.
+ * `@param` minRetries Minimum number of retry attempts (not counting the original call). Must be
+ *   greater than `0`.

As per coding guidelines, “Keep processor/queue behaviour documented via KDoc or dedicated docs when semantics evolve”.

Also applies to: 53-57, 234-245

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt`
around lines 32 - 38, The KDoc for StreamRetryPolicy is out of date: change the
invariant and parameter descriptions to reflect that minRetries must be > 0 (not
≥ 0) and that 0 is no longer allowed (so you cannot disable retries by setting
0); update all occurrences referencing `minRetries ≥ 0` and “Set to `0` to
disable retries” (including the blocks around lines referencing the class and
the other affected KDoc sections) to state the new invariant `minRetries > 0`
and explain the intended semantics, and ensure the comment mentions
`requireValid()` enforces this constraint so callers understand the validation
behavior.
🧹 Nitpick comments (1)
stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt (1)

205-225: Add @IntRange annotations to custom() parameters for consistency with other factory methods.

All three preset factories (exponential, linear, fixed) use @IntRange annotations on their numeric parameters, but custom() lacks them. This removes IDE-level validation hints for callers and creates an inconsistent API surface.

Apply annotations
         public fun custom(
-            minRetries: Int,
-            maxRetries: Int,
-            minBackoffMills: Long,
-            maxBackoffMills: Long,
-            initialDelayMillis: Long,
+            `@IntRange`(from = 1) minRetries: Int,
+            `@IntRange`(from = 1) maxRetries: Int,
+            `@IntRange`(from = 0) minBackoffMills: Long,
+            `@IntRange`(from = 0) maxBackoffMills: Long,
+            `@IntRange`(from = 0) initialDelayMillis: Long,
             giveUp: (Int, Throwable) -> Boolean = { retry, _ -> retry > maxRetries },
             nextDelay: (Int, Long) -> Long,
         ): StreamRetryPolicy =
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt`
around lines 205 - 225, The custom() factory is missing `@IntRange` annotations on
its numeric parameters, which makes it inconsistent with
exponential/linear/fixed; update the custom(...) signature in StreamRetryPolicy
to add the same `@IntRange`(from=..., to=...) annotations used by the other
factories for minRetries, maxRetries, minBackoffMills, maxBackoffMills and
initialDelayMillis (import androidx.annotation.IntRange if needed) so callers
get IDE validation; keep the rest of the signature (giveUp, nextDelay, return
StreamRetryPolicy and requireValid()) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In
`@stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt`:
- Around line 234-245: The internal function requireValid in StreamRetryPolicy
lacks an explicit return type required by explicit API mode; update its
signature to declare a Unit return type (i.e., change fun requireValid() to fun
requireValid(): Unit) so the compiler accepts the internal API, leaving the
function body unchanged; ensure you modify the declaration in the
StreamRetryPolicy class where requireValid is defined.

---

Outside diff comments:
In
`@stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt`:
- Around line 32-38: The KDoc for StreamRetryPolicy is out of date: change the
invariant and parameter descriptions to reflect that minRetries must be > 0 (not
≥ 0) and that 0 is no longer allowed (so you cannot disable retries by setting
0); update all occurrences referencing `minRetries ≥ 0` and “Set to `0` to
disable retries” (including the blocks around lines referencing the class and
the other affected KDoc sections) to state the new invariant `minRetries > 0`
and explain the intended semantics, and ensure the comment mentions
`requireValid()` enforces this constraint so callers understand the validation
behavior.

---

Nitpick comments:
In
`@stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt`:
- Around line 205-225: The custom() factory is missing `@IntRange` annotations on
its numeric parameters, which makes it inconsistent with
exponential/linear/fixed; update the custom(...) signature in StreamRetryPolicy
to add the same `@IntRange`(from=..., to=...) annotations used by the other
factories for minRetries, maxRetries, minBackoffMills, maxBackoffMills and
initialDelayMillis (import androidx.annotation.IntRange if needed) so callers
get IDE validation; keep the rest of the signature (giveUp, nextDelay, return
StreamRetryPolicy and requireValid()) unchanged.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e3ed3655-8ee3-4cda-9bec-32c47dc9d93d

📥 Commits

Reviewing files that changed from the base of the PR and between 332de07 and f634815.

📒 Files selected for processing (3)
  • stream-android-core/src/main/java/io/getstream/android/core/api/model/retry/StreamRetryPolicy.kt
  • stream-android-core/src/main/java/io/getstream/android/core/internal/processing/StreamRetryProcessorImpl.kt
  • stream-android-core/src/test/java/io/getstream/android/core/internal/processing/StreamRetryProcessorImplTest.kt

@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
21.7% Duplication on New Code (required ≤ 3%)

See analysis details on SonarQube Cloud

@github-advanced-security
Copy link
Copy Markdown

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

@aleksandar-apostolov
Copy link
Copy Markdown
Collaborator Author

The 21.7% duplication is pre-existing structural duplication from the factory pattern — exponential(), linear(), and fixed() share identical parameter signatures because they configure the same underlying StreamRetryPolicy data class. This PR only added @IntRange annotations to those existing params.

Extracting a shared config class would hurt call-site ergonomics (StreamRetryPolicy.exponential(maxRetries = 3) becomes StreamRetryPolicy.exponential(StreamRetryConfig(maxRetries = 3))). Not worth the trade-off for factory-pattern signatures.

Same pattern exists in StreamSocketConfig.jwt() / anonymous() / custom() without complaint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr:improvement Improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants