state.py 26 KB

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