proxy.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. """A module to hold state proxy classes."""
  2. from __future__ import annotations
  3. import asyncio
  4. import copy
  5. import dataclasses
  6. import functools
  7. import inspect
  8. import json
  9. from collections.abc import Callable, Sequence
  10. from types import MethodType
  11. from typing import TYPE_CHECKING, Any, SupportsIndex
  12. import pydantic
  13. import wrapt
  14. from pydantic import BaseModel as BaseModelV2
  15. from pydantic.v1 import BaseModel as BaseModelV1
  16. from sqlalchemy.orm import DeclarativeBase
  17. from reflex.base import Base
  18. from reflex.utils import prerequisites
  19. from reflex.utils.exceptions import ImmutableStateError
  20. from reflex.utils.serializers import serializer
  21. from reflex.vars.base import Var
  22. if TYPE_CHECKING:
  23. from reflex.state import BaseState, StateUpdate
  24. class StateProxy(wrapt.ObjectProxy):
  25. """Proxy of a state instance to control mutability of vars for a background task.
  26. Since a background task runs against a state instance without holding the
  27. state_manager lock for the token, the reference may become stale if the same
  28. state is modified by another event handler.
  29. The proxy object ensures that writes to the state are blocked unless
  30. explicitly entering a context which refreshes the state from state_manager
  31. and holds the lock for the token until exiting the context. After exiting
  32. the context, a StateUpdate may be emitted to the frontend to notify the
  33. client of the state change.
  34. A background task will be passed the `StateProxy` as `self`, so mutability
  35. can be safely performed inside an `async with self` block.
  36. class State(rx.State):
  37. counter: int = 0
  38. @rx.event(background=True)
  39. async def bg_increment(self):
  40. await asyncio.sleep(1)
  41. async with self:
  42. self.counter += 1
  43. """
  44. def __init__(
  45. self,
  46. state_instance: BaseState,
  47. parent_state_proxy: StateProxy | None = None,
  48. ):
  49. """Create a proxy for a state instance.
  50. If `get_state` is used on a StateProxy, the resulting state will be
  51. linked to the given state via parent_state_proxy. The first state in the
  52. chain is the state that initiated the background task.
  53. Args:
  54. state_instance: The state instance to proxy.
  55. parent_state_proxy: The parent state proxy, for linked mutability and context tracking.
  56. """
  57. super().__init__(state_instance)
  58. # compile is not relevant to backend logic
  59. self._self_app = prerequisites.get_and_validate_app().app
  60. self._self_substate_path = tuple(state_instance.get_full_name().split("."))
  61. self._self_actx = None
  62. self._self_mutable = False
  63. self._self_actx_lock = asyncio.Lock()
  64. self._self_actx_lock_holder = None
  65. self._self_parent_state_proxy = parent_state_proxy
  66. def _is_mutable(self) -> bool:
  67. """Check if the state is mutable.
  68. Returns:
  69. Whether the state is mutable.
  70. """
  71. if self._self_parent_state_proxy is not None:
  72. return self._self_parent_state_proxy._is_mutable() or self._self_mutable
  73. return self._self_mutable
  74. async def __aenter__(self) -> StateProxy:
  75. """Enter the async context manager protocol.
  76. Sets mutability to True and enters the `App.modify_state` async context,
  77. which refreshes the state from state_manager and holds the lock for the
  78. given state token until exiting the context.
  79. Background tasks should avoid blocking calls while inside the context.
  80. Returns:
  81. This StateProxy instance in mutable mode.
  82. Raises:
  83. ImmutableStateError: If the state is already mutable.
  84. """
  85. if self._self_parent_state_proxy is not None:
  86. from reflex.state import State
  87. parent_state = (
  88. await self._self_parent_state_proxy.__aenter__()
  89. ).__wrapped__
  90. super().__setattr__(
  91. "__wrapped__",
  92. await parent_state.get_state(
  93. State.get_class_substate(self._self_substate_path)
  94. ),
  95. )
  96. return self
  97. current_task = asyncio.current_task()
  98. if (
  99. self._self_actx_lock.locked()
  100. and current_task == self._self_actx_lock_holder
  101. ):
  102. raise ImmutableStateError(
  103. "The state is already mutable. Do not nest `async with self` blocks."
  104. )
  105. from reflex.state import _substate_key
  106. await self._self_actx_lock.acquire()
  107. self._self_actx_lock_holder = current_task
  108. self._self_actx = self._self_app.modify_state(
  109. token=_substate_key(
  110. self.__wrapped__.router.session.client_token,
  111. self._self_substate_path,
  112. )
  113. )
  114. mutable_state = await self._self_actx.__aenter__()
  115. super().__setattr__(
  116. "__wrapped__", mutable_state.get_substate(self._self_substate_path)
  117. )
  118. self._self_mutable = True
  119. return self
  120. async def __aexit__(self, *exc_info: Any) -> None:
  121. """Exit the async context manager protocol.
  122. Sets proxy mutability to False and persists any state changes.
  123. Args:
  124. exc_info: The exception info tuple.
  125. """
  126. if self._self_parent_state_proxy is not None:
  127. await self._self_parent_state_proxy.__aexit__(*exc_info)
  128. return
  129. if self._self_actx is None:
  130. return
  131. self._self_mutable = False
  132. try:
  133. await self._self_actx.__aexit__(*exc_info)
  134. finally:
  135. self._self_actx_lock_holder = None
  136. self._self_actx_lock.release()
  137. self._self_actx = None
  138. def __enter__(self):
  139. """Enter the regular context manager protocol.
  140. This is not supported for background tasks, and exists only to raise a more useful exception
  141. when the StateProxy is used incorrectly.
  142. Raises:
  143. TypeError: always, because only async contextmanager protocol is supported.
  144. """
  145. raise TypeError("Background task must use `async with self` to modify state.")
  146. def __exit__(self, *exc_info: Any) -> None:
  147. """Exit the regular context manager protocol.
  148. Args:
  149. exc_info: The exception info tuple.
  150. """
  151. pass
  152. def __getattr__(self, name: str) -> Any:
  153. """Get the attribute from the underlying state instance.
  154. Args:
  155. name: The name of the attribute.
  156. Returns:
  157. The value of the attribute.
  158. Raises:
  159. ImmutableStateError: If the state is not in mutable mode.
  160. """
  161. if name in ["substates", "parent_state"] and not self._is_mutable():
  162. raise ImmutableStateError(
  163. "Background task StateProxy is immutable outside of a context "
  164. "manager. Use `async with self` to modify state."
  165. )
  166. value = super().__getattr__(name)
  167. if not name.startswith("_self_") and isinstance(value, MutableProxy):
  168. # ensure mutations to these containers are blocked unless proxy is _mutable
  169. return ImmutableMutableProxy(
  170. wrapped=value.__wrapped__,
  171. state=self,
  172. field_name=value._self_field_name,
  173. )
  174. if isinstance(value, functools.partial) and value.args[0] is self.__wrapped__:
  175. # Rebind event handler to the proxy instance
  176. value = functools.partial(
  177. value.func,
  178. self,
  179. *value.args[1:],
  180. **value.keywords,
  181. )
  182. if isinstance(value, MethodType) and value.__self__ is self.__wrapped__:
  183. # Rebind methods to the proxy instance
  184. value = type(value)(value.__func__, self)
  185. return value
  186. def __setattr__(self, name: str, value: Any) -> None:
  187. """Set the attribute on the underlying state instance.
  188. If the attribute is internal, set it on the proxy instance instead.
  189. Args:
  190. name: The name of the attribute.
  191. value: The value of the attribute.
  192. Raises:
  193. ImmutableStateError: If the state is not in mutable mode.
  194. """
  195. if (
  196. name.startswith("_self_") # wrapper attribute
  197. or self._is_mutable() # lock held
  198. # non-persisted state attribute
  199. or name in self.__wrapped__.get_skip_vars()
  200. ):
  201. super().__setattr__(name, value)
  202. return
  203. raise ImmutableStateError(
  204. "Background task StateProxy is immutable outside of a context "
  205. "manager. Use `async with self` to modify state."
  206. )
  207. def get_substate(self, path: Sequence[str]) -> BaseState:
  208. """Only allow substate access with lock held.
  209. Args:
  210. path: The path to the substate.
  211. Returns:
  212. The substate.
  213. Raises:
  214. ImmutableStateError: If the state is not in mutable mode.
  215. """
  216. if not self._is_mutable():
  217. raise ImmutableStateError(
  218. "Background task StateProxy is immutable outside of a context "
  219. "manager. Use `async with self` to modify state."
  220. )
  221. return self.__wrapped__.get_substate(path)
  222. async def get_state(self, state_cls: type[BaseState]) -> BaseState:
  223. """Get an instance of the state associated with this token.
  224. Args:
  225. state_cls: The class of the state.
  226. Returns:
  227. The state.
  228. Raises:
  229. ImmutableStateError: If the state is not in mutable mode.
  230. """
  231. if not self._is_mutable():
  232. raise ImmutableStateError(
  233. "Background task StateProxy is immutable outside of a context "
  234. "manager. Use `async with self` to modify state."
  235. )
  236. return type(self)(
  237. await self.__wrapped__.get_state(state_cls), parent_state_proxy=self
  238. )
  239. async def _as_state_update(self, *args, **kwargs) -> StateUpdate:
  240. """Temporarily allow mutability to access parent_state.
  241. Args:
  242. *args: The args to pass to the underlying state instance.
  243. **kwargs: The kwargs to pass to the underlying state instance.
  244. Returns:
  245. The state update.
  246. """
  247. original_mutable = self._self_mutable
  248. self._self_mutable = True
  249. try:
  250. return await self.__wrapped__._as_state_update(*args, **kwargs)
  251. finally:
  252. self._self_mutable = original_mutable
  253. class ReadOnlyStateProxy(StateProxy):
  254. """A read-only proxy for a state."""
  255. def __setattr__(self, name: str, value: Any) -> None:
  256. """Prevent setting attributes on the state for read-only proxy.
  257. Args:
  258. name: The attribute name.
  259. value: The attribute value.
  260. Raises:
  261. NotImplementedError: Always raised when trying to set an attribute on proxied state.
  262. """
  263. if name.startswith("_self_"):
  264. # Special case attributes of the proxy itself, not applied to the wrapped object.
  265. super().__setattr__(name, value)
  266. return
  267. raise NotImplementedError("This is a read-only state proxy.")
  268. def mark_dirty(self):
  269. """Mark the state as dirty.
  270. Raises:
  271. NotImplementedError: Always raised when trying to mark the proxied state as dirty.
  272. """
  273. raise NotImplementedError("This is a read-only state proxy.")
  274. class MutableProxy(wrapt.ObjectProxy):
  275. """A proxy for a mutable object that tracks changes."""
  276. # Hint for finding the base class of the proxy.
  277. __base_proxy__ = "MutableProxy"
  278. # Methods on wrapped objects which should mark the state as dirty.
  279. __mark_dirty_attrs__ = {
  280. "add",
  281. "append",
  282. "clear",
  283. "difference_update",
  284. "discard",
  285. "extend",
  286. "insert",
  287. "intersection_update",
  288. "pop",
  289. "popitem",
  290. "remove",
  291. "reverse",
  292. "setdefault",
  293. "sort",
  294. "symmetric_difference_update",
  295. "update",
  296. }
  297. # Methods on wrapped objects might return mutable objects that should be tracked.
  298. __wrap_mutable_attrs__ = {
  299. "get",
  300. "setdefault",
  301. }
  302. # These internal attributes on rx.Base should NOT be wrapped in a MutableProxy.
  303. __never_wrap_base_attrs__ = set(Base.__dict__) - {"set"} | set(
  304. pydantic.BaseModel.__dict__
  305. )
  306. # These types will be wrapped in MutableProxy
  307. __mutable_types__ = (
  308. list,
  309. dict,
  310. set,
  311. Base,
  312. DeclarativeBase,
  313. BaseModelV2,
  314. BaseModelV1,
  315. )
  316. # Dynamically generated classes for tracking dataclass mutations.
  317. __dataclass_proxies__: dict[type, type] = {}
  318. def __new__(cls, wrapped: Any, *args, **kwargs) -> MutableProxy:
  319. """Create a proxy instance for a mutable object that tracks changes.
  320. Args:
  321. wrapped: The object to proxy.
  322. *args: Other args passed to MutableProxy (ignored).
  323. **kwargs: Other kwargs passed to MutableProxy (ignored).
  324. Returns:
  325. The proxy instance.
  326. """
  327. if dataclasses.is_dataclass(wrapped):
  328. wrapped_cls = type(wrapped)
  329. wrapper_cls_name = wrapped_cls.__name__ + cls.__name__
  330. # Find the associated class
  331. if wrapper_cls_name not in cls.__dataclass_proxies__:
  332. # Create a new class that has the __dataclass_fields__ defined
  333. cls.__dataclass_proxies__[wrapper_cls_name] = type(
  334. wrapper_cls_name,
  335. (cls,),
  336. {
  337. dataclasses._FIELDS: getattr( # pyright: ignore [reportAttributeAccessIssue]
  338. wrapped_cls,
  339. dataclasses._FIELDS, # pyright: ignore [reportAttributeAccessIssue]
  340. ),
  341. },
  342. )
  343. cls = cls.__dataclass_proxies__[wrapper_cls_name]
  344. return super().__new__(cls)
  345. def __init__(self, wrapped: Any, state: BaseState, field_name: str):
  346. """Create a proxy for a mutable object that tracks changes.
  347. Args:
  348. wrapped: The object to proxy.
  349. state: The state to mark dirty when the object is changed.
  350. field_name: The name of the field on the state associated with the
  351. wrapped object.
  352. """
  353. super().__init__(wrapped)
  354. self._self_state = state
  355. self._self_field_name = field_name
  356. def __repr__(self) -> str:
  357. """Get the representation of the wrapped object.
  358. Returns:
  359. The representation of the wrapped object.
  360. """
  361. return f"{type(self).__name__}({self.__wrapped__})"
  362. def _mark_dirty(
  363. self,
  364. wrapped: Callable | None = None,
  365. instance: BaseState | None = None,
  366. args: tuple = (),
  367. kwargs: dict | None = None,
  368. ) -> Any:
  369. """Mark the state as dirty, then call a wrapped function.
  370. Intended for use with `FunctionWrapper` from the `wrapt` library.
  371. Args:
  372. wrapped: The wrapped function.
  373. instance: The instance of the wrapped function.
  374. args: The args for the wrapped function.
  375. kwargs: The kwargs for the wrapped function.
  376. Returns:
  377. The result of the wrapped function.
  378. """
  379. self._self_state.dirty_vars.add(self._self_field_name)
  380. self._self_state._mark_dirty()
  381. if wrapped is not None:
  382. return wrapped(*args, **(kwargs or {}))
  383. @classmethod
  384. def _is_mutable_type(cls, value: Any) -> bool:
  385. """Check if a value is of a mutable type and should be wrapped.
  386. Args:
  387. value: The value to check.
  388. Returns:
  389. Whether the value is of a mutable type.
  390. """
  391. return isinstance(value, cls.__mutable_types__) or (
  392. dataclasses.is_dataclass(value) and not isinstance(value, Var)
  393. )
  394. @staticmethod
  395. def _is_called_from_dataclasses_internal() -> bool:
  396. """Check if the current function is called from dataclasses helper.
  397. Returns:
  398. Whether the current function is called from dataclasses internal code.
  399. """
  400. # Walk up the stack a bit to see if we are called from dataclasses
  401. # internal code, for example `asdict` or `astuple`.
  402. frame = inspect.currentframe()
  403. for _ in range(5):
  404. # Why not `inspect.stack()` -- this is much faster!
  405. if not (frame := frame and frame.f_back):
  406. break
  407. if inspect.getfile(frame) == dataclasses.__file__:
  408. return True
  409. return False
  410. def _wrap_recursive(self, value: Any) -> Any:
  411. """Wrap a value recursively if it is mutable.
  412. Args:
  413. value: The value to wrap.
  414. Returns:
  415. The wrapped value.
  416. """
  417. # When called from dataclasses internal code, return the unwrapped value
  418. if self._is_called_from_dataclasses_internal():
  419. return value
  420. # Recursively wrap mutable types, but do not re-wrap MutableProxy instances.
  421. if self._is_mutable_type(value) and not isinstance(value, MutableProxy):
  422. base_cls = globals()[self.__base_proxy__]
  423. return base_cls(
  424. wrapped=value,
  425. state=self._self_state,
  426. field_name=self._self_field_name,
  427. )
  428. return value
  429. def _wrap_recursive_decorator(
  430. self, wrapped: Callable, instance: BaseState, args: list, kwargs: dict
  431. ) -> Any:
  432. """Wrap a function that returns a possibly mutable value.
  433. Intended for use with `FunctionWrapper` from the `wrapt` library.
  434. Args:
  435. wrapped: The wrapped function.
  436. instance: The instance of the wrapped function.
  437. args: The args for the wrapped function.
  438. kwargs: The kwargs for the wrapped function.
  439. Returns:
  440. The result of the wrapped function (possibly wrapped in a MutableProxy).
  441. """
  442. return self._wrap_recursive(wrapped(*args, **kwargs))
  443. def __getattr__(self, __name: str) -> Any:
  444. """Get the attribute on the proxied object and return a proxy if mutable.
  445. Args:
  446. __name: The name of the attribute.
  447. Returns:
  448. The attribute value.
  449. """
  450. value = super().__getattr__(__name)
  451. if callable(value):
  452. if __name in self.__mark_dirty_attrs__:
  453. # Wrap special callables, like "append", which should mark state dirty.
  454. value = wrapt.FunctionWrapper(value, self._mark_dirty)
  455. if __name in self.__wrap_mutable_attrs__:
  456. # Wrap methods that may return mutable objects tied to the state.
  457. value = wrapt.FunctionWrapper(
  458. value,
  459. self._wrap_recursive_decorator,
  460. )
  461. if (
  462. isinstance(self.__wrapped__, Base)
  463. and __name not in self.__never_wrap_base_attrs__
  464. and hasattr(value, "__func__")
  465. ):
  466. # Wrap methods called on Base subclasses, which might do _anything_
  467. return wrapt.FunctionWrapper(
  468. functools.partial(value.__func__, self), # pyright: ignore [reportFunctionMemberAccess]
  469. self._wrap_recursive_decorator,
  470. )
  471. if self._is_mutable_type(value) and __name not in (
  472. "__wrapped__",
  473. "_self_state",
  474. "__dict__",
  475. ):
  476. # Recursively wrap mutable attribute values retrieved through this proxy.
  477. return self._wrap_recursive(value)
  478. return value
  479. def __getitem__(self, key: Any) -> Any:
  480. """Get the item on the proxied object and return a proxy if mutable.
  481. Args:
  482. key: The key of the item.
  483. Returns:
  484. The item value.
  485. """
  486. value = super().__getitem__(key)
  487. if isinstance(key, slice) and isinstance(value, list):
  488. return [self._wrap_recursive(item) for item in value]
  489. # Recursively wrap mutable items retrieved through this proxy.
  490. return self._wrap_recursive(value)
  491. def __iter__(self) -> Any:
  492. """Iterate over the proxied object and return a proxy if mutable.
  493. Yields:
  494. Each item value (possibly wrapped in MutableProxy).
  495. """
  496. for value in super().__iter__():
  497. # Recursively wrap mutable items retrieved through this proxy.
  498. yield self._wrap_recursive(value)
  499. def __delattr__(self, name: str):
  500. """Delete the attribute on the proxied object and mark state dirty.
  501. Args:
  502. name: The name of the attribute.
  503. """
  504. self._mark_dirty(super().__delattr__, args=(name,))
  505. def __delitem__(self, key: str):
  506. """Delete the item on the proxied object and mark state dirty.
  507. Args:
  508. key: The key of the item.
  509. """
  510. self._mark_dirty(super().__delitem__, args=(key,))
  511. def __setitem__(self, key: str, value: Any):
  512. """Set the item on the proxied object and mark state dirty.
  513. Args:
  514. key: The key of the item.
  515. value: The value of the item.
  516. """
  517. self._mark_dirty(super().__setitem__, args=(key, value))
  518. def __setattr__(self, name: str, value: Any):
  519. """Set the attribute on the proxied object and mark state dirty.
  520. If the attribute starts with "_self_", then the state is NOT marked
  521. dirty as these are internal proxy attributes.
  522. Args:
  523. name: The name of the attribute.
  524. value: The value of the attribute.
  525. """
  526. if name.startswith("_self_"):
  527. # Special case attributes of the proxy itself, not applied to the wrapped object.
  528. super().__setattr__(name, value)
  529. return
  530. self._mark_dirty(super().__setattr__, args=(name, value))
  531. def __copy__(self) -> Any:
  532. """Return a copy of the proxy.
  533. Returns:
  534. A copy of the wrapped object, unconnected to the proxy.
  535. """
  536. return copy.copy(self.__wrapped__)
  537. def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Any:
  538. """Return a deepcopy of the proxy.
  539. Args:
  540. memo: The memo dict to use for the deepcopy.
  541. Returns:
  542. A deepcopy of the wrapped object, unconnected to the proxy.
  543. """
  544. return copy.deepcopy(self.__wrapped__, memo=memo)
  545. def __reduce_ex__(self, protocol_version: SupportsIndex):
  546. """Get the state for redis serialization.
  547. This method is called by cloudpickle to serialize the object.
  548. It explicitly serializes the wrapped object, stripping off the mutable proxy.
  549. Args:
  550. protocol_version: The protocol version.
  551. Returns:
  552. Tuple of (wrapped class, empty args, class __getstate__)
  553. """
  554. return self.__wrapped__.__reduce_ex__(protocol_version)
  555. @serializer
  556. def serialize_mutable_proxy(mp: MutableProxy):
  557. """Return the wrapped value of a MutableProxy.
  558. Args:
  559. mp: The MutableProxy to serialize.
  560. Returns:
  561. The wrapped object.
  562. """
  563. return mp.__wrapped__
  564. _orig_json_encoder_default = json.JSONEncoder.default
  565. def _json_encoder_default_wrapper(self: json.JSONEncoder, o: Any) -> Any:
  566. """Wrap JSONEncoder.default to handle MutableProxy objects.
  567. Args:
  568. self: the JSONEncoder instance.
  569. o: the object to serialize.
  570. Returns:
  571. A JSON-able object.
  572. """
  573. try:
  574. return o.__wrapped__
  575. except AttributeError:
  576. pass
  577. return _orig_json_encoder_default(self, o)
  578. json.JSONEncoder.default = _json_encoder_default_wrapper
  579. class ImmutableMutableProxy(MutableProxy):
  580. """A proxy for a mutable object that tracks changes.
  581. This wrapper comes from StateProxy, and will raise an exception if an attempt is made
  582. to modify the wrapped object when the StateProxy is immutable.
  583. """
  584. # Ensure that recursively wrapped proxies use ImmutableMutableProxy as base.
  585. __base_proxy__ = "ImmutableMutableProxy"
  586. def _mark_dirty(
  587. self,
  588. wrapped: Callable | None = None,
  589. instance: BaseState | None = None,
  590. args: tuple = (),
  591. kwargs: dict | None = None,
  592. ) -> Any:
  593. """Raise an exception when an attempt is made to modify the object.
  594. Intended for use with `FunctionWrapper` from the `wrapt` library.
  595. Args:
  596. wrapped: The wrapped function.
  597. instance: The instance of the wrapped function.
  598. args: The args for the wrapped function.
  599. kwargs: The kwargs for the wrapped function.
  600. Returns:
  601. The result of the wrapped function.
  602. Raises:
  603. ImmutableStateError: if the StateProxy is not mutable.
  604. """
  605. if not self._self_state._is_mutable():
  606. raise ImmutableStateError(
  607. "Background task StateProxy is immutable outside of a context "
  608. "manager. Use `async with self` to modify state."
  609. )
  610. return super()._mark_dirty(
  611. wrapped=wrapped, instance=instance, args=args, kwargs=kwargs
  612. )