state.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. """Define the pynecone state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import functools
  5. import pickle
  6. import traceback
  7. from abc import ABC
  8. from typing import Any, Callable, ClassVar, Dict, List, Optional, Sequence, Set, Type
  9. from redis import Redis
  10. from pynecone import constants, utils
  11. from pynecone.base import Base
  12. from pynecone.event import Event, EventHandler, window_alert
  13. from pynecone.var import BaseVar, ComputedVar, Var
  14. Delta = Dict[str, Any]
  15. class State(Base, ABC):
  16. """The state of the app."""
  17. # A map from the var name to the var.
  18. vars: ClassVar[Dict[str, Var]] = {}
  19. # The base vars of the class.
  20. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  21. # The computed vars of the class.
  22. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  23. # vars inherited by the parent state.
  24. inherited_vars: ClassVar[Dict[str, Var]] = {}
  25. # The parent state.
  26. parent_state: Optional[State] = None
  27. # The substates of the state.
  28. substates: Dict[str, State] = {}
  29. # The set of dirty vars.
  30. dirty_vars: Set[str] = set()
  31. # The set of dirty substates.
  32. dirty_substates: Set[str] = set()
  33. def __init__(self, *args, **kwargs):
  34. """Initialize the state.
  35. Args:
  36. *args: The args to pass to the Pydantic init method.
  37. **kwargs: The kwargs to pass to the Pydantic init method.
  38. """
  39. super().__init__(*args, **kwargs)
  40. # Setup the substates.
  41. for substate in self.get_substates():
  42. self.substates[substate.get_name()] = substate().set(parent_state=self)
  43. def __repr__(self) -> str:
  44. """Get the string representation of the state.
  45. Returns:
  46. The string representation of the state.
  47. """
  48. return f"{self.__class__.__name__}({self.dict()})"
  49. @classmethod
  50. def __init_subclass__(cls, **kwargs):
  51. """Do some magic for the subclass initialization.
  52. Args:
  53. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  54. Raises:
  55. TypeError: If the class has a var with an invalid type.
  56. """
  57. super().__init_subclass__(**kwargs)
  58. # Get the parent vars.
  59. parent_state = cls.get_parent_state()
  60. if parent_state is not None:
  61. cls.inherited_vars = parent_state.vars
  62. # Set the base and computed vars.
  63. skip_vars = set(cls.inherited_vars) | {
  64. "parent_state",
  65. "substates",
  66. "dirty_vars",
  67. "dirty_substates",
  68. }
  69. cls.base_vars = {
  70. f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls)
  71. for f in cls.get_fields().values()
  72. if f.name not in skip_vars
  73. }
  74. cls.computed_vars = {
  75. v.name: v.set_state(cls)
  76. for v in cls.__dict__.values()
  77. if isinstance(v, ComputedVar)
  78. }
  79. cls.vars = {
  80. **cls.inherited_vars,
  81. **cls.base_vars,
  82. **cls.computed_vars,
  83. }
  84. # Setup the base vars at the class level.
  85. for prop in cls.base_vars.values():
  86. if not utils._issubclass(prop.type_, utils.StateVar):
  87. raise TypeError(
  88. "State vars must be primitive Python types, "
  89. "Plotly figures, Pandas dataframes, "
  90. "or subclasses of pc.Base. "
  91. f'Found var "{prop.name}" with type {prop.type_}.'
  92. )
  93. cls._set_var(prop)
  94. cls._create_setter(prop)
  95. cls._set_default_value(prop)
  96. # Set up the event handlers.
  97. events = {
  98. name: fn
  99. for name, fn in cls.__dict__.items()
  100. if not name.startswith("_") and isinstance(fn, Callable)
  101. }
  102. for name, fn in events.items():
  103. event_handler = EventHandler(fn=fn)
  104. setattr(cls, name, event_handler)
  105. @classmethod
  106. @functools.lru_cache()
  107. def get_parent_state(cls) -> Optional[Type[State]]:
  108. """Get the parent state.
  109. Returns:
  110. The parent state.
  111. """
  112. parent_states = [
  113. base
  114. for base in cls.__bases__
  115. if utils._issubclass(base, State) and base is not State
  116. ]
  117. assert len(parent_states) < 2, "Only one parent state is allowed."
  118. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  119. @classmethod
  120. @functools.lru_cache()
  121. def get_substates(cls) -> Set[Type[State]]:
  122. """Get the substates of the state.
  123. Returns:
  124. The substates of the state.
  125. """
  126. return {subclass for subclass in cls.__subclasses__()}
  127. @classmethod
  128. @functools.lru_cache()
  129. def get_name(cls) -> str:
  130. """Get the name of the state.
  131. Returns:
  132. The name of the state.
  133. """
  134. return utils.to_snake_case(cls.__name__)
  135. @classmethod
  136. @functools.lru_cache()
  137. def get_full_name(cls) -> str:
  138. """Get the full name of the state.
  139. Returns:
  140. The full name of the state.
  141. """
  142. name = cls.get_name()
  143. parent_state = cls.get_parent_state()
  144. if parent_state is not None:
  145. name = ".".join((parent_state.get_full_name(), name))
  146. return name
  147. @classmethod
  148. @functools.lru_cache()
  149. def get_class_substate(cls, path: Sequence[str]) -> Type[State]:
  150. """Get the class substate.
  151. Args:
  152. path: The path to the substate.
  153. Returns:
  154. The class substate.
  155. Raises:
  156. ValueError: If the substate is not found.
  157. """
  158. if len(path) == 0:
  159. return cls
  160. if path[0] == cls.get_name():
  161. if len(path) == 1:
  162. return cls
  163. path = path[1:]
  164. for substate in cls.get_substates():
  165. if path[0] == substate.get_name():
  166. return substate.get_class_substate(path[1:])
  167. raise ValueError(f"Invalid path: {path}")
  168. @classmethod
  169. def get_class_var(cls, path: Sequence[str]) -> Any:
  170. """Get the class var.
  171. Args:
  172. path: The path to the var.
  173. Returns:
  174. The class var.
  175. Raises:
  176. ValueError: If the path is invalid.
  177. """
  178. path, name = path[:-1], path[-1]
  179. substate = cls.get_class_substate(tuple(path))
  180. if not hasattr(substate, name):
  181. raise ValueError(f"Invalid path: {path}")
  182. return getattr(substate, name)
  183. @classmethod
  184. def _set_var(cls, prop: BaseVar):
  185. """Set the var as a class member.
  186. Args:
  187. prop: The var instance to set.
  188. """
  189. setattr(cls, prop.name, prop)
  190. @classmethod
  191. def _create_setter(cls, prop: BaseVar):
  192. """Create a setter for the var.
  193. Args:
  194. prop: The var to create a setter for.
  195. """
  196. setter_name = prop.get_setter_name(include_state=False)
  197. if setter_name not in cls.__dict__:
  198. setattr(cls, setter_name, prop.get_setter())
  199. @classmethod
  200. def _set_default_value(cls, prop: BaseVar):
  201. """Set the default value for the var.
  202. Args:
  203. prop: The var to set the default value for.
  204. """
  205. # Get the pydantic field for the var.
  206. field = cls.get_fields()[prop.name]
  207. default_value = prop.get_default_value()
  208. if field.required and default_value is not None:
  209. field.required = False
  210. field.default = default_value
  211. def __getattribute__(self, name: str) -> Any:
  212. """Get the attribute.
  213. Args:
  214. name: The name of the attribute.
  215. Returns:
  216. The attribute.
  217. Raises:
  218. Exception: If the attribute is not found.
  219. """
  220. # If it is an inherited var, return from the parent state.
  221. if name != "inherited_vars" and name in self.inherited_vars:
  222. return getattr(self.parent_state, name)
  223. try:
  224. return super().__getattribute__(name)
  225. except Exception as e:
  226. # Check if the attribute is a substate.
  227. if name in self.substates:
  228. return self.substates[name]
  229. raise e
  230. def __setattr__(self, name: str, value: Any):
  231. """Set the attribute.
  232. Args:
  233. name: The name of the attribute.
  234. value: The value of the attribute.
  235. """
  236. if name != "inherited_vars" and name in self.inherited_vars:
  237. setattr(self.parent_state, name, value)
  238. return
  239. # Set the attribute.
  240. super().__setattr__(name, value)
  241. # Add the var to the dirty list.
  242. if name in self.vars:
  243. self.dirty_vars.add(name)
  244. self.mark_dirty()
  245. def reset(self):
  246. """Reset all the base vars to their default values."""
  247. # Reset the base vars.
  248. fields = self.get_fields()
  249. for prop_name in self.base_vars:
  250. setattr(self, prop_name, fields[prop_name].default)
  251. # Recursively reset the substates.
  252. for substate in self.substates.values():
  253. substate.reset()
  254. # Clean the state.
  255. self.clean()
  256. def get_substate(self, path: Sequence[str]) -> Optional[State]:
  257. """Get the substate.
  258. Args:
  259. path: The path to the substate.
  260. Returns:
  261. The substate.
  262. Raises:
  263. ValueError: If the substate is not found.
  264. """
  265. if len(path) == 0:
  266. return self
  267. if path[0] == self.get_name():
  268. if len(path) == 1:
  269. return self
  270. path = path[1:]
  271. if path[0] not in self.substates:
  272. raise ValueError(f"Invalid path: {path}")
  273. return self.substates[path[0]].get_substate(path[1:])
  274. async def process(self, event: Event) -> StateUpdate:
  275. """Process an event.
  276. Args:
  277. event: The event to process.
  278. Returns:
  279. The state update after processing the event.
  280. """
  281. # Get the event handler.
  282. path = event.name.split(".")
  283. path, name = path[:-1], path[-1]
  284. substate = self.get_substate(path)
  285. handler = getattr(substate, name)
  286. # Process the event.
  287. fn = functools.partial(handler.fn, substate)
  288. try:
  289. if asyncio.iscoroutinefunction(fn.func):
  290. events = await fn(**event.payload)
  291. else:
  292. events = fn(**event.payload)
  293. except:
  294. error = traceback.format_exc()
  295. print(error)
  296. return StateUpdate(
  297. events=[window_alert("An error occurred. See logs for details.")]
  298. )
  299. # Fix the returned events.
  300. events = utils.fix_events(events, event.token)
  301. # Get the delta after processing the event.
  302. delta = self.get_delta()
  303. # Reset the dirty vars.
  304. self.clean()
  305. # Return the state update.
  306. return StateUpdate(delta=delta, events=events)
  307. def get_delta(self) -> Delta:
  308. """Get the delta for the state.
  309. Returns:
  310. The delta for the state.
  311. """
  312. delta = {}
  313. # Return the dirty vars, as well as all computed vars.
  314. subdelta = {
  315. prop: getattr(self, prop)
  316. for prop in self.dirty_vars | set(self.computed_vars.keys())
  317. }
  318. if len(subdelta) > 0:
  319. delta[self.get_full_name()] = subdelta
  320. # Recursively find the substate deltas.
  321. for substate in self.dirty_substates:
  322. delta.update(self.substates[substate].get_delta())
  323. # Format the delta.
  324. delta = utils.format_state(delta)
  325. # Return the delta.
  326. return delta
  327. def mark_dirty(self):
  328. """Mark the substate and all parent states as dirty."""
  329. if self.parent_state is not None:
  330. self.parent_state.dirty_substates.add(self.get_name())
  331. self.parent_state.mark_dirty()
  332. def clean(self):
  333. """Reset the dirty vars."""
  334. # Recursively clean the substates.
  335. for substate in self.dirty_substates:
  336. self.substates[substate].clean()
  337. # Clean this state.
  338. self.dirty_vars = set()
  339. self.dirty_substates = set()
  340. def dict(self, include_computed: bool = True, **kwargs) -> Dict[str, Any]:
  341. """Convert the object to a dictionary.
  342. Args:
  343. include_computed: Whether to include computed vars.
  344. **kwargs: Kwargs to pass to the pydantic dict method.
  345. Returns:
  346. The object as a dictionary.
  347. """
  348. base_vars = {
  349. prop_name: self.get_value(getattr(self, prop_name))
  350. for prop_name in self.base_vars
  351. }
  352. computed_vars = (
  353. {
  354. # Include the computed vars.
  355. prop_name: self.get_value(getattr(self, prop_name))
  356. for prop_name in self.computed_vars
  357. }
  358. if include_computed
  359. else {}
  360. )
  361. substate_vars = {
  362. k: v.dict(include_computed=include_computed, **kwargs)
  363. for k, v in self.substates.items()
  364. }
  365. vars = {**base_vars, **computed_vars, **substate_vars}
  366. return {k: vars[k] for k in sorted(vars)}
  367. class DefaultState(State):
  368. """The default empty state."""
  369. pass
  370. class StateUpdate(Base):
  371. """A state update sent to the frontend."""
  372. # The state delta.
  373. delta: Delta = {}
  374. # Events to be added to the event queue.
  375. events: List[Event] = []
  376. class StateManager(Base):
  377. """A class to manage many client states."""
  378. # The state class to use.
  379. state: Type[State] = DefaultState
  380. # The mapping of client ids to states.
  381. states: Dict[str, State] = {}
  382. # The token expiration time (s).
  383. token_expiration: int = constants.TOKEN_EXPIRATION
  384. # The redis client to use.
  385. redis: Optional[Redis] = None
  386. def setup(self, state: Type[State]):
  387. """Set up the state manager.
  388. Args:
  389. state: The state class to use.
  390. """
  391. self.state = state
  392. self.redis = utils.get_redis()
  393. def get_state(self, token: str) -> State:
  394. """Get the state for a token.
  395. Args:
  396. token: The token to get the state for.
  397. Returns:
  398. The state for the token.
  399. """
  400. if self.redis is not None:
  401. redis_state = self.redis.get(token)
  402. if redis_state is None:
  403. self.set_state(token, self.state())
  404. return self.get_state(token)
  405. return pickle.loads(redis_state)
  406. if token not in self.states:
  407. self.states[token] = self.state()
  408. return self.states[token]
  409. def set_state(self, token: str, state: State):
  410. """Set the state for a token.
  411. Args:
  412. token: The token to set the state for.
  413. state: The state to set.
  414. """
  415. if self.redis is None:
  416. return
  417. self.redis.set(token, pickle.dumps(state), ex=self.token_expiration)