state.py 26 KB

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