-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscheduler.c
More file actions
1826 lines (1470 loc) · 56.5 KB
/
scheduler.c
File metadata and controls
1826 lines (1470 loc) · 56.5 KB
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
/*
+----------------------------------------------------------------------+
| Copyright (c) The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| https://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Edmond |
+----------------------------------------------------------------------+
*/
#include <Zend/zend_async_API.h>
#include "coroutine.h"
#include "internal/zval_circular_buffer.h"
#include "scheduler.h"
#include "php_async.h"
#include "exceptions.h"
#include "scope.h"
#include "zend_common.h"
#include "zend_observer.h"
///////////////////////////////////////////////////////////
/// STATIC DECLARATIONS AND CONSTANTS
///////////////////////////////////////////////////////////
#define FIBER_DEBUG_LOG_ON false
#define FIBER_DEBUG_SWITCH false
#if FIBER_DEBUG_LOG_ON
#define FIBER_DEBUG(...) fprintf(stdout, __VA_ARGS__)
#else
#define FIBER_DEBUG(...) ((void) 0)
#endif
static zend_function root_function = { ZEND_INTERNAL_FUNCTION };
typedef enum
{
COROUTINE_NOT_EXISTS,
COROUTINE_SWITCHED,
COROUTINE_IGNORED,
COROUTINE_FINISHED,
COROUTINE_BAILOUT,
SHOULD_BE_EXIT
} switch_status;
static ZEND_STACK_ALIGNED void fiber_entry(zend_fiber_transfer *transfer);
static void fiber_context_cleanup(zend_fiber_context *context);
#define TRY_HANDLE_EXCEPTION() \
if (UNEXPECTED(EG(exception) != NULL)) { \
if (ZEND_ASYNC_GRACEFUL_SHUTDOWN) { \
finally_shutdown(); \
break; \
} \
start_graceful_shutdown(); \
}
#define TRY_HANDLE_SUSPEND_EXCEPTION() \
if (UNEXPECTED(EG(exception) != NULL)) { \
if (ZEND_ASYNC_GRACEFUL_SHUTDOWN) { \
finally_shutdown(); \
switch_to_scheduler(transfer); \
zend_exception_restore_fast(exception_ptr, prev_exception_ptr); \
return; \
} \
start_graceful_shutdown(); \
}
#define TRY_HANDLE_SUSPEND_EXCEPTION_BOOL() \
if (UNEXPECTED(EG(exception) != NULL)) { \
if (ZEND_ASYNC_GRACEFUL_SHUTDOWN) { \
finally_shutdown(); \
switch_to_scheduler(transfer); \
zend_exception_restore_fast(exception_ptr, prev_exception_ptr); \
return false; \
} \
start_graceful_shutdown(); \
}
///////////////////////////////////////////////////////////
/// MODULE INIT/SHUTDOWN
///////////////////////////////////////////////////////////
static zend_always_inline void process_resumed_coroutines(void);
static void async_reactor_tick(void)
{
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
ZEND_ASYNC_REACTOR_EXECUTE(true);
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
if (circular_buffer_is_not_empty(&ASYNC_G(resumed_coroutines))) {
process_resumed_coroutines();
}
}
void async_scheduler_startup(void)
{
zend_async_reactor_tick_fn = async_reactor_tick;
}
void async_scheduler_shutdown(void)
{
}
///////////////////////////////////////////////////////////
/// FIBER CONTEXT MANAGEMENT
///////////////////////////////////////////////////////////
static void fiber_context_cleanup(zend_fiber_context *context)
{
async_fiber_context_t *fiber_context = (async_fiber_context_t *) context;
// There's no need to destroy execute_data
// because it's also located in the fiber's stack.
efree(fiber_context);
}
async_fiber_context_t *async_fiber_context_create(void)
{
async_fiber_context_t *context = ecalloc(1, sizeof(async_fiber_context_t));
if (zend_fiber_init_context(&context->context, async_ce_coroutine, fiber_entry, EG(fiber_stack_size)) == FAILURE) {
efree(context);
return NULL;
}
context->flags = ZEND_FIBER_STATUS_INIT;
context->context.cleanup = fiber_context_cleanup;
return context;
}
static zend_always_inline void fiber_pool_init(void)
{
circular_buffer_ctor(&ASYNC_G(fiber_context_pool), ASYNC_FIBER_POOL_SIZE, sizeof(async_fiber_context_t *), NULL);
}
static void fiber_pool_cleanup(void)
{
async_fiber_context_t *fiber_context = NULL;
zend_coroutine_t *coroutine = ZEND_ASYNC_CURRENT_COROUTINE;
ZEND_ASYNC_CURRENT_COROUTINE = NULL;
while (circular_buffer_pop_ptr(&ASYNC_G(fiber_context_pool), (void **) &fiber_context) == SUCCESS) {
if (fiber_context != NULL) {
zend_fiber_transfer transfer = { .context = &fiber_context->context, .flags = 0 };
// If the current coroutine is NULL, this state explicitly tells the fiber to stop execution.
// We set this value each time, since the switch_to_scheduler function may change it.
ZEND_ASYNC_CURRENT_COROUTINE = NULL;
zend_fiber_switch_context(&transfer);
// Transfer the exception to the current coroutine.
if (UNEXPECTED(transfer.flags & ZEND_FIBER_TRANSFER_FLAG_ERROR)) {
async_rethrow_exception(Z_OBJ(transfer.value));
ZVAL_NULL(&transfer.value);
}
}
}
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
circular_buffer_dtor(&ASYNC_G(fiber_context_pool));
}
///////////////////////////////////////////////////////////
/// MICROTASK EXECUTION
///////////////////////////////////////////////////////////
zend_always_inline static void execute_microtasks(void)
{
circular_buffer_t *buffer = &ASYNC_G(microtasks);
zend_async_microtask_t *task = NULL;
while (circular_buffer_is_not_empty(buffer)) {
circular_buffer_pop(buffer, &task);
if (EXPECTED(false == task->is_cancelled)) {
task->handler(task);
}
if (task->ref_count > 0) {
task->ref_count--;
}
if (task->ref_count <= 0) {
task->dtor(task);
}
if (UNEXPECTED(EG(exception) != NULL)) {
return;
}
}
}
///////////////////////////////////////////////////////////
/// FIBER CONTEXT SWITCHING UTILITIES
///////////////////////////////////////////////////////////
static zend_always_inline void fiber_context_update_before_suspend(void)
{
async_coroutine_t *coroutine = (async_coroutine_t *) ZEND_ASYNC_CURRENT_COROUTINE;
if (coroutine != NULL && coroutine->fiber_context != NULL) {
coroutine->fiber_context->execute_data = EG(current_execute_data);
}
}
/**
* Transfers the current exception (EG(exception)) to the transfer object.
*
* @param transfer Transfer object that will hold the transfer information.
*/
static zend_always_inline void transfer_current_exception(zend_fiber_transfer *transfer)
{
if (EXPECTED(EG(exception) == NULL)) {
transfer->flags &= ~ZEND_FIBER_TRANSFER_FLAG_ERROR;
return;
}
zend_object *exception = EG(exception);
GC_ADDREF(exception);
zend_clear_exception();
transfer->flags |= ZEND_FIBER_TRANSFER_FLAG_ERROR;
ZVAL_OBJ(&transfer->value, exception);
}
/**
* Switches control from the current fiber to the coroutine's fiber.
* The coroutine's fiber must be defined!
*
* @param coroutine The coroutine to switch to.
* @param flags Flags for transferring control
*/
static zend_always_inline bool fiber_switch_context_ex(async_coroutine_t *coroutine, uint8_t flags)
{
async_fiber_context_t *fiber_context = coroutine->fiber_context;
ZEND_ASSERT(fiber_context != NULL && "Fiber context is NULL in fiber_switch_context");
zend_fiber_transfer transfer = { .context = &fiber_context->context, .flags = flags };
#if FIBER_DEBUG_SWITCH
zend_fiber_context *from = EG(current_fiber_context);
zend_fiber_context *to = &coroutine->fiber_context->context;
if (ZEND_ASYNC_SCHEDULER == &coroutine->coroutine) {
FIBER_DEBUG("Switch fiber: %p => %p for scheduler: %p\n", from, to, coroutine);
} else {
FIBER_DEBUG("Switch fiber: %p => %p for coroutine: %p\n", from, to, coroutine);
}
#endif
zend_fiber_switch_context(&transfer);
// If we initiated the switch with bailout, don't forward it back
if (UNEXPECTED(flags & ZEND_FIBER_TRANSFER_FLAG_BAILOUT)) {
return false;
}
/* Signal bailout to the caller so it can do zend_bailout() after restoring the correct context. */
if (UNEXPECTED(transfer.flags & ZEND_FIBER_TRANSFER_FLAG_BAILOUT)) {
return true;
}
// Transfer the exception to the current coroutine.
if (UNEXPECTED(transfer.flags & ZEND_FIBER_TRANSFER_FLAG_ERROR)) {
async_rethrow_exception(Z_OBJ(transfer.value));
ZVAL_NULL(&transfer.value);
}
return false;
}
static zend_always_inline bool fiber_switch_context(async_coroutine_t *coroutine)
{
return fiber_switch_context_ex(coroutine, 0);
}
/**
* Switches to the scheduler coroutine.
*
* This method is used to transfer control to the special internal Scheduler coroutine.
* The transfer parameter can be NULL for temporary suspension.
* However, if the current coroutine is losing control PERMANENTLY, you must provide transfer.
*
* If the transfer object is provided, it will define the transfer for the scheduler.
* If no transfer is provided, it will switch to the scheduler context without defining a transfer.
*
* @param transfer The transfer object to define for the scheduler, or NULL if not needed.
*/
static zend_always_inline bool switch_to_scheduler(zend_fiber_transfer *transfer)
{
async_coroutine_t *async_coroutine = (async_coroutine_t *) ZEND_ASYNC_SCHEDULER;
ZEND_ASSERT(async_coroutine != NULL && "Scheduler coroutine is not initialized");
if (transfer != NULL) {
// In case the control is transferred to the Scheduler,
// the bailout flag must be cleared so that the Scheduler continues to operate normally.
// In other words, critical exceptions should not cause the Scheduler to terminate fatally.
// Don't clear bailout flag — let it propagate to the scheduler fiber
// so it can perform cleanup via bailout_all_coroutines().
transfer->context = &async_coroutine->fiber_context->context;
transfer_current_exception(transfer);
ZEND_ASYNC_CURRENT_COROUTINE = &async_coroutine->coroutine;
return false;
} else {
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = &async_coroutine->coroutine;
return fiber_switch_context(async_coroutine);
}
}
static zend_always_inline bool switch_to_scheduler_with_bailout(void)
{
async_coroutine_t *async_coroutine = (async_coroutine_t *) ZEND_ASYNC_SCHEDULER;
ZEND_ASSERT(async_coroutine != NULL && "Scheduler coroutine is not initialized");
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = &async_coroutine->coroutine;
return fiber_switch_context_ex(async_coroutine, ZEND_FIBER_FLAG_BAILOUT);
}
static zend_always_inline void return_to_main(zend_fiber_transfer *transfer)
{
transfer->context = ASYNC_G(main_transfer)->context;
transfer_current_exception(transfer);
}
///////////////////////////////////////////////////////////
/// COROUTINE QUEUE MANAGEMENT
///////////////////////////////////////////////////////////
static zend_always_inline void process_resumed_coroutines(void)
{
circular_buffer_t *resumed_queue = &ASYNC_G(resumed_coroutines);
zend_coroutine_t *coroutine = NULL;
while (circular_buffer_pop_ptr(resumed_queue, (void **) &coroutine) == SUCCESS) {
if (EXPECTED(coroutine != NULL && coroutine->waker != NULL)) {
ZEND_ASYNC_WAKER_CLEAN_EVENTS(coroutine->waker);
}
}
}
static zend_always_inline async_coroutine_t *next_coroutine(void)
{
async_coroutine_t *coroutine;
if (UNEXPECTED(circular_buffer_pop_ptr(&ASYNC_G(coroutine_queue), (void **) &coroutine) == FAILURE)) {
ZEND_ASSERT("Failed to pop the coroutine from the pending queue.");
return NULL;
}
return coroutine;
}
static zend_always_inline bool return_fiber_to_pool(async_fiber_context_t *fiber_context)
{
circular_buffer_t *pool = &ASYNC_G(fiber_context_pool);
if (pool->capacity == 0) {
return false;
}
const size_t pool_count = circular_buffer_count(pool);
const size_t queue_count = circular_buffer_count(&ASYNC_G(coroutine_queue));
/* Always keep minimum pool */
if (pool_count < ASYNC_FIBER_POOL_SIZE) {
return circular_buffer_push_ptr_with_resize(pool, fiber_context) == SUCCESS;
}
/* Grow: queue demands more fibers than pool has */
if (pool_count < queue_count) {
return circular_buffer_push_ptr_with_resize(pool, fiber_context) == SUCCESS;
}
/* Pool already covers the queue — destroy excess fiber */
return false;
}
/**
* Executes the next coroutine in the queue.
*
* The function is used when one Fiber switches to another.
* The execute_next_coroutine_from_fiber function is used
* when a Fiber is ready to execute another coroutine within itself.
*
* @return switch_status - status of the coroutine switching.
*/
static zend_always_inline switch_status execute_next_coroutine(void)
{
async_coroutine_t *async_coroutine = next_coroutine();
if (UNEXPECTED(async_coroutine == NULL)) {
return COROUTINE_NOT_EXISTS;
}
zend_coroutine_t *coroutine = &async_coroutine->coroutine;
// If the current coroutine is the same as the one we are trying to execute,
if (UNEXPECTED(coroutine == ZEND_ASYNC_CURRENT_COROUTINE)) {
return COROUTINE_SWITCHED;
}
if (async_coroutine->waker.status == ZEND_ASYNC_WAKER_IGNORED) {
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
FIBER_DEBUG("Execute coroutine %p in Fiber %p\n", coroutine, EG(current_fiber_context));
async_coroutine_execute(async_coroutine);
ZEND_ASYNC_CURRENT_COROUTINE = NULL;
return COROUTINE_IGNORED;
} else if (async_coroutine->fiber_context != NULL) {
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
if (UNEXPECTED(fiber_switch_context(async_coroutine))) {
return COROUTINE_BAILOUT;
}
return COROUTINE_SWITCHED;
} else {
// The coroutine doesn't have its own Fiber,
// so we first need to allocate a Fiber context for it and then start it.
circular_buffer_pop_ptr(&ASYNC_G(fiber_context_pool), (void **) &async_coroutine->fiber_context);
if (async_coroutine->fiber_context == NULL) {
async_coroutine->fiber_context = async_fiber_context_create();
}
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
if (UNEXPECTED(fiber_switch_context(async_coroutine))) {
return COROUTINE_BAILOUT;
}
return COROUTINE_SWITCHED;
}
}
/**
* Executes the next coroutine in the queue.
*
* This function is used in two different cases:
* Inside a Fiber that is free to run a coroutine, in which case transfer != NULL.
* During a suspend operation, when the Fiber is occupied by the current
* coroutine but needs to switch to another Fiber with a new one.
*
* @param transfer A transfer object that is not NULL if the current Fiber has no owning coroutine.
* @param fiber_context The current Fiber context if available.
* @return switch_status - status of the coroutine switching.
*/
#define AVAILABLE_FOR_COROUTINE (transfer != NULL)
static zend_always_inline switch_status execute_next_coroutine_from_fiber(zend_fiber_transfer *transfer,
async_fiber_context_t *fiber_context)
{
async_coroutine_t *async_coroutine = next_coroutine();
if (UNEXPECTED(async_coroutine == NULL)) {
return COROUTINE_NOT_EXISTS;
}
zend_coroutine_t *coroutine = &async_coroutine->coroutine;
next_coroutine:
if (async_coroutine->waker.status == ZEND_ASYNC_WAKER_IGNORED) {
// Case: the coroutine in queue was cancelled.
// In this case, only the coroutine finalization process needs to be executed,
// and it can be done immediately.
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
FIBER_DEBUG("Execute coroutine %p in Fiber %p\n", coroutine, EG(current_fiber_context));
async_coroutine_execute(async_coroutine);
ZEND_ASYNC_CURRENT_COROUTINE = NULL;
return COROUTINE_IGNORED;
}
if (AVAILABLE_FOR_COROUTINE && async_coroutine->fiber_context == fiber_context) {
// Case: The current coroutine is assigned to this fiber.
// Just execute it without switching.
FIBER_DEBUG("Execute coroutine %p in Fiber %p\n", coroutine, EG(current_fiber_context));
async_coroutine_execute(async_coroutine);
return COROUTINE_FINISHED;
} else if (AVAILABLE_FOR_COROUTINE && async_coroutine->fiber_context != NULL) {
// Case: the current fiber has no coroutine to execute,
// but the next coroutine in the queue is already in use.
if (return_fiber_to_pool(fiber_context)) {
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
if (UNEXPECTED(fiber_switch_context(async_coroutine))) {
return COROUTINE_BAILOUT;
}
// When control returns to us, we try to execute the coroutine that is currently active.
coroutine = ZEND_ASYNC_CURRENT_COROUTINE;
if (UNEXPECTED(coroutine == NULL)) {
// There are no more coroutines to execute; we need to exit.
return SHOULD_BE_EXIT;
}
async_coroutine = (async_coroutine_t *) coroutine;
goto next_coroutine;
} else {
// The pool is already full, so the Fiber should be destroyed after the switch occurs.
transfer->context = &async_coroutine->fiber_context->context;
transfer_current_exception(transfer);
return SHOULD_BE_EXIT;
}
} else if (async_coroutine->fiber_context != NULL) {
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
if (UNEXPECTED(fiber_switch_context(async_coroutine))) {
return COROUTINE_BAILOUT;
}
return COROUTINE_SWITCHED;
} else if (AVAILABLE_FOR_COROUTINE && async_coroutine->fiber_context == NULL) {
// Note that async_coroutine_execute is also called in cases
// where the coroutine was never executed and was canceled.
// In this case, no context switch occurs, so this code executes regardless of which fiber it's running in.
async_coroutine->fiber_context = fiber_context;
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
FIBER_DEBUG("Execute coroutine %p in Fiber %p\n", coroutine, EG(current_fiber_context));
async_coroutine_execute(async_coroutine);
return COROUTINE_FINISHED;
} else {
// (AVAILABLE_FOR_COROUTINE == false)
// The coroutine doesn't have its own Fiber,
// so we first need to allocate a Fiber context for it and then start it.
circular_buffer_pop_ptr(&ASYNC_G(fiber_context_pool), (void **) &async_coroutine->fiber_context);
if (async_coroutine->fiber_context == NULL) {
async_coroutine->fiber_context = async_fiber_context_create();
}
fiber_context_update_before_suspend();
ZEND_ASYNC_CURRENT_COROUTINE = coroutine;
if (UNEXPECTED(fiber_switch_context(async_coroutine))) {
return COROUTINE_BAILOUT;
}
return COROUTINE_SWITCHED;
}
}
zend_always_inline static void execute_queued_coroutines(void)
{
zend_object *saved_exception = NULL;
while (false == circular_buffer_is_empty(&ASYNC_G(coroutine_queue))) {
execute_next_coroutine();
if (UNEXPECTED(EG(exception))) {
if (saved_exception) {
zend_exception_set_previous(EG(exception), saved_exception);
}
saved_exception = EG(exception);
EG(exception) = NULL;
}
}
if (UNEXPECTED(saved_exception)) {
if (EG(exception)) {
zend_exception_set_previous(EG(exception), saved_exception);
} else {
EG(exception) = saved_exception;
}
}
}
///////////////////////////////////////////////////////////
/// DEADLOCK RESOLUTION AND ERROR HANDLING
///////////////////////////////////////////////////////////
static void dump_deadlock_info(const zend_long real_coroutines)
{
if (!ASYNC_G(debug_deadlock)) {
return;
}
php_printf("\n=== DEADLOCK REPORT START ===\n"
"Coroutines waiting: " ZEND_LONG_FMT ", active_events: %u\n\n",
real_coroutines,
ZEND_ASYNC_G(active_event_count));
zval *value;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), value)
{
const async_coroutine_t *coroutine = (async_coroutine_t *) Z_PTR_P(value);
const zend_async_event_t *event = &coroutine->coroutine.event;
/* Print coroutine info */
if (event->info != NULL) {
zend_string *info = event->info((zend_async_event_t *) event);
php_printf("%s\n", ZSTR_VAL(info));
zend_string_release(info);
} else {
php_printf("Coroutine %d\n", coroutine->std.handle);
}
/* Print events the coroutine is waiting for */
const zend_async_waker_t *waker = coroutine->coroutine.waker;
if (waker == NULL || waker->events.nNumOfElements == 0) {
php_printf(" waiting for: <nothing>\n\n");
continue;
}
php_printf(" waiting for:\n");
zend_async_waker_trigger_t *trigger;
ZEND_HASH_FOREACH_PTR(&waker->events, trigger)
{
if (trigger->event != NULL && trigger->event->info != NULL) {
zend_string *event_info = trigger->event->info(trigger->event);
php_printf(" - %s\n", ZSTR_VAL(event_info));
zend_string_release(event_info);
} else {
php_printf(" - <unknown event>\n");
}
}
ZEND_HASH_FOREACH_END();
php_printf("\n");
}
ZEND_HASH_FOREACH_END();
php_printf("=== DEADLOCK REPORT END ===\n\n");
}
static bool resolve_deadlocks(void)
{
zval *value;
const zend_long active_coroutines = ZEND_ASYNC_ACTIVE_COROUTINE_COUNT;
const zend_long real_coroutines = zend_hash_num_elements(&ASYNC_G(coroutines));
if (active_coroutines > real_coroutines) {
async_warning("The active coroutine counter contains an incorrect value: %u, real counter: %u.",
active_coroutines,
real_coroutines);
}
if (real_coroutines == 0) {
return false;
}
//
// Let’s count the number of coroutine-fibers that are in the YIELD state.
// This state differs from the regular Suspended state in that
// the Fiber has transferred control back to the parent coroutine.
//
zend_long fiber_coroutines_count = 0;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), value)
{
const zend_coroutine_t *coroutine = (zend_coroutine_t *) Z_PTR_P(value);
if (ZEND_COROUTINE_IS_FIBER(coroutine) && ZEND_COROUTINE_IS_YIELD(coroutine) &&
coroutine->extended_data != NULL) {
fiber_coroutines_count++;
}
}
ZEND_HASH_FOREACH_END();
//
// If all coroutines are fiber coroutines in the SUSPENDED state,
// we can simply cancel them without creating a deadlock exception.
//
if (fiber_coroutines_count == real_coroutines) {
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), value)
{
zend_coroutine_t *coroutine = (zend_coroutine_t *) Z_PTR_P(value);
if (ZEND_COROUTINE_IS_FIBER(coroutine) && ZEND_COROUTINE_IS_YIELD(coroutine) &&
coroutine->extended_data != NULL) {
ZEND_ASYNC_CANCEL(coroutine, zend_create_graceful_exit(), true);
if (UNEXPECTED(EG(exception) != NULL)) {
process_resumed_coroutines();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
return true;
}
}
}
ZEND_HASH_FOREACH_END();
process_resumed_coroutines();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
return false;
}
dump_deadlock_info(real_coroutines);
// Create deadlock exception to be set as exit_exception
zend_object *deadlock_exception =
async_new_exception(async_ce_deadlock_error,
"Deadlock detected: no active coroutines, %u coroutines in waiting",
real_coroutines);
// Set as exit exception if there isn't one already
if (ZEND_ASYNC_EXIT_EXCEPTION == NULL) {
ZEND_ASYNC_EXIT_EXCEPTION = deadlock_exception;
} else {
// If there's already an exit exception, make the deadlock exception previous
zend_exception_set_previous(deadlock_exception, ZEND_ASYNC_EXIT_EXCEPTION);
ZEND_ASYNC_EXIT_EXCEPTION = deadlock_exception;
}
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), value)
{
async_coroutine_t *coroutine = (async_coroutine_t *) Z_PTR_P(value);
ZEND_ASSERT(coroutine->coroutine.waker != NULL && "The Coroutine has no waker object");
// In case a deadlock condition is detected, cancellation protection flags no longer apply.
if (ZEND_COROUTINE_IS_PROTECTED(&coroutine->coroutine)) {
ZEND_COROUTINE_CLR_PROTECTED(&coroutine->coroutine);
}
ZEND_ASYNC_CANCEL(
&coroutine->coroutine, async_new_exception(async_ce_cancellation_exception, "Deadlock detected"), true);
if (UNEXPECTED(EG(exception) != NULL)) {
process_resumed_coroutines();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
return true;
}
}
ZEND_HASH_FOREACH_END();
process_resumed_coroutines();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
return false;
}
///////////////////////////////////////////////////////////
/// SHUTDOWN AND CLEANUP
///////////////////////////////////////////////////////////
static void cancel_queued_coroutines(void)
{
zend_object **exception = &EG(exception);
zend_object *prev_exception_storage = NULL;
zend_object **prev_exception = &prev_exception_storage;
zend_exception_save_fast(exception, prev_exception);
// 1. Walk through all coroutines and cancel them if they are suspended.
zval *current;
zend_object *cancellation_exception = async_new_exception(async_ce_cancellation_exception, "Graceful shutdown");
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), current)
{
zend_coroutine_t *coroutine = Z_PTR_P(current);
if (false == ZEND_COROUTINE_IS_STARTED(coroutine)) {
// No need to cancel the fiber if it has not been started.
coroutine->waker->status = ZEND_ASYNC_WAKER_IGNORED;
ZEND_COROUTINE_SET_CANCELLED(coroutine);
coroutine->exception = cancellation_exception;
GC_ADDREF(cancellation_exception);
} else {
// In case a deadlock condition is detected, cancellation protection flags no longer apply.
if (ZEND_COROUTINE_IS_PROTECTED(coroutine)) {
ZEND_COROUTINE_CLR_PROTECTED(coroutine);
}
ZEND_ASYNC_CANCEL(coroutine, cancellation_exception, false);
}
if (*exception) {
zend_exception_save_fast(exception, prev_exception);
}
}
ZEND_HASH_FOREACH_END();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
OBJ_RELEASE(cancellation_exception);
process_resumed_coroutines();
zend_exception_restore_fast(exception, prev_exception);
}
/**
* Called when a bailout (e.g. OOM) occurs in a coroutine.
* Switches to each started coroutine's fiber with BAILOUT flag
* so it can unwind its stack, then returns control here.
*/
void bailout_all_coroutines(void)
{
// 1. First handle all coroutine in the queue
while (false == circular_buffer_is_empty(&ASYNC_G(coroutine_queue))) {
async_coroutine_t *async_coroutine = next_coroutine();
if (UNEXPECTED(async_coroutine == NULL)) {
break;
}
if (async_coroutine->fiber_context) {
ZEND_ASYNC_CURRENT_COROUTINE = &async_coroutine->coroutine;
fiber_switch_context_ex(async_coroutine, ZEND_FIBER_TRANSFER_FLAG_BAILOUT);
} else {
ZEND_COROUTINE_SET_BAILOUT(&async_coroutine->coroutine);
async_coroutine_finalize(async_coroutine);
}
}
// 2. Then we process all remaining coroutines
zval *current;
ZEND_HASH_FOREACH_VAL(&ASYNC_G(coroutines), current)
{
zend_coroutine_t *coroutine = Z_PTR_P(current);
async_coroutine_t *async_coroutine = (async_coroutine_t *) coroutine;
if (ZEND_COROUTINE_IS_FINISHED(coroutine)) {
continue;
}
ZEND_COROUTINE_SET_BAILOUT(coroutine);
if (async_coroutine->fiber_context) {
ZEND_ASYNC_CURRENT_COROUTINE = &async_coroutine->coroutine;
fiber_switch_context_ex(async_coroutine, ZEND_FIBER_TRANSFER_FLAG_BAILOUT);
} else {
ZEND_ASYNC_WAKER_DESTROY(coroutine);
async_coroutine_finalize(async_coroutine);
}
}
ZEND_HASH_FOREACH_END();
}
bool start_graceful_shutdown(void)
{
if (ZEND_ASYNC_GRACEFUL_SHUTDOWN) {
return true;
}
ZEND_ASYNC_GRACEFUL_SHUTDOWN = true;
// If the exit exception is not defined, we will define it.
// if (EG(exception) == NULL && ZEND_ASYNC_EXIT_EXCEPTION == NULL) {
// zend_error(E_CORE_WARNING, "Graceful shutdown mode was started");
// }
if (EG(exception) != NULL) {
ZEND_ASYNC_EXIT_EXCEPTION = EG(exception);
GC_ADDREF(EG(exception));
zend_clear_exception();
}
cancel_queued_coroutines();
if (UNEXPECTED(EG(exception) != NULL)) {
zend_exception_set_previous(EG(exception), ZEND_ASYNC_EXIT_EXCEPTION);
ZEND_ASYNC_EXIT_EXCEPTION = EG(exception);
GC_ADDREF(EG(exception));
zend_clear_exception();
}
// After exiting this function, EG(exception) must be 100% clean.
return true;
}
static void finally_shutdown(void)
{
if (ZEND_ASYNC_EXIT_EXCEPTION != NULL && EG(exception) != NULL) {
zend_exception_set_previous(EG(exception), ZEND_ASYNC_EXIT_EXCEPTION);
ZEND_ASYNC_EXIT_EXCEPTION = EG(exception);
GC_ADDREF(EG(exception));
zend_clear_exception();
}
cancel_queued_coroutines();
execute_queued_coroutines();
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
execute_microtasks();
if (circular_buffer_is_not_empty(&ASYNC_G(resumed_coroutines))) {
process_resumed_coroutines();
}
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
if (UNEXPECTED(EG(exception))) {
if (ZEND_ASYNC_EXIT_EXCEPTION != NULL) {
zend_exception_set_previous(EG(exception), ZEND_ASYNC_EXIT_EXCEPTION);
ZEND_ASYNC_EXIT_EXCEPTION = EG(exception);
GC_ADDREF(EG(exception));
}
}
}
static void async_scheduler_dtor(void)
{
ZEND_ASYNC_SCHEDULER_CONTEXT = true;
execute_microtasks();
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
if (UNEXPECTED(false == circular_buffer_is_empty(&ASYNC_G(microtasks)))) {
async_warning("%u microtasks were not executed", circular_buffer_count(&ASYNC_G(microtasks)));
}
if (UNEXPECTED(false == circular_buffer_is_empty(&ASYNC_G(coroutine_queue)))) {
async_warning("%u deferred coroutines were not executed", circular_buffer_count(&ASYNC_G(coroutine_queue)));
}
// Destroy the scheduler coroutine at the end.
async_coroutine_t *async_coroutine = (async_coroutine_t *) ZEND_ASYNC_SCHEDULER;
ZEND_ASYNC_SCHEDULER = NULL;
async_coroutine->fiber_context = NULL;
OBJ_RELEASE(&async_coroutine->std);
zval_c_buffer_cleanup(&ASYNC_G(coroutine_queue));
zval_c_buffer_cleanup(&ASYNC_G(resumed_coroutines));
zval_c_buffer_cleanup(&ASYNC_G(microtasks));
async_coroutine_t *coroutine;
// foreach by fibers_state and release all fibers
ZEND_HASH_FOREACH_PTR(&ASYNC_G(coroutines), coroutine)
{
OBJ_RELEASE(&coroutine->std);
}
ZEND_HASH_FOREACH_END();
zend_hash_clean(&ASYNC_G(coroutines));
zend_hash_destroy(&ASYNC_G(coroutines));
zend_hash_init(&ASYNC_G(coroutines), 0, NULL, NULL, 0);
ZEND_ASYNC_SCHEDULER_CONTEXT = false;
}
///////////////////////////////////////////////////////////
/// WAKER EVENT MANAGEMENT
///////////////////////////////////////////////////////////
static zend_always_inline void start_waker_events(zend_async_waker_t *waker)
{
ZEND_ASSERT(waker != NULL && "Waker is NULL in async_scheduler_start_waker_events");
zend_async_waker_trigger_t *trigger;
ZEND_HASH_FOREACH_PTR(&waker->events, trigger)
{
trigger->event->start(trigger->event);
}
ZEND_HASH_FOREACH_END();
}
static zend_always_inline void stop_waker_events(zend_async_waker_t *waker)
{
ZEND_ASSERT(waker != NULL && "Waker is NULL in async_scheduler_stop_waker_events");
zend_async_waker_trigger_t *trigger;
ZEND_HASH_FOREACH_PTR(&waker->events, trigger)
{
trigger->event->stop(trigger->event);
}
ZEND_HASH_FOREACH_END();
}
///////////////////////////////////////////////////////////
/// SCHEDULER CORE
///////////////////////////////////////////////////////////
/**
* The main loop of the scheduler.
*/
bool async_scheduler_launch(void)