Debian Codegraph @

gi/pygi-async.c

raw
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2 * vim: tabstop=4 shiftwidth=4 expandtab
3 *
4 * Copyright (C) 2015 Christoph Reiter <[email protected]>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "pygobject-object.h"
21
22 #include "pygboxed.h"
23 #include "pygi-async.h"
24 #include "pygi-invoke.h"
25 #include "pygi-util.h"
26
27 static PyObject *asyncio_InvalidStateError;
28 static PyObject *asyncio_get_running_loop;
29 #if defined(PYPY_VERSION)
30 static PyObject *contextvars_copy_context;
31 #endif
32 static PyObject *cancellable_info;
33
34 /* This is never instantiated. */
35 PYGI_DEFINE_TYPE ("gi._gi.Async", PyGIAsync_Type, PyGIAsync)
36
37 /**
38 * Async.__repr__() implementation.
39 * Takes the _Async.__repr_format format string and applies the finish function
40 * info to it.
41 */
42 static PyObject *
43 async_repr (PyGIAsync *self)
44 {
45 PyObject *string;
46 char *func_descr;
47
48 func_descr =
49 _pygi_gi_base_info_get_fullname (self->finish_func->base.info);
50
51 string = PyUnicode_FromFormat (
52 "%s(finish_func=%s, done=%s)", Py_TYPE (self)->tp_name, func_descr,
53 (self->result || self->exception) ? "True" : "False");
54
55 g_free (func_descr);
56
57 return string;
58 }
59
60 /**
61 * async_cancel:
62 *
63 * Cancel the asynchronous operation.
64 */
65 static PyObject *
66 async_cancel (PyGIAsync *self, PyObject *args, PyObject *kwargs)
67 {
68 static char *kwlist[] = { "msg", NULL };
69 const char *msg = NULL;
70
71 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "|z", kwlist, &msg))
72 return NULL;
73
74 return PyObject_CallMethod (self->cancellable, "cancel", NULL);
75 }
76
77 static PyObject *
78 async_done (PyGIAsync *self)
79 {
80 return PyBool_FromLong (self->result || self->exception);
81 }
82
83 static PyObject *
84 async_result (PyGIAsync *self)
85 {
86 if (!self->result && !self->exception) {
87 PyErr_SetString (asyncio_InvalidStateError,
88 "Async task is still running!");
89 return NULL;
90 }
91
92 self->log_tb = FALSE;
93
94 if (self->result) {
95 Py_INCREF (self->result);
96 return self->result;
97 } else {
98 PyErr_SetObject (PyExceptionInstance_Class (self->exception),
99 self->exception);
100 return NULL;
101 }
102 }
103
104 static PyObject *
105 async_exception (PyGIAsync *self)
106 {
107 PyObject *res;
108
109 if (!self->result && !self->exception) {
110 PyErr_SetString (asyncio_InvalidStateError,
111 "Async task is still running!");
112 return NULL;
113 }
114
115 if (self->exception)
116 res = self->exception;
117 else
118 res = Py_None;
119
120 self->log_tb = FALSE;
121
122 Py_INCREF (res);
123 return res;
124 }
125
126 static PyObject *
127 call_soon (PyGIAsync *self, PyGIAsyncCallback *cb)
128 {
129 PyObject *call_soon;
130 PyObject *args, *kwargs = NULL;
131 PyObject *ret;
132
133 call_soon = PyObject_GetAttrString (self->loop, "call_soon");
134 if (!call_soon) return NULL;
135
136 args = Py_BuildValue ("(OO)", cb->func, self);
137 kwargs = PyDict_New ();
138 PyDict_SetItemString (kwargs, "context", cb->context);
139 ret = PyObject_Call (call_soon, args, kwargs);
140
141 Py_CLEAR (args);
142 Py_CLEAR (kwargs);
143 Py_CLEAR (call_soon);
144
145 return ret;
146 }
147
148 static PyObject *
149 async_add_done_callback (PyGIAsync *self, PyObject *args, PyObject *kwargs)
150 {
151 PyGIAsyncCallback callback = { NULL };
152
153 static char *kwlist[] = { "", "context", NULL };
154
155 if (!PyArg_ParseTupleAndKeywords (args, kwargs, "O|$O:add_done_callback",
156 kwlist, &callback.func,
157 &callback.context))
158 return NULL;
159
160 Py_INCREF (callback.func);
161 if (callback.context == NULL)
162 #ifndef PYPY_VERSION
163 callback.context = PyContext_CopyCurrent ();
164 #else
165 callback.context =
166 PyObject_CallObject (contextvars_copy_context, NULL);
167 #endif
168 else
169 Py_INCREF (callback.context);
170
171 /* Note that we don't need to copy the current context in this case. */
172 if (self->result || self->exception) {
173 PyObject *res = call_soon (self, &callback);
174
175 Py_DECREF (callback.func);
176 Py_DECREF (callback.context);
177 if (res) {
178 Py_DECREF (res);
179 Py_RETURN_NONE;
180 } else {
181 return NULL;
182 }
183 }
184
185 if (!self->callbacks)
186 self->callbacks = g_array_new (TRUE, TRUE, sizeof (PyGIAsyncCallback));
187
188 g_array_append_val (self->callbacks, callback);
189
190 Py_RETURN_NONE;
191 }
192
193 static PyObject *
194 async_remove_done_callback (PyGIAsync *self, PyObject *fn)
195 {
196 guint i = 0;
197 gssize removed = 0;
198
199 while (self->callbacks && i < self->callbacks->len) {
200 PyGIAsyncCallback *cb =
201 &g_array_index (self->callbacks, PyGIAsyncCallback, i);
202
203 if (PyObject_RichCompareBool (cb->func, fn, Py_EQ) == 1) {
204 Py_DECREF (cb->func);
205 Py_DECREF (cb->context);
206
207 removed += 1;
208 g_array_remove_index (self->callbacks, i);
209 } else {
210 i += 1;
211 }
212 }
213
214 return PyLong_FromSsize_t (removed);
215 }
216
217 static int
218 async_init (PyGIAsync *self, PyObject *args, PyObject *kwargs)
219 {
220 static char *kwlist[] = { "finish_func", "cancellable", NULL };
221 PyObject *context = NULL;
222 GMainContext *ctx = NULL;
223 int ret = -1;
224
225 if (!PyArg_ParseTupleAndKeywords (
226 args, kwargs, "O!|O!$:gi._gi.Async.__init__", kwlist,
227 &PyGICallableInfo_Type, &self->finish_func, &PyGObject_Type,
228 &self->cancellable))
229 goto out;
230
231 Py_INCREF (self->finish_func);
232
233 /* We need to pull in Gio.Cancellable at some point, but we delay it
234 * until really needed to avoid having a dependency.
235 */
236 if (G_UNLIKELY (!cancellable_info)) {
237 PyObject *gio;
238
239 gio = PyImport_ImportModule ("gi.repository.Gio");
240 if (gio == NULL) goto out;
241
242 cancellable_info = PyObject_GetAttrString (gio, "Cancellable");
243 Py_DECREF (gio);
244
245 if (!cancellable_info) goto out;
246 }
247
248 if (self->cancellable) {
249 int res;
250
251 Py_INCREF (self->cancellable);
252
253 res = PyObject_IsInstance (self->cancellable, cancellable_info);
254 if (res == -1) goto out;
255
256 if (res == 0) {
257 PyErr_SetString (
258 PyExc_TypeError,
259 "cancellable argument needs to be of type Gio.Cancellable");
260 goto out;
261 }
262 } else {
263 self->cancellable = PyObject_CallObject (cancellable_info, NULL);
264 }
265
266 self->loop = PyObject_CallObject (asyncio_get_running_loop, NULL);
267 if (!self->loop) goto out;
268
269 /* We use g_main_context_ref_thread_default() here, as that is what GTask
270 * does. We then only allow creating an awaitable if python has a *running*
271 * EventLoop iterating this context (i.e. has it as its `_context` attr).
272 *
273 * NOTE: This is a bit backward. Instead, it would make more sense to just
274 * fetch the current EventLoop object for the ref'ed GMainContext.
275 * Python will then do the rest and ensure it is not awaited from the wrong
276 * EventLoop.
277 */
278 ctx = g_main_context_ref_thread_default ();
279 assert (ctx != NULL);
280
281 /* Duck-type the running loop. It needs to have a _context attribute. */
282 context = PyObject_GetAttrString (self->loop, "_context");
283 if (context == NULL) goto out;
284
285 if (!pyg_boxed_check (context, G_TYPE_MAIN_CONTEXT)
286 || pyg_boxed_get_ptr (context) != ctx) {
287 PyErr_SetString (
288 PyExc_TypeError,
289 "Running EventLoop is iterating a different GMainContext");
290 goto out;
291 }
292
293 /* Success! */
294 ret = 0;
295
296 out:
297 g_main_context_unref (ctx);
298 Py_XDECREF (context);
299
300 return ret;
301 }
302
303 static PyMethodDef async_methods[] = {
304 { "cancel", (PyCFunction)async_cancel, METH_VARARGS | METH_KEYWORDS },
305 { "done", (PyCFunction)async_done, METH_NOARGS },
306 { "result", (PyCFunction)async_result, METH_NOARGS },
307 { "exception", (PyCFunction)async_exception, METH_NOARGS },
308 { "add_done_callback", (PyCFunction)async_add_done_callback,
309 METH_VARARGS | METH_KEYWORDS },
310 { "remove_done_callback", (PyCFunction)async_remove_done_callback,
311 METH_O },
312 { NULL, NULL, 0 },
313 };
314
315 static PyObject *
316 async_await (PyGIAsync *self)
317 {
318 /* We return ourselves as iterator. This is legal in principle, but we
319 * don't stop iterating after one item and just continue indefinately,
320 * meaning that certain errors cannot be caught!
321 */
322
323 if (!self->result && !self->exception)
324 self->_asyncio_future_blocking = TRUE;
325
326 Py_INCREF (self);
327 return (PyObject *)self;
328 }
329
330 static PyObject *
331 async_iternext (PyGIAsync *self)
332 {
333 /* Return ourselves if iteration needs to continue. */
334 if (!self->result && !self->exception) {
335 Py_INCREF (self);
336 return (PyObject *)self;
337 }
338
339 if (self->exception) {
340 PyErr_SetObject (PyExceptionInstance_Class (self->exception),
341 self->exception);
342 return NULL;
343 } else {
344 PyObject *e;
345
346 e = PyObject_CallFunctionObjArgs (PyExc_StopIteration, self->result,
347 NULL);
348 if (e == NULL) return NULL;
349
350 PyErr_SetObject (PyExc_StopIteration, e);
351 Py_DECREF (e);
352 return NULL;
353 }
354 }
355
356 static PyAsyncMethods async_async_methods = {
357 .am_await = (unaryfunc)async_await,
358 };
359
360 static void
361 async_finalize (PyGIAsync *self)
362 {
363 if (self->log_tb) {
364 PyObject *error_type, *error_value, *error_traceback;
365 PyObject *context = NULL;
366 PyObject *message = NULL;
367 PyObject *call_exception_handler = NULL;
368 PyObject *res = NULL;
369
370 assert (self->exception != NULL);
371 self->log_tb = 0;
372
373 /* Save the current exception, if any. */
374 PyErr_Fetch (&error_type, &error_value, &error_traceback);
375
376 context = PyDict_New ();
377 if (!context) goto finally;
378
379 message = PyUnicode_FromFormat ("%s exception was never retrieved",
380 Py_TYPE (self)->tp_name);
381 if (!message) goto finally;
382
383 if (PyDict_SetItemString (context, "message", message) < 0
384 || PyDict_SetItemString (context, "exception", self->exception) < 0
385 || PyDict_SetItemString (context, "future", (PyObject *)self) < 0)
386 goto finally;
387
388 call_exception_handler =
389 PyObject_GetAttrString (self->loop, "call_exception_handler");
390 if (!call_exception_handler) goto finally;
391
392 res = PyObject_CallFunction (call_exception_handler, "(O)", context);
393 if (res == NULL) PyErr_WriteUnraisable (context);
394
395 finally:
396 Py_CLEAR (res);
397 Py_CLEAR (context);
398 Py_CLEAR (message);
399 Py_CLEAR (call_exception_handler);
400
401 /* Restore the saved exception. */
402 PyErr_Restore (error_type, error_value, error_traceback);
403 }
404
405 Py_CLEAR (self->loop);
406 Py_CLEAR (self->finish_func);
407 if (self->cancellable) Py_CLEAR (self->cancellable);
408 if (self->result) Py_CLEAR (self->result);
409 if (self->exception) Py_CLEAR (self->exception);
410
411 /* Precation, cannot happen */
412 if (self->callbacks) g_array_free (self->callbacks, TRUE);
413 }
414
415 static void
416 async_dealloc (PyGIAsync *self)
417 {
418 #ifndef PYPY_VERSION
419 /* The finalizer might resurrect the object */
420 if (PyObject_CallFinalizerFromDealloc ((PyObject *)self) < 0) return;
421 #endif
422
423 Py_TYPE (self)->tp_free ((PyObject *)self);
424 }
425
426 void
427 pygi_async_finish_cb (GObject *source_object, gpointer res, PyGIAsync *self)
428 {
429 PyGILState_STATE py_state;
430 PyObject *source_pyobj, *res_pyobj;
431 PyObject *args[2];
432 size_t nargs;
433 PyObject *ret;
434 guint i;
435
436 /* Lock the GIL as we are coming into this code without the lock and we
437 may be executing python code */
438 py_state = PyGILState_Ensure ();
439
440 /* We might still be called at shutdown time. */
441 if (!Py_IsInitialized ()) {
442 PyGILState_Release (py_state);
443 return;
444 }
445
446 res_pyobj = pygobject_new (res);
447 if (source_object) {
448 source_pyobj = pygobject_new (source_object);
449 args[0] = source_pyobj;
450 args[1] = res_pyobj;
451 nargs = 2;
452 } else {
453 source_pyobj = NULL;
454 args[0] = res_pyobj;
455 nargs = 1;
456 }
457 /* We are calling pygi_callable_info_invoke directly here to avoid
458 * the constructor type checks in _function_info_vectorcall.
459 *
460 * Note that the first argument does not match what is expected
461 * when invoking a constructor function (it expects a class), but
462 * things work out because the argument is discarded. We should
463 * instead check the signature of finish_func to see whether it
464 * expects source_object. */
465 ret = pygi_callable_info_invoke (self->finish_func, args, nargs, NULL);
466 Py_XDECREF (res_pyobj);
467 Py_XDECREF (source_pyobj);
468
469 if (PyErr_Occurred ()) {
470 PyObject *exc = NULL, *value = NULL, *traceback = NULL;
471
472 /* NOTE: cPython >=3.12 has PyErr_{Get,Set}RaisedException */
473 PyErr_Fetch (&exc, &value, &traceback);
474 PyErr_NormalizeException (&exc, &value, &traceback);
475
476 self->exception = value;
477 self->log_tb = TRUE;
478
479 Py_XDECREF (exc);
480 Py_XDECREF (traceback);
481 Py_XDECREF (ret);
482 } else {
483 self->result = ret;
484 }
485
486 for (i = 0; self->callbacks && i < self->callbacks->len; i++) {
487 PyGIAsyncCallback *cb =
488 &g_array_index (self->callbacks, PyGIAsyncCallback, i);
489 /* We stop calling anything after the first exception, but still clear
490 * the internal state as if we did.
491 * This matches the pure python implementation of Future.
492 */
493 if (!PyErr_Occurred ()) {
494 ret = call_soon (self, cb);
495 if (!ret)
496 PyErr_PrintEx (FALSE);
497 else
498 Py_DECREF (ret);
499 }
500
501 Py_DECREF (cb->func);
502 Py_DECREF (cb->context);
503 }
504 if (self->callbacks) g_array_free (self->callbacks, TRUE);
505 self->callbacks = NULL;
506
507 Py_DECREF (self);
508 PyGILState_Release (py_state);
509 }
510
511 /**
512 * pygi_async_new:
513 * @finish_func: A #GIFunctionInfo to wrap that is used to finish.
514 * @cancellable: A #PyObject containging a #GCancellable, or None
515 *
516 * Return a new async instance.
517 *
518 * Returns: An instance of gi.Async or %NULL on error.
519 */
520 PyObject *
521 pygi_async_new (PyObject *finish_func, PyObject *cancellable)
522 {
523 PyObject *res;
524 PyObject *args;
525
526 res = PyGIAsync_Type.tp_alloc (&PyGIAsync_Type, 0);
527
528 if (res) {
529 if (cancellable && !Py_IsNone (cancellable))
530 args = Py_BuildValue ("(OO)", finish_func, cancellable);
531 else
532 args = Py_BuildValue ("(O)", finish_func);
533
534 if (PyGIAsync_Type.tp_init (res, args, NULL) < 0) {
535 Py_DECREF (args);
536 Py_DECREF (res);
537
538 /* Ignore exception from object initializer */
539 PyErr_Clear ();
540
541 return NULL;
542 }
543
544 Py_DECREF (args);
545 }
546
547 return res;
548 }
549
550 static struct PyMemberDef async_members[] = {
551 { "_asyncio_future_blocking", Py_T_BOOL,
552 offsetof (PyGIAsync, _asyncio_future_blocking), 0, NULL },
553 { "_loop", Py_T_OBJECT_EX, offsetof (PyGIAsync, loop), Py_READONLY, NULL },
554 { "_finish_func", Py_T_OBJECT_EX, offsetof (PyGIAsync, finish_func),
555 Py_READONLY, NULL },
556 { "cancellable", Py_T_OBJECT_EX, offsetof (PyGIAsync, cancellable),
557 Py_READONLY, "The Gio.Cancellable associated with the task." },
558 {
559 NULL,
560 },
561 };
562
563
564 /**
565 * pygi_async_register_types:
566 * @module: A Python modules to which Async gets added to.
567 *
568 * Initializes the Async class and adds it to the passed @module.
569 *
570 * Returns: -1 on error, 0 on success.
571 */
572 int
573 pygi_async_register_types (PyObject *module)
574 {
575 PyObject *asyncio = NULL;
576 #ifdef PYPY_VERSION
577 PyObject *contextvars = NULL;
578 #endif
579
580 #ifndef PYPY_VERSION
581 PyGIAsync_Type.tp_finalize = (destructor)async_finalize;
582 #else
583 PyGIAsync_Type.tp_del = (destructor)async_finalize;
584 #endif
585 PyGIAsync_Type.tp_dealloc = (destructor)async_dealloc;
586 PyGIAsync_Type.tp_repr = (reprfunc)async_repr;
587 PyGIAsync_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_FINALIZE;
588 PyGIAsync_Type.tp_methods = async_methods;
589 PyGIAsync_Type.tp_members = async_members;
590 PyGIAsync_Type.tp_as_async = &async_async_methods;
591 PyGIAsync_Type.tp_iter = PyObject_SelfIter;
592 PyGIAsync_Type.tp_iternext = (iternextfunc)&async_iternext;
593 PyGIAsync_Type.tp_init = (initproc)async_init;
594 PyGIAsync_Type.tp_new = PyType_GenericNew;
595
596 if (PyType_Ready (&PyGIAsync_Type) < 0) return -1;
597
598 Py_INCREF (&PyGIAsync_Type);
599 if (PyModule_AddObject (module, "Async", (PyObject *)&PyGIAsync_Type)
600 < 0) {
601 Py_DECREF (&PyGIAsync_Type);
602 return -1;
603 }
604
605 asyncio = PyImport_ImportModule ("asyncio");
606 if (asyncio == NULL) {
607 goto fail;
608 }
609 asyncio_InvalidStateError =
610 PyObject_GetAttrString (asyncio, "InvalidStateError");
611 if (asyncio_InvalidStateError == NULL) goto fail;
612
613 asyncio_get_running_loop =
614 PyObject_GetAttrString (asyncio, "_get_running_loop");
615 if (asyncio_get_running_loop == NULL) goto fail;
616
617 #if defined(PYPY_VERSION)
618 contextvars = PyImport_ImportModule ("contextvars");
619 if (contextvars == NULL) {
620 goto fail;
621 }
622
623 contextvars_copy_context =
624 PyObject_GetAttrString (contextvars, "copy_context");
625 Py_CLEAR (contextvars);
626 if (contextvars_copy_context == NULL) goto fail;
627 #endif
628
629 /* Only initialized when really needed! */
630 cancellable_info = NULL;
631
632 Py_CLEAR (asyncio);
633 return 0;
634
635 fail:
636 Py_CLEAR (asyncio);
637 return -1;
638 }