Skip to content

feat: Use Home Assistant's shared aiohttp client session#210

Merged
firstof9 merged 2 commits intomainfrom
ha-session
Mar 10, 2026
Merged

feat: Use Home Assistant's shared aiohttp client session#210
firstof9 merged 2 commits intomainfrom
ha-session

Conversation

@firstof9
Copy link
Owner

@firstof9 firstof9 commented Mar 10, 2026

Summary by CodeRabbit

  • Chores

    • Updated py_gasbuddy dependency to version 0.4.3.
  • Refactor

    • Improved HTTP session handling for API requests used by price lookups and configuration flows, boosting reliability and reducing redundant network connections.

@coderabbitai
Copy link

coderabbitai bot commented Mar 10, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3d4034f7-66b8-4c0d-bb9c-e080eeb5ba94

📥 Commits

Reviewing files that changed from the base of the PR and between 55e5123 and a022dda.

📒 Files selected for processing (1)
  • custom_components/gasbuddy/services.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • custom_components/gasbuddy/services.py

📝 Walkthrough

Walkthrough

Config flow, coordinator, and service modules now explicitly obtain and pass Home Assistant aiohttp sessions via async_get_clientsession; related function signatures were updated to accept HomeAssistant. The GasBuddy client is instantiated with the shared session, and py_gasbuddy was bumped to 0.4.3.

Changes

Cohort / File(s) Summary
Config Flow Session Hardening
custom_components/gasbuddy/config_flow.py
Updated function signatures: validate_station and _get_station_list now accept hass: HomeAssistant. Both use async_get_clientsession(hass) for API calls and call sites now pass self.hass.
Coordinator Session Injection
custom_components/gasbuddy/coordinator.py
Added import of async_get_clientsession and instantiate GasBuddy(..., session=async_get_clientsession(hass)) in coordinator initialization.
Service Price Lookup Session Updates
custom_components/gasbuddy/services.py
Price lookup handlers (_price_lookup_gps, _price_lookup_zip) create GasBuddy with session=async_get_clientsession(self.hass) and call the consolidated price_lookup_service methods.
Dependency Version Bump
custom_components/gasbuddy/manifest.json
py_gasbuddy requirement updated from 0.4.2 to 0.4.3.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through code with careful care,

Sessions shared and tidy fare,
APIs called with one small hop,
No loose sockets left to drop,
Cheerful bytes and carrots to spare 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main objective: refactoring the codebase to use Home Assistant's shared aiohttp client session instead of creating individual sessions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ha-session

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

codecov bot commented Mar 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.07%. Comparing base (6c112e3) to head (a022dda).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main     #210   +/-   ##
=======================================
  Coverage   99.06%   99.07%           
=======================================
  Files           8        8           
  Lines         537      541    +4     
=======================================
+ Hits          532      536    +4     
  Misses          5        5           

☔ 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.

Copy link

@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

🧹 Nitpick comments (1)
custom_components/gasbuddy/services.py (1)

109-112: Consider moving GasBuddy instantiation outside the loop.

A new GasBuddy instance is created for each entity in the loop. While the shared aiohttp session is correctly reused, you could instantiate GasBuddy once before the loop since solver_url doesn't change between iterations.

♻️ Optional refactor to instantiate GasBuddy once
         results = {}
+        api = GasBuddy(
+            solver_url=solver,
+            session=async_get_clientsession(self.hass),
+        )
         for entity_id in entity_ids:
             try:
                 entity = self.hass.states.get(entity_id)
                 if entity:
                     lat = entity.attributes[ATTR_LATITUDE]
                     lon = entity.attributes[ATTR_LONGITUDE]
-                    results[entity_id] = await GasBuddy(
-                        solver_url=solver,
-                        session=async_get_clientsession(self.hass),
-                    ).price_lookup_service(lat=lat, lon=lon, limit=limit)
+                    results[entity_id] = await api.price_lookup_service(lat=lat, lon=lon, limit=limit)
             except (APIError, LibraryError, CSRFTokenMissing) as ex:
                 _LOGGER.error("Error checking prices: %s", ex)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@custom_components/gasbuddy/services.py` around lines 109 - 112, The code
creates a new GasBuddy instance inside the per-entity loop every iteration; move
the instantiation of GasBuddy(solver_url=solver,
session=async_get_clientsession(self.hass)) to a single variable created before
the loop and then call its price_lookup_service(lat=..., lon=..., limit=...) for
each entity (replace the inline GasBuddy(...) in the results[entity_id]
assignment with the precreated instance) to avoid redundant object creation
while still reusing the shared aiohttp session.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@custom_components/gasbuddy/manifest.json`:
- Line 11: Update the pinned dependency in the manifest requirements so
installation uses the published py_gasbuddy release: replace the current
"py_gasbuddy==0.4.3" entry in the requirements array with "py_gasbuddy==0.4.2"
(or alternatively remove the version pin and wait until py_gasbuddy 0.4.3 is
available on PyPI); ensure the change is made in the manifest's "requirements"
array so installs won't fail due to an unpublished 0.4.3 release.

---

Nitpick comments:
In `@custom_components/gasbuddy/services.py`:
- Around line 109-112: The code creates a new GasBuddy instance inside the
per-entity loop every iteration; move the instantiation of
GasBuddy(solver_url=solver, session=async_get_clientsession(self.hass)) to a
single variable created before the loop and then call its
price_lookup_service(lat=..., lon=..., limit=...) for each entity (replace the
inline GasBuddy(...) in the results[entity_id] assignment with the precreated
instance) to avoid redundant object creation while still reusing the shared
aiohttp session.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 561e8357-65fd-42f7-94c8-14aa6d2acebe

📥 Commits

Reviewing files that changed from the base of the PR and between 6c112e3 and 55e5123.

📒 Files selected for processing (4)
  • custom_components/gasbuddy/config_flow.py
  • custom_components/gasbuddy/coordinator.py
  • custom_components/gasbuddy/manifest.json
  • custom_components/gasbuddy/services.py

@firstof9 firstof9 merged commit 9d35a79 into main Mar 10, 2026
7 checks passed
@firstof9 firstof9 deleted the ha-session branch March 10, 2026 18:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant