-
Notifications
You must be signed in to change notification settings - Fork 606
[feat] Stream session changes and fix session liveness (9/12) #5688
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
ardaerzin
wants to merge
18
commits into
feat/mobile-approvals
Choose a base branch
from
feat/sessions-watch-and-liveness
base: feat/mobile-approvals
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
8e1de94
feat(api): publish per-session watch events for the M3 live relay
ardaerzin c65de1e
feat(api): SSE watch endpoint GET /sessions/streams/watch
ardaerzin 6af9bee
fix(mobile): mute the user bubble and fetch the session title via the…
ardaerzin 59361ea
feat(mobile): consume the session live relay via useSessionWatch
ardaerzin 0366f51
fix(mobile): queue trailing refreshes and bound the watch publish
ardaerzin 154c1c5
fix(mobile): drain the resume stream instead of cancelling it
ardaerzin 2b9899a
feat(mobile): move approvals into a bottom dock
ardaerzin 0b7460a
fix(api): write the session liveness mirror on every heartbeat
ardaerzin 9fb559c
fix(api): let the orphan sweep reclaim rows never updated since creation
ardaerzin 3a9ec06
feat(api): publish the `running` lifecycle event from the runner hear…
ardaerzin 7944681
test(mobile): cover the session-list liveness badge mapping
ardaerzin 07e044b
fix(api): treat a stale alive lock as handover, not turn takeover
ardaerzin b58f4e2
test(api): cover the second turn on a warm session and the sweep's tw…
ardaerzin 394aa90
fix(api): a superseded turn's beat must not re-arm the running lock
ardaerzin 968fed0
docs(mobile): track the parked-session lock ambiguity
ardaerzin 66fd8fe
fix(mobile): send the bearer token on the approval resume
ardaerzin 5200721
fix(api): say why a watch pubsub teardown failed
ardaerzin ff0eb26
fix(api): close the watch pubsub even when unsubscribe fails
ardaerzin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| """SSE frame generator for ``GET /sessions/streams/watch`` (M3 live relay). | ||
|
|
||
| Bridges one Redis pub/sub subscription (durable plane, one per SSE connection) | ||
| into `text/event-stream` frames. Events carry TYPE + minimal metadata only — | ||
| clients revalidate through their existing query paths; no record payloads ride | ||
| the wire. Idle periods emit ``: heartbeat`` comment frames so proxies and | ||
| clients never see a silent connection. | ||
| """ | ||
|
|
||
| import json | ||
| from typing import Any, AsyncIterator, Callable, Optional | ||
|
|
||
| from oss.src.dbs.redis.sessions.contract import ( | ||
| WATCH_EVENT_INTERACTION, | ||
| WATCH_EVENT_LIFECYCLE, | ||
| WATCH_EVENT_RECORDS_CHANGED, | ||
| ) | ||
| from oss.src.utils.logging import get_module_logger | ||
|
|
||
| log = get_module_logger(__name__) | ||
|
|
||
| HEARTBEAT_FRAME = ": heartbeat\n\n" | ||
|
|
||
| _KNOWN_EVENTS = { | ||
| WATCH_EVENT_RECORDS_CHANGED, | ||
| WATCH_EVENT_LIFECYCLE, | ||
| WATCH_EVENT_INTERACTION, | ||
| } | ||
|
|
||
|
|
||
| def format_watch_frame(raw: Any) -> Optional[str]: | ||
| """One published payload -> one SSE frame; None for anything malformed/unknown.""" | ||
| try: | ||
| payload = json.loads(raw) | ||
| except (ValueError, TypeError): | ||
| return None | ||
| if not isinstance(payload, dict): | ||
| return None | ||
| event = payload.get("type") | ||
| # `_KNOWN_EVENTS` is a set, so an unhashable `type` (a list, a dict) would raise | ||
| # TypeError out of the membership test and tear down the whole stream. A malformed | ||
| # publish must drop its own frame, never the connection. | ||
| if not isinstance(event, str) or event not in _KNOWN_EVENTS: | ||
| return None | ||
| return f"event: {event}\ndata: {json.dumps(payload)}\n\n" | ||
|
|
||
|
|
||
| async def watch_event_stream( | ||
| *, | ||
| channel: str, | ||
| pubsub_factory: Callable[[], Any], | ||
| heartbeat_seconds: float, | ||
| ) -> AsyncIterator[str]: | ||
| """Subscribe to the session's watch channel and yield SSE frames forever. | ||
|
|
||
| The subscription is torn down in ``finally`` — a client disconnect cancels | ||
| the generator (GeneratorExit/CancelledError), which is exactly the cleanup | ||
| path, so no Redis subscription outlives its SSE connection. | ||
| """ | ||
| pubsub = pubsub_factory() | ||
| try: | ||
| await pubsub.subscribe(channel) | ||
| while True: | ||
| message = await pubsub.get_message( | ||
| ignore_subscribe_messages=True, | ||
| timeout=heartbeat_seconds, | ||
| ) | ||
| if message is None: | ||
| yield HEARTBEAT_FRAME | ||
| continue | ||
| if message.get("type") != "message": | ||
| continue | ||
| frame = format_watch_frame(message.get("data")) | ||
| if frame is not None: | ||
| yield frame | ||
| finally: | ||
| # Two independent attempts: a failing unsubscribe must not skip the close, or the | ||
| # connection outlives the disconnected client. | ||
| try: | ||
| await pubsub.unsubscribe(channel) | ||
| except Exception as exc: # pragma: no cover — teardown is best-effort | ||
| log.warning( | ||
| "[WATCH] pubsub unsubscribe failed", | ||
| channel=channel, | ||
| error=repr(exc), | ||
| ) | ||
| try: | ||
| await pubsub.aclose() | ||
| except Exception as exc: # pragma: no cover — teardown is best-effort | ||
| log.warning( | ||
| "[WATCH] pubsub close failed", | ||
| channel=channel, | ||
| error=repr(exc), | ||
| ) | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.