event.py 25 KB

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