Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions docs/advanced_onboarding/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ config = rx.Config(

The setting can also be overridden with `REFLEX_EVENT_LOOP_BLOCKING_THRESHOLD`, for example `REFLEX_EVENT_LOOP_BLOCKING_THRESHOLD=0` to turn detection off.

## Awaited Browser Calls

A background event handler can [await the result of a browser script](/docs/api-reference/browser-javascript/#awaiting-results). Two settings bound how long it waits:

- `browser_call_timeout` (default `30.0`): the seconds an awaited call waits for its result before raising `TimeoutError`. A call can override it with `timeout=`.
- `browser_call_grace_period` (default `5.0`): the seconds an awaited call waits for its tab to reconnect after a disconnect before raising `BrowserDisconnectedError`.

They can also be set with `REFLEX_BROWSER_CALL_TIMEOUT` and `REFLEX_BROWSER_CALL_GRACE_PERIOD`.

## Environment Variables

Any config parameter can be overridden by setting an environment variable with the `REFLEX_` prefix and the parameter name in uppercase. Environment variables take precedence over values set in `rxconfig.py`.
Expand Down
60 changes: 60 additions & 0 deletions docs/api-reference/browser_javascript.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,66 @@ The `callback` parameter may be an `EventHandler` with one argument, or a lambda
If the callback is None, then no event is triggered.
```

## Awaiting Results

A [background event handler](/docs/events/background-events/) can `await` `rx.call_script`, `rx.call_function`, or
`rx.run_script` to get the result directly, instead of passing a callback. The handler continues once the browser sends
the value back, so the code that asks for a value and the code that uses it stay together. If the script returns a
promise, the handler gets the value the promise resolves to.

```python demo exec
class ViewportState(rx.State):
viewport: str = ""

@rx.event(background=True)
async def measure(self):
size = await rx.call_script("({w: window.innerWidth, h: window.innerHeight})")
async with self:
self.viewport = f"{size['w']} x {size['h']}"


def viewport_demo():
return rx.hstack(
rx.button("Measure Viewport", on_click=ViewportState.measure),
rx.text(ViewportState.viewport),
)
```

The result travels as JSON: objects become `dict`, arrays become `list`, and `undefined` becomes `None`. Return the
data you need from a DOM element rather than the element itself.

Await the call outside `async with self`. While the handler holds the state lock, the tab's other events would have to
wait for the browser's answer, so awaiting there raises an error. For the same reason, a regular event handler cannot
await a script. Pass either `callback=` or `await` the result, not both.

The awaited call raises an exception when no value comes back. The Reflex exceptions are imported from
`reflex.utils.exceptions`:

- `BrowserScriptError` if the script throws, or the promise it returns is rejected. The exception
carries the Javascript error's `name`, `message` and `stack`.
- `BrowserResultSerializationError` (a subclass of `BrowserScriptError`) if the value cannot be
sent as JSON.
- `TimeoutError` if no result arrives within the timeout. The timeout defaults to `browser_call_timeout` in
`rxconfig.py` (30 seconds). Pass `timeout=` to a single call to override it, or `timeout=None` to wait as long as it
takes:

```python
answer = await rx.call_script("askTheUser()", timeout=None)
```

- `BrowserDisconnectedError` (a `ConnectionError`) if the tab is not connected when the call is
made. The same error is raised if the tab disconnects and does not reconnect within `browser_call_grace_period`
(5 seconds). A tab that reconnects in time still delivers its result. A tab that reloads loses the running script, so the
call ends at its timeout.

```md alert info
# Awaiting results with multiple backend workers

The browser sends the result to the backend worker its tab is connected to. With several workers sharing state through
Redis, a background task awaits results only from tabs connected to its own worker. Calls to other tabs raise
`BrowserDisconnectedError`.
```

## Using React Hooks

To use React Hooks directly in a Reflex app, you must subclass `rx.Component`,
Expand Down
1 change: 1 addition & 0 deletions news/+await-browser-results.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The backend now receives the results of browser scripts that a background event handler awaits (`await rx.call_script(...)`), and keeps those calls alive while their tab reconnects.
11 changes: 11 additions & 0 deletions packages/reflex-base/news/+await-browser-results.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
A background event handler can now `await` `rx.call_script`, `rx.call_function` and `rx.run_script` to get the script's result directly, instead of passing a `callback`:

```python
@rx.event(background=True)
async def measure(self):
size = await rx.call_script("({w: window.innerWidth, h: window.innerHeight})")
async with self:
self.width = size["w"]
```

A script error raises `BrowserScriptError`, and a missing result raises `TimeoutError` (`browser_call_timeout` config, or `timeout=` per call). A tab that disconnects and does not reconnect within `browser_call_grace_period` raises `BrowserDisconnectedError`. See [Awaiting Results](https://reflex.dev/docs/api-reference/browser-javascript/#awaiting-results).
6 changes: 6 additions & 0 deletions packages/reflex-base/src/reflex_base/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ class BaseConfig:
disable_plugins: List of plugin types to disable in the app.
transport: The transport method for client-server communication.
event_loop_blocking_threshold: Minimum event-loop blocking duration in seconds to report in development. Set to 0 to disable detection.
browser_call_timeout: Seconds an awaited browser call, such as `await rx.call_script(...)` in a background event handler, waits for the browser's result before raising TimeoutError. A call's own `timeout=` overrides it.
browser_call_grace_period: Seconds an awaited browser call survives its tab disconnecting: a reconnect within it delivers the result, otherwise the call raises BrowserDisconnectedError.
"""

app_name: str
Expand Down Expand Up @@ -300,6 +302,10 @@ class BaseConfig:

event_loop_blocking_threshold: float = 0.2

browser_call_timeout: float = 30.0

browser_call_grace_period: float = 5.0

# Whether to skip plugin checks.
_skip_plugins_checks: bool = dataclasses.field(default=False, repr=False)

Expand Down
3 changes: 3 additions & 0 deletions packages/reflex-base/src/reflex_base/constants/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,9 @@ class SocketEvent(SimpleNamespace):
PING = "ping"
EVENT = "event"
CLIENT_ERROR = "client_error"
# Sent by the browser with the result of a call the backend awaits
# (must match RESULT_EVENT in packages/reflex-frontend/src/utils/state.js).
RESULT = "result"
# Sent on connect when the frontend was compiled for another state tree
# (must match STATE_MISMATCH_EVENT in packages/reflex-frontend/src/utils/state.js).
STATE_MISMATCH = "state_mismatch"
Expand Down
96 changes: 70 additions & 26 deletions packages/reflex-base/src/reflex_base/event/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2083,29 +2083,68 @@ def download(
)


@lru_cache
def _script_signature(fn: Callable) -> inspect.Signature:
"""Get the signature of a script event, without the timeout of an awaited call.

The timeout is not an argument of the event: ``add_args`` must not bind to it.

Args:
fn: The function creating the script event.

Returns:
The function's signature without its ``timeout`` parameter.
"""
sig = inspect.signature(fn)
return sig.replace(
parameters=[p for name, p in sig.parameters.items() if name != "timeout"]
)


def _script_kwargs(
callback: "EventType[Any] | None", timeout: float | Unset | None
) -> dict[str, Any]:
"""Build the arguments a script event takes besides its code.

Args:
callback: EventHandler that will receive the result of the script.
timeout: Seconds to wait for the result when it is awaited; left out when unset.

Returns:
The callback, as the javascript that queues it, and the timeout if set.
"""
kwargs: dict[str, Any] = {
"callback": None
if callback is None
else str(
format.format_queue_events(callback, args_spec=lambda result: [result])
)
}
if not isinstance(timeout, Unset):
kwargs["timeout"] = timeout
return kwargs


def call_script(
javascript_code: str | Var[str],
callback: "EventType[Any] | None" = None,
*,
timeout: float | Unset | None = Unset(),
) -> EventSpec:
"""Create an event handler that executes arbitrary javascript code.

Awaited in a background event handler, outside ``async with self``, it
returns the script's result: ``value = await rx.call_script(...)``.

Args:
javascript_code: The code to execute.
callback: EventHandler that will receive the result of evaluating the javascript code.
timeout: Seconds to wait for the result when it is awaited, or None to
wait until it arrives. Defaults to ``rx.Config.browser_call_timeout``.

Returns:
EventSpec: An event that will execute the client side javascript.
"""
callback_kwargs = {"callback": None}
if callback is not None:
callback_kwargs = {
"callback": str(
format.format_queue_events(
callback,
args_spec=lambda result: [result],
)
),
}
if isinstance(javascript_code, str):
# When there is VarData, include it and eval the JS code inline on the client.
javascript_code, original_code = (
Expand All @@ -2118,57 +2157,60 @@ def call_script(

return server_side(
"_call_script",
inspect.signature(call_script),
_script_signature(call_script),
javascript_code=javascript_code,
**callback_kwargs,
**_script_kwargs(callback, timeout),
)


def call_function(
javascript_code: str | Var,
callback: "EventType[Any] | None" = None,
*,
timeout: float | Unset | None = Unset(),
) -> EventSpec:
"""Create an event handler that executes arbitrary javascript code.

Awaited in a background event handler, outside ``async with self``, it
returns the script's result: ``value = await rx.call_function(...)``.

Args:
javascript_code: The code to execute.
callback: EventHandler that will receive the result of evaluating the javascript code.
timeout: Seconds to wait for the result when it is awaited, or None to
wait until it arrives. Defaults to ``rx.Config.browser_call_timeout``.

Returns:
EventSpec: An event that will execute the client side javascript.
"""
callback_kwargs = {"callback": None}
if callback is not None:
callback_kwargs = {
"callback": str(
format.format_queue_events(
callback,
args_spec=lambda result: [result],
),
)
}

javascript_code = (
Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
)

return server_side(
"_call_function",
inspect.signature(call_function),
_script_signature(call_function),
function=javascript_code,
**callback_kwargs,
**_script_kwargs(callback, timeout),
)


def run_script(
javascript_code: str | Var,
callback: "EventType[Any] | None" = None,
*,
timeout: float | Unset | None = Unset(),
) -> EventSpec:
"""Create an event handler that executes arbitrary javascript code.

Awaited in a background event handler, outside ``async with self``, it
returns the script's result: ``value = await rx.run_script(...)``.

Args:
javascript_code: The code to execute.
callback: EventHandler that will receive the result of evaluating the javascript code.
timeout: Seconds to wait for the result when it is awaited, or None to
wait until it arrives. Defaults to ``rx.Config.browser_call_timeout``.

Returns:
EventSpec: An event that will execute the client side javascript.
Expand All @@ -2177,7 +2219,9 @@ def run_script(
Var(javascript_code) if isinstance(javascript_code, str) else javascript_code
)

return call_function(ArgsFunctionOperation.create((), javascript_code), callback)
return call_function(
ArgsFunctionOperation.create((), javascript_code), callback, timeout=timeout
)


def get_event(state: "BaseState", event: str):
Expand Down
39 changes: 39 additions & 0 deletions packages/reflex-base/src/reflex_base/event/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from reflex_base import otel
from reflex_base.context.base import BaseContext
from reflex_base.utils.exceptions import BrowserDisconnectedError
from reflex_base.utils.format import to_snake_case

if TYPE_CHECKING:
Expand Down Expand Up @@ -77,6 +78,20 @@ async def __call__(self, token: str, *events: Event) -> Any:
...


class CallFrontendProtocol(Protocol):
"""Protocol for the call_frontend function in the event context."""

async def __call__(self, token: str, event: Event, timeout: float | None) -> Any:
"""Run a frontend event in the browser and wait for its result.

Args:
token: The client token whose browser runs the event.
event: The frontend event to run.
timeout: Seconds to wait for the result, or None to wait until it arrives.
"""
...


class EmitDeltaProtocol(Protocol):
"""Protocol for the emit_delta function in the event context."""

Expand Down Expand Up @@ -120,6 +135,11 @@ class EventContext(BaseContext):
emit_event_impl: EmitEventProtocol | None = dataclasses.field(
default=None, repr=False
)
# Runs a frontend event in the browser and returns its result; None when
# no frontend is attached.
call_frontend_impl: CallFrontendProtocol | None = dataclasses.field(
default=None, repr=False
)
# The app middleware an event passes through before its handler runs,
# whether it is queued or awaited inline.
middleware: MiddlewareMixin | None = dataclasses.field(default=None, repr=False)
Expand Down Expand Up @@ -164,6 +184,7 @@ def fork(
enqueue_impl=self.enqueue_impl,
emit_delta_impl=self.emit_delta_impl,
emit_event_impl=self.emit_event_impl,
call_frontend_impl=self.call_frontend_impl,
middleware=self.middleware,
router_data=router_data or self.router_data,
otel_context=otel.capture_context(),
Expand Down Expand Up @@ -242,6 +263,24 @@ async def emit_event(self, *events: Event) -> None:
if self.emit_event_impl is not None:
await self.emit_event_impl(self.token, *events)

async def call_frontend(self, event: Event, timeout: float | None) -> Any:
"""Run a frontend event in this client's browser and wait for its result.

Args:
event: The frontend event to run.
timeout: Seconds to wait for the result, or None to wait until it arrives.

Returns:
The value the browser sent back.

Raises:
BrowserDisconnectedError: If no frontend is attached to the app.
"""
if self.call_frontend_impl is None:
msg = "No browser is connected to this app, so it cannot run the script."
raise BrowserDisconnectedError(msg)
return await self.call_frontend_impl(self.token, event, timeout)

async def enqueue(self, *event: Event) -> Sequence[EventFuture]:
"""Enqueue an event handler to be executed.

Expand Down
Loading
Loading