-
-
Notifications
You must be signed in to change notification settings - Fork 343
/
_run.py
1540 lines (1279 loc) · 56.2 KB
/
_run.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import enum
from collections import deque
import threading
from time import monotonic
import os
import random
from contextlib import contextmanager, closing
import select
import sys
from math import inf
import functools
import logging
import attr
from sortedcontainers import SortedDict
from async_generator import async_generator, yield_
from .._util import acontextmanager
from .._deprecate import deprecated
from .. import _core
from ._exceptions import (
TrioInternalError, RunFinishedError, Cancelled, WouldBlock
)
from ._multierror import MultiError
from ._result import Result, Error, Value
from ._traps import (
cancel_shielded_checkpoint,
Abort,
wait_task_rescheduled,
CancelShieldedCheckpoint,
WaitTaskRescheduled,
)
from ._entry_queue import EntryQueue, TrioToken
from ._ki import (
LOCALS_KEY_KI_PROTECTION_ENABLED, currently_ki_protected, ki_manager,
enable_ki_protection
)
from . import _public
# At the bottom of this file there's also some "clever" code that generates
# wrapper functions for runner and io manager methods, and adds them to
# __all__. These are all re-exported as part of the 'trio' or 'trio.hazmat'
# namespaces.
__all__ = [
"Task", "run", "open_nursery", "open_cancel_scope", "checkpoint",
"current_task", "current_effective_deadline", "checkpoint_if_cancelled",
"TASK_STATUS_IGNORED"
]
GLOBAL_RUN_CONTEXT = threading.local()
if os.name == "nt":
from ._io_windows import WindowsIOManager as TheIOManager
elif hasattr(select, "epoll"):
from ._io_epoll import EpollIOManager as TheIOManager
elif hasattr(select, "kqueue"):
from ._io_kqueue import KqueueIOManager as TheIOManager
else: # pragma: no cover
raise NotImplementedError("unsupported platform")
_r = random.Random()
# Used to log exceptions in instruments
INSTRUMENT_LOGGER = logging.getLogger("trio.abc.Instrument")
@attr.s(frozen=True)
class SystemClock:
# Add a large random offset to our clock to ensure that if people
# accidentally call time.monotonic() directly or start comparing clocks
# between different runs, then they'll notice the bug quickly:
offset = attr.ib(default=attr.Factory(lambda: _r.uniform(10000, 200000)))
def start_clock(self):
pass
def current_time(self):
return self.offset + monotonic()
def deadline_to_sleep_time(self, deadline):
return deadline - self.current_time()
################################################################
# CancelScope and friends
################################################################
@attr.s(cmp=False, hash=False, repr=False)
class CancelScope:
_tasks = attr.ib(default=attr.Factory(set))
_effective_deadline = attr.ib(default=inf)
_deadline = attr.ib(default=inf)
_shield = attr.ib(default=False)
cancel_called = attr.ib(default=False)
cancelled_caught = attr.ib(default=False)
def __repr__(self):
return "<cancel scope object at {:#x}>".format(id(self))
@contextmanager
@enable_ki_protection
def _might_change_effective_deadline(self):
try:
yield
finally:
old = self._effective_deadline
if self.cancel_called or not self._tasks:
new = inf
else:
new = self._deadline
if old != new:
self._effective_deadline = new
runner = GLOBAL_RUN_CONTEXT.runner
if old != inf:
del runner.deadlines[old, id(self)]
if new != inf:
runner.deadlines[new, id(self)] = self
@property
def deadline(self):
return self._deadline
@deadline.setter
def deadline(self, new_deadline):
with self._might_change_effective_deadline():
self._deadline = float(new_deadline)
@property
def shield(self):
return self._shield
@shield.setter
def shield(self, new_value):
if not isinstance(new_value, bool):
raise TypeError("shield must be a bool")
self._shield = new_value
if not self._shield:
for task in self._tasks:
task._attempt_delivery_of_any_pending_cancel()
def _cancel_no_notify(self):
# returns the affected tasks
if not self.cancel_called:
with self._might_change_effective_deadline():
self.cancel_called = True
return self._tasks
else:
return set()
@enable_ki_protection
def cancel(self):
for task in self._cancel_no_notify():
task._attempt_delivery_of_any_pending_cancel()
def _add_task(self, task):
self._tasks.add(task)
task._cancel_stack.append(self)
def _remove_task(self, task):
with self._might_change_effective_deadline():
self._tasks.remove(task)
assert task._cancel_stack[-1] is self
task._cancel_stack.pop()
# Used by the nursery.start trickiness
def _tasks_removed_by_adoption(self, tasks):
with self._might_change_effective_deadline():
self._tasks.difference_update(tasks)
# Used by the nursery.start trickiness
def _tasks_added_by_adoption(self, tasks):
self._tasks.update(tasks)
def _make_exc(self):
exc = Cancelled()
exc._scope = self
return exc
def _exc_filter(self, exc):
if isinstance(exc, Cancelled) and exc._scope is self:
self.cancelled_caught = True
return None
return exc
@contextmanager
@enable_ki_protection
def open_cancel_scope(*, deadline=inf, shield=False):
"""Returns a context manager which creates a new cancellation scope.
"""
task = _core.current_task()
scope = CancelScope()
scope._add_task(task)
scope.deadline = deadline
scope.shield = shield
try:
with MultiError.catch(scope._exc_filter):
yield scope
finally:
scope._remove_task(task)
################################################################
# Nursery and friends
################################################################
# This code needs to be read alongside the code from Nursery.start to make
# sense.
@attr.s(cmp=False, hash=False, repr=False)
class _TaskStatus:
_old_nursery = attr.ib()
_new_nursery = attr.ib()
_called_started = attr.ib(default=False)
_value = attr.ib(default=None)
def __repr__(self):
return "<Task status object at {:#x}>".format(id(self))
def started(self, value=None):
if self._called_started:
raise RuntimeError(
"called 'started' twice on the same task status"
)
self._called_started = True
self._value = value
# If the old nursery is cancelled, then quietly quit now; the child
# will eventually exit on its own, and we don't want to risk moving
# the children into a different scope while they might have
# propagating Cancelled exceptions that assume they're under the old
# scope.
if _pending_cancel_scope(self._old_nursery._cancel_stack) is not None:
return
# Can't be closed, b/c we checked in start() and then _pending_starts
# should keep it open.
assert not self._new_nursery._closed
# otherwise, find all the tasks under the old nursery, and move them
# under the new nursery instead. This means:
# - changing parents of direct children
# - changing cancel stack of all direct+indirect children
# - changing cancel stack of all direct+indirect children's nurseries
# - checking for cancellation in all changed cancel stacks
old_stack = self._old_nursery._cancel_stack
new_stack = self._new_nursery._cancel_stack
# LIFO todo stack for depth-first traversal
todo = list(self._old_nursery._children)
munged_tasks = []
while todo:
task = todo.pop()
# Direct children need to be reparented
if task._parent_nursery is self._old_nursery:
self._old_nursery._children.remove(task)
task._parent_nursery = self._new_nursery
self._new_nursery._children.add(task)
# Everyone needs their cancel scopes fixed up...
assert task._cancel_stack[:len(old_stack)] == old_stack
task._cancel_stack[:len(old_stack)] = new_stack
# ...and their nurseries' cancel scopes fixed up.
for nursery in task._child_nurseries:
assert nursery._cancel_stack[:len(old_stack)] == old_stack
nursery._cancel_stack[:len(old_stack)] = new_stack
# And then add all the nursery's children to our todo list
todo.extend(nursery._children)
# And make a note to check for cancellation later
munged_tasks.append(task)
# Tell all the cancel scopes about the change. (There are probably
# some scopes in common between the two stacks, so some scopes will
# get the same tasks removed and then immediately re-added. This is
# fine though.)
for cancel_scope in old_stack:
cancel_scope._tasks_removed_by_adoption(munged_tasks)
for cancel_scope in new_stack:
cancel_scope._tasks_added_by_adoption(munged_tasks)
# That should have removed all the children from the old nursery
assert not self._old_nursery._children
# After all the delicate surgery is done, check for cancellation in
# all the tasks that had their cancel scopes munged. This can trigger
# arbitrary abort() callbacks, so we put it off until our internal
# data structures are all self-consistent again.
for task in munged_tasks:
task._attempt_delivery_of_any_pending_cancel()
# And finally, poke the old nursery so it notices that all its
# children have disappeared and can exit.
self._old_nursery._check_nursery_closed()
@acontextmanager
@async_generator
@enable_ki_protection
async def open_nursery():
"""Returns an async context manager which creates a new nursery.
This context manager's ``__aenter__`` method executes synchronously. Its
``__aexit__`` method blocks until all child tasks have exited.
"""
assert currently_ki_protected()
with open_cancel_scope() as scope:
nursery = Nursery(current_task(), scope)
nested_child_exc = None
try:
await yield_(nursery)
except BaseException as exc:
nested_child_exc = exc
assert currently_ki_protected()
await nursery._nested_child_finished(nested_child_exc)
# I *think* this is equivalent to the above, and it gives *much* nicer
# exception tracebacks... but I'm a little nervous about it because it's much
# trickier code :-(
#
# class NurseryManager:
# @enable_ki_protection
# async def __aenter__(self):
# self._scope_manager = open_cancel_scope()
# scope = self._scope_manager.__enter__()
# self._parent_nursery = Nursery(current_task(), scope)
# return self._parent_nursery
#
# @enable_ki_protection
# async def __aexit__(self, etype, exc, tb):
# try:
# await self._parent_nursery._clean_up(exc)
# except BaseException as new_exc:
# if not self._scope_manager.__exit__(
# type(new_exc), new_exc, new_exc.__traceback__):
# if exc is new_exc:
# return False
# else:
# raise
# else:
# self._scope_manager.__exit__(None, None, None)
# return True
#
# def open_nursery():
# return NurseryManager()
class Nursery:
def __init__(self, parent_task, cancel_scope):
self._parent_task = parent_task
parent_task._child_nurseries.append(self)
# the cancel stack that children inherit - we take a snapshot, so it
# won't be affected by any changes in the parent.
self._cancel_stack = list(parent_task._cancel_stack)
# the cancel scope that directly surrounds us; used for cancelling all
# children.
self.cancel_scope = cancel_scope
assert self.cancel_scope is self._cancel_stack[-1]
self._children = set()
self._pending_excs = []
# The "nested child" is how this code refers to the contents of the
# nursery's 'async with' block, which acts like a child Task in all
# the ways we can make it.
self._nested_child_running = True
self._parent_waiting_in_aexit = False
self._pending_starts = 0
self._closed = False
@property
def child_tasks(self):
return frozenset(self._children)
@property
def parent_task(self):
return self._parent_task
def _add_exc(self, exc):
self._pending_excs.append(exc)
self.cancel_scope.cancel()
def _check_nursery_closed(self):
if (
not self._nested_child_running and not self._children
and not self._pending_starts
):
self._closed = True
if self._parent_waiting_in_aexit:
self._parent_waiting_in_aexit = False
GLOBAL_RUN_CONTEXT.runner.reschedule(self._parent_task)
def _child_finished(self, task, result):
self._children.remove(task)
if type(result) is Error:
self._add_exc(result.error)
self._check_nursery_closed()
async def _nested_child_finished(self, nested_child_exc):
if nested_child_exc is not None:
self._add_exc(nested_child_exc)
self._nested_child_running = False
self._check_nursery_closed()
if not self._closed:
# If we get cancelled (or have an exception injected, like
# KeyboardInterrupt), then save that, but still wait until our
# children finish.
def aborted(raise_cancel):
self._add_exc(Result.capture(raise_cancel).error)
return Abort.FAILED
self._parent_waiting_in_aexit = True
await wait_task_rescheduled(aborted)
else:
# Nothing to wait for, so just execute a checkpoint -- but we
# still need to mix any exception (e.g. from an external
# cancellation) in with the rest of our exceptions.
try:
await checkpoint()
except BaseException as exc:
self._add_exc(exc)
popped = self._parent_task._child_nurseries.pop()
assert popped is self
if self._pending_excs:
raise MultiError(self._pending_excs)
def start_soon(self, async_fn, *args, name=None):
GLOBAL_RUN_CONTEXT.runner.spawn_impl(async_fn, args, self, name)
async def start(self, async_fn, *args, name=None):
if self._closed:
raise RuntimeError("Nursery is closed to new arrivals")
try:
self._pending_starts += 1
async with open_nursery() as old_nursery:
task_status = _TaskStatus(old_nursery, self)
thunk = functools.partial(async_fn, task_status=task_status)
old_nursery.start_soon(thunk, *args, name=name)
# Wait for either _TaskStatus.started or an exception to
# cancel this nursery:
# If we get here, then the child either got reparented or exited
# normally. The complicated logic is all in _TaskStatus.started().
# (Any exceptions propagate directly out of the above.)
if not task_status._called_started:
raise RuntimeError(
"child exited without calling task_status.started()"
)
return task_status._value
finally:
self._pending_starts -= 1
self._check_nursery_closed()
def __del__(self):
assert not self._children
################################################################
# Task and friends
################################################################
def _pending_cancel_scope(cancel_stack):
# Return the outermost exception that is is not outside a shield.
pending_scope = None
for scope in cancel_stack:
# Check shield before _exc, because shield should not block
# processing of *this* scope's exception
if scope.shield:
pending_scope = None
if pending_scope is None and scope.cancel_called:
pending_scope = scope
return pending_scope
@attr.s(cmp=False, hash=False, repr=False)
class Task:
_parent_nursery = attr.ib()
coro = attr.ib()
_runner = attr.ib()
name = attr.ib()
# Invariant:
# - for unscheduled tasks, _next_send is None
# - for scheduled tasks, _next_send is a Result object
# Tasks start out unscheduled.
_next_send = attr.ib(default=None)
# ParkingLot modifies this directly
_abort_func = attr.ib(default=None)
# For introspection and nursery.start()
_child_nurseries = attr.ib(default=attr.Factory(list))
# Task-local values, see _local.py
_locals = attr.ib(default=attr.Factory(dict))
# these are counts of how many cancel/schedule points this task has
# executed, for assert{_no,}_yields
# XX maybe these should be exposed as part of a statistics() method?
_cancel_points = attr.ib(default=0)
_schedule_points = attr.ib(default=0)
def __repr__(self):
return ("<Task {!r} at {:#x}>".format(self.name, id(self)))
@property
def parent_nursery(self):
"""The nursery this task is inside (or None if this is the "init"
take).
Example use case: drawing a visualization of the task tree in a
debugger.
"""
return self._parent_nursery
@property
def child_nurseries(self):
"""The nurseries this task contains.
This is a list, with outer nurseries before inner nurseries.
"""
return list(self._child_nurseries)
################
# Cancellation
################
_cancel_stack = attr.ib(default=attr.Factory(list), repr=False)
def _pending_cancel_scope(self):
return _pending_cancel_scope(self._cancel_stack)
def _attempt_abort(self, raise_cancel):
# Either the abort succeeds, in which case we will reschedule the
# task, or else it fails, in which case it will worry about
# rescheduling itself (hopefully eventually calling reraise to raise
# the given exception, but not necessarily).
success = self._abort_func(raise_cancel)
if type(success) is not Abort:
raise TrioInternalError("abort function must return Abort enum")
# We only attempt to abort once per blocking call, regardless of
# whether we succeeded or failed.
self._abort_func = None
if success is Abort.SUCCEEDED:
self._runner.reschedule(self, Result.capture(raise_cancel))
def _attempt_delivery_of_any_pending_cancel(self):
if self._abort_func is None:
return
pending_scope = self._pending_cancel_scope()
if pending_scope is None:
return
exc = pending_scope._make_exc()
def raise_cancel():
raise exc
self._attempt_abort(raise_cancel)
def _attempt_delivery_of_pending_ki(self):
assert self._runner.ki_pending
if self._abort_func is None:
return
def raise_cancel():
self._runner.ki_pending = False
raise KeyboardInterrupt
self._attempt_abort(raise_cancel)
################################################################
# The central Runner object
################################################################
@attr.s(frozen=True)
class _RunStatistics:
tasks_living = attr.ib()
tasks_runnable = attr.ib()
seconds_to_next_deadline = attr.ib()
io_statistics = attr.ib()
run_sync_soon_queue_size = attr.ib()
@attr.s(cmp=False, hash=False)
class Runner:
clock = attr.ib()
instruments = attr.ib()
io_manager = attr.ib()
# Run-local values, see _local.py
_locals = attr.ib(default=attr.Factory(dict))
runq = attr.ib(default=attr.Factory(deque))
tasks = attr.ib(default=attr.Factory(set))
r = attr.ib(default=attr.Factory(random.Random))
# {(deadline, id(CancelScope)): CancelScope}
# only contains scopes with non-infinite deadlines that are currently
# attached to at least one task
deadlines = attr.ib(default=attr.Factory(SortedDict))
init_task = attr.ib(default=None)
init_task_result = attr.ib(default=None)
system_nursery = attr.ib(default=None)
main_task = attr.ib(default=None)
main_task_result = attr.ib(default=None)
entry_queue = attr.ib(default=attr.Factory(EntryQueue))
trio_token = attr.ib(default=None)
def close(self):
self.io_manager.close()
self.entry_queue.close()
self.instrument("after_run")
# Methods marked with @_public get converted into functions exported by
# trio.hazmat:
@_public
def current_statistics(self):
"""Returns an object containing run-loop-level debugging information.
Currently the following fields are defined:
* ``tasks_living`` (int): The number of tasks that have been spawned
and not yet exited.
* ``tasks_runnable`` (int): The number of tasks that are currently
queued on the run queue (as opposed to blocked waiting for something
to happen).
* ``seconds_to_next_deadline`` (float): The time until the next
pending cancel scope deadline. May be negative if the deadline has
expired but we haven't yet processed cancellations. May be
:data:`~math.inf` if there are no pending deadlines.
* ``run_sync_soon_queue_size`` (int): The number of
unprocessed callbacks queued via
:meth:`trio.hazmat.TrioToken.run_sync_soon`.
* ``io_statistics`` (object): Some statistics from trio's I/O
backend. This always has an attribute ``backend`` which is a string
naming which operating-system-specific I/O backend is in use; the
other attributes vary between backends.
"""
if self.deadlines:
next_deadline, _ = self.deadlines.keys()[0]
seconds_to_next_deadline = next_deadline - self.current_time()
else:
seconds_to_next_deadline = float("inf")
return _RunStatistics(
tasks_living=len(self.tasks),
tasks_runnable=len(self.runq),
seconds_to_next_deadline=seconds_to_next_deadline,
io_statistics=self.io_manager.statistics(),
run_sync_soon_queue_size=self.entry_queue.size(),
)
@_public
def current_time(self):
"""Returns the current time according to trio's internal clock.
Returns:
float: The current time.
Raises:
RuntimeError: if not inside a call to :func:`trio.run`.
"""
return self.clock.current_time()
@_public
def current_clock(self):
"""Returns the current :class:`~trio.abc.Clock`.
"""
return self.clock
@_public
def current_root_task(self):
"""Returns the current root :class:`Task`.
This is the task that is the ultimate parent of all other tasks.
"""
return self.init_task
################
# Core task handling primitives
################
@_public
def reschedule(self, task, next_send=Value(None)):
"""Reschedule the given task with the given
:class:`~trio.hazmat.Result`.
See :func:`wait_task_rescheduled` for the gory details.
There must be exactly one call to :func:`reschedule` for every call to
:func:`wait_task_rescheduled`. (And when counting, keep in mind that
returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent
to calling :func:`reschedule` once.)
Args:
task (trio.hazmat.Task): the task to be rescheduled. Must be blocked
in a call to :func:`wait_task_rescheduled`.
next_send (trio.hazmat.Result): the value (or error) to return (or
raise) from :func:`wait_task_rescheduled`.
"""
assert task._runner is self
assert task._next_send is None
task._next_send = next_send
task._abort_func = None
self.runq.append(task)
self.instrument("task_scheduled", task)
def spawn_impl(
self, async_fn, args, nursery, name, *, ki_protection_enabled=False
):
######
# Make sure the nursery is in working order
######
# This sorta feels like it should be a method on nursery, except it
# has to handle nursery=None for init. And it touches the internals of
# all kinds of objects.
if nursery is not None and nursery._closed:
raise RuntimeError("Nursery is closed to new arrivals")
if nursery is None:
assert self.init_task is None
######
# Call the function and get the coroutine object, while giving helpful
# errors for common mistakes.
######
def _return_value_looks_like_wrong_library(value):
# Returned by legacy @asyncio.coroutine functions, which includes
# a surprising proportion of asyncio builtins.
if inspect.isgenerator(value):
return True
# The protocol for detecting an asyncio Future-like object
if getattr(value, "_asyncio_future_blocking", None) is not None:
return True
# asyncio.Future doesn't have _asyncio_future_blocking until
# 3.5.3. We don't want to import asyncio, but this janky check
# should work well enough for our purposes. And it also catches
# tornado Futures and twisted Deferreds. By the time we're calling
# this function, we already know something has gone wrong, so a
# heuristic is pretty safe.
if value.__class__.__name__ in ("Future", "Deferred"):
return True
return False
try:
coro = async_fn(*args)
except TypeError:
# Give good error for: nursery.start_soon(trio.sleep(1))
if inspect.iscoroutine(async_fn):
raise TypeError(
"trio was expecting an async function, but instead it got "
"a coroutine object {async_fn!r}\n"
"\n"
"Probably you did something like:\n"
"\n"
" trio.run({async_fn.__name__}(...)) # incorrect!\n"
" nursery.start_soon({async_fn.__name__}(...)) # incorrect!\n"
"\n"
"Instead, you want (notice the parentheses!):\n"
"\n"
" trio.run({async_fn.__name__}, ...) # correct!\n"
" nursery.start_soon({async_fn.__name__}, ...) # correct!"
.format(async_fn=async_fn)
) from None
# Give good error for: nursery.start_soon(future)
if _return_value_looks_like_wrong_library(async_fn):
raise TypeError(
"trio was expecting an async function, but instead it got "
"{!r} – are you trying to use a library written for "
"asyncio/twisted/tornado or similar? That won't work "
"without some sort of compatibility shim."
.format(async_fn)
) from None
raise
# We can't check iscoroutinefunction(async_fn), because that will fail
# for things like functools.partial objects wrapping an async
# function. So we have to just call it and then check whether the
# result is a coroutine object.
if not inspect.iscoroutine(coro):
# Give good error for: nursery.start_soon(func_returning_future)
if _return_value_looks_like_wrong_library(coro):
raise TypeError(
"start_soon got unexpected {!r} – are you trying to use a "
"library written for asyncio/twisted/tornado or similar? "
"That won't work without some sort of compatibility shim."
.format(coro)
)
# Give good error for: nursery.start_soon(some_sync_fn)
raise TypeError(
"trio expected an async function, but {!r} appears to be "
"synchronous"
.format(getattr(async_fn, "__qualname__", async_fn))
)
######
# Set up the Task object
######
if name is None:
name = async_fn
if isinstance(name, functools.partial):
name = name.func
if not isinstance(name, str):
try:
name = "{}.{}".format(name.__module__, name.__qualname__)
except AttributeError:
name = repr(name)
task = Task(coro=coro, parent_nursery=nursery, runner=self, name=name)
self.tasks.add(task)
if nursery is not None:
nursery._children.add(task)
for scope in nursery._cancel_stack:
scope._add_task(task)
coro.cr_frame.f_locals.setdefault(
LOCALS_KEY_KI_PROTECTION_ENABLED, ki_protection_enabled
)
if nursery is not None:
# Task locals are inherited from the spawning task, not the
# nursery task. The 'if nursery' check is just used as a guard to
# make sure we don't try to do this to the root task.
parent_task = current_task()
for local, values in parent_task._locals.items():
task._locals[local] = dict(values)
self.instrument("task_spawned", task)
# Special case: normally next_send should be a Result, but for the
# very first send we have to send a literal unboxed None.
self.reschedule(task, None)
return task
def task_exited(self, task, result):
while task._cancel_stack:
task._cancel_stack[-1]._remove_task(task)
self.tasks.remove(task)
if task._parent_nursery is None:
# the init task should be the last task to exit
assert not self.tasks
else:
task._parent_nursery._child_finished(task, result)
if task is self.main_task:
self.main_task_result = result
self.system_nursery.cancel_scope.cancel()
if task is self.init_task:
self.init_task_result = result
self.instrument("task_exited", task)
################
# System tasks and init
################
@_public
def spawn_system_task(self, async_fn, *args, name=None):
"""Spawn a "system" task.
System tasks have a few differences from regular tasks:
* They don't need an explicit nursery; instead they go into the
internal "system nursery".
* If a system task raises an exception, then it's converted into a
:exc:`~trio.TrioInternalError` and *all* tasks are cancelled. If you
write a system task, you should be careful to make sure it doesn't
crash.
* System tasks are automatically cancelled when the main task exits.
* By default, system tasks have :exc:`KeyboardInterrupt` protection
*enabled*. If you want your task to be interruptible by control-C,
then you need to use :func:`disable_ki_protection` explicitly.
Args:
async_fn: An async callable.
args: Positional arguments for ``async_fn``. If you want to pass
keyword arguments, use :func:`functools.partial`.
name: The name for this task. Only used for debugging/introspection
(e.g. ``repr(task_obj)``). If this isn't a string,
:func:`spawn_system_task` will try to make it one. A common use
case is if you're wrapping a function before spawning a new
task, you might pass the original function as the ``name=`` to
make debugging easier.
Returns:
Task: the newly spawned task
"""
async def system_task_wrapper(async_fn, args):
PASS = (
Cancelled, KeyboardInterrupt, GeneratorExit, TrioInternalError
)
def excfilter(exc):
if isinstance(exc, PASS):
return exc
else:
new_exc = TrioInternalError("system task crashed")
new_exc.__cause__ = exc
return new_exc
with MultiError.catch(excfilter):
await async_fn(*args)
if name is None:
name = async_fn
return self.spawn_impl(
system_task_wrapper, (async_fn, args),
self.system_nursery,
name,
ki_protection_enabled=True
)
async def init(self, async_fn, args):
async with open_nursery() as system_nursery:
self.system_nursery = system_nursery
self.main_task = self.spawn_impl(
async_fn, args, system_nursery, None
)
self.entry_queue.spawn()
return self.main_task_result.unwrap()
################
# Outside context problems
################
@_public
def current_trio_token(self):
"""Retrieve the :class:`TrioToken` for the current call to
:func:`trio.run`.
"""
if self.trio_token is None:
self.trio_token = TrioToken(self.entry_queue)
return self.trio_token
################
# KI handling
################
ki_pending = attr.ib(default=False)
# deliver_ki is broke. Maybe move all the actual logic and state into
# RunToken, and we'll only have one instance per runner? But then we can't
# have a public constructor. Eh, but current_run_token() returning a
# unique object per run feels pretty nice. Maybe let's just go for it. And
# keep the class public so people can isinstance() it if they want.
# This gets called from signal context
def deliver_ki(self):
self.ki_pending = True
try:
self.entry_queue.run_sync_soon(self._deliver_ki_cb)
except RunFinishedError:
pass
def _deliver_ki_cb(self):
if not self.ki_pending:
return
# Can't happen because main_task and run_sync_soon_task are created at
# the same time -- so even if KI arrives before main_task is created,
# we won't get here until afterwards.
assert self.main_task is not None
if self.main_task_result is not None:
# We're already in the process of exiting -- leave ki_pending set
# and we'll check it again on our way out of run().
return
self.main_task._attempt_delivery_of_pending_ki()
################
# Quiescing
################
waiting_for_idle = attr.ib(default=attr.Factory(SortedDict))
@_public
async def wait_all_tasks_blocked(self, cushion=0.0, tiebreaker=0):
"""Block until there are no runnable tasks.
This is useful in testing code when you want to give other tasks a
chance to "settle down". The calling task is blocked, and doesn't wake
up until all other tasks are also blocked for at least ``cushion``
seconds. (Setting a non-zero ``cushion`` is intended to handle cases
like two tasks talking to each other over a local socket, where we
want to ignore the potential brief moment between a send and receive
when all tasks are blocked.)