-
-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
_asynciomodule.c
3927 lines (3290 loc) · 106 KB
/
_asynciomodule.c
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
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_critical_section.h" // Py_BEGIN_CRITICAL_SECTION_MUT()
#include "pycore_dict.h" // _PyDict_GetItem_KnownHash()
#include "pycore_freelist.h" // _Py_FREELIST_POP()
#include "pycore_modsupport.h" // _PyArg_CheckPositional()
#include "pycore_moduleobject.h" // _PyModule_GetState()
#include "pycore_object.h" // _Py_SetImmortalUntracked
#include "pycore_pyerrors.h" // _PyErr_ClearExcState()
#include "pycore_pylifecycle.h" // _Py_IsInterpreterFinalizing()
#include "pycore_pystate.h" // _PyThreadState_GET()
#include "pycore_runtime_init.h" // _Py_ID()
#include <stddef.h> // offsetof()
/*[clinic input]
module _asyncio
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8fd17862aa989c69]*/
typedef enum {
STATE_PENDING,
STATE_CANCELLED,
STATE_FINISHED
} fut_state;
#define FutureObj_HEAD(prefix) \
PyObject_HEAD \
PyObject *prefix##_loop; \
PyObject *prefix##_callback0; \
PyObject *prefix##_context0; \
PyObject *prefix##_callbacks; \
PyObject *prefix##_exception; \
PyObject *prefix##_exception_tb; \
PyObject *prefix##_result; \
PyObject *prefix##_source_tb; \
PyObject *prefix##_cancel_msg; \
PyObject *prefix##_cancelled_exc; \
fut_state prefix##_state; \
/* These bitfields need to be at the end of the struct
so that these and bitfields from TaskObj are contiguous.
*/ \
unsigned prefix##_log_tb: 1; \
unsigned prefix##_blocking: 1;
typedef struct {
FutureObj_HEAD(fut)
} FutureObj;
typedef struct TaskObj {
FutureObj_HEAD(task)
unsigned task_must_cancel: 1;
unsigned task_log_destroy_pending: 1;
int task_num_cancels_requested;
PyObject *task_fut_waiter;
PyObject *task_coro;
PyObject *task_name;
PyObject *task_context;
struct TaskObj *next;
struct TaskObj *prev;
} TaskObj;
typedef struct {
PyObject_HEAD
TaskObj *sw_task;
PyObject *sw_arg;
} TaskStepMethWrapper;
#define Future_CheckExact(state, obj) Py_IS_TYPE(obj, state->FutureType)
#define Task_CheckExact(state, obj) Py_IS_TYPE(obj, state->TaskType)
#define Future_Check(state, obj) PyObject_TypeCheck(obj, state->FutureType)
#define Task_Check(state, obj) PyObject_TypeCheck(obj, state->TaskType)
#ifdef Py_GIL_DISABLED
# define ASYNCIO_STATE_LOCK(state) Py_BEGIN_CRITICAL_SECTION_MUT(&state->mutex)
# define ASYNCIO_STATE_UNLOCK(state) Py_END_CRITICAL_SECTION()
#else
# define ASYNCIO_STATE_LOCK(state) ((void)state)
# define ASYNCIO_STATE_UNLOCK(state) ((void)state)
#endif
typedef struct futureiterobject futureiterobject;
/* State of the _asyncio module */
typedef struct {
#ifdef Py_GIL_DISABLED
PyMutex mutex;
#endif
PyTypeObject *FutureIterType;
PyTypeObject *TaskStepMethWrapper_Type;
PyTypeObject *FutureType;
PyTypeObject *TaskType;
PyObject *asyncio_mod;
PyObject *context_kwname;
/* Dictionary containing tasks that are currently active in
all running event loops. {EventLoop: Task} */
PyObject *current_tasks;
/* WeakSet containing scheduled 3rd party tasks which don't
inherit from native asyncio.Task */
PyObject *non_asyncio_tasks;
/* Set containing all eagerly executing tasks. */
PyObject *eager_tasks;
/* An isinstance type cache for the 'is_coroutine()' function. */
PyObject *iscoroutine_typecache;
/* Imports from asyncio.events. */
PyObject *asyncio_get_event_loop_policy;
/* Imports from asyncio.base_futures. */
PyObject *asyncio_future_repr_func;
/* Imports from asyncio.exceptions. */
PyObject *asyncio_CancelledError;
PyObject *asyncio_InvalidStateError;
/* Imports from asyncio.base_tasks. */
PyObject *asyncio_task_get_stack_func;
PyObject *asyncio_task_print_stack_func;
PyObject *asyncio_task_repr_func;
/* Imports from asyncio.coroutines. */
PyObject *asyncio_iscoroutine_func;
/* Imports from traceback. */
PyObject *traceback_extract_stack;
/* Counter for autogenerated Task names */
uint64_t task_name_counter;
/* Linked-list of all tasks which are instances of asyncio.Task or subclasses
of it. Third party tasks implementations which don't inherit from
asyncio.Task are tracked separately using the 'non_asyncio_tasks' WeakSet.
`tail` is used as a sentinel to mark the end of the linked-list. It avoids one
branch in checking for empty list when adding a new task, the list is
initialized with `head` pointing to `tail` to mark an empty list.
Invariants:
* When the list is empty:
- asyncio_tasks.head == &asyncio_tasks.tail
- asyncio_tasks.head->prev == NULL
- asyncio_tasks.head->next == NULL
* After adding the first task 'task1':
- asyncio_tasks.head == task1
- task1->next == &asyncio_tasks.tail
- task1->prev == NULL
- asyncio_tasks.tail.prev == task1
* After adding a second task 'task2':
- asyncio_tasks.head == task2
- task2->next == task1
- task2->prev == NULL
- task1->prev == task2
- asyncio_tasks.tail.prev == task1
* After removing task 'task1':
- asyncio_tasks.head == task2
- task2->next == &asyncio_tasks.tail
- task2->prev == NULL
- asyncio_tasks.tail.prev == task2
* After removing task 'task2', the list is empty:
- asyncio_tasks.head == &asyncio_tasks.tail
- asyncio_tasks.head->prev == NULL
- asyncio_tasks.tail.prev == NULL
- asyncio_tasks.tail.next == NULL
*/
struct {
TaskObj tail;
TaskObj *head;
} asyncio_tasks;
} asyncio_state;
static inline asyncio_state *
get_asyncio_state(PyObject *mod)
{
asyncio_state *state = _PyModule_GetState(mod);
assert(state != NULL);
return state;
}
static inline asyncio_state *
get_asyncio_state_by_cls(PyTypeObject *cls)
{
asyncio_state *state = (asyncio_state *)_PyType_GetModuleState(cls);
assert(state != NULL);
return state;
}
static struct PyModuleDef _asynciomodule;
static inline asyncio_state *
get_asyncio_state_by_def(PyObject *self)
{
PyTypeObject *tp = Py_TYPE(self);
PyObject *mod = PyType_GetModuleByDef(tp, &_asynciomodule);
assert(mod != NULL);
return get_asyncio_state(mod);
}
#include "clinic/_asynciomodule.c.h"
/*[clinic input]
class _asyncio.Future "FutureObj *" "&Future_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=00d3e4abca711e0f]*/
/* Get FutureIter from Future */
static PyObject * future_new_iter(PyObject *);
static PyObject *
task_step_handle_result_impl(asyncio_state *state, TaskObj *task, PyObject *result);
static int
_is_coroutine(asyncio_state *state, PyObject *coro)
{
/* 'coro' is not a native coroutine, call asyncio.iscoroutine()
to check if it's another coroutine flavour.
Do this check after 'future_init()'; in case we need to raise
an error, __del__ needs a properly initialized object.
*/
PyObject *res = PyObject_CallOneArg(state->asyncio_iscoroutine_func, coro);
if (res == NULL) {
return -1;
}
int is_res_true = PyObject_IsTrue(res);
Py_DECREF(res);
if (is_res_true <= 0) {
return is_res_true;
}
if (PySet_GET_SIZE(state->iscoroutine_typecache) < 100) {
/* Just in case we don't want to cache more than 100
positive types. That shouldn't ever happen, unless
someone stressing the system on purpose.
*/
if (PySet_Add(state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro))) {
return -1;
}
}
return 1;
}
static inline int
is_coroutine(asyncio_state *state, PyObject *coro)
{
if (PyCoro_CheckExact(coro)) {
return 1;
}
/* Check if `type(coro)` is in the cache.
Caching makes is_coroutine() function almost as fast as
PyCoro_CheckExact() for non-native coroutine-like objects
(like coroutines compiled with Cython).
asyncio.iscoroutine() has its own type caching mechanism.
This cache allows us to avoid the cost of even calling
a pure-Python function in 99.9% cases.
*/
int has_it = PySet_Contains(
state->iscoroutine_typecache, (PyObject*) Py_TYPE(coro));
if (has_it == 0) {
/* type(coro) is not in iscoroutine_typecache */
return _is_coroutine(state, coro);
}
/* either an error has occurred or
type(coro) is in iscoroutine_typecache
*/
return has_it;
}
static PyObject *
get_future_loop(asyncio_state *state, PyObject *fut)
{
/* Implementation of `asyncio.futures._get_loop` */
PyObject *getloop;
if (Future_CheckExact(state, fut) || Task_CheckExact(state, fut)) {
PyObject *loop = ((FutureObj *)fut)->fut_loop;
return Py_NewRef(loop);
}
if (PyObject_GetOptionalAttr(fut, &_Py_ID(get_loop), &getloop) < 0) {
return NULL;
}
if (getloop != NULL) {
PyObject *res = PyObject_CallNoArgs(getloop);
Py_DECREF(getloop);
return res;
}
return PyObject_GetAttr(fut, &_Py_ID(_loop));
}
static PyObject *
get_event_loop(asyncio_state *state)
{
PyObject *loop;
PyObject *policy;
_PyThreadStateImpl *ts = (_PyThreadStateImpl *)_PyThreadState_GET();
loop = Py_XNewRef(ts->asyncio_running_loop);
if (loop != NULL) {
return loop;
}
policy = PyObject_CallNoArgs(state->asyncio_get_event_loop_policy);
if (policy == NULL) {
return NULL;
}
loop = PyObject_CallMethodNoArgs(policy, &_Py_ID(get_event_loop));
Py_DECREF(policy);
return loop;
}
static int
call_soon(asyncio_state *state, PyObject *loop, PyObject *func, PyObject *arg,
PyObject *ctx)
{
PyObject *handle;
if (ctx == NULL) {
PyObject *stack[] = {loop, func, arg};
size_t nargsf = 3 | PY_VECTORCALL_ARGUMENTS_OFFSET;
handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf, NULL);
}
else {
/* All refs in 'stack' are borrowed. */
PyObject *stack[4];
size_t nargs = 2;
stack[0] = loop;
stack[1] = func;
if (arg != NULL) {
stack[2] = arg;
nargs++;
}
stack[nargs] = (PyObject *)ctx;
size_t nargsf = nargs | PY_VECTORCALL_ARGUMENTS_OFFSET;
handle = PyObject_VectorcallMethod(&_Py_ID(call_soon), stack, nargsf,
state->context_kwname);
}
if (handle == NULL) {
return -1;
}
Py_DECREF(handle);
return 0;
}
static inline int
future_is_alive(FutureObj *fut)
{
return fut->fut_loop != NULL;
}
static inline int
future_ensure_alive(FutureObj *fut)
{
if (!future_is_alive(fut)) {
PyErr_SetString(PyExc_RuntimeError,
"Future object is not initialized.");
return -1;
}
return 0;
}
#define ENSURE_FUTURE_ALIVE(state, fut) \
do { \
assert(Future_Check(state, fut) || Task_Check(state, fut)); \
(void)state; \
if (future_ensure_alive((FutureObj*)fut)) { \
return NULL; \
} \
} while(0);
static int
future_schedule_callbacks(asyncio_state *state, FutureObj *fut)
{
if (fut->fut_callback0 != NULL) {
/* There's a 1st callback */
// Beware: An evil call_soon could alter fut_callback0 or fut_context0.
// Since we are anyway clearing them after the call, whether call_soon
// succeeds or not, the idea is to transfer ownership so that external
// code is not able to alter them during the call.
PyObject *fut_callback0 = fut->fut_callback0;
fut->fut_callback0 = NULL;
PyObject *fut_context0 = fut->fut_context0;
fut->fut_context0 = NULL;
int ret = call_soon(state, fut->fut_loop, fut_callback0,
(PyObject *)fut, fut_context0);
Py_CLEAR(fut_callback0);
Py_CLEAR(fut_context0);
if (ret) {
/* If an error occurs in pure-Python implementation,
all callbacks are cleared. */
Py_CLEAR(fut->fut_callbacks);
return ret;
}
/* we called the first callback, now try calling
callbacks from the 'fut_callbacks' list. */
}
if (fut->fut_callbacks == NULL) {
/* No more callbacks, return. */
return 0;
}
// Beware: An evil call_soon could change fut->fut_callbacks.
// The idea is to transfer the ownership of the callbacks list
// so that external code is not able to mutate the list during
// the iteration.
PyObject *callbacks = fut->fut_callbacks;
fut->fut_callbacks = NULL;
Py_ssize_t n = PyList_GET_SIZE(callbacks);
for (Py_ssize_t i = 0; i < n; i++) {
assert(PyList_GET_SIZE(callbacks) == n);
PyObject *cb_tup = PyList_GET_ITEM(callbacks, i);
PyObject *cb = PyTuple_GET_ITEM(cb_tup, 0);
PyObject *ctx = PyTuple_GET_ITEM(cb_tup, 1);
if (call_soon(state, fut->fut_loop, cb, (PyObject *)fut, ctx)) {
Py_DECREF(callbacks);
return -1;
}
}
Py_DECREF(callbacks);
return 0;
}
static int
future_init(FutureObj *fut, PyObject *loop)
{
PyObject *res;
int is_true;
Py_CLEAR(fut->fut_loop);
Py_CLEAR(fut->fut_callback0);
Py_CLEAR(fut->fut_context0);
Py_CLEAR(fut->fut_callbacks);
Py_CLEAR(fut->fut_result);
Py_CLEAR(fut->fut_exception);
Py_CLEAR(fut->fut_exception_tb);
Py_CLEAR(fut->fut_source_tb);
Py_CLEAR(fut->fut_cancel_msg);
Py_CLEAR(fut->fut_cancelled_exc);
fut->fut_state = STATE_PENDING;
fut->fut_log_tb = 0;
fut->fut_blocking = 0;
if (loop == Py_None) {
asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
loop = get_event_loop(state);
if (loop == NULL) {
return -1;
}
}
else {
Py_INCREF(loop);
}
fut->fut_loop = loop;
res = PyObject_CallMethodNoArgs(fut->fut_loop, &_Py_ID(get_debug));
if (res == NULL) {
return -1;
}
is_true = PyObject_IsTrue(res);
Py_DECREF(res);
if (is_true < 0) {
return -1;
}
if (is_true && !_Py_IsInterpreterFinalizing(_PyInterpreterState_GET())) {
/* Only try to capture the traceback if the interpreter is not being
finalized. The original motivation to add a `Py_IsFinalizing()`
call was to prevent SIGSEGV when a Future is created in a __del__
method, which is called during the interpreter shutdown and the
traceback module is already unloaded.
*/
asyncio_state *state = get_asyncio_state_by_def((PyObject *)fut);
fut->fut_source_tb = PyObject_CallNoArgs(state->traceback_extract_stack);
if (fut->fut_source_tb == NULL) {
return -1;
}
}
return 0;
}
static PyObject *
future_set_result(asyncio_state *state, FutureObj *fut, PyObject *res)
{
if (future_ensure_alive(fut)) {
return NULL;
}
if (fut->fut_state != STATE_PENDING) {
PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
return NULL;
}
assert(!fut->fut_result);
fut->fut_result = Py_NewRef(res);
fut->fut_state = STATE_FINISHED;
if (future_schedule_callbacks(state, fut) == -1) {
return NULL;
}
Py_RETURN_NONE;
}
static PyObject *
future_set_exception(asyncio_state *state, FutureObj *fut, PyObject *exc)
{
PyObject *exc_val = NULL;
if (fut->fut_state != STATE_PENDING) {
PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
return NULL;
}
if (PyExceptionClass_Check(exc)) {
exc_val = PyObject_CallNoArgs(exc);
if (exc_val == NULL) {
return NULL;
}
if (fut->fut_state != STATE_PENDING) {
Py_DECREF(exc_val);
PyErr_SetString(state->asyncio_InvalidStateError, "invalid state");
return NULL;
}
}
else {
exc_val = Py_NewRef(exc);
}
if (!PyExceptionInstance_Check(exc_val)) {
Py_DECREF(exc_val);
PyErr_SetString(PyExc_TypeError, "invalid exception object");
return NULL;
}
if (PyErr_GivenExceptionMatches(exc_val, PyExc_StopIteration)) {
const char *msg = "StopIteration interacts badly with "
"generators and cannot be raised into a "
"Future";
PyObject *message = PyUnicode_FromString(msg);
if (message == NULL) {
Py_DECREF(exc_val);
return NULL;
}
PyObject *err = PyObject_CallOneArg(PyExc_RuntimeError, message);
Py_DECREF(message);
if (err == NULL) {
Py_DECREF(exc_val);
return NULL;
}
assert(PyExceptionInstance_Check(err));
PyException_SetCause(err, Py_NewRef(exc_val));
PyException_SetContext(err, Py_NewRef(exc_val));
Py_DECREF(exc_val);
exc_val = err;
}
assert(!fut->fut_exception);
assert(!fut->fut_exception_tb);
fut->fut_exception = exc_val;
fut->fut_exception_tb = PyException_GetTraceback(exc_val);
fut->fut_state = STATE_FINISHED;
if (future_schedule_callbacks(state, fut) == -1) {
return NULL;
}
fut->fut_log_tb = 1;
Py_RETURN_NONE;
}
static PyObject *
create_cancelled_error(asyncio_state *state, FutureObj *fut)
{
PyObject *exc;
if (fut->fut_cancelled_exc != NULL) {
/* transfer ownership */
exc = fut->fut_cancelled_exc;
fut->fut_cancelled_exc = NULL;
return exc;
}
PyObject *msg = fut->fut_cancel_msg;
if (msg == NULL || msg == Py_None) {
exc = PyObject_CallNoArgs(state->asyncio_CancelledError);
} else {
exc = PyObject_CallOneArg(state->asyncio_CancelledError, msg);
}
return exc;
}
static void
future_set_cancelled_error(asyncio_state *state, FutureObj *fut)
{
PyObject *exc = create_cancelled_error(state, fut);
if (exc == NULL) {
return;
}
PyErr_SetObject(state->asyncio_CancelledError, exc);
Py_DECREF(exc);
}
static int
future_get_result(asyncio_state *state, FutureObj *fut, PyObject **result)
{
if (fut->fut_state == STATE_CANCELLED) {
future_set_cancelled_error(state, fut);
return -1;
}
if (fut->fut_state != STATE_FINISHED) {
PyErr_SetString(state->asyncio_InvalidStateError,
"Result is not set.");
return -1;
}
fut->fut_log_tb = 0;
if (fut->fut_exception != NULL) {
PyObject *tb = fut->fut_exception_tb;
if (tb == NULL) {
tb = Py_None;
}
if (PyException_SetTraceback(fut->fut_exception, tb) < 0) {
return -1;
}
*result = Py_NewRef(fut->fut_exception);
Py_CLEAR(fut->fut_exception_tb);
return 1;
}
*result = Py_NewRef(fut->fut_result);
return 0;
}
static PyObject *
future_add_done_callback(asyncio_state *state, FutureObj *fut, PyObject *arg,
PyObject *ctx)
{
if (!future_is_alive(fut)) {
PyErr_SetString(PyExc_RuntimeError, "uninitialized Future object");
return NULL;
}
if (fut->fut_state != STATE_PENDING) {
/* The future is done/cancelled, so schedule the callback
right away. */
if (call_soon(state, fut->fut_loop, arg, (PyObject*) fut, ctx)) {
return NULL;
}
}
else {
/* The future is pending, add a callback.
Callbacks in the future object are stored as follows:
callback0 -- a pointer to the first callback
callbacks -- a list of 2nd, 3rd, ... callbacks
Invariants:
* callbacks != NULL:
There are some callbacks in in the list. Just
add the new callback to it.
* callbacks == NULL and callback0 == NULL:
This is the first callback. Set it to callback0.
* callbacks == NULL and callback0 != NULL:
This is a second callback. Initialize callbacks
with a new list and add the new callback to it.
*/
if (fut->fut_callbacks == NULL && fut->fut_callback0 == NULL) {
fut->fut_callback0 = Py_NewRef(arg);
fut->fut_context0 = Py_NewRef(ctx);
}
else {
PyObject *tup = PyTuple_New(2);
if (tup == NULL) {
return NULL;
}
Py_INCREF(arg);
PyTuple_SET_ITEM(tup, 0, arg);
Py_INCREF(ctx);
PyTuple_SET_ITEM(tup, 1, (PyObject *)ctx);
if (fut->fut_callbacks != NULL) {
int err = PyList_Append(fut->fut_callbacks, tup);
if (err) {
Py_DECREF(tup);
return NULL;
}
Py_DECREF(tup);
}
else {
fut->fut_callbacks = PyList_New(1);
if (fut->fut_callbacks == NULL) {
Py_DECREF(tup);
return NULL;
}
PyList_SET_ITEM(fut->fut_callbacks, 0, tup); /* borrow */
}
}
}
Py_RETURN_NONE;
}
static PyObject *
future_cancel(asyncio_state *state, FutureObj *fut, PyObject *msg)
{
fut->fut_log_tb = 0;
if (fut->fut_state != STATE_PENDING) {
Py_RETURN_FALSE;
}
fut->fut_state = STATE_CANCELLED;
Py_XINCREF(msg);
Py_XSETREF(fut->fut_cancel_msg, msg);
if (future_schedule_callbacks(state, fut) == -1) {
return NULL;
}
Py_RETURN_TRUE;
}
/*[clinic input]
_asyncio.Future.__init__
*
loop: object = None
This class is *almost* compatible with concurrent.futures.Future.
Differences:
- result() and exception() do not take a timeout argument and
raise an exception when the future isn't done yet.
- Callbacks registered with add_done_callback() are always called
via the event loop's call_soon_threadsafe().
- This class is not compatible with the wait() and as_completed()
methods in the concurrent.futures package.
[clinic start generated code]*/
static int
_asyncio_Future___init___impl(FutureObj *self, PyObject *loop)
/*[clinic end generated code: output=9ed75799eaccb5d6 input=89af317082bc0bf8]*/
{
return future_init(self, loop);
}
static int
FutureObj_clear(FutureObj *fut)
{
Py_CLEAR(fut->fut_loop);
Py_CLEAR(fut->fut_callback0);
Py_CLEAR(fut->fut_context0);
Py_CLEAR(fut->fut_callbacks);
Py_CLEAR(fut->fut_result);
Py_CLEAR(fut->fut_exception);
Py_CLEAR(fut->fut_exception_tb);
Py_CLEAR(fut->fut_source_tb);
Py_CLEAR(fut->fut_cancel_msg);
Py_CLEAR(fut->fut_cancelled_exc);
PyObject_ClearManagedDict((PyObject *)fut);
return 0;
}
static int
FutureObj_traverse(FutureObj *fut, visitproc visit, void *arg)
{
Py_VISIT(Py_TYPE(fut));
Py_VISIT(fut->fut_loop);
Py_VISIT(fut->fut_callback0);
Py_VISIT(fut->fut_context0);
Py_VISIT(fut->fut_callbacks);
Py_VISIT(fut->fut_result);
Py_VISIT(fut->fut_exception);
Py_VISIT(fut->fut_exception_tb);
Py_VISIT(fut->fut_source_tb);
Py_VISIT(fut->fut_cancel_msg);
Py_VISIT(fut->fut_cancelled_exc);
PyObject_VisitManagedDict((PyObject *)fut, visit, arg);
return 0;
}
/*[clinic input]
_asyncio.Future.result
Return the result this future represents.
If the future has been cancelled, raises CancelledError. If the
future's result isn't yet available, raises InvalidStateError. If
the future is done and has an exception set, this exception is raised.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_result_impl(FutureObj *self)
/*[clinic end generated code: output=f35f940936a4b1e5 input=49ecf9cf5ec50dc5]*/
{
asyncio_state *state = get_asyncio_state_by_def((PyObject *)self);
PyObject *result;
if (!future_is_alive(self)) {
PyErr_SetString(state->asyncio_InvalidStateError,
"Future object is not initialized.");
return NULL;
}
int res = future_get_result(state, self, &result);
if (res == -1) {
return NULL;
}
if (res == 0) {
return result;
}
assert(res == 1);
PyErr_SetObject(PyExceptionInstance_Class(result), result);
Py_DECREF(result);
return NULL;
}
/*[clinic input]
_asyncio.Future.exception
cls: defining_class
/
Return the exception that was set on this future.
The exception (or None if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
CancelledError. If the future isn't done yet, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_exception_impl(FutureObj *self, PyTypeObject *cls)
/*[clinic end generated code: output=ce75576b187c905b input=3faf15c22acdb60d]*/
{
if (!future_is_alive(self)) {
asyncio_state *state = get_asyncio_state_by_cls(cls);
PyErr_SetString(state->asyncio_InvalidStateError,
"Future object is not initialized.");
return NULL;
}
if (self->fut_state == STATE_CANCELLED) {
asyncio_state *state = get_asyncio_state_by_cls(cls);
future_set_cancelled_error(state, self);
return NULL;
}
if (self->fut_state != STATE_FINISHED) {
asyncio_state *state = get_asyncio_state_by_cls(cls);
PyErr_SetString(state->asyncio_InvalidStateError,
"Exception is not set.");
return NULL;
}
if (self->fut_exception != NULL) {
self->fut_log_tb = 0;
return Py_NewRef(self->fut_exception);
}
Py_RETURN_NONE;
}
/*[clinic input]
_asyncio.Future.set_result
cls: defining_class
result: object
/
Mark the future done and set its result.
If the future is already done when this method is called, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_set_result_impl(FutureObj *self, PyTypeObject *cls,
PyObject *result)
/*[clinic end generated code: output=99afbbe78f99c32d input=d5a41c1e353acc2e]*/
{
asyncio_state *state = get_asyncio_state_by_cls(cls);
ENSURE_FUTURE_ALIVE(state, self)
return future_set_result(state, self, result);
}
/*[clinic input]
_asyncio.Future.set_exception
cls: defining_class
exception: object
/
Mark the future done and set an exception.
If the future is already done when this method is called, raises
InvalidStateError.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_set_exception_impl(FutureObj *self, PyTypeObject *cls,
PyObject *exception)
/*[clinic end generated code: output=0a5e8b5a52f058d6 input=a245cd49d3df939b]*/
{
asyncio_state *state = get_asyncio_state_by_cls(cls);
ENSURE_FUTURE_ALIVE(state, self)
return future_set_exception(state, self, exception);
}
/*[clinic input]
_asyncio.Future.add_done_callback
cls: defining_class
fn: object
/
*
context: object = NULL
Add a callback to be run when the future becomes done.
The callback is called with a single argument - the future object. If
the future is already done when this is called, the callback is
scheduled with call_soon.
[clinic start generated code]*/
static PyObject *
_asyncio_Future_add_done_callback_impl(FutureObj *self, PyTypeObject *cls,
PyObject *fn, PyObject *context)
/*[clinic end generated code: output=922e9a4cbd601167 input=599261c521458cc2]*/
{
asyncio_state *state = get_asyncio_state_by_cls(cls);
if (context == NULL) {
context = PyContext_CopyCurrent();
if (context == NULL) {
return NULL;
}
PyObject *res = future_add_done_callback(state, self, fn, context);
Py_DECREF(context);
return res;
}
return future_add_done_callback(state, self, fn, context);
}
/*[clinic input]
_asyncio.Future.remove_done_callback
cls: defining_class