feat: add debug logging for auth token expiry and renewal decisions#102
Conversation
Gids voor reviewersVoegt debug-level logging toe rond de evaluatie van token-verval en beslissingen over vernieuwing in FrankEnergie, plus tests om het loggedrag en de formattering te verifiëren. Sequentiediagram voor bijgewerkte auth-token-vervalcontroles en loggingsequenceDiagram
actor Client
participant FrankEnergie
participant Auth
participant Logger
Client->>FrankEnergie: validate_authentication()
FrankEnergie->>FrankEnergie: is_authenticated
alt authenticated and auth with expires_at
FrankEnergie->>FrankEnergie: datetime.now(UTC)
FrankEnergie->>Logger: debug(Token expiry check...)
end
FrankEnergie->>FrankEnergie: acquire _renew_lock
alt auth.is_expired
FrankEnergie->>Logger: debug(Token renewal required...)
FrankEnergie->>FrankEnergie: renew_token()
FrankEnergie->>FrankEnergie: _query(query)
FrankEnergie->>Auth: Authentication.from_dict(response)
Auth-->>FrankEnergie: auth
FrankEnergie->>Logger: debug(Authentication token updated, expires_at=...)
end
FrankEnergie-->>Client: bool
Client->>FrankEnergie: _requires_token_refresh(operation_name)
alt operation_name == RENEW_TOKEN_OPERATIONNAME or _auth is None
FrankEnergie-->>Client: False
else check expiry
FrankEnergie->>FrankEnergie: datetime.now(UTC)
FrankEnergie->>Logger: debug(Token expiry check...)
FrankEnergie->>FrankEnergie: is_expired = _auth.is_expired
alt is_expired and expires_at
FrankEnergie->>Logger: debug(Token renewal required...)
end
FrankEnergie-->>Client: is_expired
end
Wijzigingen per bestand
Beoordeling ten opzichte van gelinkte issues
Mogelijk gerelateerde issues
Tips en commando'sInteractie met Sourcery
Je ervaring aanpassenGa naar je dashboard om:
Hulp krijgen
Original review guide in EnglishReviewer's GuideAdds debug-level logging around token expiry evaluation and renewal decisions in FrankEnergie, plus tests to verify the logging behavior and formatting. Sequence diagram for updated auth token expiry checks and loggingsequenceDiagram
actor Client
participant FrankEnergie
participant Auth
participant Logger
Client->>FrankEnergie: validate_authentication()
FrankEnergie->>FrankEnergie: is_authenticated
alt authenticated and auth with expires_at
FrankEnergie->>FrankEnergie: datetime.now(UTC)
FrankEnergie->>Logger: debug(Token expiry check...)
end
FrankEnergie->>FrankEnergie: acquire _renew_lock
alt auth.is_expired
FrankEnergie->>Logger: debug(Token renewal required...)
FrankEnergie->>FrankEnergie: renew_token()
FrankEnergie->>FrankEnergie: _query(query)
FrankEnergie->>Auth: Authentication.from_dict(response)
Auth-->>FrankEnergie: auth
FrankEnergie->>Logger: debug(Authentication token updated, expires_at=...)
end
FrankEnergie-->>Client: bool
Client->>FrankEnergie: _requires_token_refresh(operation_name)
alt operation_name == RENEW_TOKEN_OPERATIONNAME or _auth is None
FrankEnergie-->>Client: False
else check expiry
FrankEnergie->>FrankEnergie: datetime.now(UTC)
FrankEnergie->>Logger: debug(Token expiry check...)
FrankEnergie->>FrankEnergie: is_expired = _auth.is_expired
alt is_expired and expires_at
FrankEnergie->>Logger: debug(Token renewal required...)
end
FrankEnergie-->>Client: is_expired
end
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
|
Warning Review limit reached
More reviews will be available in 52 minutes and 56 seconds. Learn how PR review limits work. Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file). ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the 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 credits. 🚦 How do rate limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate. 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, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
📝 WalkthroughWalkthroughAdds a Token Renewal Debug Logging
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Hey - ik heb 1 issue gevonden en wat high-level feedback achtergelaten:
- De nieuwe constante TOKEN_RENEWAL_MARGIN wordt momenteel alleen gebruikt voor logging en niet in de daadwerkelijke logica voor vernieuwing/verval; overweeg om deze óf te koppelen aan de
is_expired-/vernieuwingslogica, óf om te verduidelijken waarom deze puur informatief is om toekomstige verwarring te voorkomen. - De debuglogging voor tokenverval en -vernieuwing is gedupliceerd tussen
validate_authenticationen_requires_token_refresh; overweeg een kleine helper te extraheren om dit gedrag te centraliseren en toekomstige wijzigingen consistent te houden.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the `is_expired`/renewal logic or clarifying why it’s purely informational to avoid future confusion.
- The token expiry and renewal debug logging logic is duplicated between `validate_authentication` and `_requires_token_refresh`; consider extracting a small helper to centralize this behavior and keep future changes consistent.
## Individual Comments
### Comment 1
<location path="tests/test_renew_token.py" line_range="123-124" />
<code_context>
await api.close()
+
+
+@pytest.mark.asyncio
+async def test_renew_token_logging(aresponses, caplog):
+ """Test that authentication and renewal decisions generate debug log statements."""
+ import logging
</code_context>
<issue_to_address>
**issue (testing):** De nieuwe test valideert alleen logging via `validate_authentication`, maar dekt niet de `_requires_token_refresh`-, `login`- of `renew_token`-loggingpaden die in de PR-beschrijving worden genoemd.
Gezien het doel om alle nieuwe loggingpaden te valideren, dekt deze test alleen de `validate_authentication`-flow. Voeg alsjeblieft gerichte tests toe voor:
- `_requires_token_refresh` met zowel verlopen als niet-verlopende tokens om de vervalcontrole en de "Token renewal required"-logs te testen.
- `login` happy path om de log "Authentication token updated; expires_at=..." te asserten.
- `renew_token` happy path om dezelfde log voor een vernieuwd token te asserten.
Dit zorgt ervoor dat elke nieuwe loggingbranch expliciet wordt getest en beschermd is tegen regressies.
</issue_to_address>Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Original comment in English
Hey - I've found 1 issue, and left some high level feedback:
- The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the
is_expired/renewal logic or clarifying why it’s purely informational to avoid future confusion. - The token expiry and renewal debug logging logic is duplicated between
validate_authenticationand_requires_token_refresh; consider extracting a small helper to centralize this behavior and keep future changes consistent.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- The new TOKEN_RENEWAL_MARGIN constant is currently only used for logging and not in any actual renewal/expiry decision logic; consider either wiring it into the `is_expired`/renewal logic or clarifying why it’s purely informational to avoid future confusion.
- The token expiry and renewal debug logging logic is duplicated between `validate_authentication` and `_requires_token_refresh`; consider extracting a small helper to centralize this behavior and keep future changes consistent.
## Individual Comments
### Comment 1
<location path="tests/test_renew_token.py" line_range="123-124" />
<code_context>
await api.close()
+
+
+@pytest.mark.asyncio
+async def test_renew_token_logging(aresponses, caplog):
+ """Test that authentication and renewal decisions generate debug log statements."""
+ import logging
</code_context>
<issue_to_address>
**issue (testing):** The new test only validates logging via `validate_authentication`, but does not cover the `_requires_token_refresh`, `login`, or `renew_token` logging paths mentioned in the PR description.
Given the goal of validating all new logging paths, this test only covers the `validate_authentication` flow. Please add targeted tests for:
- `_requires_token_refresh` with both expiring and non-expiring tokens to exercise the expiry check and "Token renewal required" logs.
- `login` happy path to assert the "Authentication token updated; expires_at=..." log.
- `renew_token` happy path to assert the same log for a renewed token.
This will ensure each new logging branch is explicitly tested and protected against regressions.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
| @pytest.mark.asyncio | ||
| async def test_renew_token_logging(aresponses, caplog): |
There was a problem hiding this comment.
issue (testing): De nieuwe test valideert alleen logging via validate_authentication, maar dekt niet de _requires_token_refresh-, login- of renew_token-loggingpaden die in de PR-beschrijving worden genoemd.
Gezien het doel om alle nieuwe loggingpaden te valideren, dekt deze test alleen de validate_authentication-flow. Voeg alsjeblieft gerichte tests toe voor:
_requires_token_refreshmet zowel verlopen als niet-verlopende tokens om de vervalcontrole en de "Token renewal required"-logs te testen.loginhappy path om de log "Authentication token updated; expires_at=..." te asserten.renew_tokenhappy path om dezelfde log voor een vernieuwd token te asserten.
Dit zorgt ervoor dat elke nieuwe loggingbranch expliciet wordt getest en beschermd is tegen regressies.
Original comment in English
issue (testing): The new test only validates logging via validate_authentication, but does not cover the _requires_token_refresh, login, or renew_token logging paths mentioned in the PR description.
Given the goal of validating all new logging paths, this test only covers the validate_authentication flow. Please add targeted tests for:
_requires_token_refreshwith both expiring and non-expiring tokens to exercise the expiry check and "Token renewal required" logs.loginhappy path to assert the "Authentication token updated; expires_at=..." log.renew_tokenhappy path to assert the same log for a renewed token.
This will ensure each new logging branch is explicitly tested and protected against regressions.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
python_frank_energie/frank_energie.py (1)
100-100: 🏗️ Heavy liftUnify renewal threshold source of truth for decision + logs.
At Line 205 the refresh decision still comes from
self._auth.is_expired(hardcoded 5-minute margin inpython_frank_energie/models.py:323-331), while Line 210 logsTOKEN_RENEWAL_MARGIN. This can silently desync behavior vs logs if either value changes.Suggested direction
- is_expired = self._auth.is_expired + is_expired = ( + self._auth.expires_at is None + and bool(self._auth.authToken and len(self._auth.authToken.split(".")) >= 3) + ) or ( + self._auth.expires_at is not None + and now_utc >= (self._auth.expires_at - self.TOKEN_RENEWAL_MARGIN) + )If you prefer keeping expiry logic in
Authentication, expose a margin-aware method there and call it from here so both paths share one implementation.Also applies to: 205-212
🤖 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 `@python_frank_energie/frank_energie.py` at line 100, The token renewal decision at line 205 uses `self._auth.is_expired` which contains a hardcoded 5-minute margin embedded in the Authentication class, while the logging at line 210 references `TOKEN_RENEWAL_MARGIN` from the current file. To unify the source of truth, expose a margin-aware method in the Authentication class that accepts or references the `TOKEN_RENEWAL_MARGIN` constant, then replace the `self._auth.is_expired` call at line 205 with a call to this new method, ensuring both the renewal decision logic and the logging statement use the same margin value from a single source.
🤖 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 `@tests/test_renew_token.py`:
- Around line 154-172: The test currently aggregates logs from both
validate_authentication() calls (when token is not expired and when it is
expired), making it impossible to verify that the non-renewal case does not log
"Token renewal required" while the renewal case does. Insert caplog.clear()
between the two validate_authentication() calls to separate the logged output by
phase, then add explicit assertions after the first call to verify that "Token
renewal required" is NOT present (use assert not any(...)), and keep the
existing assertions after the second call to verify it IS present.
---
Nitpick comments:
In `@python_frank_energie/frank_energie.py`:
- Line 100: The token renewal decision at line 205 uses `self._auth.is_expired`
which contains a hardcoded 5-minute margin embedded in the Authentication class,
while the logging at line 210 references `TOKEN_RENEWAL_MARGIN` from the current
file. To unify the source of truth, expose a margin-aware method in the
Authentication class that accepts or references the `TOKEN_RENEWAL_MARGIN`
constant, then replace the `self._auth.is_expired` call at line 205 with a call
to this new method, ensuring both the renewal decision logic and the logging
statement use the same margin value from a single source.
🪄 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
Run ID: 4dd92e1c-630e-4e0a-93aa-40e597139d90
📒 Files selected for processing (2)
python_frank_energie/frank_energie.pytests/test_renew_token.py
|



Summary
Adds detailed debug logging around authentication token lifetime, renewal thresholds, and token update decisions to facilitate easier troubleshooting and observability of the authentication lifecycle.
Key Changes
TOKEN_RENEWAL_MARGIN = timedelta(minutes=5)onFrankEnergieclass to match the client's token renewal buffer.now,expires_at, andremainingtime) duringvalidate_authenticationand_requires_token_refresh.loginandrenew_token, including fallback handling for mock/test tokens.test_renew_token_loggingintests/test_renew_token.pyto assert that all logging paths are correctly executed and verify output formatting.Why this is needed
Resolves #93. This logging provides visibility into token expiry times, timezone alignments, and client renewal actions, which is essential for diagnosing authentication failures in production environments.
Summary by Sourcery
Voeg observability toe aan de authenticatie‑levenscyclus door het loggen van token-vervalcontroles, beslissingen over vernieuwing en tokenupdates, en verifieer dit gedrag met tests.
Nieuwe features:
Tests:
Original summary in English
Summary by Sourcery
Add observability to the authentication lifecycle by logging token expiry checks, renewal decisions, and token updates, and verify this behavior with tests.
New Features:
Tests:
Summary by CodeRabbit
Bug Fixes
Tests