1from asyncutils._internal import patch as P
2from asyncutils._internal.helpers import check_methods, fullname, subscriptable
3from asyncutils._internal.submodules import exceptions_all as __all__
4from sys import audit, exception, stderr
5CRITICAL = SystemExit, SystemError, KeyboardInterrupt
6def _unnest_helper(f, g, h, s, /, *, raise_critical=True, keep=Exception, filter_out=(), predicate=lambda _, /: True, ack1=(a := lambda _, /: None), ack2=a, ack3=a, _=audit):
7 _('asyncutils.exceptions.unnest'+'_reverse'*isinstance(s, list), len(s))
8 while s:
9 if isinstance(group := f(), BaseExceptionGroup): g(group.exceptions)
10 elif raise_critical and isinstance(group, CRITICAL): raise Critical(group)
11 elif isinstance(group, keep):
12 if isinstance(group, filter_out): ack1(group)
13 elif not predicate(group): ack2(group)
14 elif (y := (yield group)) is not None: h(y)
15 else: ack3(group)
[docs]
16def unnest(g, /, *A, d=__import__('_collections').deque, h=_unnest_helper, **k): (s := d(g.exceptions)).extend(A) if isinstance(g, BaseExceptionGroup) else (s := d(A)).appendleft(g); return h(s.popleft, lambda e, g=s.extendleft: g(reversed(e)), s.appendleft, s, **k)
[docs]
17def unnest_reverse(g, /, *A, h=_unnest_helper, **k): (g := (s := list(g.exceptions) if isinstance(g, BaseExceptionGroup) else [g]).extend)(A); return h(s.pop, g, s.append, s, **k)
[docs]
18def potent_derive(*groups, ordered=False, **k):
19 n = (P := lambda _, p=(p := k.pop): p(_, None))('notes')
20 if not isinstance(g := groups[0], BaseExceptionGroup): _ = p('suppress', False), *map(P, ('context', 'cause', 'traceback')); (g := BaseExceptionGroup(p('message'), tuple((unnest if ordered else unnest_reverse)(*groups, **k)))).__suppress_context__, g.__context__, g.__cause__, g.__traceback__ = _
21 if n:
22 if isinstance(n, str): g.add_note(n)
23 else:
24 try: g.__notes__.extend(n)
25 except AttributeError: g.__notes__ = list(n)
26 return g
[docs]
27def prepare_exception(e, /, *, traceback=None, cause=None, context=None, suppress=False, notes=(), _=exception):
28 if not isinstance(e, BaseException): raise TypeError(f'cannot prepare non-exception: {e!r}')
29 if isinstance(notes, str): e.add_note(notes)
30 elif (n := getattr(e, '__notes__', None)) is None: e.__notes__ = list(notes)
31 else: n.extend(notes)
32 if cause is None is e.__context__: e.__context__ = context or _()
33 else: e.__cause__ = cause
34 e.__suppress_context__, e.__traceback__ = suppress, traceback; return e
[docs]
35def raise_exc(e, /, *a, traceback=None, cause=None, context=None, suppress=False, notes=(), _a_=audit, _s_=stderr, **k):
36 if isinstance(e, type): e = e(*a, **k)
37 elif a or k: _s_.write('exceptions.raise_exc: no additional arguments were expected\n')
38 _a_('asyncutils.exceptions.raise_exc', e := prepare_exception(e, traceback=traceback, cause=cause, context=context, suppress=suppress, notes=notes)); raise e
39P.patch_function_signatures((unnest, s := 'group, /, *additional, raise_critical=True, keep={0}, filter_out=(), predicate={0}, ack1={0}, ack2={0}, ack3={0}'), (unnest_reverse, s), (prepare_exception, 'exc, /, *, traceback=None, cause=None, context=None, suppress=False, notes=()'), (raise_exc, 'exc, /, *args, traceback=None, cause=None, suppress=False, notes=(), **kwds'), (potent_derive, 'group, /, *groups, message={0}, ordered=False, predicate={0}, raise_critical=True, keep={0}, filter_out=(), predicate={0}, ack1={0}, ack2={0}, ack3={0}, notes=None, traceback=None, context=None, cause=None, suppress=False'))
40class ExceptionWrapper:
41 __slots__ = '__exc',
42 def __new__(cls, e, /):
43 if isinstance(e, CRITICAL): raise e
44 (s := super().__new__(cls)).__exc = e; return s
45 def __getattr__(self, n, /): return getattr(self.__exc, n)
46 def __repr__(self): return f'ExceptionWrapper({self.__exc!r})'
47 def __init_subclass__(cls): raise TypeError('cannot subclass the type of proxies to exceptions')
48exception_occurred, wrap_exc, unwrap_exc = ExceptionWrapper.__instancecheck__, ExceptionWrapper.__new__.__get__(ExceptionWrapper), ExceptionWrapper._ExceptionWrapper__exc.__get__ # ty: ignore[unresolved-attribute]
49@subscriptable
50class ref: # noqa: N801
51 __slots__ = '__obj',
52 def __new__(cls, obj, r=__import__('_weakref').ref):
53 if isinstance(obj, (cls, r)): return obj
54 try: return r(obj)
55 except TypeError: (_ := object.__new__(cls)).__obj = obj; return _
56 def __call__(self): return self.__obj # ty: ignore[unresolved-attribute]
57 def __init_subclass__(cls): raise TypeError('cannot subclass asyncutils.exceptions.ref')
[docs]
58@subscriptable
59class Critical(BaseException):
60 def __init__(self, e=None, /, _m='critical error occurred or user attempted to terminate the program', _e=exception): super().__init__(_m); self.__context__ = e.__context__ if isinstance(e, __class__) else _e() if e is None else e # ty: ignore[unresolved-reference]
61 @property
62 def __suppress_context__(self): return False # noqa: PLW3201
63 @property
64 def exc(self): return self.__cause__ or self.__context__
[docs]
65class StateCorrupted(BaseException):
66 def __init__(self, a, d, /): self.adjective, self.details = a, d; super().__init__(f'asyncutils: user tampered with {a} state; {d}')
[docs]
67class VersionError(Exception): ...
68for A, B in (('obj', '_refo'), ('normalizer', '_refn'), ('exc', '_refe')):
69 def _(self, a=A, b=B):
70 if (r := getattr(self, b, None)) is None: raise AttributeError(f'object of type {fullname(self)!r} has no attribute {a!r}')
71 if isinstance(r, ref) and (r := r()) is None: raise RuntimeError(f'{a} has been garbage collected')
72 return r
73 _.__name__, _.__qualname__ = A, f'VersionError.{A}'; setattr(VersionError, A, property(_))
[docs]
74class VersionConversionError(VersionError): ...
[docs]
75class VersionValueError(VersionConversionError, ValueError): ...
[docs]
76@subscriptable
77class VersionNormalizerMissing(VersionConversionError, TypeError):
78 def __init__(self, o, /, _='attempt to normalize object {0!r} of type {0.__class__.__qualname__!r} failed since a normalizer has not been registered'.format): self._refo = ref(o); super().__init__(_(o))
79 P.patch_method_signatures((__init__, 'obj, /'))
[docs]
80@subscriptable
81class VersionNormalizerTypeError(VersionConversionError, TypeError):
82 def __init__(self, /, *a, _='custom normalizer {0!r} for type {1.__class__.__qualname__!r} did not return an iterable of ints as expected when handling {1!r}'.format): self._refn, self._refo = map(ref, a); super().__init__(_(*a))
83 P.patch_method_signatures((__init__, 'normalizer, obj, /'))
[docs]
84@subscriptable
85class VersionNormalizerFault(VersionConversionError):
86 def __init__(self, /, *a, _='custom normalizer {0!r} for type {1.__class__.__qualname__!r} threw {2.__class__.__qualname__} when passed {1!r}'.format): self._refn, self._refo, self._refe = map(ref, a); super().__init__(_(*a))
87 P.patch_method_signatures((__init__, 'normalizer, obj, exc, /'))
[docs]
88class VersionCorrupted(VersionError, RuntimeError):
89 def __init__(self, o, /, _='instance of %s at %#x was tampered with by the user (parts: %r; should be a tuple of 3 positive integers)'): self._refo = ref(o); super().__init__(_%(type(o).__qualname__, id(o), getattr(o, 'parts', '<not present>')))
[docs]
90 def __getattr__(self, n, /): return getattr(self.obj, n)
91 P.patch_method_signatures((__init__, 'obj, /'))
[docs]
93class BulkheadFull(BulkheadError): ...
[docs]
94class BulkheadShutDown(BulkheadError): ...
[docs]
95class PoolError(RuntimeError): ...
[docs]
96class PoolFull(PoolError): ...
[docs]
97class PoolShutDown(PoolError): ...
[docs]
98class BusError(Exception): ...
[docs]
99class BusTimeout(BusError, TimeoutError): ...
[docs]
100class BusShutDown(BusError): ...
[docs]
101class BusStatsError(BusError): ...
[docs]
102class BusPublishingError(BusError):
103 def __init__(self, /, *a, _='{.name}: severe error in middleware {!r}'.format): self._rb, self._rm = map(ref, a); super().__init__(_(*a))
104 @property
105 def bus(self): return self._rb()
106 @property
107 def middleware(self): return self._rm()
108 P.patch_method_signatures((__init__, 'bus, mw, /'))
[docs]
109class CircuitBreakerError(RuntimeError): ...
[docs]
110class CircuitHalfOpen(CircuitBreakerError): ...
[docs]
111class CircuitOpen(CircuitBreakerError): ...
[docs]
112class EventValueError(ValueError): ...
[docs]
113class FutureCorrupted(RuntimeError): ...
[docs]
114class MaxIterationsError(RuntimeError): ...
[docs]
115class ItemsExhausted(ValueError): ...
[docs]
116class RateLimitExceeded(RuntimeError):
117 def __init__(self, f, a, k, c, p, l, /): self.__f, self.__a, self.__k = f, a, k; super().__init__(f'rate limit of {c} calls in {p} periods exceeded by {l} calls when calling {f!r}')
[docs]
118 async def repeat_call(self): return await self.__f(*self.__a, **self.__k)
[docs]
119class LockForceRequest(BaseException):
120 def __init__(self, s, a, l, i, /): self.requester, self.fulfill, self.lock, self.info = s, a, l, i; super().__init__(f'request from {type(s).__qualname__} to release {type(l).__qualname__}'); self.add_note(str(i))
[docs]
121class PasswordQueueError(Exception): ...
[docs]
122class PasswordRetrievalError(PasswordQueueError):
123 def __init__(self, from_): self.from_ = from_; super().__init__(f'failed to retrieve correct password of password-protected queue from closure variable of name {from_!r}')
[docs]
124class GetPasswordRetrievalError(PasswordRetrievalError): ...
[docs]
125class PutPasswordRetrievalError(PasswordRetrievalError): ...
[docs]
126class ForbiddenOperation(PasswordQueueError, TypeError):
127 def __init__(self, op, *a): self.op = op = op%a; super().__init__(f'cannot {op} PasswordQueue')
[docs]
128@subscriptable
129class PasswordError(PasswordQueueError):
130 @property
131 def wrongpass(self): return self._refp() # ty: ignore[unresolved-attribute]
[docs]
132class WrongPassword(PasswordError, ValueError):
133 def __init__(self, q, p, /, _='failure to modify queue because %r received incorrect password: %r'): self.qid, self._refp = id(q), ref(p); super().__init__(_%(q, p))
[docs]
134@subscriptable
135class WrongPasswordType(PasswordError, TypeError):
136 def __init__(self, q, *a, _='{!r} received password {!r} of wrong type {.__qualname__!r}; should be {!r}'.format): self.qid, self._refp, self._reft, self._refc = id(q), *map(ref, a); super().__init__(_(q, *a))
137 @property
138 def wrongtype(self): return self._reft()
139 @property
140 def correcttype(self): return self._refc()
[docs]
141class PasswordMissing(PasswordQueueError, TypeError):
142 def __init__(self): raise TypeError('asyncutils.exceptions.PasswordMissing: use GetPasswordMissing or PutPasswordMissing instead')
[docs]
143 def __init_subclass__(cls, *, m): cls.__init__ = lambda self, _=m: BaseException.__init__(self, _) # ty: ignore[invalid-assignment]
[docs]
144class GetPasswordMissing(PasswordMissing, m='asyncutils.queues.password_queue: no password provided when trying to get from password-protected queue'): ...
[docs]
145class PutPasswordMissing(PasswordMissing, m='asyncutils.queues.password_queue: no password provided when trying to put to password-protected queue'): ...
[docs]
146class IgnoreErrors:
147 __slots__ = 'but', 'exc'
148 def __init__(self, /, *_, exclude=(), d=(Exception,)): a, b = map(frozenset, (_ or d, exclude)); a, b = a-b, b-a; self.exc, self.but = map(tuple, (a, (c for c in b if any(d in a for d in c.__mro__))))
[docs]
149 def __enter__(self): return self
[docs]
150 def __exit__(self, t, /, *_): return False if t is None else issubclass(t, self.exc) and not issubclass(t, self.but)
151 def __repr__(self): return f'IgnoreErrors{self.exc!r}.excluding{self.but!r}'
[docs]
152 async def __aenter__(self): return self
[docs]
153 async def __aexit__(self, /, *_): return self.__exit__(*_)
[docs]
154 def excluding(self, *O, _=__import__('itertools').chain): return type(self)(*self.exc, exclude=_(self.but, O))
[docs]
155 def combined(self, *O, _=check_methods):
156 f, g, h, j, p = (S := set(self.exc)).update, (P := set(self.but)).update, S.add, (d := []).extend, d.pop
157 for o in O:
158 if isinstance(o, IgnoreErrors): f(o.exc); g(o.but)
159 elif isinstance(o, type): h(o)
160 elif _(o, '__iter__'): j(o)
161 while d:
162 if isinstance(o := p(), type): h(o)
163 else: f(o.exc); g(o.but)
164 return type(self)(*S, exclude=P)
165 P.patch_method_signatures((__init__, '*exc, exclude=()'), (excluding, r := '*others'), (combined, r), (__exit__, P.xsig), (__aexit__, P.xsig)); del r
166ignore_noncritical, ignore_typical = (ignore_all := IgnoreErrors(BaseException)).excluding(*CRITICAL), IgnoreErrors()
167ignore_stopiteration, ignore_stopaiteration, ignore_valerrs, ignore_typeerrs = map(IgnoreErrors, (StopIteration, StopAsyncIteration, ValueError, TypeError))
[docs]
168class WarningToError:
169 __slots__ = '_cm', '_w'
170 def __init__(self, /, *_): self._w, self._cm = _ or (Warning,), None
[docs]
171 def __enter__(self): self._cm = c = __import__('warnings').catch_warnings(action='error', category=self._w); c.__enter__(); return self
[docs]
172 def __exit__(self, t, /, *_):
173 if (c := self._cm) is None: raise RuntimeError('asyncutils.exceptions.WarningToError: __aexit__ called without prior __aenter__ call')
174 c.__exit__(t, *_)
[docs]
175 async def __aenter__(self): return self.__enter__()
[docs]
176 async def __aexit__(self, /, *_): self.__exit__(*_)
177 P.patch_method_signatures((__enter__, ''), (__aenter__, ''), (__exit__, P.xsig), (__aexit__, P.xsig))
178del P, s, _, A, B, stderr, ExceptionWrapper, _unnest_helper, audit, exception, subscriptable # ty: ignore[possibly-unresolved-reference]