Debian Codegraph @

src/dex-channel.c

raw symbols SCIP
1 /*
2 * dex-channel.c
3 *
4 * Copyright 2022-2023 Christian Hergert <[email protected]>
5 *
6 * This program 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 program 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 License
17 * along with this library; if not, see <http://www.gnu.org/licenses/>.
18 *
19 * SPDX-License-Identifier: LGPL-2.1-or-later
20 */
21
22 #include "config.h"
23
24 #include <gio/gio.h>
25
26 #include "dex-error.h"
27 #include "dex-channel.h"
28 #include "dex-future-private.h"
29 #include "dex-object-private.h"
30 #include "dex-promise.h"
31
32 static GError channel_closed_error;
33 static GValue success_value;
34
35 typedef enum _DexChannelStateFlags
36 {
37 DEX_CHANNEL_STATE_CAN_SEND = 1 << 0,
38 DEX_CHANNEL_STATE_CAN_RECEIVE = 1 << 1,
39 } DexChannelStateFlags;
40
41 typedef struct _DexChannelReceiver
42 {
43 DexFuture parent_instance;
44 GList link;
45 } DexChannelReceiver;
46
47 typedef struct _DexChannelReceiverClass
48 {
49 DexFutureClass parent_class;
50 } DexChannelReceiverClass;
51
52 #define DEX_IS_CHANNEL_RECEIVER(obj) (G_TYPE_CHECK_INSTANCE_TYPE(obj, dex_channel_receiver_type))
53
54 GType dex_channel_receiver_get_type (void);
55
56 DEX_DEFINE_FINAL_TYPE (DexChannelReceiver, dex_channel_receiver, DEX_TYPE_FUTURE)
57
58 static inline guint
59 steal_uint (guint *value)
60 {
61 guint ret = *value;
62 *value = 0;
63 return ret;
64 }
65
66 static inline GQueue
67 steal_queue (GQueue *queue)
68 {
69 return (GQueue) {
70 .head = g_steal_pointer (&queue->head),
71 .tail = g_steal_pointer (&queue->tail),
72 .length = steal_uint (&queue->length),
73 };
74 }
75
76 static void
77 dex_channel_receiver_class_init (DexChannelReceiverClass *channel_receiver_class)
78 {
79 success_value = (GValue) {G_TYPE_BOOLEAN, {{.v_int = TRUE}}};
80 }
81
82 static void
83 dex_channel_receiver_init (DexChannelReceiver *channel_receiver)
84 {
85 channel_receiver->link.data = channel_receiver;
86 }
87
88 static inline void
89 dex_channel_receiver_complete (DexChannelReceiver *channel_receiver,
90 gboolean success)
91 {
92 dex_future_complete ((DexFuture *)channel_receiver,
93 success ? &success_value : NULL,
94 success ? NULL : g_error_copy (&channel_closed_error));
95 }
96
97 static inline DexChannelReceiver *
98 dex_channel_receiver_new (void)
99 {
100 return (DexChannelReceiver *)dex_object_create_instance (dex_channel_receiver_type);
101 }
102
103 struct _DexChannel
104 {
105 DexObject parent_instance;
106
107 /* Queue of senders waiting to insert an item in queue once the
108 * capacity threshold has reduced.
109 */
110 GQueue sendq;
111
112 /* Queue of receivers waiting for an item to be inserted into the
113 * queue so they can have it.
114 */
115 GQueue recvq;
116
117 /* The actual queue of items in the channel that have been sent and
118 * not yet picked up by a receiver.
119 */
120 GQueue queue;
121
122 /* The max capacity of @queue. Both the @sendq and @recvq can be
123 * greater than this as those represent callers and their futures.
124 */
125 guint capacity;
126
127 /* Flags indicating what sides of the channel are open/closed */
128 DexChannelStateFlags flags : 2;
129 };
130
131 typedef struct _DexChannelClass
132 {
133 DexObjectClass parent_class;
134 } DexChannelClass;
135
136 typedef struct _DexChannelItem
137 {
138 /* Used to insert the item into queues */
139 GList link;
140
141 /* The future which is provided to the caller of dex_channel_send(). */
142 DexPromise *send;
143
144 /* The future which was sent with dex_channel_send(). */
145 DexFuture *future;
146 } DexChannelItem;
147
148 typedef struct _DexChannelSendResolve
149 {
150 DexPromise *promise;
151 guint qlen;
152 } DexChannelSendResolve;
153
154 DEX_DEFINE_FINAL_TYPE (DexChannel, dex_channel, DEX_TYPE_OBJECT)
155
156 #undef DEX_TYPE_CHANNEL
157 #define DEX_TYPE_CHANNEL dex_channel_type
158
159 static void dex_channel_unset_state_flags (DexChannel *channel,
160 DexChannelStateFlags flags);
161
162 static DexChannelItem *
163 dex_channel_item_new (DexFuture *future)
164 {
165 DexChannelItem *item;
166
167 g_assert (DEX_IS_FUTURE (future));
168
169 item = g_new0 (DexChannelItem, 1);
170 item->link.data = item;
171 item->future = future;
172 item->send = dex_promise_new ();
173
174 return item;
175 }
176
177 static void
178 dex_channel_item_free (DexChannelItem *item)
179 {
180 g_assert (item != NULL);
181 g_assert (!item->future || DEX_IS_FUTURE (item->future));
182 g_assert (!item->send || DEX_IS_PROMISE (item->send));
183 g_assert (item->link.data == item);
184 g_assert (item->link.prev == NULL);
185 g_assert (item->link.next == NULL);
186
187 dex_clear (&item->future);
188 dex_clear (&item->send);
189 g_free (item);
190 }
191
192 static void
193 dex_channel_finalize (DexObject *object)
194 {
195 DexChannel *channel = DEX_CHANNEL (object);
196
197 dex_channel_unset_state_flags (channel,
198 (DEX_CHANNEL_STATE_CAN_SEND |
199 DEX_CHANNEL_STATE_CAN_RECEIVE));
200
201 g_assert (channel->queue.length == 0);
202 g_assert (channel->sendq.length == 0);
203 g_assert (channel->recvq.length == 0);
204 g_assert (channel->flags == 0);
205
206 DEX_OBJECT_CLASS (dex_channel_parent_class)->finalize (object);
207 }
208
209 static void
210 dex_channel_class_init (DexChannelClass *channel_class)
211 {
212 DexObjectClass *object_class = DEX_OBJECT_CLASS (channel_class);
213
214 object_class->finalize = dex_channel_finalize;
215
216 g_type_ensure (dex_channel_receiver_get_type ());
217
218 channel_closed_error = (GError) {
219 .domain = DEX_ERROR,
220 .code = DEX_ERROR_CHANNEL_CLOSED,
221 .message = (gpointer)"Channel closed",
222 };
223 }
224
225 static void
226 dex_channel_init (DexChannel *channel)
227 {
228 channel->capacity = G_MAXUINT;
229 }
230
231 /**
232 * dex_channel_new:
233 * @capacity: the channel queue depth or 0 for unlimited
234 *
235 * Creates a new [[email protected]].
236 *
237 * If capacity is non-zero, it can be used to limit the size of the channel
238 * so that functions can asynchronously stall until items have been removed
239 * from the channel. This is useful in buffering situations so that the
240 * producer does not outpace the consumer.
241 *
242 * Returns: a new [[email protected]]
243 */
244 DexChannel *
245 dex_channel_new (guint capacity)
246 {
247 DexChannel *channel;
248
249 if (capacity == 0)
250 capacity = G_MAXUINT;
251
252 channel = (DexChannel *)dex_object_create_instance (DEX_TYPE_CHANNEL);
253 channel->capacity = capacity;
254 channel->flags = DEX_CHANNEL_STATE_CAN_SEND | DEX_CHANNEL_STATE_CAN_RECEIVE;
255
256 return channel;
257 }
258
259 static inline gboolean
260 has_capacity_locked (DexChannel *channel)
261 {
262 return channel->sendq.length == 0 && channel->queue.length < channel->capacity;
263 }
264
265 static void
266 dex_channel_one_receive_and_unlock (DexChannel *channel)
267 {
268 DexChannelItem *item = NULL;
269 DexChannelReceiver *recv = NULL;
270 DexPromise *to_resolve = NULL;
271 guint qlen = 0;
272
273 g_assert (DEX_IS_CHANNEL (channel));
274
275 /* This function removes a single item from the head of the queue and
276 * pairs it with a future that was delivered to a caller of
277 * dex_channel_receive(). The #DexPromise they were returned is
278 * completed using the future that was provided to dex_channel_send()
279 * (which itself still may not be ready, but we must preserve ordering).
280 */
281
282 if (channel->queue.length > 0 && channel->recvq.length > 0)
283 {
284 recv = g_queue_pop_head_link (&channel->recvq)->data;
285 item = g_queue_pop_head_link (&channel->queue)->data;
286
287 g_assert (DEX_IS_CHANNEL_RECEIVER (recv));
288 g_assert (item != NULL);
289
290 /* Try to advance a @sendq item into @queue */
291 if (channel->sendq.length > 0 && channel->queue.length < channel->capacity)
292 {
293 DexChannelItem *sendq_item = g_queue_peek_head (&channel->sendq);
294 g_queue_unlink (&channel->sendq, &sendq_item->link);
295 g_queue_push_tail_link (&channel->queue, &sendq_item->link);
296 qlen = channel->queue.length;
297 to_resolve = dex_ref (sendq_item->send);
298 }
299 }
300
301 dex_object_unlock (channel);
302
303 g_assert (item == NULL || recv != NULL);
304
305 if (item != NULL)
306 {
307 dex_future_chain (item->future, DEX_FUTURE (recv));
308 dex_channel_item_free (item);
309 dex_unref (recv);
310 }
311
312 if (to_resolve != NULL)
313 {
314 dex_promise_resolve_uint (to_resolve, qlen);
315 dex_unref (to_resolve);
316 }
317 }
318
319 /**
320 * dex_channel_send:
321 * @channel: a [[email protected]]
322 * @future: (transfer full): a [[email protected]]
323 *
324 * Queues @future into the channel.
325 *
326 * The other end of the channel can receive the future (or a future that will
327 * eventually resolve to @future) using [[email protected]].
328 *
329 * This function returns a [[email protected]] that will resolve when the channels
330 * capacity is low enough to queue more items.
331 *
332 * If the send side of the channel is closed, the returned [[email protected]] will be
333 * rejected with %DEX_ERROR_CHANNEL_CLOSED.
334 *
335 * Returns: (transfer full): a [[email protected]]
336 */
337 DexFuture *
338 dex_channel_send (DexChannel *channel,
339 DexFuture *future)
340 {
341 const DexChannelStateFlags required = DEX_CHANNEL_STATE_CAN_SEND|DEX_CHANNEL_STATE_CAN_RECEIVE;
342 DexChannelItem *item;
343 DexFuture *ret;
344
345 g_return_val_if_fail (DEX_IS_CHANNEL (channel), NULL);
346 g_return_val_if_fail (DEX_IS_FUTURE (future), NULL);
347
348 item = dex_channel_item_new (g_steal_pointer (&future));
349
350 dex_object_lock (channel);
351
352 if ((channel->flags & required) != required)
353 {
354 dex_object_unlock (channel);
355 dex_channel_item_free (item);
356 return DEX_FUTURE (dex_future_new_reject (DEX_ERROR,
357 DEX_ERROR_CHANNEL_CLOSED,
358 "Channel is closed"));
359 }
360
361 ret = dex_ref (item->send);
362
363 /* Try to place future directly into @queue. Otherwise, place it in @sendq
364 * and we'll process it when more items have been received.
365 */
366 if (!has_capacity_locked (channel))
367 {
368 g_queue_push_tail_link (&channel->sendq, &item->link);
369 dex_object_unlock (channel);
370 }
371 else
372 {
373 g_queue_push_tail_link (&channel->queue, &item->link);
374 dex_promise_resolve_uint (item->send, channel->queue.length);
375 dex_channel_one_receive_and_unlock (channel);
376 }
377
378 return ret;
379 }
380
381 /**
382 * dex_channel_receive:
383 * @channel: a [[email protected]]
384 *
385 * Receives the next item from the channel.
386 *
387 * The resulting future will resolve or reject when an item is available
388 * to the channel or when send side has closed (in that order).
389 *
390 * Returns: (transfer full): a [[email protected]]
391 */
392 DexFuture *
393 dex_channel_receive (DexChannel *channel)
394 {
395 DexChannelReceiver *recv;
396
397 g_return_val_if_fail (DEX_IS_CHANNEL (channel), NULL);
398
399 recv = dex_channel_receiver_new ();
400
401 dex_object_lock (channel);
402
403 if ((channel->flags & DEX_CHANNEL_STATE_CAN_RECEIVE) == 0)
404 goto reject_receive;
405
406 /* If no more items can be sent, and there are no items immediately
407 * to fulfill this request, then we have to reject as it can never
408 * be fulfilled.
409 */
410 if ((channel->flags & DEX_CHANNEL_STATE_CAN_SEND) == 0)
411 {
412 if (channel->queue.length + channel->sendq.length <= channel->recvq.length)
413 goto reject_receive;
414 }
415
416 /* Enqueue this receiver and then flush a queued operation if possible */
417 dex_ref (recv);
418 g_queue_push_tail_link (&channel->recvq, &recv->link);
419 dex_channel_one_receive_and_unlock (channel);
420
421 return DEX_FUTURE (recv);
422
423 reject_receive:
424 dex_object_unlock (channel);
425 dex_channel_receiver_complete (recv, FALSE);
426
427 return DEX_FUTURE (recv);
428 }
429
430 /**
431 * dex_channel_receive_all:
432 * @channel: a [[email protected]]
433 *
434 * Will attempt to receive all items in the channel as a [[email protected]].
435 *
436 * If the receive side of the channel is closed, then the future will
437 * reject with an error.
438 *
439 * If there are items in the queue, then they will be returned as part
440 * of a [[email protected]] containing each of the futures.
441 *
442 * Otherwise, a [[email protected]] will be returned which will resolve or
443 * reject when the next item is available in the channel (or the send
444 * or receive sides are closed).
445 *
446 * Returns: (transfer full): a [[email protected]]
447 */
448 DexFuture *
449 dex_channel_receive_all (DexChannel *channel)
450 {
451 GPtrArray *ret = NULL;
452 GArray *send_resolves = NULL;
453 GQueue stolen = G_QUEUE_INIT;
454 DexFuture *future = NULL;
455
456 g_return_val_if_fail (DEX_IS_CHANNEL (channel), NULL);
457
458 ret = g_ptr_array_new_with_free_func (dex_unref);
459
460 dex_object_lock (channel);
461
462 if ((channel->flags & DEX_CHANNEL_STATE_CAN_RECEIVE) == 0)
463 goto reject_receive;
464
465 if (channel->queue.length == 0)
466 goto wait_for_result;
467
468 stolen = steal_queue (&channel->queue);
469
470 for (const GList *iter = stolen.head; iter; iter = iter->next)
471 {
472 DexChannelItem *item = iter->data;
473 g_ptr_array_add (ret, g_steal_pointer (&item->future));
474 }
475
476 while (channel->sendq.length > 0 && channel->queue.length < channel->capacity)
477 {
478 DexChannelItem *sendq_item = g_queue_peek_head (&channel->sendq);
479
480 g_queue_unlink (&channel->sendq, &sendq_item->link);
481 g_queue_push_tail_link (&channel->queue, &sendq_item->link);
482
483 if (send_resolves == NULL)
484 send_resolves = g_array_new (FALSE, FALSE, sizeof (DexChannelSendResolve));
485
486 g_array_append_val (send_resolves,
487 ((DexChannelSendResolve) {
488 dex_ref (sendq_item->send),
489 channel->queue.length,
490 }));
491 }
492
493 dex_object_unlock (channel);
494
495 while (stolen.length > 0)
496 dex_channel_item_free (g_queue_pop_head_link (&stolen)->data);
497
498 if (send_resolves != NULL)
499 {
500 for (guint i = 0; i < send_resolves->len; i++)
501 {
502 DexChannelSendResolve *resolve = &g_array_index (send_resolves,
503 DexChannelSendResolve,
504 i);
505
506 dex_promise_resolve_uint (resolve->promise, resolve->qlen);
507 dex_unref (resolve->promise);
508 }
509 }
510
511 future = dex_future_allv ((DexFuture **)ret->pdata, ret->len);
512 goto cleanup;
513
514 reject_receive:
515 dex_object_unlock (channel);
516 future = dex_future_new_for_error (g_error_copy (&channel_closed_error));
517 goto cleanup;
518
519 wait_for_result:
520 dex_object_unlock (channel);
521 future = dex_future_all (dex_channel_receive (channel), NULL);
522 goto cleanup;
523
524 cleanup:
525 g_clear_pointer (&send_resolves, g_array_unref);
526 g_clear_pointer (&ret, g_ptr_array_unref);
527 return future;
528 }
529
530 static void
531 dex_channel_unset_state_flags (DexChannel *channel,
532 DexChannelStateFlags flags)
533 {
534 GQueue queue = G_QUEUE_INIT;
535 GQueue sendq = G_QUEUE_INIT;
536 GQueue recvq = G_QUEUE_INIT;
537 GQueue trunc = G_QUEUE_INIT;
538
539 g_assert (DEX_IS_CHANNEL (channel));
540
541 dex_object_lock (channel);
542
543 /* If we need to close the send-side, do so now */
544 if (flags & DEX_CHANNEL_STATE_CAN_SEND)
545 {
546 guint pending = channel->sendq.length + channel->queue.length;
547
548 channel->flags &= ~DEX_CHANNEL_STATE_CAN_SEND;
549
550 while (channel->recvq.length > pending)
551 g_queue_push_head_link (&trunc, g_queue_pop_tail_link (&channel->recvq));
552 }
553
554 /* If we need to close the receive-side, do so now and steal
555 * all of the items and promises that need to be rejected.
556 */
557 if (flags & DEX_CHANNEL_STATE_CAN_RECEIVE)
558 {
559 channel->flags &= ~DEX_CHANNEL_STATE_CAN_RECEIVE;
560
561 queue = steal_queue (&channel->queue);
562 sendq = steal_queue (&channel->sendq);
563 recvq = steal_queue (&channel->recvq);
564 }
565
566 dex_object_unlock (channel);
567
568 while (recvq.length > 0)
569 {
570 DexChannelReceiver *recv = g_queue_pop_head_link (&recvq)->data;
571 dex_channel_receiver_complete (recv, FALSE);
572 dex_unref (recv);
573 }
574
575 while (trunc.length > 0)
576 {
577 DexChannelReceiver *recv = g_queue_pop_head_link (&trunc)->data;
578 dex_channel_receiver_complete (recv, FALSE);
579 dex_unref (recv);
580 }
581
582 while (queue.length > 0)
583 {
584 DexChannelItem *item = g_queue_pop_head_link (&queue)->data;
585 dex_channel_item_free (item);
586 }
587
588 while (sendq.length > 0)
589 {
590 DexChannelItem *item = g_queue_pop_head_link (&sendq)->data;
591 dex_promise_reject (item->send, g_error_copy (&channel_closed_error));
592 dex_channel_item_free (item);
593 }
594 }
595
596 void
597 dex_channel_close_send (DexChannel *channel)
598 {
599 g_return_if_fail (DEX_IS_CHANNEL (channel));
600
601 dex_channel_unset_state_flags (channel, DEX_CHANNEL_STATE_CAN_SEND);
602 }
603
604 void
605 dex_channel_close_receive (DexChannel *channel)
606 {
607 g_return_if_fail (DEX_IS_CHANNEL (channel));
608
609 dex_channel_unset_state_flags (channel, DEX_CHANNEL_STATE_CAN_RECEIVE);
610 }
611
612 gboolean
613 dex_channel_can_send (DexChannel *channel)
614 {
615 gboolean ret;
616
617 g_return_val_if_fail (DEX_IS_CHANNEL (channel), FALSE);
618
619 dex_object_lock (channel);
620 ret = (channel->flags & DEX_CHANNEL_STATE_CAN_SEND) != 0;
621 dex_object_unlock (channel);
622
623 return ret;
624 }
625
626 gboolean
627 dex_channel_can_receive (DexChannel *channel)
628 {
629 gboolean ret;
630
631 g_return_val_if_fail (DEX_IS_CHANNEL (channel), FALSE);
632
633 dex_object_lock (channel);
634 ret = (channel->flags & DEX_CHANNEL_STATE_CAN_RECEIVE) != 0;
635 dex_object_unlock (channel);
636
637 return ret;
638 }