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
U
Z±dʄã@sLddlZddlZddlZddlZddlZddlZddlmZddlm    Z    ddl
Z
ddl Z ddl m Z ddlmZddlmZddlmZmZddlmZddlZdd    lmZmZmZdd
lmZdd lmZm Z m!Z!m"Z"d d l#m$Z$m%Z%d dl&m'Z'm(Z(m)Z)d dl*m+Z+m,Z,m-Z-d dl.m/Z/m0Z0d dl1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7d dl8m9Z9d dl:m;Z;d dl<m=Z=ddl>m?Z?ddl@mAZAmBZBmCZCejDdkrœddlEmFZFdZGeHƒZIdd„ZJdZKe L¡ZMdd„ZNeNƒZOejPd d d!Gd"d#„d#ƒƒZQGd$d%„d%e jRƒZSd&d'„ZTejPdd d(Gd)d*„d*ƒƒZUejPdd d(Gd+d,„d,ƒƒZVd-ZWejPddd d.Gd/d0„d0eAd1ƒZXejPdddd2Gd3d4„d4ƒƒZYejPGd5d6„d6ƒƒZZdgd7d8„Z[Gd9d:„d:eBd1Z\ejPdddd d;Gd<d=„d=eBd1ƒZ]Gd>d?„d?ej^ƒZ_e_ƒZ`ejPd d@GdAdB„dBƒƒZaejPddd dCGdDdE„dEƒƒZbejPddd dCGdFdG„dGƒƒZcdHdI„ZdddJdddKœdLdM„ZeddddJdddNœdOdP„ZfdQZgdhdRdS„ZhGdTdU„dUƒZieiƒZjdVdW„ZkdXdY„ZldZd[„Zmd\d]„Znejod^krÔd d_lpmqZrd d`lsTndejodaksòesetedbƒrd dclumvZrd d`lwTn0eseteddƒr0d delxmyZrd d`lzTne{dfƒ‚d d`l|Td d`l}TdS)iéN)Údeque)Úcontextmanager)Ú copy_context)Úinf)Ú perf_counter)ÚCallableÚ TYPE_CHECKING)Úcurrent_async_library_cvar)ÚheapifyÚheappopÚheappush)Ú
SortedDict)ÚErrorÚOutcomeÚValueÚcaptureé)Ú
EntryQueueÚ    TrioToken)ÚTrioInternalErrorÚRunFinishedErrorÚ    Cancelled)Ú LOCALS_KEY_KI_PROTECTION_ENABLEDÚ    KIManagerÚenable_ki_protection)Ú
MultiErrorÚ    concat_tb)ÚAbortÚwait_task_rescheduledÚcancel_shielded_checkpointÚCancelShieldedCheckpointÚ PermanentlyDetachCoroutineObjectÚWaitTaskRescheduled)ÚAsyncGenerators)Ústart_thread_soon)Ú Instrumentsé)Ú_core)ÚFinalÚNoPublicConstructorÚcoroutine_or_error)éé )ÚBaseExceptionGroupiècCs|S©N©)Úfnr/r/úFd:\z\workplace\vscode\pyvenv\venv\Lib\site-packages\trio/_core/_run.pyÚ_public8sr2Fc
Cszdd„}tƒ}z| |¡WnXtk
rt}z:|j}|j}d}|jjjdkr\|j}|d7}q>|WY¢Sd}~XYnXdS)NcSs dddS)Nrrr/r/r/r/r1Úfunction_with_unique_name_xyzzyHszE_count_context_run_tb_frames.<locals>.function_with_unique_name_xyzzyrr3r)rÚrunÚZeroDivisionErrorÚ __traceback__Útb_nextÚtb_frameÚf_codeÚco_name)r3ÚctxÚexcÚtbÚcountr/r/r1Ú_count_context_run_tb_framesGs
r?T)ÚfrozenÚslotsc@s4eZdZejdd„dZdd„Zdd„Zdd    „Zd
S) Ú SystemClockcCs t dd¡S)Ni'i@ )Ú_rÚuniformr/r/r/r1Ú<lambda>aózSystemClock.<lambda>©ÚfactorycCsdSr.r/©Úselfr/r/r1Ú start_clockcszSystemClock.start_clockcCs |jtƒSr.)ÚoffsetrrIr/r/r1Ú current_timeiszSystemClock.current_timecCs || ¡Sr.)rM)rJÚdeadliner/r/r1Údeadline_to_sleep_timelsz"SystemClock.deadline_to_sleep_timeN)    Ú__name__Ú
__module__Ú __qualname__ÚattrÚibrLrKrMrOr/r/r/r1rB\srBc@seZdZdZdZdS)ÚIdlePrimedTypesrr&N)rPrQrRÚWAITING_FOR_IDLEÚAUTOJUMP_CLOCKr/r/r/r1rUpsrUcCs˜t|jƒ}d}t|ƒD].\}}t|tƒrt|ƒ}||k    rd}|||<qt|ƒdkr‚t|tƒr‚|jr‚t    |j
|dj
ƒ|d_
|dS|r|  |¡S|SdS)z`Recursively collapse any single-exception groups into that single contained
    exception.
 
    FTrrN) ÚlistÚ
exceptionsÚ    enumerateÚ
isinstancer-Úcollapse_exception_groupÚlenrZcollapserr6Zderive)ZexcgrouprYÚmodifiedÚir<Únew_excr/r/r1r\zs"
 
 
ÿ
 
r\)ÚeqrAc@sPeZdZdZejedZejddZdd„Z    dd„Z
d    d
„Z d d „Z d d„Z dS)Ú    Deadlinesz™A container of deadlined cancel scopes.
 
    Only contains scopes with non-infinite deadlines that are currently
    attached to at least one task.
 
    rGr©ÚdefaultcCs(t|j|t|ƒ|fƒ|jd7_dS©Nr)r Ú_heapÚidÚ_active©rJrNÚ cancel_scoper/r/r1Úadd¡sz Deadlines.addcCs|jd8_dSre)rhrir/r/r1Úremove¥szDeadlines.removecCs4|jr0|jd\}}}||jkr$|St|jƒqtS)Nr)rfÚ_registered_deadliner r)rJrNÚ_rjr/r/r1Ú next_deadline¨s 
 zDeadlines.next_deadlinecCsntƒ}g}|jD]8\}}}||jkr||kr.q| |¡| |||f¡qt|ƒ|jks\t‚t|ƒ||_dSr.)    ÚsetrfrmrkÚappendr]rhÚAssertionErrorr
)rJÚseenZ pruned_heaprNZ
tiebreakerrjr/r/r1Ú_prune²s
 
zDeadlines._prunecCshd}|jrD|jdd|krDt|jƒ\}}}||jkrd}| ¡qt|jƒ|jdtkrd| ¡|S)NFrTr&)rfr rmÚcancelr]rhÚ!DEADLINE_HEAP_MIN_PRUNE_THRESHOLDrt)rJÚnowZ did_somethingrNrnrjr/r/r1ÚexpireÇs
 
zDeadlines.expireN)rPrQrRÚ__doc__rSrTrXrfrhrkrlrortrxr/r/r/r1rb“s  
rbc@sÐeZdZdZe ¡ZejddZejdddZeje    dddZ
eje    dddZ ejddddZ dd    „Z ed
d „ƒZejd d „ƒZed d„ƒZedd„ƒZdd„Zdd„Zedd„ƒZdd„Zdd„Zdd„ZdS)Ú CancelStatusavTracks the cancellation status for a contiguous extent
    of code that will become cancelled, or not, as a unit.
 
    Each task has at all times a single "active" CancelStatus whose
    cancellation state determines whether checkpoints executed in that
    task raise Cancelled. Each 'with CancelScope(...)' context is
    associated with a particular CancelStatus.  When a task enters
    such a context, a CancelStatus is created which becomes the active
    CancelStatus for that task; when the 'with' block is exited, the
    active CancelStatus for that task goes back to whatever it was
    before.
 
    CancelStatus objects are arranged in a tree whose structure
    mirrors the lexical nesting of the cancel scope contexts.  When a
    CancelStatus becomes cancelled, it notifies all of its direct
    children, who become cancelled in turn (and continue propagating
    the cancellation down the tree) unless they are shielded. (There
    will be at most one such child except in the case of a
    CancelStatus that immediately encloses a nursery.) At the leaves
    of this tree are the tasks themselves, which get woken up to deliver
    an abort when their direct parent CancelStatus becomes cancelled.
 
    You can think of CancelStatus as being responsible for the
    "plumbing" of cancellations as oppposed to CancelScope which is
    responsible for the origination of them.
 
    FrcN©rdÚrepr)rHÚinitr|)rdr}r|cCs$|jdk    r |jj |¡| ¡dSr.)Ú_parentÚ    _childrenrkÚ recalculaterIr/r/r1Ú__attrs_post_init__s
z CancelStatus.__attrs_post_init__cCs|jSr.)r~rIr/r/r1Úparent"szCancelStatus.parentcCsB|jdk    r|jj |¡||_|jdk    r>|jj |¡| ¡dSr.)r~rrlrkr€)rJr‚r/r/r1r‚&s 
 
cCs
t|jƒSr.©Ú    frozensetrrIr/r/r1Úchildren/szCancelStatus.childrencCs
t|jƒSr.)r„Ú_tasksrIr/r/r1Útasks3szCancelStatus.taskscCs |dk    r||krdS|j}qdS)z…Returns true if this cancel status is a direct or indirect
        parent of cancel status *other*, or if *other* is *self*.
        NTF)r‚)rJÚotherr/r/r1Úencloses7s
zCancelStatus.enclosescCsLd|_|js|jrH| ¡d|_|jD] }| ¡q&|jD] }| ¡q:dS©NT)r‚r†rÚ_mark_abandonedÚeffectively_cancelledÚ'_attempt_delivery_of_any_pending_cancelr€)rJÚtaskÚchildr/r/r1ÚcloseAs 
 
 
zCancelStatus.closecCs|jdk    o|jj o|jjSr.)r~Ú_scopeÚshieldrŒrIr/r/r1Ú$parent_cancellation_is_visible_to_us]s
 
ÿýz1CancelStatus.parent_cancellation_is_visible_to_uscCsZ|g}|rV| ¡}|jjp|j}||jkr||_|rH|jD] }| ¡q:| |j¡qdSr.)    Úpopr‘Ú cancel_calledr“rŒr†rÚextendr)rJÚtodoÚcurrentZ    new_staterŽr/r/r1r€esþ
 
 
zCancelStatus.recalculatecCsd|_|jD] }| ¡q dSrŠ)Úabandoned_by_misnestingrr‹)rJrr/r/r1r‹xs
zCancelStatus._mark_abandonedcCs:|jr t S|jdks|jjr&|jjSt|jj|j ¡ƒSr.)rŒrr~r‘r’rNÚminÚeffective_deadlinerIr/r/r1r›}s
zCancelStatus.effective_deadline)rPrQrRryrSrTr‘rŒr~rprr†r™rÚpropertyr‚Úsetterr…r‡r‰rr“r€r‹r›r/r/r/r1rzØs.
 
 
 
 
 
 
rza
This is probably a bug in your code, that has caused Trio's internal state to
become corrupted. We'll do our best to recover, but from now on there are
no guarantees.
 
Typically this is caused by one of the following:
  - yielding within a generator or async generator that's opened a cancel
    scope or nursery (unless the generator is a @contextmanager or
    @asynccontextmanager); see https://github.com/python-trio/trio/issues/638
  - manually calling __enter__ or __exit__ on a trio.CancelScope, or
    __aenter__ or __aexit__ on the object returned by trio.open_nursery();
    doing so correctly is difficult and you should use @[async]contextmanager
    instead, or maybe [Async]ExitStack
  - using [Async]ExitStack to interleave the entries/exits of cancel scopes
    and/or nurseries in a way that couldn't be achieved by some nesting of
    'with' and 'async with' blocks
  - using the low-level coroutine object protocol to execute some parts of
    an async function in a different cancel scope/nursery context than
    other parts
If you don't believe you're doing any of these things, please file a bug:
https://github.com/python-trio/trio/issues/new
)rar|rAc@söeZdZdZejdddZejdddZejeddZ    ejdddZ
ejdddZ ejeddZ ejdddZ edd„ƒZd    d
„Zd d „Zd d„Zeedd„ƒƒZedd„ƒZejdd„ƒZedd„ƒZejedd„ƒƒZedd„ƒZedd„ƒZdS)Ú CancelScopeaA *cancellation scope*: the link between a unit of cancellable
    work and Trio's cancellation system.
 
    A :class:`CancelScope` becomes associated with some cancellable work
    when it is used as a context manager surrounding that work::
 
        cancel_scope = trio.CancelScope()
        ...
        with cancel_scope:
            await long_running_operation()
 
    Inside the ``with`` block, a cancellation of ``cancel_scope`` (via
    a call to its :meth:`cancel` method or via the expiry of its
    :attr:`deadline`) will immediately interrupt the
    ``long_running_operation()`` by raising :exc:`Cancelled` at its
    next :ref:`checkpoint <checkpoints>`.
 
    The context manager ``__enter__`` returns the :class:`CancelScope`
    object itself, so you can also write ``with trio.CancelScope() as
    cancel_scope:``.
 
    If a cancel scope becomes cancelled before entering its ``with`` block,
    the :exc:`Cancelled` exception will be raised at the first
    checkpoint inside the ``with`` block. This allows a
    :class:`CancelScope` to be created in one :ref:`task <tasks>` and
    passed to another, so that the first task can later cancel some work
    inside the second.
 
    Cancel scopes are not reusable or reentrant; that is, each cancel
    scope can be used for at most one ``with`` block.  (You'll get a
    :exc:`RuntimeError` if you violate this rule.)
 
    The :class:`CancelScope` constructor takes initial values for the
    cancel scope's :attr:`deadline` and :attr:`shield` attributes; these
    may be freely modified after construction, whether or not the scope
    has been entered yet, and changes take immediate effect.
    NF)rdr}T)rdZkw_onlyc    Csdt ¡}|jrtdƒ‚d|_tƒ|jkr0| ¡| ¡"t||j    d|_    | 
|j    ¡W5QRX|S)Nz;Each CancelScope may only be used for a single 'with' blockT)Zscoper‚) r'Ú current_taskÚ_has_been_enteredÚ RuntimeErrorrMÚ    _deadlineruÚ!_might_change_registered_deadlinerzÚ_cancel_statusÚ_activate_cancel_status)rJrŽr/r/r1Ú    __enter__Ïsÿ 
zCancelScope.__enter__c    Cs8|jdkr"td |¡ƒ}||_|Stƒ}|j|jk    rš|jjr>q¨|j |j¡shtd ||t¡ƒ}||_|Std |||jjt¡ƒ}||_|}|     |jj
¡n|     |jj
¡|dk    r|jj r|jj st |tƒrÜd|_d}n4t |tƒr| t¡\}}|rd|_|rt|ƒ}|j ¡| ¡ d|_W5QRX|S)NzRCancel scope stack corrupted: attempted to exit {!r} which had already been exitedzKCancel scope stack corrupted: attempted to exit {!r} from unrelated {!r}
{}zbCancel scope stack corrupted: attempted to exit {!r} in {!r} that's still within its child {!r}
{}T)r¤r¡ÚformatÚ __context__rŸr™r‰ÚMISNESTING_ADVICEr‘r¥r‚rŒr“r[rÚcancelled_caughtr-Úsplitr\rr£)rJr<r`Z
scope_taskÚmatchedr/r/r1Ú_closeÞsj
ÿÿ þÿûÿ    ÿþý
 
 
zCancelScope._closec    Cspdtƒt<| |¡}|dkr dS||kr,dS|j}z|‚W5t ¡\}}}||ksVt‚||_~~~~tƒXdS©NTF)Úlocalsrr­r¨ÚsysÚexc_inforr)rJÚetyper<r=Z"remaining_error_after_cancel_scopeÚ old_contextrnÚvaluer/r/r1Ú__exit__'s
 
 zCancelScope.__exit__cCs–|jdk    rd}n|jrd}nd}|jr,d}nX|jtkr<d}nHz
tƒ}Wntk
r^d}Yn&Xd t|j|ƒ|j|kr~dnd¡}d     t    |ƒ||¡S)
NÚactiveZexitedÚunboundz , cancelledÚz, deadline is {:.2f} seconds {}zfrom nowZagoz!<trio.CancelScope at {:#x}, {}{}>)
r¤r Ú_cancel_calledr¢rrMr¡r§Úabsrg)rJZbindingÚstaterwr/r/r1Ú__repr__Is$
 
 
 
 þzCancelScope.__repr__c
cs¤z
dVW5|j}|jdks"|jr(t}n|j}||krž||_tj}|jrR|j     ¡}|tkrh|j 
||¡|tkr~|j  ||¡|jrž|j     ¡}||krž|  ¡XdSr.) rmr¤r¹rr¢ÚGLOBAL_RUN_CONTEXTÚrunnerÚis_guestÚ    deadlinesrorlrkÚforce_guest_tick_asap)rJÚoldÚnewr¾Zold_next_deadlineZnew_next_deadliner/r/r1r£bs&
 
 
z-CancelScope._might_change_registered_deadlinecCs|jS)a4Read-write, :class:`float`. An absolute time on the current
        run's clock at which this scope will automatically become
        cancelled. You can adjust the deadline by modifying this
        attribute, e.g.::
 
           # I need a little more time!
           cancel_scope.deadline += 30
 
        Note that for efficiency, the core run loop only checks for
        expired deadlines every once in a while. This means that in
        certain cases there may be a short delay between when the clock
        says the deadline should have expired, and when checkpoints
        start raising :exc:`~trio.Cancelled`. This is a very obscure
        corner case that you're unlikely to notice, but we document it
        for completeness. (If this *does* cause problems for you, of
        course, then `we want to know!
        <https://github.com/python-trio/trio/issues>`__)
 
        Defaults to :data:`math.inf`, which means "no deadline", though
        this can be overridden by the ``deadline=`` argument to
        the :class:`~trio.CancelScope` constructor.
        )r¢rIr/r/r1rN{szCancelScope.deadlinec    Cs"| ¡t|ƒ|_W5QRXdSr.)r£Úfloatr¢)rJZ new_deadliner/r/r1rN•s
cCs|jS)aRead-write, :class:`bool`, default :data:`False`. So long as
        this is set to :data:`True`, then the code inside this scope
        will not receive :exc:`~trio.Cancelled` exceptions from scopes
        that are outside this scope. They can still receive
        :exc:`~trio.Cancelled` exceptions from (1) this scope, or (2)
        scopes inside this scope. You can modify this attribute::
 
           with trio.CancelScope() as cancel_scope:
               cancel_scope.shield = True
               # This cannot be interrupted by any means short of
               # killing the process:
               await sleep(10)
 
               cancel_scope.shield = False
               # Now this can be cancelled normally:
               await sleep(10)
 
        Defaults to :data:`False`, though this can be overridden by the
        ``shield=`` argument to the :class:`~trio.CancelScope` constructor.
        )Ú_shieldrIr/r/r1r’šszCancelScope.shieldcCs0t|tƒstdƒ‚||_|jdk    r,|j ¡dS)Nzshield must be a bool)r[ÚboolÚ    TypeErrorrÅr¤r€)rJÚ    new_valuer/r/r1r’²s
 
 
c    Cs<|jr
dS| ¡ d|_W5QRX|jdk    r8|j ¡dS)z¥Cancels this scope immediately.
 
        This method is idempotent, i.e., if the scope was already
        cancelled then this method silently does nothing.
        NT)r¹r£r¤r€rIr/r/r1ru»s 
 
zCancelScope.cancelcCs0|jdk    s|js*|js*tƒ|jkr*| ¡|jS)a!Readonly :class:`bool`. Records whether cancellation has been
        requested for this scope, either by an explicit call to
        :meth:`cancel` or by the deadline expiring.
 
        This attribute being True does *not* necessarily mean that the
        code within the scope has been, or will be, affected by the
        cancellation. For example, if :meth:`cancel` was called after
        the last checkpoint in the ``with`` block, when it's too late to
        deliver a :exc:`~trio.Cancelled` exception, then this attribute
        will still be True.
 
        This attribute is mostly useful for debugging and introspection.
        If you want to know whether or not a chunk of code was actually
        cancelled, then :attr:`cancelled_caught` is usually more
        appropriate.
        N)r¤r r¹rMr¢rurIr/r/r1r•ÉszCancelScope.cancel_called)rPrQrRryrSrTr¤r rrmr¹rªr¢rÅrr¦r­rµr¼rr£rœrNrr’rur•r/r/r/r1ržs:&
I" 
 
 
 
rž)Ú    metaclass)raÚhashr|c@sFeZdZe ¡Ze ¡ZejddZejddZdd„Z    ddd„Z
dS)    Ú _TaskStatusFrcNcCsd t|ƒ¡S)Nz<Task status object at {:#x}>)r§rgrIr/r/r1r¼õsz_TaskStatus.__repr__cCsü|jrtdƒ‚d|_||_|jjjr(dS|jjr4t‚|jj    }t
ƒ|j_    |D] }|j|_ d|_ |jj      |¡qJ|jjj}t
|jjjƒ}| |jj¡|D]
}d|_q–|D]}| d¡q¦|D]}|jj|_qº|D]}| |jj¡qÎ|jj    rît‚|j ¡dS)Nz.called 'started' twice on the same task statusT)Ú_called_startedr¡Ú_valueÚ _old_nurseryr¤rŒÚ _new_nurseryÚ_closedrrrrpÚ_parent_nurseryÚ_eventual_parent_nurseryrkr…r‡ÚdiscardÚ _parent_taskr‚r¥Ú_check_nursery_closed)rJr´r‡rŽZcancel_status_childrenZcancel_status_tasksÚ cancel_statusr/r/r1Ústartedøs4
 
 
 
   z_TaskStatus.started)N) rPrQrRrSrTrÎrÏrÌrÍr¼r×r/r/r/r1rËîs   rËc@sDeZdZdZejddZedd„ƒZedd„ƒZ    dd    „Z
d
d „Z d S) ÚNurseryManageraNursery context manager.
 
    Note we explicitly avoid @asynccontextmanager and @async_generator
    since they add a lot of extraneous stack frames to exceptions, as
    well as cause problematic behavior with handling of StopIteration
    and StopAsyncIteration.
 
    FrccÃs.tƒ|_|j ¡t tƒ|j|j¡|_|jSr.)ržr‘r¦ÚNurseryÚ_createrŸÚstrict_exception_groupsÚ_nurseryrIr/r/r1Ú
__aenter__:s
ÿzNurseryManager.__aenter__c        Ãst|j |¡IdH}|j |¡}|dkr*dS||kr6dS|j}z|‚W5t ¡\}}}||ks`t‚||_~~~~XdSr®)rÜÚ_nested_child_finishedr‘r­r¨r°r±rr)    rJr²r<r=r`Zcombined_error_from_nurseryr³rnr´r/r/r1Ú    __aexit__Cs  zNurseryManager.__aexit__cCs tdƒ‚dS)Nz@use 'async with open_nursery(...)', not 'with open_nursery(...)')r¡rIr/r/r1r¦[sÿzNurseryManager.__enter__cCsds tdƒ‚dS)NFz#Never called, but should be defined)rrrIr/r/r1rµ`szNurseryManager.__exit__N) rPrQrRryrSrTrÛrrÝrßr¦rµr/r/r/r1rØ-s     
 
rØcCs|dkrtjj}t|dS)a°Returns an async context manager which must be used to create a
    new `Nursery`.
 
    It does not block on entry; on exit it blocks until all child tasks
    have exited.
 
    Args:
      strict_exception_groups (bool): If true, even a single raised exception will be
          wrapped in an exception group. This will eventually become the default
          behavior. If not specified, uses the value passed to :func:`run`.
 
    N©rÛ)r½r¾rÛrØràr/r/r1Ú open_nurseryds rác@steZdZdZdd„Zedd„ƒZedd„ƒZdd    „Zd
d „Z    d d „Z
dd„Z ddœdd„Z ddœdd„Z dd„ZdS)rÙatA context which may be used to spawn (or cancel) child tasks.
 
    Not constructed directly, use `open_nursery` instead.
 
    The nursery will remain open until all child tasks have completed,
    or until it is cancelled, at which point it will cancel all its
    remaining child tasks and close.
 
    Nurseries ensure the absence of orphaned Tasks, since all running
    tasks will belong to an open Nursery.
 
    Attributes:
        cancel_scope:
            Creating a nursery also implicitly creates a cancellation scope,
            which is exposed as the :attr:`cancel_scope` attribute. This is
            used internally to implement the logic where if an error occurs
            then ``__aexit__`` cancels all children, but you can use it for
            other things, e.g. if you want to explicitly cancel all children
            in response to some external event.
    cCsb||_||_|j |¡|j|_||_|jj|jks8t‚tƒ|_g|_    d|_
d|_ d|_ d|_ dS)NTFr)rÔÚ_strict_exception_groupsÚ_child_nurseriesrqr¤rjrrrprÚ _pending_excsÚ_nested_child_runningÚ_parent_waiting_in_aexitÚ_pending_startsrÐ)rJÚ parent_taskrjrÛr/r/r1Ú__init__s zNursery.__init__cCs
t|jƒS)zk(`frozenset`): Contains all the child :class:`~trio.lowlevel.Task`
        objects which are still running.rƒrIr/r/r1Ú child_tasks¢szNursery.child_taskscCs|jS)z<(`~trio.lowlevel.Task`):  The Task that opened this nursery.)rÔrIr/r/r1rè¨szNursery.parent_taskcCs|j |¡|j ¡dSr.)rärqrjru)rJr<r/r/r1Ú_add_exc­s zNursery._add_exccCs8t|j|j|jgƒs4d|_|jr4d|_tj |j    ¡dSr®)
ÚanyrårrçrÐrær½r¾Ú
reschedulerÔrIr/r/r1rÕ±s
zNursery._check_nursery_closedcCs.|j |¡t|tƒr"| |j¡| ¡dSr.)rrlr[rrëÚerrorrÕ)rJrŽÚoutcomer/r/r1Ú_child_finished¸s 
 zNursery._child_finishedc
ƒsÆ|dk    rˆ |¡dˆ_ˆ ¡ˆjsH‡fdd„}dˆ_t|ƒIdHn>ztƒIdHWn,tk
r„}zˆ |¡W5d}~XYnXˆjj     
¡}|ˆksžt ‚ˆj rÂzt ˆj ˆj dW¢Sˆ` XdS)NFcsˆ t|ƒj¡tjSr.)rërrîrZFAILED)Ú raise_cancelrIr/r1ÚabortedÊsz/Nursery._nested_child_finished.<locals>.abortedT)Z    _collapse)rërårÕrÐrærÚ
checkpointÚ BaseExceptionrÔrãr”rrrärrâ)rJZnested_child_excròr<Úpoppedr/rIr1rÞ¾s*
   ÿ
zNursery._nested_child_finishedN)ÚnamecGstj ||||¡dS)uVCreates a child task, scheduling ``await async_fn(*args)``.
 
        This and :meth:`start` are the two fundamental methods for
        creating concurrent tasks in Trio.
 
        Note that this is *not* an async function and you don't use await
        when calling it. It sets up the new task, but then returns
        immediately, *before* it has a chance to run. The new task won’t
        actually get a chance to do anything until some later point when
        you execute a checkpoint and the scheduler decides to run it.
        If you want to run a function and immediately wait for its result,
        then you don't need a nursery; just use ``await async_fn(*args)``.
        If you want to wait for the task to initialize itself before
        continuing, see :meth:`start`.
 
        It's possible to pass a nursery object into another task, which
        allows that task to start new child tasks in the first task's
        nursery.
 
        The child task inherits its parent nursery's cancel scopes.
 
        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,
                  :meth:`start_soon` 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.
 
        Raises:
            RuntimeError: If this nursery is no longer open
                          (i.e. its ``async with`` block has
                          exited).
        N)r½r¾Ú
spawn_impl)rJÚasync_fnröÚargsr/r/r1Ú
start_soonås)zNursery.start_soonc
Çs¢|jrtdƒ‚zv|jd7_tƒ4IdHš6}t||ƒ}tj||d}tj     
||||¡}||_ W5QIdHRX|j s|tdƒ‚|j W¢S|jd8_| ¡XdS)aöCreates and initializes a child task.
 
        Like :meth:`start_soon`, but blocks until the new task has
        finished initializing itself, and optionally returns some
        information from it.
 
        The ``async_fn`` must accept a ``task_status`` keyword argument,
        and it must make sure that it (or someone) eventually calls
        ``task_status.started()``.
 
        The conventional way to define ``async_fn`` is like::
 
            async def async_fn(arg1, arg2, *, task_status=trio.TASK_STATUS_IGNORED):
                ...
                task_status.started()
                ...
 
        :attr:`trio.TASK_STATUS_IGNORED` is a special global object with
        a do-nothing ``started`` method. This way your function supports
        being called either like ``await nursery.start(async_fn, arg1,
        arg2)`` or directly like ``await async_fn(arg1, arg2)``, and
        either way it can call ``task_status.started()`` without
        worrying about which mode it's in. Defining your function like
        this will make it obvious to readers that it supports being used
        in both modes.
 
        Before the child calls ``task_status.started()``, it's
        effectively run underneath the call to :meth:`start`: if it
        raises an exception then that exception is reported by
        :meth:`start`, and does *not* propagate out of the nursery. If
        :meth:`start` is cancelled, then the child task is also
        cancelled.
 
        When the child calls ``task_status.started()``, it's moved out
        from underneath :meth:`start` and into the given nursery.
 
        If the child task passes a value to
        ``task_status.started(value)``, then :meth:`start` returns this
        value. Otherwise it returns ``None``.
        ú!Nursery is closed to new arrivalsrN)Ú task_statusz2child exited without calling task_status.started())rÐr¡rçrÕrárËÚ    functoolsÚpartialr½r¾r÷rÒrÌrÍ)rJrørörùZ old_nurseryrüZthunkrŽr/r/r1Ústarts&)
ÿ
z Nursery.startcCs|jr
t‚dSr.)rrrrIr/r/r1Ú__del__PszNursery.__del__)rPrQrRryrérœrêrèrërÕrðrÞrúrÿrr/r/r/r1rÙws
 
'+@rÙ)rarÊr|rAc@seZdZe ¡Ze ¡Ze ¡Ze ¡Ze ¡Z    ejde
  ¡j dZ ejddZejddZejddZejddZejedZejddZejddZejddZdd„Zed    d
„ƒZed d „ƒZed d„ƒZejdddZdd„Zdd„Zdd„Zdd„Z dS)ÚTaskF)r}rHNrcrGrcCsd |jt|ƒ¡S)Nz<Task {!r} at {:#x}>)r§rörgrIr/r/r1r¼}sz Task.__repr__cCs|jS)z²The nursery this task is inside (or None if this is the "init"
        task).
 
        Example use case: drawing a visualization of the task tree in a
        debugger.
 
        )rÑrIr/r/r1Úparent_nursery€s    zTask.parent_nurserycCs|jS)aThe nursery this task will be inside after it calls
        ``task_status.started()``.
 
        If this task has already called ``started()``, or if it was not
        spawned using `nursery.start() <trio.Nursery.start>`, then
        its `eventual_parent_nursery` is ``None``.
 
        )rÒrIr/r/r1Úeventual_parent_nursery‹s
zTask.eventual_parent_nurserycCs
t|jƒS)zqThe nurseries this task contains.
 
        This is a list, with outer nurseries before inner nurseries.
 
        )rXrãrIr/r/r1Úchild_nurseries—szTask.child_nurseriesr{cCsJ|jdk    r|jj |¡||_|jdk    rF|jj |¡|jjrF| ¡dSr.)r¤r†rlrkrŒr)rJrÖr/r/r1r¥¨s
 
zTask._activate_cancel_statuscCsD| |¡}t|ƒtk    rtdƒ‚d|_|tjkr@|j |t|ƒ¡dS)Nz%abort function must return Abort enum)Ú _abort_funcÚtyperrÚ    SUCCEEDEDÚ_runnerrír)rJrñÚsuccessr/r/r1Ú_attempt_abort±s 
 
zTask._attempt_abortcCs0|jdkrdS|jjsdSdd„}| |¡dS)NcSs t ¡‚dSr.)rrÚr/r/r/r1rñÅszBTask._attempt_delivery_of_any_pending_cancel.<locals>.raise_cancel)rr¤rŒr
©rJrñr/r/r1r¿s 
z,Task._attempt_delivery_of_any_pending_cancelcs4ˆjjs t‚ˆjdkrdS‡fdd„}ˆ |¡dS)Ncsdˆj_t‚dS)NF)rÚ
ki_pendingÚKeyboardInterruptr/rIr/r1rñÏsz:Task._attempt_delivery_of_pending_ki.<locals>.raise_cancel)rr rrrr
r r/rIr1Ú_attempt_delivery_of_pending_kiÊs
 
 z$Task._attempt_delivery_of_pending_ki)!rPrQrRrSrTrÑÚcororröÚcontextÚ    itertoolsr>Ú__next__Ú_counterÚ _next_send_fnÚ
_next_sendrÚcustom_sleep_datarXrãrÒÚ_cancel_pointsÚ_schedule_pointsr¼rœrrrr¤r¥r
rrr/r/r/r1rYs4        
 
 
 
     rc@seZdZUded<eed<dS)Ú
RunContextÚRunnerr¾rŽN)rPrQrRÚ__annotations__rr/r/r/r1rÛs
r)r@c@s4eZdZe ¡Ze ¡Ze ¡Ze ¡Ze ¡Z    dS)Ú_RunStatisticsN)
rPrQrRrSrTÚ tasks_livingÚtasks_runnableÚseconds_to_next_deadlineÚ io_statisticsÚrun_sync_soon_queue_sizer/r/r/r1rãs
r)rarÊrAc@sdeZdZUe ¡Ze ¡Ze ¡Ze ¡Ze ¡Z    dd„Z
e ge fe d<eje
edZdd„ZdS)Ú
GuestStatecCstdƒSr.)rr/r/r/r1rErFzGuestState.<lambda>Ú_value_factory)rHrc
sàzˆj ˆj¡‰WnXtk
r6ˆ ˆjj¡YdStk
rj}zˆ t|ƒ¡WY¢dSd}~XYnXt    ˆjj
j dƒ}ˆdks”t |tƒs”|j r°|ˆ_dˆj_ˆ ˆj¡n,dˆj_‡‡fdd„}‡fdd„}t||ƒdS)NrTFcsˆjj ˆ¡Sr.)r¾Ú
io_managerÚ
get_eventsr/©rJÚtimeoutr/r1r%sz)GuestState.guest_tick.<locals>.get_eventscs‡‡fdd„}ˆ |¡dS)Ncsˆˆ_dˆj_ˆ ¡dSrŠ)Úunrolled_run_next_sendr¾Úguest_tick_scheduledÚ
guest_tickr/)Úevents_outcomerJr/r1Úin_main_thread"sz>GuestState.guest_tick.<locals>.deliver.<locals>.in_main_thread)Úrun_sync_soon_threadsafe)r+r,rI)r+r1Údeliver!sz&GuestState.guest_tick.<locals>.deliver)r(ÚsendÚunrolled_run_genÚ StopIterationÚ done_callbackr¾Úmain_task_outcomerrrr$r%r[r´r)Úrun_sync_soon_not_threadsafer*r$)rJr<r+r%r.r/r&r1r*    s" zGuestState.guest_tickN)rPrQrRrSrTr¾r-r4r2r0r#rrrrr(r*r/r/r/r1r"ÿs
r"c@s¸eZdZUe ¡Ze ¡Zeed<e ¡Z    e ¡Z
e ¡Z eje dZ ejedZejedZejedZejddZejddZejddZejddZejddZejedZejddZejedZejedZejddZ ejddZ!dd„Z"dd    „Z#e$d
d „ƒZ%e$d d „ƒZ&e$dd„ƒZ'e$dd„ƒZ(e$e)fdd„ƒZ*dddœdd„Z+dd„Z,e$dddœdd„ƒZ-dd„Z.e$dd„ƒZ/ejddZ0d d!„Z1d"d#„Z2eje3dZ4e$d'd%d&„ƒZ5dS)(rÚ instrumentsrGNrcFcCs|jr
dSd|_|j ¡dSrŠ)r)r$Z force_wakeuprIr/r/r1rÁMszRunner.force_guest_tick_asapcCsB|j ¡|j ¡|j ¡d|jkr4|j d¡|j ¡dS)NZ    after_run)r$rÚ entry_queueÚ    asyncgensr5ÚcallÚ
ki_managerrIr/r/r1rSs 
 
 
 
 z Runner.closecCs<|j ¡| ¡}tt|jƒt|jƒ||j ¡|j     
¡dS)ahReturns 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.lowlevel.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.
 
        )rrrr r!) rÀrorMrr]r‡Úrunqr$Z
statisticsr6Úsize)rJrr/r/r1Úcurrent_statistics\sûzRunner.current_statisticscCs
|j ¡S)zÒ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`.
 
        )ÚclockrMrIr/r/r1rM}s zRunner.current_timecCs|jS)z-Returns the current :class:`~trio.abc.Clock`.)r=rIr/r/r1Ú current_clockŠszRunner.current_clockcCs|jS)z{Returns the current root :class:`Task`.
 
        This is the task that is the ultimate parent of all other tasks.
 
        )Ú    init_taskrIr/r/r1Úcurrent_root_taskszRunner.current_root_taskcCs„|tkrtdƒ}|j|kst‚|jdks,t‚|jj|_||_d|_d|_    |j
s\|j r\|  ¡|j
  |¡d|jkr€|j d|¡dS)aËReschedule the given task with the given
        :class:`outcome.Outcome`.
 
        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.lowlevel.Task): the task to be rescheduled. Must be blocked
              in a call to :func:`wait_task_rescheduled`.
          next_send (outcome.Outcome): the value (or error) to return (or
              raise) from :func:`wait_task_rescheduled`.
 
        NZtask_scheduled)Ú_NO_SENDrrrrrrr/rrrr:r¿rÁrqr5r8)rJrŽÚ    next_sendr/r/r1ríœs
 
zRunner.reschedule©Ú system_taskrc
CsH|dk    r|jrtdƒ‚|dkr,|jdks,t‚t|f|žŽ}|dkrF|}t|tjƒrX|j}t|t    ƒs”zd 
|j |j ¡}Wnt k
r’t|ƒ}YnX|dkr²|r¬|j ¡}ntƒ}t|dƒsÌdd„}||ƒ}|jj t|¡tj|||||d}    |j |    ¡|dk    r|j |    ¡|     |j¡d|jkr8|j d|    ¡|  |    d¡|    S)Nrûz{}.{}Úcr_framecÓs
|IdHSr.r/)Z    orig_coror/r/r1Úpython_wrapperæsz)Runner.spawn_impl.<locals>.python_wrapper)rrr¾rörZ task_spawned)!rÐr¡r?rrr*r[rýrþÚfuncÚstrr§rQrRÚAttributeErrorr|Úsystem_contextÚcopyrÚhasattrrEÚf_localsÚ
setdefaultrrrÚr‡rkrr¥r¤r5r8rí)
rJrørùZnurseryrörDrrrFrŽr/r/r1r÷¾sJ  
 
ÿ 
    zRunner.spawn_implc
Csæ|jdk    rp|jjrp|jjdkrpztd |t¡ƒ‚Wn<tk
rn}zt|tƒrV|j|_    t|ƒ}W5d}~XYnX| 
d¡|j   |¡||j kr¤| ¡|j rÊt‚n&||jkr¼||_tdƒ}|j ||¡d|jkrâ|j d|¡dS)Nz`Cancel scope stack corrupted: cancel scope surrounding {!r} was closed before the task exited
{}Ú task_exited)r¤r™r‚r¡r§r©r[rrîr¨r¥r‡rlr?ÚunwraprÚ    main_taskr3rrÑrðr5r8)rJrŽrïr`r/r/r1rOÿs:ÿþ
ý    þÿ
 
 
 
 
zRunner.task_exited)rörcGs"t d¡|j|||j|d|dS)a»    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 (and
          come up with some plan for what to do with a
          :exc:`KeyboardInterrupt`, given that system tasks aren't allowed to
          raise exceptions).
 
        * System tasks do not inherit context variables from their creator.
 
        Towards the end of a call to :meth:`trio.run`, after the main
        task and all system tasks have exited, the system nursery
        becomes closed. At this point, new calls to
        :func:`spawn_system_task` will raise ``RuntimeError("Nursery
        is closed to new arrivals")`` instead of creating a system
        task. It's possible to encounter this state either in
        a ``finally`` block in an async generator, or in a callback
        passed to :meth:`TrioToken.run_sync_soon` at the right moment.
 
        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.
          context: An optional ``contextvars.Context`` object with context variables
              to use for this task. You would normally get a copy of the current
              context with ``context = contextvars.copy_context()`` and then you would
              pass that ``context`` object here.
 
        Returns:
          Task: the newly spawned task
 
        ÚtrioTrC)r    rpr÷Úsystem_nursery)rJrørörrùr/r/r1Úspawn_system_task/s5
úzRunner.spawn_system_taskc Ãs"tƒ4IdHš}tƒ4IdHšÆ|_tƒ4IdHš˜}z| |||d¡|_Wnbtk
r¬}zDt|ƒ|_WY¢4W5QIdHR£W5QIdHR£W5QIdHR£dSd}~XYnX|j|jjd|dddW5QIdHRX|jj     
¡W5QIdHRX|j   |¡IdH|j     
¡W5QIdHRXdS)Nr/z<TrioToken.run_sync_soon task>T©rD) rárSr÷rQrôrr3r6rŽrjrur7Zfinalize_remaining)rJrørùZrun_sync_soon_nurseryZmain_task_nurseryr<r/r/r1r}ns.ÿ
 
Hû    z Runner.initcCs|jdkrt |j¡|_|jS)z[Retrieve the :class:`TrioToken` for the current call to
        :func:`trio.run`.
 
        N)Ú
trio_tokenrrÚr6rIr/r/r1Úcurrent_trio_token“s
zRunner.current_trio_tokencCs2d|_z|j |j¡Wntk
r,YnXdSrŠ)r r6Z run_sync_soonÚ_deliver_ki_cbrrIr/r/r1Ú
deliver_kiªs
zRunner.deliver_kicCs4|js
dS|jdk    st‚|jdk    r&dS|j ¡dSr.)r rQrrr3rrIr/r/r1rX±s 
zRunner._deliver_ki_cbçcƒs<tƒ}|t|ƒf‰|ˆjˆ<‡‡fdd„}t|ƒIdHdS)a¬
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.)
 
        Note that ``cushion`` is measured in *real* time, not the Trio clock
        time.
 
        If there are multiple tasks blocked in :func:`wait_all_tasks_blocked`,
        then the one with the shortest ``cushion`` is the one woken (and
        this task becoming unblocked resets the timers for the remaining
        tasks). If there are multiple tasks that have exactly the same
        ``cushion``, then all are woken.
 
        You should also consider :class:`trio.testing.Sequencer`, which
        provides a more explicit way to control execution ordering within a
        test, and will often produce more readable tests.
 
        Example:
          Here's an example of one way to test that Trio's locks are fair: we
          take the lock in the parent, start a child, wait for the child to be
          blocked waiting for the lock (!), and then check that we can't
          release and immediately re-acquire the lock::
 
             async def lock_taker(lock):
                 await lock.acquire()
                 lock.release()
 
             async def test_lock_fairness():
                 lock = trio.Lock()
                 await lock.acquire()
                 async with trio.open_nursery() as nursery:
                     nursery.start_soon(lock_taker, lock)
                     # child hasn't run yet, we have the lock
                     assert lock.locked()
                     assert lock._owner is trio.lowlevel.current_task()
                     await trio.testing.wait_all_tasks_blocked()
                     # now the child has run and is blocked on lock.acquire(), we
                     # still have the lock
                     assert lock.locked()
                     assert lock._owner is trio.lowlevel.current_task()
                     lock.release()
                     try:
                         # The child has a prior claim, so we can't have it
                         lock.acquire_nowait()
                     except trio.WouldBlock:
                         assert lock._owner is not trio.lowlevel.current_task()
                         print("PASS")
                     else:
                         print("FAIL")
 
        csˆjˆ=tjSr.)Úwaiting_for_idlerr©rn©ÚkeyrJr/r1Úabortsz,Runner.wait_all_tasks_blocked.<locals>.abortN)rŸrgr[r)rJÚcushionrŽr_r/r]r1Úwait_all_tasks_blockedÄs
; 
zRunner.wait_all_tasks_blocked)rZ)6rPrQrRrSrTr=r5r%rr$r9rÛÚdictZ_localsrr:rpr‡rbrÀr?rSrJrQr3rr6rVr#r7rÚclock_autojump_thresholdr¿r)rÁrr2r<rMr>r@rArír÷rOrTr}rWr rYrXr r[rar/r/r/r1r,s^
                   
 
 
 
"ÿ A0>%
     rcCs€ttdƒrtdƒ‚|dkr tƒ}t|ƒ}tƒ}tƒ}| tj    d¡t
ƒ}t ||||||d}|j   |¡| |j|¡|t_|S)z@Create a Runner object and install it as the GLOBAL_RUN_CONTEXT.r¾z+Attempted to call run() from inside a run()NrR)r=r5r$rJr9rÛ)rLr½r¡rBr%Ú TheIOManagerrr4r    rprrr7Z install_hooksÚinstallrYr¾)r=r5Ú*restrict_keyboard_interrupt_to_checkpointsrÛr$rJr9r¾r/r/r1Ú setup_runnerMs*
 
ú rgr/)r=r5rfrÛc Gsxd}t||||ƒ}t|||ƒ}d}    z| |    ¡}
Wntk
rHYqXYnX|j |
¡}    q"t|jtƒrl|jj    S|jj
‚dS)aj Run a Trio-flavored async function, and return the result.
 
    Calling::
 
       run(async_fn, *args)
 
    is the equivalent of::
 
       await async_fn(*args)
 
    except that :func:`run` can (and must) be called from a synchronous
    context.
 
    This is Trio's main entry point. Almost every other function in Trio
    requires that you be inside a call to :func:`run`.
 
    Args:
      async_fn: An async function.
 
      args: Positional arguments to be passed to *async_fn*. If you need to
          pass keyword arguments, then use :func:`functools.partial`.
 
      clock: ``None`` to use the default system-specific monotonic clock;
          otherwise, an object implementing the :class:`trio.abc.Clock`
          interface, like (for example) a :class:`trio.testing.MockClock`
          instance.
 
      instruments (list of :class:`trio.abc.Instrument` objects): Any
          instrumentation you want to apply to this run. This can also be
          modified during the run; see :ref:`instrumentation`.
 
      restrict_keyboard_interrupt_to_checkpoints (bool): What happens if the
          user hits control-C while :func:`run` is running? If this argument
          is False (the default), then you get the standard Python behavior: a
          :exc:`KeyboardInterrupt` exception will immediately interrupt
          whatever task is running (or if no task is running, then Trio will
          wake up a task to be interrupted). Alternatively, if you set this
          argument to True, then :exc:`KeyboardInterrupt` delivery will be
          delayed: it will be *only* be raised at :ref:`checkpoints
          <checkpoints>`, like a :exc:`Cancelled` exception.
 
          The default behavior is nice because it means that even if you
          accidentally write an infinite loop that never executes any
          checkpoints, then you can still break out of it using control-C.
          The alternative behavior is nice if you're paranoid about a
          :exc:`KeyboardInterrupt` at just the wrong place leaving your
          program in an inconsistent state, because it means that you only
          have to worry about :exc:`KeyboardInterrupt` at the exact same
          places where you already have to worry about :exc:`Cancelled`.
 
          This setting has no effect if your program has registered a custom
          SIGINT handler, or if :func:`run` is called from anywhere but the
          main thread (this is a Python limitation), or if you use
          :func:`open_signal_receiver` to catch SIGINT.
 
      strict_exception_groups (bool): If true, nurseries will always wrap even a single
          raised exception in an exception group. This can be overridden on the level of
          individual nurseries. This will eventually become the default behavior.
 
    Returns:
      Whatever ``async_fn`` returns.
 
    Raises:
      TrioInternalError: if an unexpected error is encountered inside Trio's
          internal machinery. This is a bug and you should `let us know
          <https://github.com/python-trio/trio/issues>`__.
 
      Anything else: if ``async_fn`` raises an exception, then :func:`run`
          propagates it.
 
    TN) rgÚ unrolled_runr/r1r$r%r[r3rr´rî) rør=r5rfrÛrùÚ__tracebackhide__r¾ÚgenrBr'r/r/r1r4ts"Pü 
 r4)r4Úhost_uses_signal_set_wakeup_fdr=r5rfrÛc GsRt||||ƒ}
d|
_d|
_|dkr&|}t|
|||t|
||    |dd} || jƒdS)aStart a "guest" run of Trio on top of some other "host" event loop.
 
    Each host loop can only have one guest run at a time.
 
    You should always let the Trio run finish before stopping the host loop;
    if not, it may leave Trio's internal data structures in an inconsistent
    state. You might be able to get away with it if you immediately exit the
    program, but it's safest not to go there in the first place.
 
    Generally, the best way to do this is wrap this in a function that starts
    the host loop and then immediately starts the guest run, and then shuts
    down the host when the guest run completes.
 
    Args:
 
      run_sync_soon_threadsafe: An arbitrary callable, which will be passed a
         function as its sole argument::
 
            def my_run_sync_soon_threadsafe(fn):
                ...
 
         This callable should schedule ``fn()`` to be run by the host on its
         next pass through its loop. **Must support being called from
         arbitrary threads.**
 
      done_callback: An arbitrary callable::
 
            def my_done_callback(run_outcome):
                ...
 
         When the Trio run has finished, Trio will invoke this callback to let
         you know. The argument is an `outcome.Outcome`, reporting what would
         have been returned or raised by `trio.run`. This function can do
         anything you want, but commonly you'll want it to shut down the
         host loop, unwrap the outcome, etc.
 
      run_sync_soon_not_threadsafe: Like ``run_sync_soon_threadsafe``, but
         will only be called from inside the host loop's main thread.
         Optional, but if your host loop allows you to implement this more
         efficiently than ``run_sync_soon_threadsafe`` then passing it will
         make things a bit faster.
 
      host_uses_signal_set_wakeup_fd (bool): Pass `True` if your host loop
         uses `signal.set_wakeup_fd`, and `False` otherwise. For more details,
         see :ref:`guest-run-implementation`.
 
    For the meaning of other arguments, see `trio.run`.
 
    TN)rk)r¾r-r4r2r0)rgr¿r)r"rhr*) rør-r2r4rkr=r5rfrÛrùr¾Z guest_stater/r/r1Ústart_guest_runÝs.=üüû rli€Qc
cs˜dtƒt<d}z>zÐ|s&|j j ¡d|jkr<|j d¡|j ¡|j|j||fdddd|_|jrâ|jrvd}n|j ¡}|j |¡}ttd|ƒtƒ}d}|jrÌ|j  ¡d\}    }
|    |krâ|    }t!j"}n|j#|krâ|j#}t!j$}d|jkrú|j d|¡|V} |j% &| ¡d|jkr&|j d|¡|j '¡} |j (| ¡rBd}|dk    rÄ|jsÄ| sÄ|t!j"krª|jrÄ|j )d¡\} }| d|    kr¨|j| =| *|¡nqĐqfn|t!j$ksºt+‚|j ,¡t-|jƒ}|j ¡t.rú|j/dd    „d
t0 1|¡nt0 2¡d kr| 3¡|rb| 4¡}|t_5d |jkr<|j d |¡|j6}|j7}d|_6|_7d}z|j8 9||¡}Wn~t:k
r˜}zt;|j<ƒ}W5d}~XYnRt=k
rè}z2|j>j?}t@tAƒD] }
|j?}qºt
| B|¡ƒ}~W5d}~XYnX|dk    r| C||¡d}n²|jDd 7_D|tEkr*| *|¡nŒtF|ƒtGkrt|jHd 7_H|jI|_J|jrj||jKkrj| L¡| M¡nBtF|ƒtNkr’| C||jO¡n$tPd Q|¡ƒ}| *||¡|jRjS|_6~d|jkrÒ|j d|¡t`5~~~qqbWnftTk
rtU VtWdƒ¡YnDtXk
r‚Yn.t=k
rJ}ztXdƒ|‚W5d}~XYnXW5tj ¡| ¡|jr’tƒ}t|j    t
ƒrˆ|j    j |_ t
|ƒ|_    XdS)NTZ
before_runz<init>rUrZbefore_io_waitZ after_io_waitcSs|jSr.)r)Útr/r/r1rE¯rFzunrolled_run.<locals>.<lambda>)r^gà?Zbefore_task_steprzºtrio.run received unrecognized yield message {!r}. Are you trying to use a library written for some other framework like asyncio? That won't work without some kind of compatibility shim.Zafter_task_stepzSTrio guest run got abandoned without properly finishing... weird stuff might happenz+internal error in Trio - please file a bug!)Yr¯rr½Ú__dict__Úclearrr r r[r3rrîr¨r6ÚwakeupZwakeup_on_signalsr5r8r=rKr÷r}r?r‡r:rÀrorOršÚmaxÚ _MAX_TIMEOUTr[ÚkeysrUrVrcrWr$Zprocess_eventsrMrxZpeekitemrírrZ    _autojumprXÚ_ALLOW_DETERMINISTIC_SCHEDULINGÚsortrCÚshuffleÚrandomÚreverser”rŽrrrr4r1rr´rôr6r7ÚrangeÚCONTEXT_RUN_TB_FRAMESÚwith_tracebackrOrr rr"rZ
abort_funcrrQrrr!Ú final_outcomerÇr§rÚthrowÚ GeneratorExitÚwarningsÚwarnÚRuntimeWarningr)r¾rørùrkriZkir'rNZ idle_primedr`rnÚeventsrwr^rŽÚbatchZ next_send_fnrBr|ÚmsgZstop_iterationZtask_excr=r<r/r/r1rh>sì
 
 
ÿ
 
 
 
 
 
 
 
 
 
 
 
ýÿ
 
 ÿÿ 
 
rhc@seZdZdd„Zddd„ZdS)Ú_TaskStatusIgnoredcCsdS)NÚTASK_STATUS_IGNOREDr/rIr/r/r1r¼*    sz_TaskStatusIgnored.__repr__NcCsdSr.r/)rJr´r/r/r1r×-    sz_TaskStatusIgnored.started)N)rPrQrRr¼r×r/r/r/r1r…)    sr…cCs,ztjWStk
r&tdƒd‚YnXdS)z’Return the :class:`Task` object representing the current task.
 
    Returns:
      Task: the :class:`Task` that called :func:`current_task`.
 
    z!must be called from async contextN)r½rŽrIr¡r/r/r/r1rŸ4    srŸcCs tƒj ¡S)aPReturns the current effective deadline for the current task.
 
    This function examines all the cancellation scopes that are currently in
    effect (taking into account shielding), and returns the deadline that will
    expire first.
 
    One example of where this might be is useful is if your code is trying to
    decide whether to begin an expensive operation like an RPC call, but wants
    to skip it if it knows that it can't possibly complete in the available
    time. Another example would be if you're using a protocol like gRPC that
    `propagates timeout information to the remote peer
    <http://www.grpc.io/docs/guides/concepts.html#deadlines>`__; this function
    gives a way to fetch that information so you can send it along.
 
    If this is called in a context where a cancellation is currently active
    (i.e., a blocking call will immediately raise :exc:`Cancelled`), then
    returned deadline is ``-inf``. If it is called in a context where no
    scopes have a deadline set, it returns ``inf``.
 
    Returns:
        float: the effective deadline, as an absolute time.
 
    )rŸr¤r›r/r/r/r1Úcurrent_effective_deadlineB    sr‡c    ÃsltƒIdHtƒ}|jd7_|jjs<||jjkrh|jjrhtt     dt
  dd„¡IdHW5QRXdS)a«A pure :ref:`checkpoint <checkpoints>`.
 
    This checks for cancellation and allows other tasks to be scheduled,
    without otherwise blocking.
 
    Note that the scheduler has the option of ignoring this and continuing to
    run the current task if it decides this is appropriate (e.g. for increased
    efficiency).
 
    Equivalent to ``await trio.sleep(0)`` (which is implemented by calling
    :func:`checkpoint`.)
 
    Nr)rNcSstjjSr.)r'rrr\r/r/r1rEu    rFzcheckpoint.<locals>.<lambda>) rrŸrr¤rŒrrQr ržrr'r©rŽr/r/r1ró]    s 
ÿÿrócÃsJtƒ}|jjs"||jjkr8|jjr8t ¡IdHds8t‚|j    d7_    dS)a¶Issue a :ref:`checkpoint <checkpoints>` if the calling context has been
    cancelled.
 
    Equivalent to (but potentially more efficient than)::
 
        if trio.current_effective_deadline() == -inf:
            await trio.lowlevel.checkpoint()
 
    This is either a no-op, or else it allow other tasks to be scheduled and
    then raises :exc:`trio.Cancelled`.
 
    Typically used together with :func:`cancel_shielded_checkpoint`.
 
    NFr)
rŸr¤rŒrrQr r'rórrrrˆr/r/r1Úcheckpoint_if_cancelledx    s
ÿÿr‰Úwin32)ÚWindowsIOManager)Ú*ÚlinuxZepoll)ÚEpollIOManagerZkqueue)ÚKqueueIOManagerzunsupported platform)N)F)~rýrrwÚselectr°Ú    threadingÚ collectionsrÚ
contextlibrrÚenumZ contextvarsrÚmathrÚtimerÚtypingrrZsniffior    rSÚheapqr
r r Zsortedcontainersr rïrrrrZ _entry_queuerrÚ _exceptionsrrrZ_kirrrZ _multierrorrrZ_trapsrrrr r!r"Z
_asyncgensr#Z _thread_cacher$Z_instrumentationr%r¸r'Z_utilr(r)r*Ú version_infoZexceptiongroupr-rvÚobjectrAr2rtÚRandomrCr?rzÚsrBÚEnumrUr\rbrzr©ržrËrØrárÙrÚlocalrr½rr"rrgr4rlrrrhr…r†rŸr‡rór‰ÚplatformZ _io_windowsr‹rdZ_generated_io_windowsrLZ    _io_epollrŽZ_generated_io_epollZ
_io_kqueuerZ_generated_io_kqueueÚNotImplementedErrorZ_generated_runZ_generated_instrumentationr/r/r/r1Ú<module>sÖ                   
 D -R>6
c
,$*ú nö Z
l