Skip to content

Add auto-resume session from GARTH_HOME or GARTH_TOKEN env vars (#172)#175

Merged
matin merged 6 commits intomainfrom
auto-resume
Jan 12, 2026
Merged

Add auto-resume session from GARTH_HOME or GARTH_TOKEN env vars (#172)#175
matin merged 6 commits intomainfrom
auto-resume

Conversation

@matin
Copy link
Copy Markdown
Owner

@matin matin commented Jan 12, 2026

Summary

  • Adds automatic session restoration when Client() is initialized
  • Supports GARTH_HOME env var pointing to directory with saved tokens
  • Supports GARTH_TOKEN env var with base64-encoded token string
  • Raises GarthException if both env vars are set simultaneously
  • Adds __str__ method to GarthException for proper message display in exceptions

Test plan

  • test_auto_resume_garth_home - Verify loading from directory path
  • test_auto_resume_garth_token - Verify loading from base64 token
  • test_auto_resume_both_set_raises - Verify error when both env vars set
  • All existing tests pass (127 tests)

Closes #172

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Automatic session resumption: The client now automatically loads and resumes session data from configured environment variables during initialization, enabling seamless reconnection without requiring manual session setup each time
  • Improvements

    • Enhanced error handling with improved exception messages for clearer diagnostics
    • Added configuration validation to prevent conflicts between multiple environment variable settings

✏️ Tip: You can customize this high-level summary in your review settings.

- Add _auto_resume() method to Client class that checks env vars on init
- Support GARTH_HOME (directory path) or GARTH_TOKEN (base64 token string)
- Raise GarthException if both env vars are set simultaneously
- Add __str__ method to GarthException for proper exception message display
- Update client test fixture to clear env vars for clean test isolation

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 12, 2026

Warning

Rate limit exceeded

@matin has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 31 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2c50c72 and 839b36b.

📒 Files selected for processing (7)
  • README.md
  • docs/getting-started.md
  • src/garth/auth_tokens.py
  • src/garth/http.py
  • tests/conftest.py
  • tests/test_auth_tokens.py
  • tests/test_http.py

Walkthrough

This pull request implements auto-resumption of Garth sessions using environment variables. When a Client is initialized, it automatically loads session data from GARTH_HOME (directory) or GARTH_TOKEN (token string). If both variables are set, an exception is raised. A __str__ method was added to GarthException for consistent string representation.

Changes

Cohort / File(s) Summary
Exception handling
src/garth/exc.py
Added __str__(self) -> str method to GarthException class that returns self.msg, aligning string representation with stored message.
Auto-resume logic
src/garth/http.py
Introduced _auto_resume() private method invoked during Client initialization. Checks GARTH_HOME and GARTH_TOKEN environment variables with mutual exclusion (raises GarthException if both set); loads session from GARTH_HOME via Client.load() or from GARTH_TOKEN via Client.loads(). Updated imports to include GarthException.
Test configuration
tests/conftest.py
Updated client fixture to accept monkeypatch parameter and clean up GARTH_HOME and GARTH_TOKEN environment variables before returning Client instance, preventing unintended auto-resume during tests.
Test coverage
tests/test_http.py
Added three new test cases: test_auto_resume_garth_home (verifies session restoration from directory), test_auto_resume_garth_token (verifies session restoration from token string), and test_auto_resume_both_set_raises (verifies exception when both env vars are set). Updated imports to include GarthException.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.09% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding auto-resume functionality for sessions using GARTH_HOME or GARTH_TOKEN environment variables, matching the primary objective of the PR.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from issue #172: auto-resume via GARTH_HOME (Client.load()) and GARTH_TOKEN (Client.loads()), mutual exclusion with exception raising, and three comprehensive tests validating the functionality.
Out of Scope Changes check ✅ Passed All changes are in scope: the _auto_resume method in Client, environment variable handling, GarthException str method, test fixture updates for env cleanup, and three new tests all directly support the auto-resume feature objective.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch auto-resume

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented Jan 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (cd02e1a) to head (839b36b).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main      #175   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           66        66           
  Lines         3044      3118   +74     
=========================================
+ Hits          3044      3118   +74     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

When a client was loaded from GARTH_HOME and the OAuth2 token is refreshed,
automatically dump the updated tokens back to GARTH_HOME to keep the persisted
session current.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@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: 0

🧹 Nitpick comments (1)
src/garth/http.py (1)

95-108: Implementation looks correct.

The mutual exclusion logic and conditional loading are well-implemented. The truthiness checks handle edge cases like empty strings correctly.

Consider adding a return type hint for consistency with other methods:

-    def _auto_resume(self):
+    def _auto_resume(self) -> None:
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd02e1a and 2c50c72.

📒 Files selected for processing (4)
  • src/garth/exc.py
  • src/garth/http.py
  • tests/conftest.py
  • tests/test_http.py
🧰 Additional context used
📓 Path-based instructions (2)
tests/**/*.py

📄 CodeRabbit inference engine (CLAUDE.md)

tests/**/*.py: Use pytest with VCR cassettes for HTTP recording/playback in tests
Mirror test directory structure to match source code structure

Files:

  • tests/conftest.py
  • tests/test_http.py
tests/**

⚙️ CodeRabbit configuration file

tests/**: - test functions shouldn't have a return type hint

  • it's ok to use assert instead of pytest.assume()

Files:

  • tests/conftest.py
  • tests/test_http.py
🧠 Learnings (1)
📚 Learning: 2026-01-09T22:41:07.978Z
Learnt from: CR
Repo: matin/garth PR: 0
File: CLAUDE.md:0-0
Timestamp: 2026-01-09T22:41:07.978Z
Learning: Expose main client instance as `garth.client` and provide `connectapi()` method for direct API calls returning JSON

Applied to files:

  • tests/test_http.py
🧬 Code graph analysis (2)
tests/test_http.py (3)
src/garth/exc.py (2)
  • GarthException (7-13)
  • GarthHTTPError (17-21)
tests/conftest.py (4)
  • authed_client (68-78)
  • client (21-25)
  • oauth1_token (40-41)
  • oauth2_token (58-64)
src/garth/http.py (1)
  • Client (19-261)
src/garth/http.py (1)
src/garth/exc.py (2)
  • GarthException (7-13)
  • GarthHTTPError (17-21)
🔇 Additional comments (6)
src/garth/exc.py (1)

12-13: LGTM!

The __str__ method correctly returns the message, ensuring consistent string representation for GarthException instances. This aligns well with the existing GarthHTTPError.__str__ pattern and enables proper display when the exception is raised (e.g., in the auto-resume conflict scenario).

src/garth/http.py (1)

43-43: LGTM!

The _auto_resume() call is correctly placed after configure(), ensuring the client is properly initialized before attempting to load tokens from environment variables.

tests/test_http.py (3)

32-43: LGTM!

The test correctly verifies that a new Client auto-resumes from GARTH_HOME. Good use of monkeypatch to isolate the environment and tempfile.TemporaryDirectory for cleanup.


45-54: LGTM!

The test correctly verifies that a new Client auto-resumes from GARTH_TOKEN. The setup mirrors test_auto_resume_garth_home appropriately.


57-62: LGTM!

The test correctly verifies that GarthException is raised with the expected message when both environment variables are set. Good use of pytest.raises with match for precise error validation.

tests/conftest.py (1)

20-25: LGTM!

The fixture correctly clears environment variables before creating the Client, preventing auto-resume from interfering with tests that don't explicitly test that behavior. The raising=False parameter properly handles cases where the variables aren't set.

- Update README with auto-resume in features list
- Add environment variable examples to README
- Add comprehensive auto-resume section in getting-started docs
- Document GARTH_HOME, GARTH_TOKEN, and auto-persist behavior

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@matin matin mentioned this pull request Jan 12, 2026
19 tasks
matin and others added 3 commits January 12, 2026 15:54
- OAuth1Token: mask oauth_token_secret as '***'
- OAuth2Token: mask access_token and refresh_token as '***'
- Use @DataClass(repr=False) with custom __repr__ methods

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add oauth2_only parameter to Client.dump()
- Use oauth2_only=True in refresh_oauth2() to avoid unnecessary oauth1 file write
- Add test to verify oauth1 file is not modified on refresh

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Clear _garth_home in authed_client fixture to prevent tests from
auto-persisting tokens back to the user's actual GARTH_HOME directory.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@matin matin merged commit dc3dad1 into main Jan 12, 2026
26 checks passed
@matin matin deleted the auto-resume branch January 12, 2026 22:04
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.

Auto resume session using GARTH_HOME and GARTH_TOKEN

1 participant