state.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. """Define the pynecone state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import functools
  5. import traceback
  6. from abc import ABC
  7. from typing import (
  8. Any,
  9. Callable,
  10. ClassVar,
  11. Dict,
  12. List,
  13. Optional,
  14. Sequence,
  15. Set,
  16. Type,
  17. Union,
  18. )
  19. import cloudpickle
  20. from redis import Redis
  21. from pynecone import constants
  22. from pynecone.base import Base
  23. from pynecone.event import Event, EventHandler, fix_events, window_alert
  24. from pynecone.utils import format, prerequisites, types
  25. from pynecone.var import BaseVar, ComputedVar, PCDict, PCList, Var
  26. Delta = Dict[str, Any]
  27. class State(Base, ABC):
  28. """The state of the app."""
  29. # A map from the var name to the var.
  30. vars: ClassVar[Dict[str, Var]] = {}
  31. # The base vars of the class.
  32. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  33. # The computed vars of the class.
  34. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  35. # Vars inherited by the parent state.
  36. inherited_vars: ClassVar[Dict[str, Var]] = {}
  37. # Backend vars that are never sent to the client.
  38. backend_vars: ClassVar[Dict[str, Any]] = {}
  39. # Backend vars inherited
  40. inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
  41. # The parent state.
  42. parent_state: Optional[State] = None
  43. # The substates of the state.
  44. substates: Dict[str, State] = {}
  45. # The set of dirty vars.
  46. dirty_vars: Set[str] = set()
  47. # The set of dirty substates.
  48. dirty_substates: Set[str] = set()
  49. # The routing path that triggered the state
  50. router_data: Dict[str, Any] = {}
  51. def __init__(self, *args, **kwargs):
  52. """Initialize the state.
  53. Args:
  54. *args: The args to pass to the Pydantic init method.
  55. **kwargs: The kwargs to pass to the Pydantic init method.
  56. """
  57. super().__init__(*args, **kwargs)
  58. # Setup the substates.
  59. for substate in self.get_substates():
  60. self.substates[substate.get_name()] = substate().set(parent_state=self)
  61. self._init_mutable_fields()
  62. def _init_mutable_fields(self):
  63. """Initialize mutable fields.
  64. So that mutation to them can be detected by the app:
  65. * list
  66. """
  67. for field in self.base_vars.values():
  68. value = getattr(self, field.name)
  69. value_in_pc_data = _convert_mutable_datatypes(
  70. value, self._reassign_field, field.name
  71. )
  72. if types._issubclass(field.type_, Union[List, Dict]):
  73. setattr(self, field.name, value_in_pc_data)
  74. self.clean()
  75. def _reassign_field(self, field_name: str):
  76. """Reassign the given field.
  77. Primarily for mutation in fields of mutable data types.
  78. Args:
  79. field_name: The name of the field we want to reassign
  80. """
  81. setattr(
  82. self,
  83. field_name,
  84. getattr(self, field_name),
  85. )
  86. def __repr__(self) -> str:
  87. """Get the string representation of the state.
  88. Returns:
  89. The string representation of the state.
  90. """
  91. return f"{self.__class__.__name__}({self.dict()})"
  92. @classmethod
  93. def __init_subclass__(cls, **kwargs):
  94. """Do some magic for the subclass initialization.
  95. Args:
  96. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  97. """
  98. super().__init_subclass__(**kwargs)
  99. # Get the parent vars.
  100. parent_state = cls.get_parent_state()
  101. if parent_state is not None:
  102. cls.inherited_vars = parent_state.vars
  103. cls.inherited_backend_vars = parent_state.backend_vars
  104. cls.new_backend_vars = {
  105. name: value
  106. for name, value in cls.__dict__.items()
  107. if types.is_backend_variable(name)
  108. and name not in cls.inherited_backend_vars
  109. }
  110. cls.backend_vars = {**cls.inherited_backend_vars, **cls.new_backend_vars}
  111. # Set the base and computed vars.
  112. skip_vars = set(cls.inherited_vars) | {
  113. "parent_state",
  114. "substates",
  115. "dirty_vars",
  116. "dirty_substates",
  117. "router_data",
  118. }
  119. cls.base_vars = {
  120. f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls)
  121. for f in cls.get_fields().values()
  122. if f.name not in skip_vars
  123. }
  124. cls.computed_vars = {
  125. v.name: v.set_state(cls)
  126. for v in cls.__dict__.values()
  127. if isinstance(v, ComputedVar)
  128. }
  129. cls.vars = {
  130. **cls.inherited_vars,
  131. **cls.base_vars,
  132. **cls.computed_vars,
  133. }
  134. # Setup the base vars at the class level.
  135. for prop in cls.base_vars.values():
  136. cls._init_var(prop)
  137. # Set up the event handlers.
  138. events = {
  139. name: fn
  140. for name, fn in cls.__dict__.items()
  141. if not name.startswith("_") and isinstance(fn, Callable)
  142. }
  143. for name, fn in events.items():
  144. event_handler = EventHandler(fn=fn)
  145. setattr(cls, name, event_handler)
  146. @classmethod
  147. @functools.lru_cache()
  148. def get_parent_state(cls) -> Optional[Type[State]]:
  149. """Get the parent state.
  150. Returns:
  151. The parent state.
  152. """
  153. parent_states = [
  154. base
  155. for base in cls.__bases__
  156. if types._issubclass(base, State) and base is not State
  157. ]
  158. assert len(parent_states) < 2, "Only one parent state is allowed."
  159. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  160. @classmethod
  161. @functools.lru_cache()
  162. def get_substates(cls) -> Set[Type[State]]:
  163. """Get the substates of the state.
  164. Returns:
  165. The substates of the state.
  166. """
  167. return set(cls.__subclasses__())
  168. @classmethod
  169. @functools.lru_cache()
  170. def get_name(cls) -> str:
  171. """Get the name of the state.
  172. Returns:
  173. The name of the state.
  174. """
  175. return format.to_snake_case(cls.__name__)
  176. @classmethod
  177. @functools.lru_cache()
  178. def get_full_name(cls) -> str:
  179. """Get the full name of the state.
  180. Returns:
  181. The full name of the state.
  182. """
  183. name = cls.get_name()
  184. parent_state = cls.get_parent_state()
  185. if parent_state is not None:
  186. name = ".".join((parent_state.get_full_name(), name))
  187. return name
  188. @classmethod
  189. @functools.lru_cache()
  190. def get_class_substate(cls, path: Sequence[str]) -> Type[State]:
  191. """Get the class substate.
  192. Args:
  193. path: The path to the substate.
  194. Returns:
  195. The class substate.
  196. Raises:
  197. ValueError: If the substate is not found.
  198. """
  199. if len(path) == 0:
  200. return cls
  201. if path[0] == cls.get_name():
  202. if len(path) == 1:
  203. return cls
  204. path = path[1:]
  205. for substate in cls.get_substates():
  206. if path[0] == substate.get_name():
  207. return substate.get_class_substate(path[1:])
  208. raise ValueError(f"Invalid path: {path}")
  209. @classmethod
  210. def get_class_var(cls, path: Sequence[str]) -> Any:
  211. """Get the class var.
  212. Args:
  213. path: The path to the var.
  214. Returns:
  215. The class var.
  216. Raises:
  217. ValueError: If the path is invalid.
  218. """
  219. path, name = path[:-1], path[-1]
  220. substate = cls.get_class_substate(tuple(path))
  221. if not hasattr(substate, name):
  222. raise ValueError(f"Invalid path: {path}")
  223. return getattr(substate, name)
  224. @classmethod
  225. def _init_var(cls, prop: BaseVar):
  226. """Initialize a variable.
  227. Args:
  228. prop (BaseVar): The variable to initialize
  229. Raises:
  230. TypeError: if the variable has an incorrect type
  231. """
  232. if not types.is_valid_var_type(prop.type_):
  233. raise TypeError(
  234. "State vars must be primitive Python types, "
  235. "Plotly figures, Pandas dataframes, "
  236. "or subclasses of pc.Base. "
  237. f'Found var "{prop.name}" with type {prop.type_}.'
  238. )
  239. cls._set_var(prop)
  240. cls._create_setter(prop)
  241. cls._set_default_value(prop)
  242. @classmethod
  243. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  244. """Add dynamically a variable to the State.
  245. The variable added this way can be used in the same way as a variable
  246. defined statically in the model.
  247. Args:
  248. name: The name of the variable
  249. type_: The type of the variable
  250. default_value: The default value of the variable
  251. Raises:
  252. NameError: if a variable of this name already exists
  253. """
  254. if name in cls.__fields__:
  255. raise NameError(
  256. f"The variable '{name}' already exist. Use a different name"
  257. )
  258. # create the variable based on name and type
  259. var = BaseVar(name=name, type_=type_)
  260. var.set_state(cls)
  261. # add the pydantic field dynamically (must be done before _init_var)
  262. cls.add_field(var, default_value)
  263. cls._init_var(var)
  264. # update the internal dicts so the new variable is correctly handled
  265. cls.base_vars.update({name: var})
  266. cls.vars.update({name: var})
  267. @classmethod
  268. def _set_var(cls, prop: BaseVar):
  269. """Set the var as a class member.
  270. Args:
  271. prop: The var instance to set.
  272. """
  273. setattr(cls, prop.name, prop)
  274. @classmethod
  275. def _create_setter(cls, prop: BaseVar):
  276. """Create a setter for the var.
  277. Args:
  278. prop: The var to create a setter for.
  279. """
  280. setter_name = prop.get_setter_name(include_state=False)
  281. if setter_name not in cls.__dict__:
  282. setattr(cls, setter_name, prop.get_setter())
  283. @classmethod
  284. def _set_default_value(cls, prop: BaseVar):
  285. """Set the default value for the var.
  286. Args:
  287. prop: The var to set the default value for.
  288. """
  289. # Get the pydantic field for the var.
  290. field = cls.get_fields()[prop.name]
  291. default_value = prop.get_default_value()
  292. if field.required and default_value is not None:
  293. field.required = False
  294. field.default = default_value
  295. def get_token(self) -> str:
  296. """Return the token of the client associated with this state.
  297. Returns:
  298. The token of the client.
  299. """
  300. return self.router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  301. def get_sid(self) -> str:
  302. """Return the session ID of the client associated with this state.
  303. Returns:
  304. The session ID of the client.
  305. """
  306. return self.router_data.get(constants.RouteVar.SESSION_ID, "")
  307. def get_headers(self) -> Dict:
  308. """Return the headers of the client associated with this state.
  309. Returns:
  310. The headers of the client.
  311. """
  312. return self.router_data.get(constants.RouteVar.HEADERS, {})
  313. def get_client_ip(self) -> str:
  314. """Return the IP of the client associated with this state.
  315. Returns:
  316. The IP of the client.
  317. """
  318. return self.router_data.get(constants.RouteVar.CLIENT_IP, "")
  319. def get_current_page(self) -> str:
  320. """Obtain the path of current page from the router data.
  321. Returns:
  322. The current page.
  323. """
  324. return self.router_data.get(constants.RouteVar.PATH, "")
  325. def get_query_params(self) -> Dict[str, str]:
  326. """Obtain the query parameters for the queried page.
  327. The query object contains both the URI parameters and the GET parameters.
  328. Returns:
  329. The dict of query parameters.
  330. """
  331. return self.router_data.get(constants.RouteVar.QUERY, {})
  332. @classmethod
  333. def setup_dynamic_args(cls, args: dict[str, str]):
  334. """Set up args for easy access in renderer.
  335. Args:
  336. args: a dict of args
  337. """
  338. def argsingle_factory(param):
  339. @ComputedVar
  340. def inner_func(self) -> str:
  341. return self.get_query_params().get(param, "")
  342. return inner_func
  343. def arglist_factory(param):
  344. @ComputedVar
  345. def inner_func(self) -> List:
  346. return self.get_query_params().get(param, [])
  347. return inner_func
  348. for param, value in args.items():
  349. if value == constants.RouteArgType.SINGLE:
  350. func = argsingle_factory(param)
  351. elif value == constants.RouteArgType.LIST:
  352. func = arglist_factory(param)
  353. else:
  354. continue
  355. cls.computed_vars[param] = func.set_state(cls) # type: ignore
  356. setattr(cls, param, func)
  357. def __getattribute__(self, name: str) -> Any:
  358. """Get the state var.
  359. If the var is inherited, get the var from the parent state.
  360. Args:
  361. name: The name of the var.
  362. Returns:
  363. The value of the var.
  364. """
  365. inherited_vars = {
  366. **super().__getattribute__("inherited_vars"),
  367. **super().__getattribute__("inherited_backend_vars"),
  368. }
  369. if name in inherited_vars:
  370. return getattr(super().__getattribute__("parent_state"), name)
  371. elif name in super().__getattribute__("backend_vars"):
  372. return super().__getattribute__("backend_vars").__getitem__(name)
  373. return super().__getattribute__(name)
  374. def __setattr__(self, name: str, value: Any):
  375. """Set the attribute.
  376. If the attribute is inherited, set the attribute on the parent state.
  377. Args:
  378. name: The name of the attribute.
  379. value: The value of the attribute.
  380. """
  381. # Set the var on the parent state.
  382. inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
  383. if name in inherited_vars:
  384. setattr(self.parent_state, name, value)
  385. return
  386. if types.is_backend_variable(name):
  387. self.backend_vars.__setitem__(name, value)
  388. self.mark_dirty()
  389. return
  390. # Set the attribute.
  391. super().__setattr__(name, value)
  392. # Add the var to the dirty list.
  393. if name in self.vars:
  394. self.dirty_vars.add(name)
  395. self.mark_dirty()
  396. def reset(self):
  397. """Reset all the base vars to their default values."""
  398. # Reset the base vars.
  399. fields = self.get_fields()
  400. for prop_name in self.base_vars:
  401. setattr(self, prop_name, fields[prop_name].default)
  402. # Recursively reset the substates.
  403. for substate in self.substates.values():
  404. substate.reset()
  405. # Clean the state.
  406. self.clean()
  407. def get_substate(self, path: Sequence[str]) -> Optional[State]:
  408. """Get the substate.
  409. Args:
  410. path: The path to the substate.
  411. Returns:
  412. The substate.
  413. Raises:
  414. ValueError: If the substate is not found.
  415. """
  416. if len(path) == 0:
  417. return self
  418. if path[0] == self.get_name():
  419. if len(path) == 1:
  420. return self
  421. path = path[1:]
  422. if path[0] not in self.substates:
  423. raise ValueError(f"Invalid path: {path}")
  424. return self.substates[path[0]].get_substate(path[1:])
  425. async def process(self, event: Event) -> StateUpdate:
  426. """Process an event.
  427. Args:
  428. event: The event to process.
  429. Returns:
  430. The state update after processing the event.
  431. """
  432. # Get the event handler.
  433. path = event.name.split(".")
  434. path, name = path[:-1], path[-1]
  435. substate = self.get_substate(path)
  436. handler = getattr(substate, name)
  437. # Process the event.
  438. fn = functools.partial(handler.fn, substate)
  439. try:
  440. if asyncio.iscoroutinefunction(fn.func):
  441. events = await fn(**event.payload)
  442. else:
  443. events = fn(**event.payload)
  444. except Exception:
  445. error = traceback.format_exc()
  446. print(error)
  447. events = fix_events(
  448. [window_alert("An error occurred. See logs for details.")], event.token
  449. )
  450. return StateUpdate(events=events)
  451. # Fix the returned events.
  452. events = fix_events(events, event.token)
  453. # Get the delta after processing the event.
  454. delta = self.get_delta()
  455. # Reset the dirty vars.
  456. self.clean()
  457. # Return the state update.
  458. return StateUpdate(delta=delta, events=events)
  459. def get_delta(self) -> Delta:
  460. """Get the delta for the state.
  461. Returns:
  462. The delta for the state.
  463. """
  464. delta = {}
  465. # Return the dirty vars, as well as all computed vars.
  466. subdelta = {
  467. prop: getattr(self, prop)
  468. for prop in self.dirty_vars | self.computed_vars.keys()
  469. }
  470. if len(subdelta) > 0:
  471. delta[self.get_full_name()] = subdelta
  472. # Recursively find the substate deltas.
  473. substates = self.substates
  474. for substate in self.dirty_substates:
  475. delta.update(substates[substate].get_delta())
  476. # Format the delta.
  477. delta = format.format_state(delta)
  478. # Return the delta.
  479. return delta
  480. def mark_dirty(self):
  481. """Mark the substate and all parent states as dirty."""
  482. if self.parent_state is not None:
  483. self.parent_state.dirty_substates.add(self.get_name())
  484. self.parent_state.mark_dirty()
  485. def clean(self):
  486. """Reset the dirty vars."""
  487. # Recursively clean the substates.
  488. for substate in self.dirty_substates:
  489. self.substates[substate].clean()
  490. # Clean this state.
  491. self.dirty_vars = set()
  492. self.dirty_substates = set()
  493. def dict(self, include_computed: bool = True, **kwargs) -> Dict[str, Any]:
  494. """Convert the object to a dictionary.
  495. Args:
  496. include_computed: Whether to include computed vars.
  497. **kwargs: Kwargs to pass to the pydantic dict method.
  498. Returns:
  499. The object as a dictionary.
  500. """
  501. base_vars = {
  502. prop_name: self.get_value(getattr(self, prop_name))
  503. for prop_name in self.base_vars
  504. }
  505. computed_vars = (
  506. {
  507. # Include the computed vars.
  508. prop_name: self.get_value(getattr(self, prop_name))
  509. for prop_name in self.computed_vars
  510. }
  511. if include_computed
  512. else {}
  513. )
  514. substate_vars = {
  515. k: v.dict(include_computed=include_computed, **kwargs)
  516. for k, v in self.substates.items()
  517. }
  518. variables = {**base_vars, **computed_vars, **substate_vars}
  519. return {k: variables[k] for k in sorted(variables)}
  520. class DefaultState(State):
  521. """The default empty state."""
  522. pass
  523. class StateUpdate(Base):
  524. """A state update sent to the frontend."""
  525. # The state delta.
  526. delta: Delta = {}
  527. # Events to be added to the event queue.
  528. events: List[Event] = []
  529. class StateManager(Base):
  530. """A class to manage many client states."""
  531. # The state class to use.
  532. state: Type[State] = DefaultState
  533. # The mapping of client ids to states.
  534. states: Dict[str, State] = {}
  535. # The token expiration time (s).
  536. token_expiration: int = constants.TOKEN_EXPIRATION
  537. # The redis client to use.
  538. redis: Optional[Redis] = None
  539. def setup(self, state: Type[State]):
  540. """Set up the state manager.
  541. Args:
  542. state: The state class to use.
  543. """
  544. self.state = state
  545. self.redis = prerequisites.get_redis()
  546. def get_state(self, token: str) -> State:
  547. """Get the state for a token.
  548. Args:
  549. token: The token to get the state for.
  550. Returns:
  551. The state for the token.
  552. """
  553. if self.redis is not None:
  554. redis_state = self.redis.get(token)
  555. if redis_state is None:
  556. self.set_state(token, self.state())
  557. return self.get_state(token)
  558. return cloudpickle.loads(redis_state)
  559. if token not in self.states:
  560. self.states[token] = self.state()
  561. return self.states[token]
  562. def set_state(self, token: str, state: State):
  563. """Set the state for a token.
  564. Args:
  565. token: The token to set the state for.
  566. state: The state to set.
  567. """
  568. if self.redis is None:
  569. return
  570. self.redis.set(token, cloudpickle.dumps(state), ex=self.token_expiration)
  571. def _convert_mutable_datatypes(
  572. field_value: Any, reassign_field: Callable, field_name: str
  573. ) -> Any:
  574. """Recursively convert mutable data to the Pc data types.
  575. Note: right now only list & dict would be handled recursively.
  576. Args:
  577. field_value: The target field_value.
  578. reassign_field:
  579. The function to reassign the field in the parent state.
  580. field_name: the name of the field in the parent state
  581. Returns:
  582. The converted field_value
  583. """
  584. if isinstance(field_value, list):
  585. for index in range(len(field_value)):
  586. field_value[index] = _convert_mutable_datatypes(
  587. field_value[index], reassign_field, field_name
  588. )
  589. field_value = PCList(
  590. field_value, reassign_field=reassign_field, field_name=field_name
  591. )
  592. if isinstance(field_value, dict):
  593. for key, value in field_value.items():
  594. field_value[key] = _convert_mutable_datatypes(
  595. value, reassign_field, field_name
  596. )
  597. field_value = PCDict(
  598. field_value, reassign_field=reassign_field, field_name=field_name
  599. )
  600. return field_value