reflex 0.7.9a1__py3-none-any.whl → 0.7.10a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of reflex might be problematic. Click here for more details.

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