event.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. """Define event classes to connect the frontend and backend."""
  2. from __future__ import annotations
  3. import inspect
  4. from base64 import b64encode
  5. from types import FunctionType
  6. from typing import (
  7. TYPE_CHECKING,
  8. Any,
  9. Callable,
  10. Dict,
  11. List,
  12. Optional,
  13. Tuple,
  14. Type,
  15. Union,
  16. )
  17. from reflex import constants
  18. from reflex.base import Base
  19. from reflex.utils import console, format
  20. from reflex.utils.types import ArgsSpec
  21. from reflex.vars import BaseVar, Var
  22. if TYPE_CHECKING:
  23. from reflex.state import BaseState
  24. class Event(Base):
  25. """An event that describes any state change in the app."""
  26. # The token to specify the client that the event is for.
  27. token: str
  28. # The event name.
  29. name: str
  30. # The routing data where event occurred
  31. router_data: Dict[str, Any] = {}
  32. # The event payload.
  33. payload: Dict[str, Any] = {}
  34. @property
  35. def substate_token(self) -> str:
  36. """Get the substate token for the event.
  37. Returns:
  38. The substate token.
  39. """
  40. substate = self.name.rpartition(".")[0]
  41. return f"{self.token}_{substate}"
  42. BACKGROUND_TASK_MARKER = "_reflex_background_task"
  43. def background(fn):
  44. """Decorator to mark event handler as running in the background.
  45. Args:
  46. fn: The function to decorate.
  47. Returns:
  48. The same function, but with a marker set.
  49. Raises:
  50. TypeError: If the function is not a coroutine function or async generator.
  51. """
  52. if not inspect.iscoroutinefunction(fn) and not inspect.isasyncgenfunction(fn):
  53. raise TypeError("Background task must be async function or generator.")
  54. setattr(fn, BACKGROUND_TASK_MARKER, True)
  55. return fn
  56. def _no_chain_background_task(
  57. state_cls: Type["BaseState"], name: str, fn: Callable
  58. ) -> Callable:
  59. """Protect against directly chaining a background task from another event handler.
  60. Args:
  61. state_cls: The state class that the event handler is in.
  62. name: The name of the background task.
  63. fn: The background task coroutine function / generator.
  64. Returns:
  65. A compatible coroutine function / generator that raises a runtime error.
  66. Raises:
  67. TypeError: If the background task is not async.
  68. """
  69. call = f"{state_cls.__name__}.{name}"
  70. message = (
  71. f"Cannot directly call background task {name!r}, use "
  72. f"`yield {call}` or `return {call}` instead."
  73. )
  74. if inspect.iscoroutinefunction(fn):
  75. async def _no_chain_background_task_co(*args, **kwargs):
  76. raise RuntimeError(message)
  77. return _no_chain_background_task_co
  78. if inspect.isasyncgenfunction(fn):
  79. async def _no_chain_background_task_gen(*args, **kwargs):
  80. yield
  81. raise RuntimeError(message)
  82. return _no_chain_background_task_gen
  83. raise TypeError(f"{fn} is marked as a background task, but is not async.")
  84. class EventActionsMixin(Base):
  85. """Mixin for DOM event actions."""
  86. # Whether to `preventDefault` or `stopPropagation` on the event.
  87. event_actions: Dict[str, bool] = {}
  88. @property
  89. def stop_propagation(self):
  90. """Stop the event from bubbling up the DOM tree.
  91. Returns:
  92. New EventHandler-like with stopPropagation set to True.
  93. """
  94. return self.copy(
  95. update={"event_actions": {"stopPropagation": True, **self.event_actions}},
  96. )
  97. @property
  98. def prevent_default(self):
  99. """Prevent the default behavior of the event.
  100. Returns:
  101. New EventHandler-like with preventDefault set to True.
  102. """
  103. return self.copy(
  104. update={"event_actions": {"preventDefault": True, **self.event_actions}},
  105. )
  106. class EventHandler(EventActionsMixin):
  107. """An event handler responds to an event to update the state."""
  108. # The function to call in response to the event.
  109. fn: Any
  110. class Config:
  111. """The Pydantic config."""
  112. # Needed to allow serialization of Callable.
  113. frozen = True
  114. @property
  115. def is_background(self) -> bool:
  116. """Whether the event handler is a background task.
  117. Returns:
  118. True if the event handler is marked as a background task.
  119. """
  120. return getattr(self.fn, BACKGROUND_TASK_MARKER, False)
  121. def __call__(self, *args: Var) -> EventSpec:
  122. """Pass arguments to the handler to get an event spec.
  123. This method configures event handlers that take in arguments.
  124. Args:
  125. *args: The arguments to pass to the handler.
  126. Returns:
  127. The event spec, containing both the function and args.
  128. Raises:
  129. TypeError: If the arguments are invalid.
  130. """
  131. # Get the function args.
  132. fn_args = inspect.getfullargspec(self.fn).args[1:]
  133. fn_args = (Var.create_safe(arg) for arg in fn_args)
  134. # Construct the payload.
  135. values = []
  136. for arg in args:
  137. # Special case for file uploads.
  138. if isinstance(arg, FileUpload):
  139. return arg.as_event_spec(handler=self)
  140. # Otherwise, convert to JSON.
  141. try:
  142. values.append(Var.create(arg, _var_is_string=type(arg) is str))
  143. except TypeError as e:
  144. raise TypeError(
  145. f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."
  146. ) from e
  147. payload = tuple(zip(fn_args, values))
  148. # Return the event spec.
  149. return EventSpec(
  150. handler=self, args=payload, event_actions=self.event_actions.copy()
  151. )
  152. class EventSpec(EventActionsMixin):
  153. """An event specification.
  154. Whereas an Event object is passed during runtime, a spec is used
  155. during compile time to outline the structure of an event.
  156. """
  157. # The event handler.
  158. handler: EventHandler
  159. # The handler on the client to process event.
  160. client_handler_name: str = ""
  161. # The arguments to pass to the function.
  162. args: Tuple[Tuple[Var, Var], ...] = ()
  163. class Config:
  164. """The Pydantic config."""
  165. # Required to allow tuple fields.
  166. frozen = True
  167. def with_args(self, args: Tuple[Tuple[Var, Var], ...]) -> EventSpec:
  168. """Copy the event spec, with updated args.
  169. Args:
  170. args: The new args to pass to the function.
  171. Returns:
  172. A copy of the event spec, with the new args.
  173. """
  174. return type(self)(
  175. handler=self.handler,
  176. client_handler_name=self.client_handler_name,
  177. args=args,
  178. event_actions=self.event_actions.copy(),
  179. )
  180. class CallableEventSpec(EventSpec):
  181. """Decorate an EventSpec-returning function to act as both a EventSpec and a function.
  182. This is used as a compatibility shim for replacing EventSpec objects in the
  183. API with functions that return a family of EventSpec.
  184. """
  185. fn: Optional[Callable[..., EventSpec]] = None
  186. def __init__(self, fn: Callable[..., EventSpec] | None = None, **kwargs):
  187. """Initialize a CallableEventSpec.
  188. Args:
  189. fn: The function to decorate.
  190. **kwargs: The kwargs to pass to pydantic initializer
  191. """
  192. if fn is not None:
  193. default_event_spec = fn()
  194. super().__init__(
  195. fn=fn, # type: ignore
  196. **default_event_spec.dict(),
  197. **kwargs,
  198. )
  199. else:
  200. super().__init__(**kwargs)
  201. def __call__(self, *args, **kwargs) -> EventSpec:
  202. """Call the decorated function.
  203. Args:
  204. *args: The args to pass to the function.
  205. **kwargs: The kwargs to pass to the function.
  206. Returns:
  207. The EventSpec returned from calling the function.
  208. Raises:
  209. TypeError: If the CallableEventSpec has no associated function.
  210. """
  211. if self.fn is None:
  212. raise TypeError("CallableEventSpec has no associated function.")
  213. return self.fn(*args, **kwargs)
  214. class EventChain(EventActionsMixin):
  215. """Container for a chain of events that will be executed in order."""
  216. events: List[EventSpec]
  217. args_spec: Optional[Callable]
  218. # These chains can be used for their side effects when no other events are desired.
  219. stop_propagation = EventChain(events=[], args_spec=lambda: []).stop_propagation
  220. prevent_default = EventChain(events=[], args_spec=lambda: []).prevent_default
  221. class Target(Base):
  222. """A Javascript event target."""
  223. checked: bool = False
  224. value: Any = None
  225. class FrontendEvent(Base):
  226. """A Javascript event."""
  227. target: Target = Target()
  228. key: str = ""
  229. value: Any = None
  230. class FileUpload(Base):
  231. """Class to represent a file upload."""
  232. upload_id: Optional[str] = None
  233. on_upload_progress: Optional[Union[EventHandler, Callable]] = None
  234. @staticmethod
  235. def on_upload_progress_args_spec(_prog: dict[str, int | float | bool]):
  236. """Args spec for on_upload_progress event handler.
  237. Returns:
  238. The arg mapping passed to backend event handler
  239. """
  240. return [_prog]
  241. def as_event_spec(self, handler: EventHandler) -> EventSpec:
  242. """Get the EventSpec for the file upload.
  243. Args:
  244. handler: The event handler.
  245. Returns:
  246. The event spec for the handler.
  247. Raises:
  248. ValueError: If the on_upload_progress is not a valid event handler.
  249. """
  250. from reflex.components.core.upload import (
  251. DEFAULT_UPLOAD_ID,
  252. upload_files_context_var_data,
  253. )
  254. upload_id = self.upload_id or DEFAULT_UPLOAD_ID
  255. spec_args = [
  256. (
  257. Var.create_safe("files"),
  258. Var.create_safe(f"filesById.{upload_id}")._replace(
  259. _var_data=upload_files_context_var_data
  260. ),
  261. ),
  262. (
  263. Var.create_safe("upload_id"),
  264. Var.create_safe(upload_id, _var_is_string=True),
  265. ),
  266. ]
  267. if self.on_upload_progress is not None:
  268. on_upload_progress = self.on_upload_progress
  269. if isinstance(on_upload_progress, EventHandler):
  270. events = [
  271. call_event_handler(
  272. on_upload_progress,
  273. self.on_upload_progress_args_spec,
  274. ),
  275. ]
  276. elif isinstance(on_upload_progress, Callable):
  277. # Call the lambda to get the event chain.
  278. events = call_event_fn(on_upload_progress, self.on_upload_progress_args_spec) # type: ignore
  279. else:
  280. raise ValueError(f"{on_upload_progress} is not a valid event handler.")
  281. on_upload_progress_chain = EventChain(
  282. events=events,
  283. args_spec=self.on_upload_progress_args_spec,
  284. )
  285. formatted_chain = str(format.format_prop(on_upload_progress_chain))
  286. spec_args.append(
  287. (
  288. Var.create_safe("on_upload_progress"),
  289. BaseVar(
  290. _var_name=formatted_chain.strip("{}"),
  291. _var_type=EventChain,
  292. ),
  293. ),
  294. )
  295. return EventSpec(
  296. handler=handler,
  297. client_handler_name="uploadFiles",
  298. args=tuple(spec_args),
  299. event_actions=handler.event_actions.copy(),
  300. )
  301. # Alias for rx.upload_files
  302. upload_files = FileUpload
  303. # Special server-side events.
  304. def server_side(name: str, sig: inspect.Signature, **kwargs) -> EventSpec:
  305. """A server-side event.
  306. Args:
  307. name: The name of the event.
  308. sig: The function signature of the event.
  309. **kwargs: The arguments to pass to the event.
  310. Returns:
  311. An event spec for a server-side event.
  312. """
  313. def fn():
  314. return None
  315. fn.__qualname__ = name
  316. fn.__signature__ = sig
  317. return EventSpec(
  318. handler=EventHandler(fn=fn),
  319. args=tuple(
  320. (Var.create_safe(k), Var.create_safe(v, _var_is_string=type(v) is str))
  321. for k, v in kwargs.items()
  322. ),
  323. )
  324. def redirect(path: str | Var[str], external: Optional[bool] = False) -> EventSpec:
  325. """Redirect to a new path.
  326. Args:
  327. path: The path to redirect to.
  328. external: Whether to open in new tab or not.
  329. Returns:
  330. An event to redirect to the path.
  331. """
  332. return server_side(
  333. "_redirect", get_fn_signature(redirect), path=path, external=external
  334. )
  335. def console_log(message: str | Var[str]) -> EventSpec:
  336. """Do a console.log on the browser.
  337. Args:
  338. message: The message to log.
  339. Returns:
  340. An event to log the message.
  341. """
  342. return server_side("_console", get_fn_signature(console_log), message=message)
  343. def window_alert(message: str | Var[str]) -> EventSpec:
  344. """Create a window alert on the browser.
  345. Args:
  346. message: The message to alert.
  347. Returns:
  348. An event to alert the message.
  349. """
  350. return server_side("_alert", get_fn_signature(window_alert), message=message)
  351. def set_focus(ref: str) -> EventSpec:
  352. """Set focus to specified ref.
  353. Args:
  354. ref: The ref.
  355. Returns:
  356. An event to set focus on the ref
  357. """
  358. return server_side(
  359. "_set_focus",
  360. get_fn_signature(set_focus),
  361. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  362. )
  363. def set_value(ref: str, value: Any) -> EventSpec:
  364. """Set the value of a ref.
  365. Args:
  366. ref: The ref.
  367. value: The value to set.
  368. Returns:
  369. An event to set the ref.
  370. """
  371. return server_side(
  372. "_set_value",
  373. get_fn_signature(set_value),
  374. ref=Var.create_safe(format.format_ref(ref), _var_is_string=True),
  375. value=value,
  376. )
  377. def remove_cookie(key: str, options: dict[str, Any] | None = None) -> EventSpec:
  378. """Remove a cookie on the frontend.
  379. Args:
  380. key: The key identifying the cookie to be removed.
  381. options: Support all the cookie options from RFC 6265
  382. Returns:
  383. EventSpec: An event to remove a cookie.
  384. """
  385. options = options or {}
  386. options["path"] = options.get("path", "/")
  387. return server_side(
  388. "_remove_cookie",
  389. get_fn_signature(remove_cookie),
  390. key=key,
  391. options=options,
  392. )
  393. def clear_local_storage() -> EventSpec:
  394. """Set a value in the local storage on the frontend.
  395. Returns:
  396. EventSpec: An event to clear the local storage.
  397. """
  398. return server_side(
  399. "_clear_local_storage",
  400. get_fn_signature(clear_local_storage),
  401. )
  402. def remove_local_storage(key: str) -> EventSpec:
  403. """Set a value in the local storage on the frontend.
  404. Args:
  405. key: The key identifying the variable in the local storage to remove.
  406. Returns:
  407. EventSpec: An event to remove an item based on the provided key in local storage.
  408. """
  409. return server_side(
  410. "_remove_local_storage",
  411. get_fn_signature(remove_local_storage),
  412. key=key,
  413. )
  414. def set_clipboard(content: str) -> EventSpec:
  415. """Set the text in content in the clipboard.
  416. Args:
  417. content: The text to add to clipboard.
  418. Returns:
  419. EventSpec: An event to set some content in the clipboard.
  420. """
  421. return server_side(
  422. "_set_clipboard",
  423. get_fn_signature(set_clipboard),
  424. content=content,
  425. )
  426. def download(
  427. url: str | Var | None = None,
  428. filename: Optional[str | Var] = None,
  429. data: str | bytes | Var | None = None,
  430. ) -> EventSpec:
  431. """Download the file at a given path or with the specified data.
  432. Args:
  433. url: The URL to the file to download.
  434. filename: The name that the file should be saved as after download.
  435. data: The data to download.
  436. Raises:
  437. ValueError: If the URL provided is invalid, both URL and data are provided,
  438. or the data is not an expected type.
  439. Returns:
  440. EventSpec: An event to download the associated file.
  441. """
  442. from reflex.components.core.cond import cond
  443. if isinstance(url, str):
  444. if not url.startswith("/"):
  445. raise ValueError("The URL argument should start with a /")
  446. # if filename is not provided, infer it from url
  447. if filename is None:
  448. filename = url.rpartition("/")[-1]
  449. if filename is None:
  450. filename = ""
  451. if data is not None:
  452. if url is not None:
  453. raise ValueError("Cannot provide both URL and data to download.")
  454. if isinstance(data, str):
  455. # Caller provided a plain text string to download.
  456. url = "data:text/plain," + data
  457. elif isinstance(data, Var):
  458. # Need to check on the frontend if the Var already looks like a data: URI.
  459. is_data_url = data._replace(
  460. _var_name=(
  461. f"typeof {data._var_full_name} == 'string' && "
  462. f"{data._var_full_name}.startsWith('data:')"
  463. ),
  464. _var_type=bool,
  465. _var_is_string=False,
  466. _var_full_name_needs_state_prefix=False,
  467. )
  468. # If it's a data: URI, use it as is, otherwise convert the Var to JSON in a data: URI.
  469. url = cond( # type: ignore
  470. is_data_url,
  471. data,
  472. "data:text/plain," + data.to_string(), # type: ignore
  473. )
  474. elif isinstance(data, bytes):
  475. # Caller provided bytes, so base64 encode it as a data: URI.
  476. b64_data = b64encode(data).decode("utf-8")
  477. url = "data:application/octet-stream;base64," + b64_data
  478. else:
  479. raise ValueError(
  480. f"Invalid data type {type(data)} for download. Use `str` or `bytes`."
  481. )
  482. return server_side(
  483. "_download",
  484. get_fn_signature(download),
  485. url=url,
  486. filename=filename,
  487. )
  488. def _callback_arg_spec(eval_result):
  489. """ArgSpec for call_script callback function.
  490. Args:
  491. eval_result: The result of the javascript execution.
  492. Returns:
  493. Args for the callback function
  494. """
  495. return [eval_result]
  496. def call_script(
  497. javascript_code: str,
  498. callback: EventHandler | Callable | None = None,
  499. ) -> EventSpec:
  500. """Create an event handler that executes arbitrary javascript code.
  501. Args:
  502. javascript_code: The code to execute.
  503. callback: EventHandler that will receive the result of evaluating the javascript code.
  504. Returns:
  505. EventSpec: An event that will execute the client side javascript.
  506. Raises:
  507. ValueError: If the callback is not a valid event handler.
  508. """
  509. callback_kwargs = {}
  510. if callback is not None:
  511. arg_name = parse_args_spec(_callback_arg_spec)[0]._var_name
  512. if isinstance(callback, EventHandler):
  513. event_spec = call_event_handler(callback, _callback_arg_spec)
  514. elif isinstance(callback, FunctionType):
  515. event_spec = call_event_fn(callback, _callback_arg_spec)[0]
  516. else:
  517. raise ValueError("Cannot use {callback!r} as a call_script callback.")
  518. callback_kwargs = {
  519. "callback": f"({arg_name}) => queueEvents([{format.format_event(event_spec)}], {constants.CompileVars.SOCKET})"
  520. }
  521. return server_side(
  522. "_call_script",
  523. get_fn_signature(call_script),
  524. javascript_code=javascript_code,
  525. **callback_kwargs,
  526. )
  527. def get_event(state, event):
  528. """Get the event from the given state.
  529. Args:
  530. state: The state.
  531. event: The event.
  532. Returns:
  533. The event.
  534. """
  535. return f"{state.get_name()}.{event}"
  536. def get_hydrate_event(state) -> str:
  537. """Get the name of the hydrate event for the state.
  538. Args:
  539. state: The state.
  540. Returns:
  541. The name of the hydrate event.
  542. """
  543. return get_event(state, constants.CompileVars.HYDRATE)
  544. def call_event_handler(
  545. event_handler: EventHandler, arg_spec: Union[Var, ArgsSpec]
  546. ) -> EventSpec:
  547. """Call an event handler to get the event spec.
  548. This function will inspect the function signature of the event handler.
  549. If it takes in an arg, the arg will be passed to the event handler.
  550. Otherwise, the event handler will be called with no args.
  551. Args:
  552. event_handler: The event handler.
  553. arg_spec: The lambda that define the argument(s) to pass to the event handler.
  554. Raises:
  555. ValueError: if number of arguments expected by event_handler doesn't match the spec.
  556. Returns:
  557. The event spec from calling the event handler.
  558. """
  559. args = inspect.getfullargspec(event_handler.fn).args
  560. # handle new API using lambda to define triggers
  561. if isinstance(arg_spec, ArgsSpec):
  562. parsed_args = parse_args_spec(arg_spec) # type: ignore
  563. if len(args) == len(["self", *parsed_args]):
  564. return event_handler(*parsed_args) # type: ignore
  565. else:
  566. source = inspect.getsource(arg_spec) # type: ignore
  567. raise ValueError(
  568. f"number of arguments in {event_handler.fn.__qualname__} "
  569. f"doesn't match the definition of the event trigger '{source.strip().strip(',')}'"
  570. )
  571. else:
  572. console.deprecate(
  573. feature_name="EVENT_ARG API for triggers",
  574. reason="Replaced by new API using lambda allow arbitrary number of args",
  575. deprecation_version="0.2.8",
  576. removal_version="0.5.0",
  577. )
  578. if len(args) == 1:
  579. return event_handler()
  580. assert (
  581. len(args) == 2
  582. ), f"Event handler {event_handler.fn} must have 1 or 2 arguments."
  583. return event_handler(arg_spec) # type: ignore
  584. def parse_args_spec(arg_spec: ArgsSpec):
  585. """Parse the args provided in the ArgsSpec of an event trigger.
  586. Args:
  587. arg_spec: The spec of the args.
  588. Returns:
  589. The parsed args.
  590. """
  591. spec = inspect.getfullargspec(arg_spec)
  592. return arg_spec(
  593. *[
  594. BaseVar(
  595. _var_name=f"_{l_arg}",
  596. _var_type=spec.annotations.get(l_arg, FrontendEvent),
  597. _var_is_local=True,
  598. )
  599. for l_arg in spec.args
  600. ]
  601. )
  602. def call_event_fn(fn: Callable, arg: Union[Var, ArgsSpec]) -> list[EventSpec]:
  603. """Call a function to a list of event specs.
  604. The function should return either a single EventSpec or a list of EventSpecs.
  605. If the function takes in an arg, the arg will be passed to the function.
  606. Otherwise, the function will be called with no args.
  607. Args:
  608. fn: The function to call.
  609. arg: The argument to pass to the function.
  610. Returns:
  611. The event specs from calling the function.
  612. Raises:
  613. ValueError: If the lambda has an invalid signature.
  614. """
  615. # Import here to avoid circular imports.
  616. from reflex.event import EventHandler, EventSpec
  617. # Get the args of the lambda.
  618. args = inspect.getfullargspec(fn).args
  619. if isinstance(arg, ArgsSpec):
  620. out = fn(*parse_args_spec(arg)) # type: ignore
  621. else:
  622. # Call the lambda.
  623. if len(args) == 0:
  624. out = fn()
  625. elif len(args) == 1:
  626. out = fn(arg)
  627. else:
  628. raise ValueError(f"Lambda {fn} must have 0 or 1 arguments.")
  629. # Convert the output to a list.
  630. if not isinstance(out, List):
  631. out = [out]
  632. # Convert any event specs to event specs.
  633. events = []
  634. for e in out:
  635. # Convert handlers to event specs.
  636. if isinstance(e, EventHandler):
  637. if len(args) == 0:
  638. e = e()
  639. elif len(args) == 1:
  640. e = e(arg) # type: ignore
  641. # Make sure the event spec is valid.
  642. if not isinstance(e, EventSpec):
  643. raise ValueError(f"Lambda {fn} returned an invalid event spec: {e}.")
  644. # Add the event spec to the chain.
  645. events.append(e)
  646. # Return the events.
  647. return events
  648. def get_handler_args(event_spec: EventSpec) -> tuple[tuple[Var, Var], ...]:
  649. """Get the handler args for the given event spec.
  650. Args:
  651. event_spec: The event spec.
  652. Returns:
  653. The handler args.
  654. """
  655. args = inspect.getfullargspec(event_spec.handler.fn).args
  656. return event_spec.args if len(args) > 1 else tuple()
  657. def fix_events(
  658. events: list[EventHandler | EventSpec] | None,
  659. token: str,
  660. router_data: dict[str, Any] | None = None,
  661. ) -> list[Event]:
  662. """Fix a list of events returned by an event handler.
  663. Args:
  664. events: The events to fix.
  665. token: The user token.
  666. router_data: The optional router data to set in the event.
  667. Returns:
  668. The fixed events.
  669. """
  670. # If the event handler returns nothing, return an empty list.
  671. if events is None:
  672. return []
  673. # If the handler returns a single event, wrap it in a list.
  674. if not isinstance(events, List):
  675. events = [events]
  676. # Fix the events created by the handler.
  677. out = []
  678. for e in events:
  679. if isinstance(e, Event):
  680. # If the event is already an event, append it to the list.
  681. out.append(e)
  682. continue
  683. if not isinstance(e, (EventHandler, EventSpec)):
  684. e = EventHandler(fn=e)
  685. # Otherwise, create an event from the event spec.
  686. if isinstance(e, EventHandler):
  687. e = e()
  688. assert isinstance(e, EventSpec), f"Unexpected event type, {type(e)}."
  689. name = format.format_event_handler(e.handler)
  690. payload = {k._var_name: v._decode() for k, v in e.args} # type: ignore
  691. # Filter router_data to reduce payload size
  692. event_router_data = {
  693. k: v
  694. for k, v in (router_data or {}).items()
  695. if k in constants.route.ROUTER_DATA_INCLUDE
  696. }
  697. # Create an event and append it to the list.
  698. out.append(
  699. Event(
  700. token=token,
  701. name=name,
  702. payload=payload,
  703. router_data=event_router_data,
  704. )
  705. )
  706. return out
  707. def get_fn_signature(fn: Callable) -> inspect.Signature:
  708. """Get the signature of a function.
  709. Args:
  710. fn: The function.
  711. Returns:
  712. The signature of the function.
  713. """
  714. signature = inspect.signature(fn)
  715. new_param = inspect.Parameter(
  716. "state", inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Any
  717. )
  718. return signature.replace(parameters=(new_param, *signature.parameters.values()))