-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathasync_API.c
More file actions
1282 lines (1060 loc) · 39.4 KB
/
async_API.c
File metadata and controls
1282 lines (1060 loc) · 39.4 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 "async_API.h"
#include "context.h"
#include "coroutine.h"
#include "exceptions.h"
#include "future.h"
#include "iterator.h"
#include "php_async.h"
#include "pool.h"
#include "scheduler.h"
#include "scope.h"
#include "task_group.h"
#include "zend_common.h"
zend_async_scope_t *async_provide_scope(zend_object *scope_provider)
{
zval retval;
if (zend_call_method_with_0_params(scope_provider, scope_provider->ce, NULL, "provideScope", &retval) == NULL) {
return NULL;
}
if (Z_TYPE(retval) == IS_OBJECT && instanceof_function(Z_OBJCE(retval), async_ce_scope)) {
zend_async_scope_t *scope = &((async_scope_object_t *) Z_OBJ(retval))->scope->scope;
zval_ptr_dtor(&retval);
return scope;
}
zval_ptr_dtor(&retval);
if (UNEXPECTED(EG(exception))) {
return NULL;
}
if (Z_TYPE(retval) == IS_NULL) {
return NULL;
}
zend_async_throw(ZEND_ASYNC_EXCEPTION_DEFAULT, "Scope provider must return an instance of Async\\Scope");
return NULL;
}
zend_coroutine_t *spawn(zend_async_scope_t *scope, zend_object *scope_provider, int32_t priority)
{
if (UNEXPECTED(ZEND_ASYNC_IS_OFF)) {
async_throw_error("Cannot spawn a coroutine when async is disabled");
return NULL;
} else if (UNEXPECTED(ZEND_ASYNC_IS_READY)) {
if (UNEXPECTED(!async_scheduler_launch())) {
return NULL;
}
}
if (scope == NULL && scope_provider != NULL) {
scope = async_provide_scope(scope_provider);
if (UNEXPECTED(EG(exception))) {
return NULL;
}
}
if (scope == NULL) {
zend_async_scope_t **main_scope_ptr = &ZEND_ASYNC_MAIN_SCOPE;
if (UNEXPECTED(ZEND_ASYNC_CURRENT_SCOPE == NULL && *main_scope_ptr == NULL)) {
*main_scope_ptr = ZEND_ASYNC_NEW_SCOPE(NULL);
if (UNEXPECTED(*main_scope_ptr == NULL)) {
return NULL;
}
}
if (EXPECTED(ZEND_ASYNC_CURRENT_SCOPE != NULL)) {
scope = ZEND_ASYNC_CURRENT_SCOPE;
} else {
scope = *main_scope_ptr;
}
}
if (UNEXPECTED(scope == NULL)) {
async_throw_error("Cannot spawn a coroutine without a scope");
return NULL;
}
if (UNEXPECTED(ZEND_ASYNC_SCOPE_IS_CLOSED(scope))) {
async_throw_error("Cannot spawn a coroutine in a closed scope");
return NULL;
}
if (UNEXPECTED(ZEND_ASYNC_SCHEDULER != NULL && scope == ZEND_ASYNC_SCHEDULER->scope)) {
async_throw_error("You cannot use the Scheduler scope to create coroutines");
return NULL;
}
async_coroutine_t *coroutine = (async_coroutine_t *) async_new_coroutine(scope);
if (UNEXPECTED(coroutine == NULL)) {
return NULL;
}
zend_apply_current_filename_and_line(&coroutine->coroutine.filename, &coroutine->coroutine.lineno);
const bool is_spawn_strategy =
scope_provider != NULL && instanceof_function(scope_provider->ce, async_ce_spawn_strategy);
zval options;
ZVAL_UNDEF(&options);
// call SpawnStrategy::beforeCoroutineEnqueue
if (is_spawn_strategy) {
zval coroutine_zval, scope_zval;
ZVAL_OBJ(&coroutine_zval, &coroutine->std);
ZVAL_OBJ(&scope_zval, scope->scope_object);
if (zend_call_method_with_2_params(scope_provider,
scope_provider->ce,
NULL,
"beforeCoroutineEnqueue",
&options,
&coroutine_zval,
&scope_zval) == NULL) {
coroutine->coroutine.event.dispose(&coroutine->coroutine.event);
return NULL;
}
zval_ptr_dtor(&options);
}
zend_async_waker_t *waker = ZEND_ASYNC_WAKER_NEW(&coroutine->coroutine);
if (UNEXPECTED(waker == NULL)) {
coroutine->coroutine.event.dispose(&coroutine->coroutine.event);
return NULL;
}
waker->status = ZEND_ASYNC_WAKER_QUEUED;
// Use priority to determine enqueue method
zend_result enqueue_result;
if (priority > 0) {
// High priority: add to front of queue
enqueue_result = circular_buffer_push_front(&ASYNC_G(coroutine_queue), &coroutine, true);
} else {
// Normal or low priority: add to back of queue
enqueue_result = circular_buffer_push(&ASYNC_G(coroutine_queue), &coroutine, true);
}
if (UNEXPECTED(enqueue_result == FAILURE)) {
coroutine->coroutine.event.dispose(&coroutine->coroutine.event);
async_throw_error("Failed to enqueue coroutine");
return NULL;
}
if (UNEXPECTED(zend_hash_index_add_ptr(&ASYNC_G(coroutines), coroutine->std.handle, coroutine) == NULL)) {
waker->status = ZEND_ASYNC_WAKER_IGNORED;
async_throw_error("Failed to add coroutine to the list");
return NULL;
}
ZEND_ASYNC_INCREASE_COROUTINE_COUNT;
scope->after_coroutine_enqueue(&coroutine->coroutine, scope);
if (UNEXPECTED(EG(exception))) {
waker->status = ZEND_ASYNC_WAKER_IGNORED;
return NULL;
}
// call SpawnStrategy::afterCoroutineEnqueue
if (is_spawn_strategy) {
zval coroutine_zval, scope_zval;
ZVAL_OBJ(&coroutine_zval, &coroutine->std);
ZVAL_OBJ(&scope_zval, scope->scope_object);
if (zend_call_method_with_2_params(scope_provider,
scope_provider->ce,
NULL,
"afterCoroutineEnqueue",
&options,
&coroutine_zval,
&scope_zval) == NULL) {
waker->status = ZEND_ASYNC_WAKER_IGNORED;
return NULL;
}
zval_ptr_dtor(&options);
}
return &coroutine->coroutine;
}
static bool engine_shutdown(void)
{
ZEND_ASYNC_REACTOR_SHUTDOWN();
circular_buffer_dtor(&ASYNC_G(microtasks));
circular_buffer_dtor(&ASYNC_G(coroutine_queue));
circular_buffer_dtor(&ASYNC_G(resumed_coroutines));
zend_hash_destroy(&ASYNC_G(coroutines));
if (ASYNC_G(root_context) != NULL) {
async_context_t *root_context = (async_context_t *) ASYNC_G(root_context);
ASYNC_G(root_context) = NULL;
OBJ_RELEASE(&root_context->std);
}
// async_host_name_list_dtor();
return true;
}
zend_array *get_coroutines(void)
{
return &ASYNC_G(coroutines);
}
bool add_microtask(zend_async_microtask_t *microtask)
{
if (microtask->is_cancelled) {
return true;
}
if (UNEXPECTED(circular_buffer_push(&ASYNC_G(microtasks), µtask, true) == FAILURE)) {
async_throw_error("Failed to enqueue microtask");
return false;
}
microtask->ref_count++;
return true;
}
zend_array *get_awaiting_info(zend_coroutine_t *coroutine)
{
/* @todo: implement get_awaiting_info */
return NULL;
}
static zend_class_entry *async_get_class_ce(zend_async_class type)
{
switch (type) {
case ZEND_ASYNC_CLASS_COMPLETABLE:
return async_ce_completable;
case ZEND_ASYNC_CLASS_COROUTINE:
return async_ce_coroutine;
case ZEND_ASYNC_CLASS_SCOPE:
return async_ce_scope;
case ZEND_ASYNC_CLASS_TIMEOUT:
return async_ce_timeout;
case ZEND_ASYNC_EXCEPTION_DEFAULT:
return async_ce_async_exception;
case ZEND_ASYNC_EXCEPTION_CANCELLATION:
return async_ce_cancellation_exception;
case ZEND_ASYNC_EXCEPTION_TIMEOUT:
return async_ce_timeout_exception;
case ZEND_ASYNC_EXCEPTION_INPUT_OUTPUT:
return async_ce_input_output_exception;
case ZEND_ASYNC_EXCEPTION_POLL:
return async_ce_poll_exception;
case ZEND_ASYNC_EXCEPTION_DNS:
return async_ce_dns_exception;
case ZEND_ASYNC_EXCEPTION_DEADLOCK:
return async_ce_deadlock_error;
case ZEND_ASYNC_EXCEPTION_SERVICE_UNAVAILABLE:
return async_ce_service_unavailable_exception;
case ZEND_ASYNC_EXCEPTION_OPERATION_CANCELLED:
return async_ce_operation_cancelled_exception;
default:
return NULL;
}
}
////////////////////////////////////////////////////////////////////
/// async_await_futures
////////////////////////////////////////////////////////////////////
#define AWAIT_ALL(await_context) \
((await_context)->waiting_count == 0 || (await_context)->waiting_count == (await_context)->total)
#define AWAIT_ITERATOR_IS_FINISHED(await_context) \
((await_context->waiting_count > 0 && \
(await_context->ignore_errors ? await_context->success_count : await_context->resolved_count) >= \
await_context->waiting_count) || \
(await_context->total != 0 && await_context->resolved_count >= await_context->total))
static zend_always_inline zend_async_event_t *zval_to_event(const zval *current)
{
// An array element can be either an object implementing
// the Awaitable interface
// or an internal structure zend_async_event_t.
if (Z_TYPE_P(current) == IS_OBJECT && instanceof_function(Z_OBJCE_P(current), async_ce_awaitable)) {
return ZEND_ASYNC_OBJECT_TO_EVENT(Z_OBJ_P(current));
} else if (Z_TYPE_P(current) == IS_PTR) {
return (zend_async_event_t *) Z_PTR_P(current);
} else if (Z_TYPE_P(current) == IS_NULL || Z_TYPE_P(current) == IS_UNDEF) {
return NULL;
} else {
async_throw_error("Expected item to be an Async\\Awaitable object");
return NULL;
}
}
/**
* The function is called to release resources for the callback structure.
*
* @param callback
* @param event
*/
static void async_waiting_callback_dispose(zend_async_event_callback_t *callback, zend_async_event_t *event)
{
if (callback->ref_count > 1) {
callback->ref_count--;
return;
} else if (UNEXPECTED(callback->ref_count == 0)) {
return;
}
async_await_callback_t *await_callback = (async_await_callback_t *) callback;
async_await_context_t *await_context = await_callback->await_context;
await_callback->await_context = NULL;
callback->ref_count = 0;
if (!Z_ISUNDEF(await_callback->key)) {
zval_ptr_dtor(&await_callback->key);
ZVAL_UNDEF(&await_callback->key);
}
if (await_context != NULL) {
await_context->dtor(await_context);
}
if (await_callback->prev_dispose != NULL) {
callback->ref_count = 1;
await_callback->prev_dispose(callback, event);
} else {
efree(callback);
}
}
/**
* This callback is used for awaiting futures.
* It is called when the future is resolved or rejected.
* It updates the await context and resumes the coroutine if necessary.
*
* @param event
* @param callback
* @param result
* @param exception
*/
static void async_waiting_callback(zend_async_event_t *event,
zend_async_event_callback_t *callback,
void *result,
zend_object *exception)
{
async_await_callback_t *await_callback = (async_await_callback_t *) callback;
async_await_context_t *await_context = await_callback->await_context;
await_context->resolved_count++;
// remove the callback from the event
// We remove the callback because we treat all events
// as FUTURE-type objects, where the trigger can be activated only once.
ZEND_ASYNC_EVENT_CALLBACK_ADD_REF(callback);
if (!event->del_callback(event, callback)) {
// Optimized: ignore del_callback failure in callback context
}
ZEND_ASYNC_EVENT_CALLBACK_DEC_REF(callback);
if (exception != NULL) {
ZEND_ASYNC_EVENT_SET_EXCEPTION_HANDLED(event);
}
if (await_context->errors != NULL && exception != NULL) {
const zval *success = NULL;
zval exception_obj;
ZVAL_OBJ(&exception_obj, exception);
if (Z_TYPE(await_callback->key) == IS_STRING) {
success = zend_hash_update(await_context->errors, Z_STR(await_callback->key), &exception_obj);
} else if (Z_TYPE(await_callback->key) == IS_LONG) {
success = zend_hash_index_update(await_context->errors, Z_LVAL(await_callback->key), &exception_obj);
} else if (Z_TYPE(await_callback->key) == IS_NULL || Z_TYPE(await_callback->key) == IS_UNDEF) {
success = zend_hash_next_index_insert_new(await_context->errors, &exception_obj);
ZVAL_LONG(&await_callback->key, await_context->errors->nNextFreeElement - 1);
} else {
ZEND_ASSERT("Invalid key type: must be string, long or null");
}
if (success != NULL) {
GC_ADDREF(exception);
}
}
if (exception != NULL && false == await_context->ignore_errors) {
ZEND_ASYNC_RESUME_WITH_ERROR(await_callback->callback.coroutine, exception, false);
callback->dispose(callback, NULL);
return;
}
// If the exception exists, and we are ignoring errors, we do not resume the coroutine.
if (exception != NULL && await_context->ignore_errors) {
// But if there's no one left to wait for, stop waiting.
if (await_context->total != 0 && await_context->resolved_count >= await_context->total) {
ZEND_ASYNC_RESUME(await_callback->callback.coroutine);
}
callback->dispose(callback, NULL);
return;
}
if (exception == NULL && await_context->results != NULL && ZEND_ASYNC_EVENT_WILL_ZVAL_RESULT(event) &&
result != NULL) {
const zval *success = NULL;
await_context->success_count++;
if (Z_TYPE(await_callback->key) == IS_STRING) {
success = zend_hash_update(await_context->results, Z_STR(await_callback->key), result);
} else if (Z_TYPE(await_callback->key) == IS_LONG) {
success = zend_hash_index_update(await_context->results, Z_LVAL(await_callback->key), result);
} else if (Z_TYPE(await_callback->key) == IS_NULL || Z_TYPE(await_callback->key) == IS_UNDEF) {
success = zend_hash_next_index_insert_new(await_context->results, result);
ZVAL_LONG(&await_callback->key, await_context->results->nNextFreeElement - 1);
} else {
ZEND_ASSERT("Invalid key type: must be string, long or null");
}
if (success != NULL) {
Z_TRY_ADDREF_P(result);
}
}
if (UNEXPECTED(AWAIT_ITERATOR_IS_FINISHED(await_context) && await_callback->callback.coroutine != NULL)) {
ZEND_ASYNC_RESUME(await_callback->callback.coroutine);
}
ZEND_ASYNC_EVENT_CALLBACK_RELEASE(callback);
}
/**
* This callback is used only for awaiting cancelled coroutines.
* It resumes the target coroutine only after
* all coroutines awaiting cancellation have fully completed.
*
* @param event
* @param callback
* @param result
* @param exception
*/
static void async_waiting_cancellation_callback(zend_async_event_t *event,
zend_async_event_callback_t *callback,
void *result,
zend_object *exception)
{
async_await_callback_t *await_callback = (async_await_callback_t *) callback;
async_await_context_t *await_context = await_callback->await_context;
await_context->resolved_count++;
ZEND_ASYNC_EVENT_CALLBACK_ADD_REF(callback);
if (!event->del_callback(event, callback)) {
// Optimized: ignore del_callback failure in callback context
}
ZEND_ASYNC_EVENT_CALLBACK_DEC_REF(callback);
if (exception != NULL) {
ZEND_ASYNC_EVENT_SET_EXCEPTION_HANDLED(event);
}
if (await_context->errors != NULL && exception != NULL) {
const zval *success = NULL;
zval exception_obj;
ZVAL_OBJ(&exception_obj, exception);
if (Z_TYPE(await_callback->key) == IS_STRING) {
success = zend_hash_update(await_context->errors, Z_STR(await_callback->key), &exception_obj);
} else if (Z_TYPE(await_callback->key) == IS_LONG) {
success = zend_hash_index_update(await_context->errors, Z_LVAL(await_callback->key), &exception_obj);
} else if (Z_TYPE(await_callback->key) == IS_NULL || Z_TYPE(await_callback->key) == IS_UNDEF) {
success = zend_hash_next_index_insert_new(await_context->errors, &exception_obj);
ZVAL_LONG(&await_callback->key, await_context->errors->nNextFreeElement - 1);
} else {
ZEND_ASSERT("Invalid key type: must be string, long or null");
}
if (success != NULL) {
GC_ADDREF(exception);
}
}
if (await_context->total != 0 && await_context->resolved_count >= await_context->total) {
ZEND_ASYNC_RESUME(await_callback->callback.coroutine);
}
callback->dispose(callback, NULL);
}
/**
* A function that is called to process a single iteration element.
*
* @param iterator
* @param current
* @param key
* @return
*/
static zend_result await_iterator_handler(async_iterator_t *iterator, zval *current, zval *key)
{
async_await_iterator_t *await_iterator = ((async_await_iterator_iterator_t *) iterator)->await_iterator;
// An array element can be either an object implementing
// the Awaitable interface
// or an internal structure zend_async_event_t.
zend_async_event_t *awaitable = zval_to_event(current);
if (UNEXPECTED(EG(exception))) {
return FAILURE;
}
if (awaitable == NULL || zend_async_waker_is_event_exists(await_iterator->waiting_coroutine, awaitable)) {
return SUCCESS;
}
if (Z_TYPE_P(key) != IS_STRING && Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_NULL &&
Z_TYPE_P(key) != IS_UNDEF) {
async_throw_error("Invalid key type: must be string, long or null");
return FAILURE;
}
async_await_callback_t *callback = ecalloc(1, sizeof(async_await_callback_t));
callback->callback.base.callback = async_waiting_callback;
async_await_context_t *await_context = await_iterator->await_context;
callback->await_context = await_context;
await_context->ref_count++;
ZVAL_COPY(&callback->key, key);
// If the futures array is defined, we collect all new objects into it.
if (await_iterator->futures != NULL) {
if (Z_TYPE_P(key) == IS_STRING) {
zend_hash_update(await_iterator->futures, Z_STR_P(key), current);
} else if (Z_TYPE_P(key) == IS_LONG) {
zend_hash_index_update(await_iterator->futures, Z_LVAL_P(key), current);
} else if (Z_TYPE_P(key) == IS_NULL || Z_TYPE_P(key) == IS_UNDEF) {
// If the key is NULL, we use the next index
if (zend_hash_next_index_insert_new(await_iterator->futures, current) != NULL) {
ZVAL_LONG(&callback->key, await_iterator->futures->nNextFreeElement - 1);
}
}
}
// Add the empty element to the results array if all elements are awaited
if (await_context->results != NULL && await_context->fill_missing_with_null) {
if (Z_TYPE(callback->key) == IS_STRING) {
zend_hash_add_empty_element(await_context->results, Z_STR_P(key));
} else if (Z_TYPE(callback->key) == IS_LONG) {
zend_hash_index_add_empty_element(await_context->results, Z_LVAL_P(key));
}
} else if (await_context->results != NULL && await_context->preserve_key_order) {
zval undef_val;
// The PRT NULL type is used to fill the array with empty elements that will later be removed.
ZVAL_PTR(&undef_val, NULL);
if (Z_TYPE(callback->key) == IS_STRING) {
zend_hash_add(await_context->results, Z_STR_P(key), &undef_val);
} else if (Z_TYPE(callback->key) == IS_LONG) {
zend_hash_index_add(await_context->results, Z_LVAL_P(key), &undef_val);
}
}
if (ZEND_ASYNC_EVENT_IS_CLOSED(awaitable)) {
//
// The event is already closed.
// But if it supports the replay method, we can retrieve the resulting value again.
//
if (false == awaitable->replay) {
async_waiting_callback_dispose(&callback->callback.base, NULL);
return SUCCESS;
}
callback->callback.base.dispose = async_waiting_callback_dispose;
awaitable->replay(awaitable, &callback->callback.base, NULL, NULL);
if (UNEXPECTED(EG(exception))) {
return FAILURE;
}
return SUCCESS;
}
zend_async_resume_when(await_iterator->waiting_coroutine, awaitable, false, NULL, &callback->callback);
if (UNEXPECTED(EG(exception))) {
async_waiting_callback_dispose(&callback->callback.base, NULL);
return FAILURE;
}
callback->prev_dispose = callback->callback.base.dispose;
callback->callback.base.dispose = async_waiting_callback_dispose;
await_context->futures_count++;
return SUCCESS;
}
/**
* This function is called when the await_iterator is disposed.
* It cleans up the internal state and releases resources.
*
* @param iterator
* @param concurrent_iterator
*/
static void await_iterator_dispose(async_await_iterator_t *iterator, async_iterator_t *concurrent_iterator)
{
// If the iterator was completed with an exception,
// pass that exception to the coroutine that is waiting.
if (concurrent_iterator != NULL && concurrent_iterator->exception != NULL) {
zend_object *exception = concurrent_iterator->exception;
concurrent_iterator->exception = NULL;
ZEND_ASYNC_RESUME_WITH_ERROR(iterator->waiting_coroutine, exception, true);
}
if (iterator->zend_iterator != NULL) {
zend_object_iterator *zend_iterator = iterator->zend_iterator;
iterator->zend_iterator = NULL;
// When the iterator has finished, it’s now possible to specify the exact number of elements since it’s known.
iterator->await_context->total =
iterator->await_context->futures_count + iterator->await_context->resolved_count;
// Scenario: the iterator has already finished, and there’s nothing left to await.
// In that case, the coroutine needs to be terminated.
if ((AWAIT_ITERATOR_IS_FINISHED(iterator->await_context) || iterator->await_context->total == 0) &&
iterator->waiting_coroutine != NULL &&
false == ZEND_ASYNC_WAKER_IN_QUEUE(iterator->waiting_coroutine->waker)) {
ZEND_ASYNC_RESUME(iterator->waiting_coroutine);
}
if (zend_iterator->funcs->invalidate_current) {
zend_iterator->funcs->invalidate_current(zend_iterator);
}
zend_iterator_dtor(zend_iterator);
}
efree(iterator);
}
/**
* This function is called when the internal concurrent iterator is finished.
* It disposes of the await_iterator and cleans up the internal state.
*
* @param internal_iterator
*/
static void await_iterator_finish_callback(zend_async_iterator_t *internal_iterator)
{
async_await_iterator_iterator_t *iterator = (async_await_iterator_iterator_t *) internal_iterator;
async_await_iterator_t *await_iterator = iterator->await_iterator;
iterator->await_iterator = NULL;
await_iterator_dispose(await_iterator, &iterator->iterator);
}
/**
* This function is called when the iterator coroutine is first entered.
* It initializes the await_iterator and starts the iteration process.
*
* @return void
*/
static void iterator_coroutine_first_entry(void)
{
zend_coroutine_t *coroutine = ZEND_ASYNC_CURRENT_COROUTINE;
if (UNEXPECTED(coroutine == NULL)) {
async_throw_error("Cannot run iterator coroutine");
return;
}
async_await_iterator_t *await_iterator = coroutine->extended_data;
coroutine->extended_data = NULL;
ZEND_ASSERT(await_iterator != NULL && "The async_await_iterator_t should not be NULL");
if (UNEXPECTED(await_iterator == NULL)) {
async_throw_error("Cannot run concurrent iterator coroutine");
return;
}
async_await_context_t *await_context = await_iterator->await_context;
if (UNEXPECTED(await_context == NULL)) {
await_iterator_dispose(await_iterator, NULL);
return;
}
async_await_iterator_iterator_t *iterator =
(async_await_iterator_iterator_t *) async_iterator_new(NULL,
await_iterator->zend_iterator,
NULL,
await_iterator_handler,
ZEND_ASYNC_CURRENT_SCOPE,
await_context->concurrency,
ZEND_COROUTINE_NORMAL,
sizeof(async_await_iterator_iterator_t));
iterator->await_iterator = await_iterator;
iterator->iterator.extended_dtor = await_iterator_finish_callback;
if (UNEXPECTED(iterator == NULL)) {
await_iterator_dispose(await_iterator, NULL);
return;
}
async_iterator_run(&iterator->iterator);
iterator->iterator.microtask.dtor(&iterator->iterator.microtask);
}
/**
* This callback is triggered when the main iteration coroutine finishes.
* It’s needed in case the coroutine gets cancelled.
* In that scenario, extended_data will contain the async_await_iterator_t structure.
*
* @param event
* @param callback
* @param result
* @param exception
*/
static void iterator_coroutine_finish_callback(zend_async_event_t *event,
zend_async_event_callback_t *callback,
void *result,
zend_object *exception)
{
async_await_iterator_t *iterator = (async_await_iterator_t *) ((zend_coroutine_t *) event)->extended_data;
if (iterator == NULL) {
return;
}
if (exception != NULL) {
// Resume the waiting coroutine with the exception
ZEND_ASYNC_RESUME_WITH_ERROR(iterator->waiting_coroutine, exception, false);
} else if (AWAIT_ITERATOR_IS_FINISHED(iterator->await_context)) {
// If iteration is finished, resume the waiting coroutine
ZEND_ASYNC_RESUME(iterator->waiting_coroutine);
}
}
static void async_await_iterator_coroutine_dispose(zend_coroutine_t *coroutine)
{
if (coroutine == NULL || coroutine->extended_data == NULL) {
return;
}
async_await_iterator_t *await_iterator = (async_await_iterator_t *) coroutine->extended_data;
coroutine->extended_data = NULL;
await_iterator_dispose(await_iterator, NULL);
}
static void await_context_dtor(async_await_context_t *context)
{
if (context == NULL) {
return;
}
if (context->ref_count > 1) {
context->ref_count--;
return;
}
efree(context);
}
static void async_cancel_awaited_futures(async_await_context_t *await_context, HashTable *futures)
{
zend_coroutine_t *this_coroutine = ZEND_ASYNC_CURRENT_COROUTINE;
if (UNEXPECTED(ZEND_ASYNC_WAKER_NEW(this_coroutine) == NULL)) {
return;
}
if (futures == NULL) {
// TODO: Write code to await the coroutine Scope.
return;
}
zend_ulong index;
zend_string *key;
zval *current;
bool not_need_wait = true;
ZEND_HASH_FOREACH_KEY_VAL(futures, index, key, current)
{
// Handle only the Coroutine objects
if (Z_TYPE_P(current) != IS_OBJECT || false == instanceof_function(Z_OBJCE_P(current), async_ce_coroutine)) {
continue;
}
zend_async_event_t *awaitable = zval_to_event(current);
if (UNEXPECTED(EG(exception))) {
return;
}
if (awaitable == NULL || ZEND_ASYNC_EVENT_IS_CLOSED(awaitable)) {
continue;
}
async_await_callback_t *callback = ecalloc(1, sizeof(async_await_callback_t));
callback->callback.base.callback = async_waiting_cancellation_callback;
callback->await_context = await_context;
ZEND_ASYNC_EVENT_SET_RESULT_USED(awaitable);
ZEND_ASYNC_EVENT_SET_EXC_CAUGHT(awaitable);
if (key != NULL) {
ZVAL_STR(&callback->key, key);
zval_add_ref(&callback->key);
} else {
ZVAL_LONG(&callback->key, index);
}
zend_async_resume_when(this_coroutine, awaitable, false, NULL, &callback->callback);
if (UNEXPECTED(EG(exception))) {
await_context->dtor(await_context);
return;
}
not_need_wait = false;
callback->prev_dispose = callback->callback.base.dispose;
callback->callback.base.dispose = async_waiting_callback_dispose;
await_context->ref_count++;
}
ZEND_HASH_FOREACH_END();
if (not_need_wait) {
return;
}
ZEND_ASYNC_SUSPEND();
zend_async_waker_clean(ZEND_ASYNC_CURRENT_COROUTINE);
}
/**
* This function is used to await multiple futures concurrently.
* It takes an iterable of futures, a count of futures to wait for,
* and various options for handling results and errors.
*
* @param iterable The iterable containing futures (array or Traversable object).
* @param count The number of futures to wait for (0 means all).
* @param ignore_errors Whether to ignore errors in the futures.
* @param cancellation Optional cancellation event.
* @param timeout Timeout for awaiting futures.
* @param concurrency Maximum number of concurrent futures to await.
* @param results HashTable to store results.
* @param errors HashTable to store errors.
* @param fill_missing_with_null Whether to fill missing results with null.
* @param preserve_key_order Whether to preserve the order of keys in results.
* @param cancel_on_exit Whether to cancel awaiting on exit.
*/
void async_await_futures(zval *iterable,
int count,
bool ignore_errors,
zend_async_event_t *cancellation,
zend_ulong timeout,
unsigned int concurrency,
HashTable *results,
HashTable *errors,
bool fill_missing_with_null,
bool preserve_key_order,
bool cancel_on_exit)
{
HashTable *futures = NULL;
zend_object_iterator *zend_iterator = NULL;
HashTable *tmp_results = NULL;
if (Z_TYPE_P(iterable) == IS_ARRAY) {
futures = Z_ARR_P(iterable);
} else if (Z_TYPE_P(iterable) == IS_OBJECT && Z_OBJCE_P(iterable)->get_iterator) {
zend_iterator = Z_OBJCE_P(iterable)->get_iterator(Z_OBJCE_P(iterable), iterable, 0);
if (EG(exception) == NULL && zend_iterator == NULL) {
async_throw_error("Failed to create iterator");
}
} else {
async_throw_error("Expected parameter 'iterable' to be an array or an object implementing Traversable");
}
if (UNEXPECTED(EG(exception))) {
return;
}
zend_ulong index;
zend_string *key;
zval *current;
async_await_context_t *await_context = NULL;
if (UNEXPECTED(futures != NULL && zend_hash_num_elements(futures) == 0)) {
return;
}
zend_coroutine_t *coroutine = ZEND_ASYNC_CURRENT_COROUTINE;
if (UNEXPECTED(coroutine == NULL)) {
if (zend_iterator != NULL) {
zend_iterator_dtor(zend_iterator);
}
async_throw_error("Cannot await futures outside of a coroutine");
return;
}
if (UNEXPECTED(zend_async_waker_new_with_timeout(coroutine, timeout, cancellation) == NULL)) {
if (zend_iterator != NULL) {
zend_iterator_dtor(zend_iterator);
}
return;
}
if (concurrency == 0) {
concurrency = ASYNC_G(default_concurrency);
}
await_context = ecalloc(1, sizeof(async_await_context_t));
await_context->total = futures != NULL ? (int) zend_hash_num_elements(futures) : 0;
await_context->futures_count = 0;
await_context->waiting_count = count > 0 ? count : await_context->total;
await_context->resolved_count = 0;
await_context->success_count = 0;
await_context->ignore_errors = ignore_errors;
await_context->concurrency = concurrency;
await_context->fill_missing_with_null = fill_missing_with_null;
await_context->preserve_key_order = preserve_key_order;
await_context->cancel_on_exit = cancel_on_exit;
if (preserve_key_order && false == fill_missing_with_null) {
tmp_results = zend_new_array(await_context->total);
await_context->results = tmp_results;
} else {
await_context->results = results;
}
await_context->errors = errors;
await_context->dtor = await_context_dtor;
await_context->ref_count = 1;
if (futures != NULL) {
zval undef_val;
// The PRT NULL type is used to fill the array with empty elements that will later be removed.
ZVAL_PTR(&undef_val, NULL);
ZEND_HASH_FOREACH_KEY_VAL(futures, index, key, current)
{
// An array element can be either an object implementing
// the Awaitable interface
// or an internal structure zend_async_event_t.
zend_async_event_t *awaitable = zval_to_event(current);
if (UNEXPECTED(EG(exception))) {
await_context->dtor(await_context);
return;
}
if (awaitable == NULL) {
continue;
}
async_await_callback_t *callback = ecalloc(1, sizeof(async_await_callback_t));
callback->callback.base.callback = async_waiting_callback;
callback->await_context = await_context;
ZEND_ASYNC_EVENT_SET_RESULT_USED(awaitable);
ZEND_ASYNC_EVENT_SET_EXC_CAUGHT(awaitable);
if (key != NULL) {
ZVAL_STR(&callback->key, key);
zval_add_ref(&callback->key);
if (await_context->results != NULL && fill_missing_with_null) {
zend_hash_add_empty_element(await_context->results, key);
} else if (await_context->results != NULL && preserve_key_order) {