state.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. """Define the pynecone state specification."""
  2. from __future__ import annotations
  3. import asyncio
  4. import copy
  5. import functools
  6. import inspect
  7. import traceback
  8. from abc import ABC
  9. from collections import defaultdict
  10. from typing import (
  11. Any,
  12. AsyncIterator,
  13. Callable,
  14. ClassVar,
  15. Dict,
  16. List,
  17. Optional,
  18. Sequence,
  19. Set,
  20. Type,
  21. Union,
  22. )
  23. import cloudpickle
  24. import pydantic
  25. from redis import Redis
  26. from pynecone import constants
  27. from pynecone.base import Base
  28. from pynecone.event import Event, EventHandler, EventSpec, fix_events, window_alert
  29. from pynecone.utils import format, prerequisites, types
  30. from pynecone.vars import BaseVar, ComputedVar, PCDict, PCList, Var
  31. Delta = Dict[str, Any]
  32. class State(Base, ABC, extra=pydantic.Extra.allow):
  33. """The state of the app."""
  34. # A map from the var name to the var.
  35. vars: ClassVar[Dict[str, Var]] = {}
  36. # The base vars of the class.
  37. base_vars: ClassVar[Dict[str, BaseVar]] = {}
  38. # The computed vars of the class.
  39. computed_vars: ClassVar[Dict[str, ComputedVar]] = {}
  40. # Vars inherited by the parent state.
  41. inherited_vars: ClassVar[Dict[str, Var]] = {}
  42. # Backend vars that are never sent to the client.
  43. backend_vars: ClassVar[Dict[str, Any]] = {}
  44. # Backend vars inherited
  45. inherited_backend_vars: ClassVar[Dict[str, Any]] = {}
  46. # The event handlers.
  47. event_handlers: ClassVar[Dict[str, EventHandler]] = {}
  48. # The parent state.
  49. parent_state: Optional[State] = None
  50. # The substates of the state.
  51. substates: Dict[str, State] = {}
  52. # The set of dirty vars.
  53. dirty_vars: Set[str] = set()
  54. # The set of dirty substates.
  55. dirty_substates: Set[str] = set()
  56. # The routing path that triggered the state
  57. router_data: Dict[str, Any] = {}
  58. # Mapping of var name to set of computed variables that depend on it
  59. computed_var_dependencies: Dict[str, Set[str]] = {}
  60. # Mapping of var name to set of substates that depend on it
  61. substate_var_dependencies: Dict[str, Set[str]] = {}
  62. # Per-instance copy of backend variable values
  63. _backend_vars: Dict[str, Any] = {}
  64. def __init__(self, *args, parent_state: Optional[State] = None, **kwargs):
  65. """Initialize the state.
  66. Args:
  67. *args: The args to pass to the Pydantic init method.
  68. parent_state: The parent state.
  69. **kwargs: The kwargs to pass to the Pydantic init method.
  70. """
  71. kwargs["parent_state"] = parent_state
  72. super().__init__(*args, **kwargs)
  73. # initialize per-instance var dependency tracking
  74. self.computed_var_dependencies = defaultdict(set)
  75. self.substate_var_dependencies = defaultdict(set)
  76. # Setup the substates.
  77. for substate in self.get_substates():
  78. self.substates[substate.get_name()] = substate(parent_state=self)
  79. # Convert the event handlers to functions.
  80. for name, event_handler in self.event_handlers.items():
  81. fn = functools.partial(event_handler.fn, self)
  82. fn.__module__ = event_handler.fn.__module__ # type: ignore
  83. fn.__qualname__ = event_handler.fn.__qualname__ # type: ignore
  84. setattr(self, name, fn)
  85. # Initialize computed vars dependencies.
  86. inherited_vars = set(self.inherited_vars).union(
  87. set(self.inherited_backend_vars),
  88. )
  89. for cvar_name, cvar in self.computed_vars.items():
  90. # Add the dependencies.
  91. for var in cvar.deps(objclass=type(self)):
  92. self.computed_var_dependencies[var].add(cvar_name)
  93. if var in inherited_vars:
  94. # track that this substate depends on its parent for this var
  95. state_name = self.get_name()
  96. parent_state = self.parent_state
  97. while parent_state is not None and var in parent_state.vars:
  98. parent_state.substate_var_dependencies[var].add(state_name)
  99. state_name, parent_state = (
  100. parent_state.get_name(),
  101. parent_state.parent_state,
  102. )
  103. # Initialize the mutable fields.
  104. self._init_mutable_fields()
  105. # Create a fresh copy of the backend variables for this instance
  106. self._backend_vars = copy.deepcopy(self.backend_vars)
  107. def _init_mutable_fields(self):
  108. """Initialize mutable fields.
  109. So that mutation to them can be detected by the app:
  110. * list
  111. """
  112. for field in self.base_vars.values():
  113. value = getattr(self, field.name)
  114. value_in_pc_data = _convert_mutable_datatypes(
  115. value, self._reassign_field, field.name
  116. )
  117. if types._issubclass(field.type_, Union[List, Dict]):
  118. setattr(self, field.name, value_in_pc_data)
  119. self.clean()
  120. def _reassign_field(self, field_name: str):
  121. """Reassign the given field.
  122. Primarily for mutation in fields of mutable data types.
  123. Args:
  124. field_name: The name of the field we want to reassign
  125. """
  126. setattr(
  127. self,
  128. field_name,
  129. getattr(self, field_name),
  130. )
  131. def __repr__(self) -> str:
  132. """Get the string representation of the state.
  133. Returns:
  134. The string representation of the state.
  135. """
  136. return f"{self.__class__.__name__}({self.dict()})"
  137. @classmethod
  138. def __init_subclass__(cls, **kwargs):
  139. """Do some magic for the subclass initialization.
  140. Args:
  141. **kwargs: The kwargs to pass to the pydantic init_subclass method.
  142. """
  143. super().__init_subclass__(**kwargs)
  144. # Get the parent vars.
  145. parent_state = cls.get_parent_state()
  146. if parent_state is not None:
  147. cls.inherited_vars = parent_state.vars
  148. cls.inherited_backend_vars = parent_state.backend_vars
  149. cls.new_backend_vars = {
  150. name: value
  151. for name, value in cls.__dict__.items()
  152. if types.is_backend_variable(name)
  153. and name not in cls.inherited_backend_vars
  154. }
  155. cls.backend_vars = {**cls.inherited_backend_vars, **cls.new_backend_vars}
  156. # Set the base and computed vars.
  157. cls.base_vars = {
  158. f.name: BaseVar(name=f.name, type_=f.outer_type_).set_state(cls)
  159. for f in cls.get_fields().values()
  160. if f.name not in cls.get_skip_vars()
  161. }
  162. cls.computed_vars = {
  163. v.name: v.set_state(cls)
  164. for v in cls.__dict__.values()
  165. if isinstance(v, ComputedVar)
  166. }
  167. cls.vars = {
  168. **cls.inherited_vars,
  169. **cls.base_vars,
  170. **cls.computed_vars,
  171. }
  172. cls.event_handlers = {}
  173. # Setup the base vars at the class level.
  174. for prop in cls.base_vars.values():
  175. cls._init_var(prop)
  176. # Set up the event handlers.
  177. events = {
  178. name: fn
  179. for name, fn in cls.__dict__.items()
  180. if not name.startswith("_")
  181. and isinstance(fn, Callable)
  182. and not isinstance(fn, EventHandler)
  183. }
  184. for name, fn in events.items():
  185. handler = EventHandler(fn=fn)
  186. cls.event_handlers[name] = handler
  187. setattr(cls, name, handler)
  188. @classmethod
  189. def get_skip_vars(cls) -> Set[str]:
  190. """Get the vars to skip when serializing.
  191. Returns:
  192. The vars to skip when serializing.
  193. """
  194. return set(cls.inherited_vars) | {
  195. "parent_state",
  196. "substates",
  197. "dirty_vars",
  198. "dirty_substates",
  199. "router_data",
  200. "computed_var_dependencies",
  201. "substate_var_dependencies",
  202. "_backend_vars",
  203. }
  204. @classmethod
  205. @functools.lru_cache()
  206. def get_parent_state(cls) -> Optional[Type[State]]:
  207. """Get the parent state.
  208. Returns:
  209. The parent state.
  210. """
  211. parent_states = [
  212. base
  213. for base in cls.__bases__
  214. if types._issubclass(base, State) and base is not State
  215. ]
  216. assert len(parent_states) < 2, "Only one parent state is allowed."
  217. return parent_states[0] if len(parent_states) == 1 else None # type: ignore
  218. @classmethod
  219. @functools.lru_cache()
  220. def get_substates(cls) -> Set[Type[State]]:
  221. """Get the substates of the state.
  222. Returns:
  223. The substates of the state.
  224. """
  225. return set(cls.__subclasses__())
  226. @classmethod
  227. @functools.lru_cache()
  228. def get_name(cls) -> str:
  229. """Get the name of the state.
  230. Returns:
  231. The name of the state.
  232. """
  233. return format.to_snake_case(cls.__name__)
  234. @classmethod
  235. @functools.lru_cache()
  236. def get_full_name(cls) -> str:
  237. """Get the full name of the state.
  238. Returns:
  239. The full name of the state.
  240. """
  241. name = cls.get_name()
  242. parent_state = cls.get_parent_state()
  243. if parent_state is not None:
  244. name = ".".join((parent_state.get_full_name(), name))
  245. return name
  246. @classmethod
  247. @functools.lru_cache()
  248. def get_class_substate(cls, path: Sequence[str]) -> Type[State]:
  249. """Get the class substate.
  250. Args:
  251. path: The path to the substate.
  252. Returns:
  253. The class substate.
  254. Raises:
  255. ValueError: If the substate is not found.
  256. """
  257. if len(path) == 0:
  258. return cls
  259. if path[0] == cls.get_name():
  260. if len(path) == 1:
  261. return cls
  262. path = path[1:]
  263. for substate in cls.get_substates():
  264. if path[0] == substate.get_name():
  265. return substate.get_class_substate(path[1:])
  266. raise ValueError(f"Invalid path: {path}")
  267. @classmethod
  268. def get_class_var(cls, path: Sequence[str]) -> Any:
  269. """Get the class var.
  270. Args:
  271. path: The path to the var.
  272. Returns:
  273. The class var.
  274. Raises:
  275. ValueError: If the path is invalid.
  276. """
  277. path, name = path[:-1], path[-1]
  278. substate = cls.get_class_substate(tuple(path))
  279. if not hasattr(substate, name):
  280. raise ValueError(f"Invalid path: {path}")
  281. return getattr(substate, name)
  282. @classmethod
  283. def _init_var(cls, prop: BaseVar):
  284. """Initialize a variable.
  285. Args:
  286. prop (BaseVar): The variable to initialize
  287. Raises:
  288. TypeError: if the variable has an incorrect type
  289. """
  290. if not types.is_valid_var_type(prop.type_):
  291. raise TypeError(
  292. "State vars must be primitive Python types, "
  293. "Plotly figures, Pandas dataframes, "
  294. "or subclasses of pc.Base. "
  295. f'Found var "{prop.name}" with type {prop.type_}.'
  296. )
  297. cls._set_var(prop)
  298. cls._create_setter(prop)
  299. cls._set_default_value(prop)
  300. @classmethod
  301. def add_var(cls, name: str, type_: Any, default_value: Any = None):
  302. """Add dynamically a variable to the State.
  303. The variable added this way can be used in the same way as a variable
  304. defined statically in the model.
  305. Args:
  306. name: The name of the variable
  307. type_: The type of the variable
  308. default_value: The default value of the variable
  309. Raises:
  310. NameError: if a variable of this name already exists
  311. """
  312. if name in cls.__fields__:
  313. raise NameError(
  314. f"The variable '{name}' already exist. Use a different name"
  315. )
  316. # create the variable based on name and type
  317. var = BaseVar(name=name, type_=type_)
  318. var.set_state(cls)
  319. # add the pydantic field dynamically (must be done before _init_var)
  320. cls.add_field(var, default_value)
  321. cls._init_var(var)
  322. # update the internal dicts so the new variable is correctly handled
  323. cls.base_vars.update({name: var})
  324. cls.vars.update({name: var})
  325. # let substates know about the new variable
  326. for substate_class in cls.__subclasses__():
  327. substate_class.vars.setdefault(name, var)
  328. @classmethod
  329. def _set_var(cls, prop: BaseVar):
  330. """Set the var as a class member.
  331. Args:
  332. prop: The var instance to set.
  333. """
  334. setattr(cls, prop.name, prop)
  335. @classmethod
  336. def _create_setter(cls, prop: BaseVar):
  337. """Create a setter for the var.
  338. Args:
  339. prop: The var to create a setter for.
  340. """
  341. setter_name = prop.get_setter_name(include_state=False)
  342. if setter_name not in cls.__dict__:
  343. event_handler = EventHandler(fn=prop.get_setter())
  344. cls.event_handlers[setter_name] = event_handler
  345. setattr(cls, setter_name, event_handler)
  346. @classmethod
  347. def _set_default_value(cls, prop: BaseVar):
  348. """Set the default value for the var.
  349. Args:
  350. prop: The var to set the default value for.
  351. """
  352. # Get the pydantic field for the var.
  353. field = cls.get_fields()[prop.name]
  354. default_value = prop.get_default_value()
  355. if field.required and default_value is not None:
  356. field.required = False
  357. field.default = default_value
  358. def get_token(self) -> str:
  359. """Return the token of the client associated with this state.
  360. Returns:
  361. The token of the client.
  362. """
  363. return self.router_data.get(constants.RouteVar.CLIENT_TOKEN, "")
  364. def get_sid(self) -> str:
  365. """Return the session ID of the client associated with this state.
  366. Returns:
  367. The session ID of the client.
  368. """
  369. return self.router_data.get(constants.RouteVar.SESSION_ID, "")
  370. def get_headers(self) -> Dict:
  371. """Return the headers of the client associated with this state.
  372. Returns:
  373. The headers of the client.
  374. """
  375. return self.router_data.get(constants.RouteVar.HEADERS, {})
  376. def get_client_ip(self) -> str:
  377. """Return the IP of the client associated with this state.
  378. Returns:
  379. The IP of the client.
  380. """
  381. return self.router_data.get(constants.RouteVar.CLIENT_IP, "")
  382. def get_current_page(self) -> str:
  383. """Obtain the path of current page from the router data.
  384. Returns:
  385. The current page.
  386. """
  387. return self.router_data.get(constants.RouteVar.PATH, "")
  388. def get_query_params(self) -> Dict[str, str]:
  389. """Obtain the query parameters for the queried page.
  390. The query object contains both the URI parameters and the GET parameters.
  391. Returns:
  392. The dict of query parameters.
  393. """
  394. return self.router_data.get(constants.RouteVar.QUERY, {})
  395. @classmethod
  396. def setup_dynamic_args(cls, args: dict[str, str]):
  397. """Set up args for easy access in renderer.
  398. Args:
  399. args: a dict of args
  400. """
  401. def argsingle_factory(param):
  402. @ComputedVar
  403. def inner_func(self) -> str:
  404. return self.get_query_params().get(param, "")
  405. return inner_func
  406. def arglist_factory(param):
  407. @ComputedVar
  408. def inner_func(self) -> List:
  409. return self.get_query_params().get(param, [])
  410. return inner_func
  411. for param, value in args.items():
  412. if value == constants.RouteArgType.SINGLE:
  413. func = argsingle_factory(param)
  414. elif value == constants.RouteArgType.LIST:
  415. func = arglist_factory(param)
  416. else:
  417. continue
  418. func.fget.__name__ = param # to allow passing as a prop
  419. cls.vars[param] = cls.computed_vars[param] = func.set_state(cls) # type: ignore
  420. setattr(cls, param, func)
  421. def __getattribute__(self, name: str) -> Any:
  422. """Get the state var.
  423. If the var is inherited, get the var from the parent state.
  424. Args:
  425. name: The name of the var.
  426. Returns:
  427. The value of the var.
  428. """
  429. # If the state hasn't been initialized yet, return the default value.
  430. if not super().__getattribute__("__dict__"):
  431. return super().__getattribute__(name)
  432. inherited_vars = {
  433. **super().__getattribute__("inherited_vars"),
  434. **super().__getattribute__("inherited_backend_vars"),
  435. }
  436. if name in inherited_vars:
  437. return getattr(super().__getattribute__("parent_state"), name)
  438. elif name in super().__getattribute__("_backend_vars"):
  439. return super().__getattribute__("_backend_vars").__getitem__(name)
  440. return super().__getattribute__(name)
  441. def __setattr__(self, name: str, value: Any):
  442. """Set the attribute.
  443. If the attribute is inherited, set the attribute on the parent state.
  444. Args:
  445. name: The name of the attribute.
  446. value: The value of the attribute.
  447. """
  448. # Set the var on the parent state.
  449. inherited_vars = {**self.inherited_vars, **self.inherited_backend_vars}
  450. if name in inherited_vars:
  451. setattr(self.parent_state, name, value)
  452. return
  453. if types.is_backend_variable(name) and name != "_backend_vars":
  454. self._backend_vars.__setitem__(name, value)
  455. self.dirty_vars.add(name)
  456. self.mark_dirty()
  457. return
  458. # Set the attribute.
  459. super().__setattr__(name, value)
  460. # Add the var to the dirty list.
  461. if name in self.vars or name in self.computed_var_dependencies:
  462. self.dirty_vars.add(name)
  463. self.mark_dirty()
  464. # For now, handle router_data updates as a special case
  465. if name == constants.ROUTER_DATA:
  466. self.dirty_vars.add(name)
  467. self.mark_dirty()
  468. # propagate router_data updates down the state tree
  469. for substate in self.substates.values():
  470. setattr(substate, name, value)
  471. def reset(self):
  472. """Reset all the base vars to their default values."""
  473. # Reset the base vars.
  474. fields = self.get_fields()
  475. for prop_name in self.base_vars:
  476. setattr(self, prop_name, fields[prop_name].default)
  477. # Recursively reset the substates.
  478. for substate in self.substates.values():
  479. substate.reset()
  480. # Clean the state.
  481. self.clean()
  482. def get_substate(self, path: Sequence[str]) -> Optional[State]:
  483. """Get the substate.
  484. Args:
  485. path: The path to the substate.
  486. Returns:
  487. The substate.
  488. Raises:
  489. ValueError: If the substate is not found.
  490. """
  491. if len(path) == 0:
  492. return self
  493. if path[0] == self.get_name():
  494. if len(path) == 1:
  495. return self
  496. path = path[1:]
  497. if path[0] not in self.substates:
  498. raise ValueError(f"Invalid path: {path}")
  499. return self.substates[path[0]].get_substate(path[1:])
  500. async def _process(self, event: Event) -> AsyncIterator[StateUpdate]:
  501. """Obtain event info and process event.
  502. Args:
  503. event: The event to process.
  504. Yields:
  505. The state update after processing the event.
  506. Raises:
  507. ValueError: If the state value is None.
  508. """
  509. # Get the event handler.
  510. path = event.name.split(".")
  511. path, name = path[:-1], path[-1]
  512. substate = self.get_substate(path)
  513. handler = substate.event_handlers[name] # type: ignore
  514. if not substate:
  515. raise ValueError(
  516. "The value of state cannot be None when processing an event."
  517. )
  518. # Get the event generator.
  519. event_iter = self._process_event(
  520. handler=handler,
  521. state=substate,
  522. payload=event.payload,
  523. )
  524. # Clean the state before processing the event.
  525. self.clean()
  526. # Run the event generator and return state updates.
  527. async for events in event_iter:
  528. # Fix the returned events.
  529. events = fix_events(events, event.token) # type: ignore
  530. # Get the delta after processing the event.
  531. delta = self.get_delta()
  532. # Yield the state update.
  533. yield StateUpdate(delta=delta, events=events)
  534. # Clean the state to prepare for the next event.
  535. self.clean()
  536. async def _process_event(
  537. self, handler: EventHandler, state: State, payload: Dict
  538. ) -> AsyncIterator[Optional[List[EventSpec]]]:
  539. """Process event.
  540. Args:
  541. handler: Eventhandler to process.
  542. state: State to process the handler.
  543. payload: The event payload.
  544. Yields:
  545. The state update after processing the event.
  546. """
  547. # Get the function to process the event.
  548. fn = functools.partial(handler.fn, state)
  549. # Wrap the function in a try/except block.
  550. try:
  551. # Handle async functions.
  552. if asyncio.iscoroutinefunction(fn.func):
  553. events = await fn(**payload)
  554. # Handle regular functions.
  555. else:
  556. events = fn(**payload)
  557. # Handle async generators.
  558. if inspect.isasyncgen(events):
  559. async for event in events:
  560. yield event
  561. # Handle regular generators.
  562. elif inspect.isgenerator(events):
  563. for event in events:
  564. yield event
  565. # Handle regular event chains.
  566. else:
  567. yield events
  568. # If an error occurs, throw a window alert.
  569. except Exception:
  570. error = traceback.format_exc()
  571. print(error)
  572. yield [window_alert("An error occurred. See logs for details.")]
  573. def _always_dirty_computed_vars(self) -> Set[str]:
  574. """The set of ComputedVars that always need to be recalculated.
  575. Returns:
  576. Set of all ComputedVar in this state where cache=False
  577. """
  578. return set(
  579. cvar_name
  580. for cvar_name, cvar in self.computed_vars.items()
  581. if not cvar.cache
  582. )
  583. def _mark_dirty_computed_vars(self) -> None:
  584. """Mark ComputedVars that need to be recalculated based on dirty_vars."""
  585. dirty_vars = self.dirty_vars
  586. while dirty_vars:
  587. calc_vars, dirty_vars = dirty_vars, set()
  588. for cvar in self._dirty_computed_vars(from_vars=calc_vars):
  589. self.dirty_vars.add(cvar)
  590. dirty_vars.add(cvar)
  591. actual_var = self.computed_vars.get(cvar)
  592. if actual_var:
  593. actual_var.mark_dirty(instance=self)
  594. def _dirty_computed_vars(self, from_vars: Optional[Set[str]] = None) -> Set[str]:
  595. """Determine ComputedVars that need to be recalculated based on the given vars.
  596. Args:
  597. from_vars: find ComputedVar that depend on this set of vars. If unspecified, will use the dirty_vars.
  598. Returns:
  599. Set of computed vars to include in the delta.
  600. """
  601. return set(
  602. cvar
  603. for dirty_var in from_vars or self.dirty_vars
  604. for cvar in self.computed_var_dependencies[dirty_var]
  605. )
  606. def get_delta(self) -> Delta:
  607. """Get the delta for the state.
  608. Returns:
  609. The delta for the state.
  610. """
  611. delta = {}
  612. # Apply dirty variables down into substates
  613. self.dirty_vars.update(self._always_dirty_computed_vars())
  614. self.mark_dirty()
  615. # Return the dirty vars for this instance, any cached/dependent computed vars,
  616. # and always dirty computed vars (cache=False)
  617. delta_vars = (
  618. self.dirty_vars.intersection(self.base_vars)
  619. .union(self._dirty_computed_vars())
  620. .union(self._always_dirty_computed_vars())
  621. )
  622. subdelta = {
  623. prop: getattr(self, prop)
  624. for prop in delta_vars
  625. if not types.is_backend_variable(prop)
  626. }
  627. if len(subdelta) > 0:
  628. delta[self.get_full_name()] = subdelta
  629. # Recursively find the substate deltas.
  630. substates = self.substates
  631. for substate in self.dirty_substates:
  632. delta.update(substates[substate].get_delta())
  633. # Format the delta.
  634. delta = format.format_state(delta)
  635. # Return the delta.
  636. return delta
  637. def mark_dirty(self):
  638. """Mark the substate and all parent states as dirty."""
  639. state_name = self.get_name()
  640. if (
  641. self.parent_state is not None
  642. and state_name not in self.parent_state.dirty_substates
  643. ):
  644. self.parent_state.dirty_substates.add(self.get_name())
  645. self.parent_state.mark_dirty()
  646. # have to mark computed vars dirty to allow access to newly computed
  647. # values within the same ComputedVar function
  648. self._mark_dirty_computed_vars()
  649. # Propagate dirty var / computed var status into substates
  650. substates = self.substates
  651. for var in self.dirty_vars:
  652. for substate_name in self.substate_var_dependencies[var]:
  653. self.dirty_substates.add(substate_name)
  654. substate = substates[substate_name]
  655. substate.dirty_vars.add(var)
  656. substate.mark_dirty()
  657. def clean(self):
  658. """Reset the dirty vars."""
  659. # Recursively clean the substates.
  660. for substate in self.dirty_substates:
  661. self.substates[substate].clean()
  662. # Clean this state.
  663. self.dirty_vars = set()
  664. self.dirty_substates = set()
  665. def dict(self, include_computed: bool = True, **kwargs) -> Dict[str, Any]:
  666. """Convert the object to a dictionary.
  667. Args:
  668. include_computed: Whether to include computed vars.
  669. **kwargs: Kwargs to pass to the pydantic dict method.
  670. Returns:
  671. The object as a dictionary.
  672. """
  673. if include_computed:
  674. # Apply dirty variables down into substates to allow never-cached ComputedVar to
  675. # trigger recalculation of dependent vars
  676. self.dirty_vars.update(self._always_dirty_computed_vars())
  677. self.mark_dirty()
  678. base_vars = {
  679. prop_name: self.get_value(getattr(self, prop_name))
  680. for prop_name in self.base_vars
  681. }
  682. computed_vars = (
  683. {
  684. # Include the computed vars.
  685. prop_name: self.get_value(getattr(self, prop_name))
  686. for prop_name in self.computed_vars
  687. }
  688. if include_computed
  689. else {}
  690. )
  691. substate_vars = {
  692. k: v.dict(include_computed=include_computed, **kwargs)
  693. for k, v in self.substates.items()
  694. }
  695. variables = {**base_vars, **computed_vars, **substate_vars}
  696. return {k: variables[k] for k in sorted(variables)}
  697. class DefaultState(State):
  698. """The default empty state."""
  699. pass
  700. class StateUpdate(Base):
  701. """A state update sent to the frontend."""
  702. # The state delta.
  703. delta: Delta = {}
  704. # Events to be added to the event queue.
  705. events: List[Event] = []
  706. class StateManager(Base):
  707. """A class to manage many client states."""
  708. # The state class to use.
  709. state: Type[State] = DefaultState
  710. # The mapping of client ids to states.
  711. states: Dict[str, State] = {}
  712. # The token expiration time (s).
  713. token_expiration: int = constants.TOKEN_EXPIRATION
  714. # The redis client to use.
  715. redis: Optional[Redis] = None
  716. def setup(self, state: Type[State]):
  717. """Set up the state manager.
  718. Args:
  719. state: The state class to use.
  720. """
  721. self.state = state
  722. self.redis = prerequisites.get_redis()
  723. def get_state(self, token: str) -> State:
  724. """Get the state for a token.
  725. Args:
  726. token: The token to get the state for.
  727. Returns:
  728. The state for the token.
  729. """
  730. if self.redis is not None:
  731. redis_state = self.redis.get(token)
  732. if redis_state is None:
  733. self.set_state(token, self.state())
  734. return self.get_state(token)
  735. return cloudpickle.loads(redis_state)
  736. if token not in self.states:
  737. self.states[token] = self.state()
  738. return self.states[token]
  739. def set_state(self, token: str, state: State):
  740. """Set the state for a token.
  741. Args:
  742. token: The token to set the state for.
  743. state: The state to set.
  744. """
  745. if self.redis is None:
  746. return
  747. self.redis.set(token, cloudpickle.dumps(state), ex=self.token_expiration)
  748. def _convert_mutable_datatypes(
  749. field_value: Any, reassign_field: Callable, field_name: str
  750. ) -> Any:
  751. """Recursively convert mutable data to the Pc data types.
  752. Note: right now only list & dict would be handled recursively.
  753. Args:
  754. field_value: The target field_value.
  755. reassign_field:
  756. The function to reassign the field in the parent state.
  757. field_name: the name of the field in the parent state
  758. Returns:
  759. The converted field_value
  760. """
  761. if isinstance(field_value, list):
  762. for index in range(len(field_value)):
  763. field_value[index] = _convert_mutable_datatypes(
  764. field_value[index], reassign_field, field_name
  765. )
  766. field_value = PCList(
  767. field_value, reassign_field=reassign_field, field_name=field_name
  768. )
  769. if isinstance(field_value, dict):
  770. for key, value in field_value.items():
  771. field_value[key] = _convert_mutable_datatypes(
  772. value, reassign_field, field_name
  773. )
  774. field_value = PCDict(
  775. field_value, reassign_field=reassign_field, field_name=field_name
  776. )
  777. return field_value