state.py 17 KB

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