Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
assert len(err.exceptions) == subactor_breadth
for subexc in err.exceptions:
# verify first level actor errors are wrapped as remote
if platform.system() == 'Windows':
# windows is often too slow and cancellation seems
# to happen before an actor is spawned
if isinstance(subexc, trio.Cancelled):
continue
else:
# on windows it seems we can't exactly be sure wtf
# will happen..
assert subexc.type in (
tractor.RemoteActorError,
trio.Cancelled,
trio.MultiError
)
else:
assert isinstance(subexc, tractor.RemoteActorError)
if depth > 0 and subactor_breadth > 1:
# XXX not sure what's up with this..
# on windows sometimes spawning is just too slow and
# we get back the (sent) cancel signal instead
if platform.system() == 'Windows':
assert (subexc.type is trio.MultiError) or (
subexc.type is tractor.RemoteActorError)
else:
assert subexc.type is trio.MultiError
else:
assert (subexc.type is tractor.RemoteActorError) or (
(multi_error_defer_to(trio.Cancelled, ValueError),
trio.MultiError([_cancelled(), ValueError()]),
trio.Cancelled),
# nested MultiError
(multi_error_defer_to(trio.Cancelled, ValueError),
trio.MultiError([
ValueError(),
trio.MultiError([_cancelled(), _cancelled()])
]),
trio.Cancelled),
# exception subclass
(multi_error_defer_to(MyExceptionBase, trio.Cancelled),
trio.MultiError([_cancelled(), MyException()]),
MyException),
# exception objects with same repr are grouped
(multi_error_defer_to(ValueError, trio.Cancelled),
trio.MultiError([ValueError(), ValueError(), _cancelled()]),
:param args: One or more exception types which will defer to
trio.Cancelled. By default, all exception types will be filtered.
Example::
# If MultiError([Cancelled, Obstacle]) occurs, propagate only Cancelled
# to the parent cancel scope.
with defer_to_cancelled(Obstacle):
try:
# async call which may raise exception as part of API
await advance(speed)
except Obstacle:
# handle API exception (unless Cancelled raised simultaneously)
...
"""
return multi_error_defer_to(trio.Cancelled, *args)
async def waste_time_freely():
'''This method is also run by trio and periodically prints something.'''
try:
while True:
print('Sitting on the beach')
await trio.sleep(2)
except trio.Cancelled as e:
print('Wasting time was canceled', e)
finally:
# when canceled, print that it finished
print('Done wasting time')
log.debug(
f"Waiting on subactors {anursery._children}"
"to complete"
)
except (BaseException, Exception) as err:
# if the caller's scope errored then we activate our
# one-cancels-all supervisor strategy (don't
# worry more are coming).
anursery._join_procs.set()
try:
# XXX: hypothetically an error could be raised and then
# a cancel signal shows up slightly after in which case
# the `else:` block here might not complete?
# For now, shield both.
with trio.CancelScope(shield=True):
if err in (trio.Cancelled, KeyboardInterrupt):
log.warning(
f"Nursery for {current_actor().uid} was "
f"cancelled with {err}")
else:
log.exception(
f"Nursery for {current_actor().uid} "
f"errored with {err}, ")
# cancel all subactors
await anursery.cancel()
except trio.MultiError as merr:
# If we receive additional errors while waiting on
# remaining subactors that were cancelled,
# aggregate those errors with the original error
# that triggered this teardown.
try:
i = 0
while True:
if self.root is not None:
status = self.root.ids.label.status
print('{} on the beach'.format(status))
# get some sleep
if self.root.ids.btn1.state != 'down' and i >= 2:
i = 0
print('Yawn, getting tired. Going to sleep')
self.root.ids.btn1.trigger_action()
i += 1
await trio.sleep(2)
except trio.Cancelled as e:
print('Wasting time was canceled', e)
finally:
# when canceled, print that it finished
print('Done wasting time')
def thread_fn(self):
while True:
try:
request = self._portal.run(self._receive_from_trio.receive)
except (Cancelled, RunFinishedError):
break
except trio.EndOfChannel:
with suppress(Cancelled, RunFinishedError):
self._portal.run(self._send_to_trio.aclose)
break
response = outcome.capture(request)
self._portal.run(self._send_to_trio.send, response)
def exc_filter(exc):
''' Filter out Cancelled exceptions raised by the nursery. '''
if isinstance(exc, trio.Cancelled):
return None
return exc
def thread_fn(self):
while True:
try:
request = self._portal.run(self._receive_from_trio.receive)
except (Cancelled, RunFinishedError):
break
except trio.EndOfChannel:
with suppress(Cancelled, RunFinishedError):
self._portal.run(self._send_to_trio.aclose)
break
response = outcome.capture(request)
self._portal.run(self._send_to_trio.send, response)
def dispatch(self, event):
'''
This function will be call in the context of the watchdog worker
thread. We need to use a BlockingTrioPortal to communicate with
our trio program.
'''
with self.lock:
try:
trio.from_thread.run(self.handle_event, event, trio_token=self.token)
except (trio.RunFinishedError, trio.Cancelled):
pass
except Exception:
logger.exception('Unknown exception during trio.from_thread.run')