LCOV - code coverage report
Current view: top level - extmod - modasyncio.c (source / functions) Hit Total Coverage
Test: unix_coverage_v1.22.0-344-ge60e8079a.info Lines: 126 127 99.2 %
Date: 2024-04-26 14:58:11 Functions: 14 14 100.0 %
Branches: 47 54 87.0 %

           Branch data     Line data    Source code
       1                 :            : /*
       2                 :            :  * This file is part of the MicroPython project, http://micropython.org/
       3                 :            :  *
       4                 :            :  * The MIT License (MIT)
       5                 :            :  *
       6                 :            :  * Copyright (c) 2020 Damien P. George
       7                 :            :  *
       8                 :            :  * Permission is hereby granted, free of charge, to any person obtaining a copy
       9                 :            :  * of this software and associated documentation files (the "Software"), to deal
      10                 :            :  * in the Software without restriction, including without limitation the rights
      11                 :            :  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
      12                 :            :  * copies of the Software, and to permit persons to whom the Software is
      13                 :            :  * furnished to do so, subject to the following conditions:
      14                 :            :  *
      15                 :            :  * The above copyright notice and this permission notice shall be included in
      16                 :            :  * all copies or substantial portions of the Software.
      17                 :            :  *
      18                 :            :  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
      19                 :            :  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
      20                 :            :  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
      21                 :            :  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
      22                 :            :  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      23                 :            :  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
      24                 :            :  * THE SOFTWARE.
      25                 :            :  */
      26                 :            : 
      27                 :            : #include "py/runtime.h"
      28                 :            : #include "py/smallint.h"
      29                 :            : #include "py/pairheap.h"
      30                 :            : #include "py/mphal.h"
      31                 :            : 
      32                 :            : #if MICROPY_PY_ASYNCIO
      33                 :            : 
      34                 :            : // Used when task cannot be guaranteed to be non-NULL.
      35                 :            : #define TASK_PAIRHEAP(task) ((task) ? &(task)->pairheap : NULL)
      36                 :            : 
      37                 :            : #define TASK_STATE_RUNNING_NOT_WAITED_ON (mp_const_true)
      38                 :            : #define TASK_STATE_DONE_NOT_WAITED_ON (mp_const_none)
      39                 :            : #define TASK_STATE_DONE_WAS_WAITED_ON (mp_const_false)
      40                 :            : 
      41                 :            : #define TASK_IS_DONE(task) ( \
      42                 :            :     (task)->state == TASK_STATE_DONE_NOT_WAITED_ON \
      43                 :            :     || (task)->state == TASK_STATE_DONE_WAS_WAITED_ON)
      44                 :            : 
      45                 :            : typedef struct _mp_obj_task_t {
      46                 :            :     mp_pairheap_t pairheap;
      47                 :            :     mp_obj_t coro;
      48                 :            :     mp_obj_t data;
      49                 :            :     mp_obj_t state;
      50                 :            :     mp_obj_t ph_key;
      51                 :            : } mp_obj_task_t;
      52                 :            : 
      53                 :            : typedef struct _mp_obj_task_queue_t {
      54                 :            :     mp_obj_base_t base;
      55                 :            :     mp_obj_task_t *heap;
      56                 :            : } mp_obj_task_queue_t;
      57                 :            : 
      58                 :            : static const mp_obj_type_t task_queue_type;
      59                 :            : static const mp_obj_type_t task_type;
      60                 :            : 
      61                 :            : static mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args);
      62                 :            : 
      63                 :            : /******************************************************************************/
      64                 :            : // Ticks for task ordering in pairing heap
      65                 :            : 
      66                 :        898 : static mp_obj_t ticks(void) {
      67                 :        898 :     return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_ms() & (MICROPY_PY_TIME_TICKS_PERIOD - 1));
      68                 :            : }
      69                 :            : 
      70                 :     339677 : static mp_int_t ticks_diff(mp_obj_t t1_in, mp_obj_t t0_in) {
      71                 :     339677 :     mp_uint_t t0 = MP_OBJ_SMALL_INT_VALUE(t0_in);
      72                 :     339677 :     mp_uint_t t1 = MP_OBJ_SMALL_INT_VALUE(t1_in);
      73                 :     339677 :     mp_int_t diff = ((t1 - t0 + MICROPY_PY_TIME_TICKS_PERIOD / 2) & (MICROPY_PY_TIME_TICKS_PERIOD - 1))
      74                 :     339677 :         - MICROPY_PY_TIME_TICKS_PERIOD / 2;
      75                 :     339677 :     return diff;
      76                 :            : }
      77                 :            : 
      78                 :     339582 : static int task_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) {
      79                 :     339582 :     mp_obj_task_t *t1 = (mp_obj_task_t *)n1;
      80                 :     339582 :     mp_obj_task_t *t2 = (mp_obj_task_t *)n2;
      81                 :     339582 :     return MP_OBJ_SMALL_INT_VALUE(ticks_diff(t1->ph_key, t2->ph_key)) < 0;
      82                 :            : }
      83                 :            : 
      84                 :            : /******************************************************************************/
      85                 :            : // TaskQueue class
      86                 :            : 
      87                 :        180 : static mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
      88                 :        180 :     (void)args;
      89                 :        180 :     mp_arg_check_num(n_args, n_kw, 0, 0, false);
      90                 :        180 :     mp_obj_task_queue_t *self = mp_obj_malloc(mp_obj_task_queue_t, type);
      91                 :        180 :     self->heap = (mp_obj_task_t *)mp_pairheap_new(task_lt);
      92                 :        180 :     return MP_OBJ_FROM_PTR(self);
      93                 :            : }
      94                 :            : 
      95                 :     114228 : static mp_obj_t task_queue_peek(mp_obj_t self_in) {
      96                 :     114228 :     mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in);
      97         [ +  + ]:     114228 :     if (self->heap == NULL) {
      98                 :            :         return mp_const_none;
      99                 :            :     } else {
     100                 :     114078 :         return MP_OBJ_FROM_PTR(self->heap);
     101                 :            :     }
     102                 :            : }
     103                 :            : static MP_DEFINE_CONST_FUN_OBJ_1(task_queue_peek_obj, task_queue_peek);
     104                 :            : 
     105                 :     114049 : static mp_obj_t task_queue_push(size_t n_args, const mp_obj_t *args) {
     106                 :     114049 :     mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(args[0]);
     107                 :     114049 :     mp_obj_task_t *task = MP_OBJ_TO_PTR(args[1]);
     108                 :     114049 :     task->data = mp_const_none;
     109         [ +  + ]:     114049 :     if (n_args == 2) {
     110                 :        803 :         task->ph_key = ticks();
     111                 :            :     } else {
     112         [ -  + ]:     113246 :         assert(mp_obj_is_small_int(args[2]));
     113                 :     113246 :         task->ph_key = args[2];
     114                 :            :     }
     115         [ +  + ]:     114049 :     self->heap = (mp_obj_task_t *)mp_pairheap_push(task_lt, TASK_PAIRHEAP(self->heap), TASK_PAIRHEAP(task));
     116                 :     114049 :     return mp_const_none;
     117                 :            : }
     118                 :            : static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(task_queue_push_obj, 2, 3, task_queue_push);
     119                 :            : 
     120                 :     113964 : static mp_obj_t task_queue_pop(mp_obj_t self_in) {
     121                 :     113964 :     mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in);
     122                 :     113964 :     mp_obj_task_t *head = (mp_obj_task_t *)mp_pairheap_peek(task_lt, &self->heap->pairheap);
     123         [ -  + ]:     113964 :     if (head == NULL) {
     124                 :          0 :         mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty heap"));
     125                 :            :     }
     126                 :     113964 :     self->heap = (mp_obj_task_t *)mp_pairheap_pop(task_lt, &self->heap->pairheap);
     127                 :     113964 :     return MP_OBJ_FROM_PTR(head);
     128                 :            : }
     129                 :            : static MP_DEFINE_CONST_FUN_OBJ_1(task_queue_pop_obj, task_queue_pop);
     130                 :            : 
     131                 :         59 : static mp_obj_t task_queue_remove(mp_obj_t self_in, mp_obj_t task_in) {
     132                 :         59 :     mp_obj_task_queue_t *self = MP_OBJ_TO_PTR(self_in);
     133                 :         59 :     mp_obj_task_t *task = MP_OBJ_TO_PTR(task_in);
     134                 :         59 :     self->heap = (mp_obj_task_t *)mp_pairheap_delete(task_lt, &self->heap->pairheap, &task->pairheap);
     135                 :         59 :     return mp_const_none;
     136                 :            : }
     137                 :            : static MP_DEFINE_CONST_FUN_OBJ_2(task_queue_remove_obj, task_queue_remove);
     138                 :            : 
     139                 :            : static const mp_rom_map_elem_t task_queue_locals_dict_table[] = {
     140                 :            :     { MP_ROM_QSTR(MP_QSTR_peek), MP_ROM_PTR(&task_queue_peek_obj) },
     141                 :            :     { MP_ROM_QSTR(MP_QSTR_push), MP_ROM_PTR(&task_queue_push_obj) },
     142                 :            :     { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&task_queue_pop_obj) },
     143                 :            :     { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&task_queue_remove_obj) },
     144                 :            : };
     145                 :            : static MP_DEFINE_CONST_DICT(task_queue_locals_dict, task_queue_locals_dict_table);
     146                 :            : 
     147                 :            : static MP_DEFINE_CONST_OBJ_TYPE(
     148                 :            :     task_queue_type,
     149                 :            :     MP_QSTR_TaskQueue,
     150                 :            :     MP_TYPE_FLAG_NONE,
     151                 :            :     make_new, task_queue_make_new,
     152                 :            :     locals_dict, &task_queue_locals_dict
     153                 :            :     );
     154                 :            : 
     155                 :            : /******************************************************************************/
     156                 :            : // Task class
     157                 :            : 
     158                 :            : // This is the core asyncio context with cur_task, _task_queue and CancelledError.
     159                 :            : mp_obj_t mp_asyncio_context = MP_OBJ_NULL;
     160                 :            : 
     161                 :        392 : static mp_obj_t task_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
     162                 :        392 :     mp_arg_check_num(n_args, n_kw, 1, 2, false);
     163                 :        392 :     mp_obj_task_t *self = m_new_obj(mp_obj_task_t);
     164                 :        392 :     self->pairheap.base.type = type;
     165         [ +  - ]:        392 :     mp_pairheap_init_node(task_lt, &self->pairheap);
     166                 :        392 :     self->coro = args[0];
     167                 :        392 :     self->data = mp_const_none;
     168                 :        392 :     self->state = TASK_STATE_RUNNING_NOT_WAITED_ON;
     169                 :        392 :     self->ph_key = MP_OBJ_NEW_SMALL_INT(0);
     170         [ +  - ]:        392 :     if (n_args == 2) {
     171                 :        392 :         mp_asyncio_context = args[1];
     172                 :            :     }
     173                 :        392 :     return MP_OBJ_FROM_PTR(self);
     174                 :            : }
     175                 :            : 
     176                 :         38 : static mp_obj_t task_done(mp_obj_t self_in) {
     177                 :         38 :     mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in);
     178         [ +  + ]:         38 :     return mp_obj_new_bool(TASK_IS_DONE(self));
     179                 :            : }
     180                 :            : static MP_DEFINE_CONST_FUN_OBJ_1(task_done_obj, task_done);
     181                 :            : 
     182                 :        124 : static mp_obj_t task_cancel(mp_obj_t self_in) {
     183                 :        124 :     mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in);
     184                 :            :     // Check if task is already finished.
     185         [ +  + ]:        124 :     if (TASK_IS_DONE(self)) {
     186                 :            :         return mp_const_false;
     187                 :            :     }
     188                 :            :     // Can't cancel self (not supported yet).
     189                 :        110 :     mp_obj_t cur_task = mp_obj_dict_get(mp_asyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_cur_task));
     190         [ +  + ]:        110 :     if (self_in == cur_task) {
     191                 :          2 :         mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("can't cancel self"));
     192                 :            :     }
     193                 :            :     // If Task waits on another task then forward the cancel to the one it's waiting on.
     194         [ +  + ]:        127 :     while (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(self->data)), MP_OBJ_FROM_PTR(&task_type))) {
     195                 :         19 :         self = MP_OBJ_TO_PTR(self->data);
     196                 :            :     }
     197                 :            : 
     198                 :        108 :     mp_obj_t _task_queue = mp_obj_dict_get(mp_asyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR__task_queue));
     199                 :            : 
     200                 :            :     // Reschedule Task as a cancelled task.
     201                 :        108 :     mp_obj_t dest[3];
     202                 :        108 :     mp_load_method_maybe(self->data, MP_QSTR_remove, dest);
     203         [ +  + ]:        108 :     if (dest[0] != MP_OBJ_NULL) {
     204                 :            :         // Not on the main running queue, remove the task from the queue it's on.
     205                 :         13 :         dest[2] = MP_OBJ_FROM_PTR(self);
     206                 :         13 :         mp_call_method_n_kw(1, 0, dest);
     207                 :            :         // _task_queue.push(self)
     208                 :         13 :         dest[0] = _task_queue;
     209                 :         13 :         dest[1] = MP_OBJ_FROM_PTR(self);
     210                 :         13 :         task_queue_push(2, dest);
     211         [ +  + ]:         95 :     } else if (ticks_diff(self->ph_key, ticks()) > 0) {
     212                 :            :         // On the main running queue but scheduled in the future, so bring it forward to now.
     213                 :            :         // _task_queue.remove(self)
     214                 :         52 :         task_queue_remove(_task_queue, MP_OBJ_FROM_PTR(self));
     215                 :            :         // _task_queue.push(self)
     216                 :         52 :         dest[0] = _task_queue;
     217                 :         52 :         dest[1] = MP_OBJ_FROM_PTR(self);
     218                 :         52 :         task_queue_push(2, dest);
     219                 :            :     }
     220                 :            : 
     221                 :        108 :     self->data = mp_obj_dict_get(mp_asyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_CancelledError));
     222                 :            : 
     223                 :        108 :     return mp_const_true;
     224                 :            : }
     225                 :            : static MP_DEFINE_CONST_FUN_OBJ_1(task_cancel_obj, task_cancel);
     226                 :            : 
     227                 :     344480 : static void task_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
     228                 :     344480 :     mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in);
     229         [ +  + ]:     344480 :     if (dest[0] == MP_OBJ_NULL) {
     230                 :            :         // Load
     231         [ +  + ]:     343604 :         if (attr == MP_QSTR_coro) {
     232                 :     113823 :             dest[0] = self->coro;
     233         [ +  + ]:     229781 :         } else if (attr == MP_QSTR_data) {
     234                 :     114441 :             dest[0] = self->data;
     235         [ +  + ]:     115340 :         } else if (attr == MP_QSTR_state) {
     236                 :       1238 :             dest[0] = self->state;
     237         [ +  + ]:     114102 :         } else if (attr == MP_QSTR_done) {
     238                 :         38 :             dest[0] = MP_OBJ_FROM_PTR(&task_done_obj);
     239                 :         38 :             dest[1] = self_in;
     240         [ +  + ]:     114064 :         } else if (attr == MP_QSTR_cancel) {
     241                 :        124 :             dest[0] = MP_OBJ_FROM_PTR(&task_cancel_obj);
     242                 :        124 :             dest[1] = self_in;
     243         [ +  + ]:     113940 :         } else if (attr == MP_QSTR_ph_key) {
     244                 :     113937 :             dest[0] = self->ph_key;
     245                 :            :         }
     246         [ +  - ]:        876 :     } else if (dest[1] != MP_OBJ_NULL) {
     247                 :            :         // Store
     248         [ +  + ]:        876 :         if (attr == MP_QSTR_data) {
     249                 :        530 :             self->data = dest[1];
     250                 :        530 :             dest[0] = MP_OBJ_NULL;
     251         [ +  - ]:        346 :         } else if (attr == MP_QSTR_state) {
     252                 :        346 :             self->state = dest[1];
     253                 :        346 :             dest[0] = MP_OBJ_NULL;
     254                 :            :         }
     255                 :            :     }
     256                 :     344480 : }
     257                 :            : 
     258                 :        111 : static mp_obj_t task_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) {
     259                 :        111 :     (void)iter_buf;
     260                 :        111 :     mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in);
     261         [ +  + ]:        111 :     if (TASK_IS_DONE(self)) {
     262                 :            :         // Signal that the completed-task has been await'ed on.
     263                 :         25 :         self->state = TASK_STATE_DONE_WAS_WAITED_ON;
     264         [ +  + ]:         86 :     } else if (self->state == TASK_STATE_RUNNING_NOT_WAITED_ON) {
     265                 :            :         // Allocate the waiting queue.
     266                 :         84 :         self->state = task_queue_make_new(&task_queue_type, 0, 0, NULL);
     267         [ +  - ]:          2 :     } else if (mp_obj_get_type(self->state) != &task_queue_type) {
     268                 :            :         // Task has state used for another purpose, so can't also wait on it.
     269                 :          2 :         mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("can't wait"));
     270                 :            :     }
     271                 :        109 :     return self_in;
     272                 :            : }
     273                 :            : 
     274                 :        188 : static mp_obj_t task_iternext(mp_obj_t self_in) {
     275                 :        188 :     mp_obj_task_t *self = MP_OBJ_TO_PTR(self_in);
     276         [ +  + ]:        188 :     if (TASK_IS_DONE(self)) {
     277                 :            :         // Task finished, raise return value to caller so it can continue.
     278                 :        104 :         nlr_raise(self->data);
     279                 :            :     } else {
     280                 :            :         // Put calling task on waiting queue.
     281                 :         84 :         mp_obj_t cur_task = mp_obj_dict_get(mp_asyncio_context, MP_OBJ_NEW_QSTR(MP_QSTR_cur_task));
     282                 :         84 :         mp_obj_t args[2] = { self->state, cur_task };
     283                 :         84 :         task_queue_push(2, args);
     284                 :            :         // Set calling task's data to this task that it waits on, to double-link it.
     285                 :         84 :         ((mp_obj_task_t *)MP_OBJ_TO_PTR(cur_task))->data = self_in;
     286                 :            :     }
     287                 :         84 :     return mp_const_none;
     288                 :            : }
     289                 :            : 
     290                 :            : static const mp_getiter_iternext_custom_t task_getiter_iternext = {
     291                 :            :     .getiter = task_getiter,
     292                 :            :     .iternext = task_iternext,
     293                 :            : };
     294                 :            : 
     295                 :            : static MP_DEFINE_CONST_OBJ_TYPE(
     296                 :            :     task_type,
     297                 :            :     MP_QSTR_Task,
     298                 :            :     MP_TYPE_FLAG_ITER_IS_CUSTOM,
     299                 :            :     make_new, task_make_new,
     300                 :            :     attr, task_attr,
     301                 :            :     iter, &task_getiter_iternext
     302                 :            :     );
     303                 :            : 
     304                 :            : /******************************************************************************/
     305                 :            : // C-level asyncio module
     306                 :            : 
     307                 :            : static const mp_rom_map_elem_t mp_module_asyncio_globals_table[] = {
     308                 :            :     { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__asyncio) },
     309                 :            :     { MP_ROM_QSTR(MP_QSTR_TaskQueue), MP_ROM_PTR(&task_queue_type) },
     310                 :            :     { MP_ROM_QSTR(MP_QSTR_Task), MP_ROM_PTR(&task_type) },
     311                 :            : };
     312                 :            : static MP_DEFINE_CONST_DICT(mp_module_asyncio_globals, mp_module_asyncio_globals_table);
     313                 :            : 
     314                 :            : const mp_obj_module_t mp_module_asyncio = {
     315                 :            :     .base = { &mp_type_module },
     316                 :            :     .globals = (mp_obj_dict_t *)&mp_module_asyncio_globals,
     317                 :            : };
     318                 :            : 
     319                 :            : MP_REGISTER_MODULE(MP_QSTR__asyncio, mp_module_asyncio);
     320                 :            : 
     321                 :            : #endif // MICROPY_PY_ASYNCIO

Generated by: LCOV version 1.15-5-g462f71d