state.py 26 KB

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