state.py 14 KB

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