refacto: helper refacto async sync session#35
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
📝 WalkthroughWalkthroughA new ChangesLive V2 Session Helper Extraction and Refactor
Sequence DiagramsequenceDiagram
participant Client
participant LiveV2Session
participant _helpers
participant WebSocket
participant _EventEmitter
Client->>LiveV2Session: start_session()
LiveV2Session->>_helpers: with_acknowledgments_enabled(options)
LiveV2Session->>_helpers: emit_started_if_needed(status="starting")
_helpers->>_EventEmitter: emit("started", session)
_helpers->>LiveV2Session: status="started"
LiveV2Session->>_helpers: maybe_emit_start_session_message(options, session)
_helpers->>_EventEmitter: emit("message", start_session_payload)
LiveV2Session->>_helpers: send_audio_in_chunks(ws, audio_buffer)
_helpers->>WebSocket: send chunks of 512 KiB
WebSocket-->>LiveV2Session: incoming message
LiveV2Session->>_helpers: parse_ws_message(raw_payload)
_helpers-->>LiveV2Session: typed LiveV2WebSocketMessage
LiveV2Session->>_helpers: should_emit_ws_message(message, config)
_helpers-->>LiveV2Session: boolean decision
alt message should be emitted
LiveV2Session->>_EventEmitter: emit("message", message)
end
alt acknowledged audio_chunk
LiveV2Session->>_helpers: trim_acknowledged_audio_buffer(audio_buffer, bytes_sent, byte_end)
_helpers-->>LiveV2Session: (trimmed_buffer, updated_bytes_sent)
end
Client->>LiveV2Session: close_session()
LiveV2Session->>_helpers: emit_session_ending_events(status, code, reason)
_helpers->>_EventEmitter: emit("ending") and emit("ended")
_helpers-->>LiveV2Session: status="ended"
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 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 |
Extract duplicated sync/async live v2 session code into _helpers.py: chunked audio resend, ws message parsing, lifecycle events, and the typed event listener mixin. Co-authored-by: Cursor <cursoragent@cursor.com>
Update _EventEmitter method signatures to match pyee EventEmitter and AsyncIOEventEmitter so session classes type-check cleanly in CI. Co-authored-by: Cursor <cursoragent@cursor.com>
49b2ed0 to
b9cd8a3
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (1)
packages/sdk-python/src/gladiaio_sdk/v2/live/_helpers.py (1)
70-78: Consider using explicit type discrimination instead ofhasattrfor clarityThe
acknowledgedfield exists only onLiveV2AudioChunkAckMessage(type="audio_chunk") andLiveV2StopRecordingAckMessage(type="stop_recording"). The current logic correctly preserves non-acknowledgment messages while filtering ack messages based on the config flag.However, using
hasattr(message, "acknowledged")relies on a runtime check. Since all message variants have a typedtypefield, prefer checkingmessage.type not in ("audio_chunk", "stop_recording")for better clarity and type safety.🤖 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 `@packages/sdk-python/src/gladiaio_sdk/v2/live/_helpers.py` around lines 70 - 78, Replace the runtime `hasattr(message, "acknowledged")` check in the should_emit_ws_message function with an explicit type discrimination check. Instead of `not hasattr(message, "acknowledged")`, use `message.type not in ("audio_chunk", "stop_recording")` since the acknowledged field only exists on LiveV2AudioChunkAckMessage and LiveV2StopRecordingAckMessage types. This provides better clarity and type safety by explicitly checking message type rather than relying on attribute presence detection.
🤖 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 `@packages/sdk-python/src/gladiaio_sdk/v2/live/_helpers.py`:
- Around line 81-87: The trim_acknowledged_audio_buffer function at line 86 uses
`byte_end - bytes_sent` as a buffer slice index, which can become negative when
bytes_sent exceeds byte_end, causing already-acknowledged bytes to remain in the
buffer and moving the resend state backward. Clamp the trim index calculation to
a minimum of 0 to ensure you never slice from a negative position, and also
clamp the returned offset to prevent state regression. Use Python's max()
function to ensure both values stay non-negative.
- Around line 115-124: The function emit_session_ending_events does not prevent
re-emission of terminal events when the session status is already "ended".
Currently, the function only checks if status is not "ending" before emitting
the "ending" event, but if status is already "ended", it will still emit both
"ending" and "ended" events again, causing duplicates. Add an early return at
the beginning of the function to exit immediately if the status is already
"ended", since all terminal events have already been emitted and there is
nothing more to do.
In `@packages/sdk-python/src/gladiaio_sdk/v2/live/async_session.py`:
- Around line 157-158: The async session's call to send_audio_in_chunks is
unguarded while the sync session wraps this call with
contextlib.suppress(Exception) for consistency. Update the async session to wrap
the send_audio_in_chunks call with contextlib.suppress(Exception) to match the
sync session's error handling pattern and prevent unhandled exceptions from
leaving the session in an inconsistent state during WebSocket failures.
---
Nitpick comments:
In `@packages/sdk-python/src/gladiaio_sdk/v2/live/_helpers.py`:
- Around line 70-78: Replace the runtime `hasattr(message, "acknowledged")`
check in the should_emit_ws_message function with an explicit type
discrimination check. Instead of `not hasattr(message, "acknowledged")`, use
`message.type not in ("audio_chunk", "stop_recording")` since the acknowledged
field only exists on LiveV2AudioChunkAckMessage and
LiveV2StopRecordingAckMessage types. This provides better clarity and type
safety by explicitly checking message type rather than relying on attribute
presence detection.
🪄 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: 7b2a2f95-d266-4937-869c-59dbc340bc85
📒 Files selected for processing (4)
packages/sdk-python/src/gladiaio_sdk/v2/live/_helpers.pypackages/sdk-python/src/gladiaio_sdk/v2/live/async_session.pypackages/sdk-python/src/gladiaio_sdk/v2/live/session.pypackages/sdk-python/src/gladiaio_sdk/v2/live/types.py
Co-authored-by: Cursor <cursoragent@cursor.com>
Summary by CodeRabbit
LiveV2SessionStatustype for consistent session-state handling across implementations.