-
Notifications
You must be signed in to change notification settings - Fork 114
feat(session): Add allow_reconnect() method to control client behavior on disconnect
#2102
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
Copilot
wants to merge
7
commits into
main
Choose a base branch
from
copilot/add-reconnect-support-python
base: main
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.
+302
−0
Draft
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8f63e85
Initial plan
Copilot e966c8b
Implement allow_reconnect() method for Session classes
Copilot 85629f7
Add API examples and documentation for allow_reconnect
Copilot 7ef73d2
Add comprehensive documentation to allow_reconnect method
Copilot e134068
Add allow_reconnect stub method to ExpressStubSession
Copilot 6042768
Apply suggestion from @schloerke
schloerke 2e8d4e9
Fix trailing whitespace in example files
Copilot 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| from shiny import App, Inputs, Outputs, Session, reactive, render, ui | ||
|
|
||
| app_ui = ui.page_fluid( | ||
| ui.h2("Session Reconnection Control"), | ||
| ui.p( | ||
| """ | ||
| This example demonstrates the session.allow_reconnect() method. | ||
| Click a button to set the reconnection behavior, then you can test it | ||
| by simulating a disconnect (e.g., close the browser tab and reopen it, | ||
| or use browser developer tools to close the WebSocket connection). | ||
| """ | ||
| ), | ||
| ui.layout_columns( | ||
| ui.input_action_button("allow_true", "Allow Reconnect"), | ||
| ui.input_action_button("allow_false", "Disallow Reconnect"), | ||
| ui.input_action_button("allow_force", "Force Reconnect"), | ||
| col_widths=[4, 4, 4], | ||
| ), | ||
| ui.output_text("status"), | ||
| ) | ||
|
|
||
|
|
||
| def server(input: Inputs, output: Outputs, session: Session): | ||
| status = reactive.Value("Reconnection not configured yet") | ||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_true) | ||
| def _(): | ||
| session.allow_reconnect(True) | ||
| status.set("✓ Reconnection allowed (True)") | ||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_false) | ||
| def _(): | ||
| session.allow_reconnect(False) | ||
| status.set("✗ Reconnection disallowed (False)") | ||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_force) | ||
| def _(): | ||
| session.allow_reconnect("force") | ||
| status.set("⚡ Reconnection forced") | ||
|
|
||
| @output | ||
| @render.text | ||
| def status(): | ||
| return status.get() | ||
|
|
||
|
|
||
| app = App(app_ui, server) |
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,45 @@ | ||
| from shiny import reactive, render | ||
| from shiny.express import input, session, ui | ||
|
|
||
| ui.h2("Session Reconnection Control") | ||
| ui.p( | ||
| """ | ||
| This example demonstrates the session.allow_reconnect() method. | ||
| Click a button to set the reconnection behavior, then you can test it | ||
| by simulating a disconnect (e.g., close the browser tab and reopen it, | ||
| or use browser developer tools to close the WebSocket connection). | ||
| """ | ||
| ) | ||
|
|
||
| with ui.layout_columns(col_widths=[4, 4, 4]): | ||
| ui.input_action_button("allow_true", "Allow Reconnect") | ||
| ui.input_action_button("allow_false", "Disallow Reconnect") | ||
| ui.input_action_button("allow_force", "Force Reconnect") | ||
|
|
||
| status = reactive.Value("Reconnection not configured yet") | ||
|
|
||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_true) | ||
| def _(): | ||
| session.allow_reconnect(True) | ||
| status.set("✓ Reconnection allowed (True)") | ||
|
|
||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_false) | ||
| def _(): | ||
| session.allow_reconnect(False) | ||
| status.set("✗ Reconnection disallowed (False)") | ||
|
|
||
|
|
||
| @reactive.effect | ||
| @reactive.event(input.allow_force) | ||
| def _(): | ||
| session.allow_reconnect("force") | ||
| status.set("⚡ Reconnection forced") | ||
|
|
||
|
|
||
| @render.text | ||
| def status_output(): | ||
| return status.get() |
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,157 @@ | ||
| """Tests for Session.allow_reconnect() method.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import json | ||
|
|
||
| import pytest | ||
|
|
||
| from shiny import App, Inputs, Outputs, Session, ui | ||
| from shiny._connection import MockConnection | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_allow_reconnect_true(): | ||
| """Test that allow_reconnect(True) sends the correct message.""" | ||
| messages: list[str] = [] | ||
|
|
||
| def server(input: Inputs, output: Outputs, session: Session): | ||
| session.allow_reconnect(True) | ||
|
|
||
| conn = MockConnection() | ||
| # Capture all messages sent by the session | ||
| original_send = conn.send | ||
|
|
||
| async def capture_send(message: str): | ||
| messages.append(message) | ||
| await original_send(message) | ||
|
|
||
| conn.send = capture_send | ||
|
|
||
| sess = App(ui.TagList(), server)._create_session(conn) | ||
|
|
||
| async def mock_client(): | ||
| conn.cause_receive('{"method":"init","data":{}}') | ||
| await asyncio.sleep(0.1) # Give time for the server to process | ||
| conn.cause_disconnect() | ||
|
|
||
| await asyncio.gather(mock_client(), sess._run()) | ||
|
|
||
| # Check that allowReconnect message was sent | ||
| reconnect_messages = [ | ||
| msg for msg in messages if "allowReconnect" in msg and msg != "{}" | ||
| ] | ||
| assert len(reconnect_messages) > 0, "No allowReconnect message found" | ||
|
|
||
| # Verify the message content | ||
| for msg in reconnect_messages: | ||
| parsed = json.loads(msg) | ||
| if "allowReconnect" in parsed: | ||
| assert parsed["allowReconnect"] is True | ||
| break | ||
| else: | ||
| pytest.fail("allowReconnect message not found in sent messages") | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_allow_reconnect_false(): | ||
| """Test that allow_reconnect(False) sends the correct message.""" | ||
| messages: list[str] = [] | ||
|
|
||
| def server(input: Inputs, output: Outputs, session: Session): | ||
| session.allow_reconnect(False) | ||
|
|
||
| conn = MockConnection() | ||
| original_send = conn.send | ||
|
|
||
| async def capture_send(message: str): | ||
| messages.append(message) | ||
| await original_send(message) | ||
|
|
||
| conn.send = capture_send | ||
|
|
||
| sess = App(ui.TagList(), server)._create_session(conn) | ||
|
|
||
| async def mock_client(): | ||
| conn.cause_receive('{"method":"init","data":{}}') | ||
| await asyncio.sleep(0.1) | ||
| conn.cause_disconnect() | ||
|
|
||
| await asyncio.gather(mock_client(), sess._run()) | ||
|
|
||
| # Check that allowReconnect message was sent with False | ||
| reconnect_messages = [ | ||
| msg for msg in messages if "allowReconnect" in msg and msg != "{}" | ||
| ] | ||
| assert len(reconnect_messages) > 0, "No allowReconnect message found" | ||
|
|
||
| for msg in reconnect_messages: | ||
| parsed = json.loads(msg) | ||
| if "allowReconnect" in parsed: | ||
| assert parsed["allowReconnect"] is False | ||
| break | ||
| else: | ||
| pytest.fail("allowReconnect message not found in sent messages") | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_allow_reconnect_force(): | ||
| """Test that allow_reconnect('force') sends the correct message.""" | ||
| messages: list[str] = [] | ||
|
|
||
| def server(input: Inputs, output: Outputs, session: Session): | ||
| session.allow_reconnect("force") | ||
|
|
||
| conn = MockConnection() | ||
| original_send = conn.send | ||
|
|
||
| async def capture_send(message: str): | ||
| messages.append(message) | ||
| await original_send(message) | ||
|
|
||
| conn.send = capture_send | ||
|
|
||
| sess = App(ui.TagList(), server)._create_session(conn) | ||
|
|
||
| async def mock_client(): | ||
| conn.cause_receive('{"method":"init","data":{}}') | ||
| await asyncio.sleep(0.1) | ||
| conn.cause_disconnect() | ||
|
|
||
| await asyncio.gather(mock_client(), sess._run()) | ||
|
|
||
| # Check that allowReconnect message was sent with "force" | ||
| reconnect_messages = [ | ||
| msg for msg in messages if "allowReconnect" in msg and msg != "{}" | ||
| ] | ||
| assert len(reconnect_messages) > 0, "No allowReconnect message found" | ||
|
|
||
| for msg in reconnect_messages: | ||
| parsed = json.loads(msg) | ||
| if "allowReconnect" in parsed: | ||
| assert parsed["allowReconnect"] == "force" | ||
| break | ||
| else: | ||
| pytest.fail("allowReconnect message not found in sent messages") | ||
|
|
||
|
|
||
| def test_allow_reconnect_invalid_value(): | ||
| """Test that allow_reconnect raises ValueError for invalid values.""" | ||
| from shiny._connection import MockConnection | ||
| from shiny.session._session import AppSession | ||
|
|
||
| conn = MockConnection() | ||
| sess = AppSession( | ||
| app=App(ui.TagList(), lambda i, o, s: None), id="test", conn=conn | ||
| ) | ||
|
|
||
| # Test invalid values | ||
| with pytest.raises(ValueError, match='value must be True, False, or "force"'): | ||
| sess.allow_reconnect("invalid") # type: ignore | ||
|
|
||
| with pytest.raises(ValueError, match='value must be True, False, or "force"'): | ||
| sess.allow_reconnect(None) # type: ignore | ||
|
|
||
| with pytest.raises(ValueError, match='value must be True, False, or "force"'): | ||
| sess.allow_reconnect(1) # type: ignore |
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.