Skip to content

Conversation

@yujonglee
Copy link
Contributor

@yujonglee yujonglee commented Dec 4, 2025

refactor(gladia): clean up adapter code

Summary

Refactors the Gladia STT adapter code to improve readability and reduce duplication:

  • URL building: Extracted shared build_url_with_scheme helper to eliminate duplicate scheme/host/port logic between WebSocket and HTTP URL construction
  • Session tracking: Encapsulated global session channel state into a SessionChannels struct with clear helper methods (insert, get, remove, get_or_infer)
  • Error handling: Simplified verbose match statements to idiomatic map_err().ok()? pattern
  • Conditional options: Replaced if-else blocks with .then() and .then_some() for cleaner conditional Option creation
  • Default derives: Added Default to response structs to enable unwrap_or_default()

Net reduction of ~12 lines while improving code organization.

Review & Testing Checklist for Human

  • Test with Gladia API key: Run the ignored tests with GLADIA_API_KEY=00239f35-f300-45c5-8fe0-dc5eb4402712 cargo test -p owhisper-client -- --ignored gladia to verify both single and dual channel transcription work
  • Verify multichannel behavior: The SessionChannels refactor manages channel count tracking - confirm dual-channel transcription correctly identifies speaker channels
  • Verify URL construction: Check that build_http_url produces correct URLs (e.g., https://api.gladia.io/v2/live for empty base, correct scheme for localhost)

Notes

- Extract shared URL building helper (build_url_with_scheme)
- Add SessionChannels struct to encapsulate session channel tracking
- Simplify error handling with map_err().ok()? pattern
- Use .then() for conditional Option creation
- Add Default derive to structs for unwrap_or_default()
- Remove duplicate code in build_ws_url_with_api_key

Co-Authored-By: yujonglee <[email protected]>
@devin-ai-integration
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI' or '@devin'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

@netlify
Copy link

netlify bot commented Dec 4, 2025

Deploy Preview for hyprnote ready!

Name Link
🔨 Latest commit 1e12064
🔍 Latest deploy log https://app.netlify.com/projects/hyprnote/deploys/69319bc798a14a000810cb99
😎 Deploy Preview https://deploy-preview-2121--hyprnote.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@netlify
Copy link

netlify bot commented Dec 4, 2025

Deploy Preview for hyprnote-storybook ready!

Name Link
🔨 Latest commit 1e12064
🔍 Latest deploy log https://app.netlify.com/projects/hyprnote-storybook/deploys/69319bc75a47fe000827bc00
😎 Deploy Preview https://deploy-preview-2121--hyprnote-storybook.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 4, 2025

📝 Walkthrough

Walkthrough

This pull request refactors the Gladia adapter module to improve code clarity and maintainability. Changes include introducing a SessionChannels struct for session-to-channels mapping management, adding Default trait derivations for cleaner deserialization handling, simplifying conditional expressions throughout, and centralizing HTTP URL construction logic.

Changes

Cohort / File(s) Summary
Session and Channel Management
owhisper/owhisper-client/src/adapter/gladia/live.rs
Replaces free-standing session_channels() helper with a private SessionChannels struct to encapsulate session-id-to-channels mappings. Adds insert, get, remove, and get_or_infer methods for lockable map access. Refactors all session initialization, EndSession handling, and channel lookups to use the new abstraction. Simplifies conditional expressions and adjusts error handling with map_err and .ok()? patterns.
Batch Response Processing
owhisper/owhisper-client/src/adapter/gladia/batch.rs
Derives Default trait on TranscriptResult and Transcription for automatic default construction during deserialization. Replaces unwrap_or with unwrap_or_default for cleaner fallbacks on missing result and transcription fields. Simplifies language_config construction using concise conditional options.
URL Construction Helper
owhisper/owhisper-client/src/adapter/gladia/mod.rs
Adds new public helper method build_http_url(api_base: &str) → url::Url that constructs URLs with appropriate scheme selection based on api_base input or defaults when empty. Centralizes URL construction logic via dedicated methods rather than inlining default values.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • SessionChannels abstraction in live.rs: Verify that the new struct correctly manages concurrent access and that all previous map-locking patterns are properly replaced with the encapsulated methods.
  • Error handling refactor: Review map_err and .ok()? usage to ensure error propagation and tracing remain consistent.
  • Default trait usage: Confirm that Default implementations align with expected deserialization behavior in batch.rs.

Possibly related PRs

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'refactor(gladia): clean up adapter code' clearly and concisely describes the main change—refactoring the Gladia adapter to improve code cleanliness, which aligns with the detailed changes across all three modified files.
Description check ✅ Passed The description is directly related to the changeset, providing detailed context about the refactoring efforts including URL building extraction, session tracking encapsulation, error handling improvements, and default derives.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch devin/1764858194-gladia-adapter-cleanup

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
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 (2)
owhisper/owhisper-client/src/adapter/gladia/live.rs (2)

21-25: Consider logging lock acquisition failures.

The insert method silently ignores lock acquisition failures, which could lead to missing session data and confusing behavior downstream. Consider adding a warning log when the lock fails.

 fn insert(session_id: String, channels: u8) {
-    if let Ok(mut map) = Self::store().lock() {
-        map.insert(session_id, channels);
+    match Self::store().lock() {
+        Ok(mut map) => {
+            map.insert(session_id, channels);
+        }
+        Err(e) => {
+            tracing::warn!(session_id = %session_id, error = ?e, "failed_to_lock_session_channels_for_insert");
+        }
     }
 }

27-39: Lock failure returns None, which is ambiguous with "not found".

The get and remove methods return None on both lock failure and missing entries. While this simplifies the API, it could mask concurrency issues. Consider logging lock failures to aid debugging.

📜 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 ea7518a and 1e12064.

📒 Files selected for processing (3)
  • owhisper/owhisper-client/src/adapter/gladia/batch.rs (4 hunks)
  • owhisper/owhisper-client/src/adapter/gladia/live.rs (5 hunks)
  • owhisper/owhisper-client/src/adapter/gladia/mod.rs (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
owhisper/owhisper-client/src/adapter/gladia/live.rs (1)
owhisper/owhisper-client/src/adapter/gladia/mod.rs (1)
  • build_http_url (39-46)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Redirect rules - hyprnote
  • GitHub Check: Header rules - hyprnote
  • GitHub Check: Pages changed - hyprnote
  • GitHub Check: fmt
  • GitHub Check: Devin
🔇 Additional comments (12)
owhisper/owhisper-client/src/adapter/gladia/batch.rs (3)

76-76: LGTM: Default implementations improve deserialization resilience.

Adding Default to these structs enables cleaner fallback handling when API responses are missing optional fields.

Also applies to: 90-90


188-191: LGTM: Idiomatic conditional construction.

The use of .then() and .then_some() is more concise and idiomatic than explicit if/else blocks.


265-266: LGTM: Cleaner fallback handling.

Using unwrap_or_default() is more concise than explicit struct construction and leverages the Default implementations added above.

owhisper/owhisper-client/src/adapter/gladia/mod.rs (4)

48-64: LGTM: Centralized URL construction.

The build_url_with_scheme function effectively consolidates scheme determination logic, reducing duplication and improving maintainability.


66-76: LGTM: Improved organization of default URLs.

Extracting default URL construction into dedicated functions improves code organization and provides a single source of truth.


83-83: LGTM: Simplified URL parsing.

Direct parsing is cleaner and more straightforward.


39-46: The WS_PATH constant is intentionally used for both WebSocket and HTTP endpoints. The Gladia API uses the /v2/live path for both connection types, as confirmed by the default_http_url() function on line 73, which also uses WS_PATH. The build_url_with_scheme function correctly handles this by varying only the scheme (http/https vs ws/wss) based on the use_ws parameter, while the path remains consistent. No separate HTTP path constant is needed.

Likely an incorrect or invalid review comment.

owhisper/owhisper-client/src/adapter/gladia/live.rs (5)

41-43: LGTM: Sensible fallback strategy.

The get_or_infer method provides a reasonable fallback when session data is missing, improving resilience.


87-97: LGTM: Clean usage of helpers and idiomatic conditionals.

The code effectively uses the new build_http_url helper and employs idiomatic .then() for conditional construction, matching the improvements in batch.rs.


111-131: LGTM: Cleaner error handling pattern.

The refactored error handling using map_err and .ok()? is more concise while maintaining error logging. Returning None allows initialization to fail gracefully.


134-134: LGTM: Clean usage of SessionChannels API.

Using SessionChannels::insert is cleaner than direct map manipulation.


176-179: LGTM: Graceful fallback handling.

Both SessionChannels::remove with fallback and get_or_infer provide resilient error handling with appropriate logging.

Also applies to: 365-365

@yujonglee yujonglee merged commit 301ae71 into main Dec 4, 2025
12 of 13 checks passed
@yujonglee yujonglee deleted the devin/1764858194-gladia-adapter-cleanup branch December 4, 2025 23:00
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.

2 participants