Debian Codegraph @

src/dispatcher.c

raw symbols SCIP
1 // nanonext - dispatcher implementation -----------------------------------------
2
3 #define NANONEXT_PROTOCOLS
4 #include "nanonext.h"
5
6 // L'Ecuyer-CMRG RNG stream advancement ----------------------------------------
7 //
8 // Pure-C implementation of MRG32k3a stream jumping. Moduli and jump matrix
9 // constants below are from the RngStreams package by Pierre L'Ecuyer,
10 // University of Montreal (https://github.com/umontreal-simul/RngStreams),
11 // licensed under the Apache License, Version 2.0. The original copyright
12 // notice requests citation of:
13 //
14 // P. L'Ecuyer, "Good Parameter Sets for Combined Multiple Recursive Random
15 // Number Generators", Operations Research, 47, 1 (1999), 159-164.
16 // P. L'Ecuyer, R. Simard, E. J. Chen, and W. D. Kelton, "An Objected-
17 // Oriented Random-Number Package with Many Long Streams and Substreams",
18 // Operations Research, 50, 6 (2002), 1073-1075.
19 //
20
21 #define M1 4294967087ULL
22 #define M2 4294944443ULL
23
24 // Jump matrices A1^(2^127) mod m1 and A2^(2^127) mod m2
25 static const unsigned long long A1p127[3][3] = {
26 { 2427906178ULL, 3580155704ULL, 949770784ULL },
27 { 226153695ULL, 1230515664ULL, 3580155704ULL },
28 { 1988835001ULL, 986791581ULL, 1230515664ULL }
29 };
30 static const unsigned long long A2p127[3][3] = {
31 { 1464411153ULL, 277697599ULL, 1610723613ULL },
32 { 32183930ULL, 1464411153ULL, 1022607788ULL },
33 { 2824425944ULL, 32183930ULL, 2093834863ULL }
34 };
35
36 static void mat_vec_mod(const unsigned long long A[3][3],
37 const unsigned long long *v,
38 unsigned long long *out, unsigned long long m) {
39 for (int i = 0; i < 3; i++) {
40 unsigned long long s = 0;
41 for (int j = 0; j < 3; j++) {
42 s = (s + (A[i][j] * v[j]) % m) % m;
43 }
44 out[i] = s;
45 }
46 }
47
48 static void next_rng_stream_c(int *seed) {
49 unsigned long long v1[3] = { (unsigned int) seed[0], (unsigned int) seed[1], (unsigned int) seed[2] };
50 unsigned long long v2[3] = { (unsigned int) seed[3], (unsigned int) seed[4], (unsigned int) seed[5] };
51 unsigned long long out1[3], out2[3];
52 mat_vec_mod(A1p127, v1, out1, M1);
53 mat_vec_mod(A2p127, v2, out2, M2);
54 for (int i = 0; i < 3; i++) {
55 seed[i] = (int) out1[i];
56 seed[i + 3] = (int) out2[i];
57 }
58 }
59
60 // data structures -------------------------------------------------------------
61
62 #define DISPATCH_INITIAL_SIZE 16
63
64 typedef struct nano_dispatch_task_s {
65 nng_ctx ctx;
66 nng_msg *msg;
67 int msgid;
68 int is_sync;
69 struct nano_dispatch_task_s *next;
70 } nano_dispatch_task;
71
72 typedef struct nano_dispatch_daemon_s {
73 int pipe;
74 nng_ctx ctx;
75 int msgid;
76 int sync_gen;
77 } nano_dispatch_daemon;
78
79 typedef struct nano_dispatcher_s {
80 nng_socket *rep_sock;
81 nng_socket *poly_sock;
82 nano_cv *cv;
83 nano_monitor *monitor;
84 nano_dispatch_task *inq_head;
85 nano_dispatch_task *inq_tail;
86 nano_dispatch_daemon *daemons;
87 int inq_count;
88 int outq_capacity;
89 int outq_count;
90 int connections;
91 int count;
92 int executing;
93 nng_aio *host_aio;
94 nng_aio *daemon_aio;
95 nng_ctx host_ctx;
96 int host_recv_ready;
97 int daemon_recv_ready;
98 int rng_seed[6];
99 unsigned char *init_template;
100 size_t init_template_len;
101 size_t init_seed_offset;
102 unsigned char *conn_reset_buf;
103 size_t conn_reset_len;
104 int syncing;
105 int sync_generation;
106 int *pipe_events;
107 int pipe_events_size;
108 size_t limit_bytes;
109 size_t queued_bytes;
110 size_t peak_queued_bytes;
111 } nano_dispatcher;
112
113 // forward declarations --------------------------------------------------------
114
115 static void dispatch_shutdown(nano_dispatcher *d);
116 static void dispatch_handle_connect(nano_dispatcher *d, int pipe);
117 static void dispatch_handle_disconnect(nano_dispatcher *d, int pipe);
118 static void dispatch_dispatch_tasks(nano_dispatcher *d);
119 static int dispatch_cancel_inq(nano_dispatcher *d, int id);
120 static nano_dispatch_daemon *dispatch_find_idle_daemon(nano_dispatcher *d);
121
122 // daemon array operations -----------------------------------------------------
123
124 static nano_dispatch_daemon *dispatch_find_daemon(nano_dispatcher *d, int pipe) {
125
126 for (int i = 0; i < d->outq_count; i++)
127 if (d->daemons[i].pipe == pipe)
128 return &d->daemons[i];
129
130 return NULL;
131
132 }
133
134 static void dispatch_insert_daemon(nano_dispatcher *d, int pipe) {
135
136 if (d->outq_count >= d->outq_capacity) {
137 int new_cap = d->outq_capacity * 2;
138 nano_dispatch_daemon *new_arr = realloc(d->daemons, new_cap * sizeof(nano_dispatch_daemon));
139 if (new_arr == NULL) {
140 REprintf("dispatcher: allocation failed for pipe %d\n", pipe);
141 return;
142 }
143 d->daemons = new_arr;
144 d->outq_capacity = new_cap;
145 }
146
147 nano_dispatch_daemon *dd = &d->daemons[d->outq_count++];
148 dd->pipe = pipe;
149 dd->msgid = 0;
150 dd->sync_gen = d->sync_generation - 1;
151
152 }
153
154 // queue operations ------------------------------------------------------------
155
156 static void dispatch_enqueue(nano_dispatcher *d, nng_ctx ctx,
157 nng_msg *msg, int msgid, int is_sync) {
158
159 nano_dispatch_task *t = malloc(sizeof(nano_dispatch_task));
160 if (t == NULL) {
161 nng_ctx_close(ctx);
162 nng_msg_free(msg);
163 return;
164 }
165 t->ctx = ctx;
166 t->msg = msg;
167 t->msgid = msgid;
168 t->is_sync = is_sync;
169 t->next = NULL;
170
171 if (d->inq_tail)
172 d->inq_tail->next = t;
173 else
174 d->inq_head = t;
175 d->inq_tail = t;
176 d->inq_count++;
177 d->queued_bytes += nng_msg_len(msg);
178 if (d->queued_bytes > d->peak_queued_bytes)
179 d->peak_queued_bytes = d->queued_bytes;
180
181 }
182
183 static void dispatch_dequeue(nano_dispatcher *d) {
184
185 nano_dispatch_task *t = d->inq_head;
186 if (t) {
187 d->inq_head = t->next;
188 if (d->inq_head == NULL)
189 d->inq_tail = NULL;
190 d->inq_count--;
191 free(t);
192 }
193
194 }
195
196 static void dispatch_free_task(nano_dispatch_task *t) {
197
198 nng_ctx_close(t->ctx);
199 if (t->msg)
200 nng_msg_free(t->msg);
201 free(t);
202
203 }
204
205 // send operations -------------------------------------------------------------
206
207 static int dispatch_send_to_daemon(nano_dispatcher *d, int pipe,
208 unsigned char *data, size_t len) {
209
210 nng_msg *msg;
211 if (nng_msg_alloc(&msg, len))
212 return -1;
213 if (len)
214 memcpy(nng_msg_body(msg), data, len);
215 nng_msg_set_pipe(msg, (nng_pipe) {.id = (uint32_t) pipe});
216 int xc = nng_sendmsg(*d->poly_sock, msg, 0);
217 if (xc != 0)
218 nng_msg_free(msg);
219 return xc;
220
221 }
222
223 static int dispatch_send_msg_to_daemon(nano_dispatcher *d, int pipe, nng_msg *msg) {
224
225 nng_msg_set_pipe(msg, (nng_pipe) {.id = (uint32_t) pipe});
226 return nng_sendmsg(*d->poly_sock, msg, 0);
227
228 }
229
230 static int dispatch_send_reply(nng_ctx ctx, unsigned char *data, size_t len) {
231
232 nng_msg *msg;
233 if (nng_msg_alloc(&msg, len))
234 return -1;
235 memcpy(nng_msg_body(msg), data, len);
236 int xc = nng_ctx_sendmsg(ctx, msg, 0);
237 if (xc != 0)
238 nng_msg_free(msg);
239 return xc;
240
241 }
242
243 static int dispatch_send_msg_reply(nng_ctx ctx, nng_msg *msg) {
244
245 return nng_ctx_sendmsg(ctx, msg, 0);
246
247 }
248
249 // AIO Callbacks ---------------------------------------------------------------
250
251 static void host_recv_cb(void *arg) {
252
253 nano_dispatcher *d = (nano_dispatcher *) arg;
254 nng_mtx *mtx = d->cv->mtx;
255
256 nng_mtx_lock(mtx);
257 d->host_recv_ready = 1;
258 d->cv->condition++;
259 nng_cv_wake(d->cv->cv);
260 nng_mtx_unlock(mtx);
261
262 }
263
264 static void daemon_recv_cb(void *arg) {
265
266 nano_dispatcher *d = (nano_dispatcher *) arg;
267 nng_mtx *mtx = d->cv->mtx;
268
269 nng_mtx_lock(mtx);
270 d->daemon_recv_ready = 1;
271 d->cv->condition++;
272 nng_cv_wake(d->cv->cv);
273 nng_mtx_unlock(mtx);
274
275 }
276
277 // message utilities -----------------------------------------------------------
278
279 static inline void dispatch_read_msg_info(unsigned char *buf, size_t len,
280 int *msgid, int *is_sync) {
281
282 if (len > 12 && buf[0] == 0x7) {
283 memcpy(msgid, buf + 4, sizeof(int));
284 *is_sync = buf[3] == 0x1;
285 } else {
286 *msgid = 0;
287 *is_sync = 0;
288 }
289
290 }
291
292 // monitor processing ----------------------------------------------------------
293
294 static int dispatch_ensure_pipe_events(nano_dispatcher *d, int needed) {
295
296 if (needed <= d->pipe_events_size)
297 return 1;
298
299 int new_size = d->pipe_events_size ? d->pipe_events_size : DISPATCH_INITIAL_SIZE;
300 while (new_size < needed)
301 new_size *= 2;
302
303 int *new_buf = realloc(d->pipe_events, new_size * sizeof(int));
304 if (new_buf == NULL)
305 return 0;
306
307 d->pipe_events = new_buf;
308 d->pipe_events_size = new_size;
309 return 1;
310
311 }
312
313 static void dispatch_process_monitor(nano_dispatcher *d, int count) {
314
315 for (int i = 0; i < count; i++) {
316 if (d->pipe_events[i] > 0)
317 dispatch_handle_connect(d, d->pipe_events[i]);
318 else
319 dispatch_handle_disconnect(d, -d->pipe_events[i]);
320 }
321
322 }
323
324 // init template ---------------------------------------------------------------
325
326 static int dispatch_prepare_init_template(nano_dispatcher *d, SEXP stream,
327 SEXP serial) {
328
329 int *sdata = INTEGER(stream);
330 for (int i = 0; i < 6; i++)
331 d->rng_seed[i] = sdata[i + 1];
332
333 int saved[6];
334 memcpy(saved, sdata + 1, 6 * sizeof(int));
335
336 const int sentinel_val = 0x7F7F7F7F;
337 for (int i = 0; i < 6; i++)
338 sdata[i + 1] = sentinel_val;
339
340 SEXP init_data;
341 PROTECT(init_data = Rf_allocVector(VECSXP, 2));
342 SET_VECTOR_ELT(init_data, 0, stream);
343 SET_VECTOR_ELT(init_data, 1, serial);
344
345 nano_buf buf;
346 nano_serialize(&buf, init_data, serial, 0);
347 UNPROTECT(1);
348
349 memcpy(sdata + 1, saved, 6 * sizeof(int));
350
351 unsigned char sentinel[24];
352 memset(sentinel, 0x7F, 24);
353 size_t offset = 0;
354 int found = 0;
355
356 for (size_t i = 0; i + 24 <= buf.cur; i++) {
357 if (memcmp(buf.buf + i, sentinel, 24) == 0) {
358 offset = i;
359 found = 1;
360 break;
361 }
362 }
363
364 if (!found) {
365 NANO_FREE(buf);
366 return -1;
367 }
368
369 d->init_template = malloc(buf.cur);
370 if (d->init_template == NULL) {
371 NANO_FREE(buf);
372 return -1;
373 }
374 memcpy(d->init_template, buf.buf, buf.cur);
375 d->init_template_len = buf.cur;
376 d->init_seed_offset = offset;
377 NANO_FREE(buf);
378
379 return 0;
380
381 }
382
383 // event handlers --------------------------------------------------------------
384
385 static void dispatch_handle_connect(nano_dispatcher *d, int pipe) {
386
387 next_rng_stream_c(d->rng_seed);
388
389 nng_msg *msg;
390 if (nng_msg_alloc(&msg, d->init_template_len))
391 return;
392 unsigned char *buf = nng_msg_body(msg);
393 memcpy(buf, d->init_template, d->init_template_len);
394
395 memcpy(buf + d->init_seed_offset, d->rng_seed, sizeof(d->rng_seed));
396
397 if (dispatch_send_msg_to_daemon(d, pipe, msg) != 0)
398 nng_msg_free(msg);
399 else {
400 nng_mtx_lock(d->cv->mtx);
401 dispatch_insert_daemon(d, pipe);
402 d->connections++;
403 nng_mtx_unlock(d->cv->mtx);
404 }
405
406 }
407
408 static void dispatch_handle_disconnect(nano_dispatcher *d, int pipe) {
409
410 nng_mtx_lock(d->cv->mtx);
411 nano_dispatch_daemon *dd = dispatch_find_daemon(d, pipe);
412 if (dd == NULL) {
413 nng_mtx_unlock(d->cv->mtx);
414 return;
415 }
416
417 int busy = dd->msgid != 0;
418 nng_ctx ctx;
419 if (busy) {
420 d->executing--;
421 ctx = dd->ctx;
422 }
423
424 *dd = d->daemons[--d->outq_count];
425 nng_mtx_unlock(d->cv->mtx);
426
427 if (busy) {
428 dispatch_send_reply(ctx, d->conn_reset_buf, d->conn_reset_len);
429 nng_ctx_close(ctx);
430 }
431
432 }
433
434 static void dispatch_handle_host_recv(nano_dispatcher *d) {
435
436 nng_msg *msg = nng_aio_get_msg(d->host_aio);
437 unsigned char *buf = nng_msg_body(msg);
438 size_t len = nng_msg_len(msg);
439
440 if (buf[0] == 0) {
441 int id = 0;
442 if (len >= 8)
443 memcpy(&id, buf + 4, sizeof(int));
444
445 nng_mtx_lock(d->cv->mtx);
446 if (id == 0) {
447 int completed = d->count - d->inq_count - d->executing;
448 int result[5] = {d->outq_count, d->connections, d->inq_count, d->executing, completed};
449 nng_mtx_unlock(d->cv->mtx);
450 dispatch_send_reply(d->host_ctx, (unsigned char *) result, sizeof(result));
451 } else {
452 int found = 0;
453 int cancel_pipe = 0;
454 for (int i = 0; i < d->outq_count; i++) {
455 if (d->daemons[i].msgid == id) {
456 cancel_pipe = d->daemons[i].pipe;
457 found = 1;
458 break;
459 }
460 }
461 if (!found)
462 found = dispatch_cancel_inq(d, id);
463 nng_mtx_unlock(d->cv->mtx);
464 if (cancel_pipe)
465 dispatch_send_to_daemon(d, cancel_pipe, NULL, 0);
466 dispatch_send_reply(d->host_ctx, (unsigned char *) &found, sizeof(int));
467 }
468 nng_ctx_close(d->host_ctx);
469 } else {
470 int msgid, is_sync;
471 dispatch_read_msg_info(buf, len, &msgid, &is_sync);
472
473 int send_pipe = 0;
474 nng_mtx_lock(d->cv->mtx);
475 d->count++;
476
477 nano_dispatch_daemon *dd = dispatch_find_idle_daemon(d);
478 if (dd != NULL) {
479 send_pipe = dd->pipe;
480 dd->ctx = d->host_ctx;
481 dd->msgid = msgid;
482 d->executing++;
483 if (is_sync) {
484 dd->sync_gen = d->sync_generation;
485 d->syncing = 1;
486 } else if (d->syncing) {
487 d->syncing = 0;
488 d->sync_generation++;
489 }
490 } else {
491 dispatch_enqueue(d, d->host_ctx, msg, msgid, is_sync);
492 msg = NULL;
493 }
494 nng_mtx_unlock(d->cv->mtx);
495
496 if (send_pipe) {
497 if (dispatch_send_msg_to_daemon(d, send_pipe, msg) == 0)
498 msg = NULL;
499 }
500 }
501
502 if (msg)
503 nng_msg_free(msg);
504
505 if (nng_ctx_open(&d->host_ctx, *d->rep_sock) == 0) {
506 nng_ctx_recv(d->host_ctx, d->host_aio);
507 } else {
508 nng_mtx_lock(d->cv->mtx);
509 d->cv->flag = -1;
510 nng_mtx_unlock(d->cv->mtx);
511 }
512
513 }
514
515 static void dispatch_handle_daemon_recv(nano_dispatcher *d) {
516
517 nng_msg *msg = nng_aio_get_msg(d->daemon_aio);
518 nng_pipe pipe = nng_msg_get_pipe(msg);
519 int pipe_id = (int) pipe.id;
520 int dummy, is_marker;
521 dispatch_read_msg_info(nng_msg_body(msg), nng_msg_len(msg), &dummy, &is_marker);
522
523 nng_mtx_lock(d->cv->mtx);
524 nano_dispatch_daemon *dd = dispatch_find_daemon(d, pipe_id);
525 if (dd != NULL && dd->msgid != 0) {
526 d->executing--;
527 nng_ctx ctx = dd->ctx;
528
529 if (is_marker) {
530 *dd = d->daemons[--d->outq_count];
531 } else {
532 dd->msgid = 0;
533 }
534 nng_mtx_unlock(d->cv->mtx);
535
536 if (dispatch_send_msg_reply(ctx, msg) == 0)
537 msg = NULL;
538 nng_ctx_close(ctx);
539
540 if (is_marker)
541 dispatch_send_to_daemon(d, pipe_id, NULL, 0);
542 } else {
543 nng_mtx_unlock(d->cv->mtx);
544 }
545
546 if (msg)
547 nng_msg_free(msg);
548
549 nng_recv_aio(*d->poly_sock, d->daemon_aio);
550
551 }
552
553 // helper functions ------------------------------------------------------------
554
555 static int dispatch_cancel_inq(nano_dispatcher *d, int id) {
556
557 nano_dispatch_task **pp = &d->inq_head;
558 nano_dispatch_task *prev = NULL;
559 while (*pp) {
560 if ((*pp)->msgid == id) {
561 nano_dispatch_task *t = *pp;
562 *pp = t->next;
563 if (t == d->inq_tail)
564 d->inq_tail = prev;
565 d->queued_bytes -= nng_msg_len(t->msg);
566 dispatch_free_task(t);
567 d->inq_count--;
568 if (d->limit_bytes > 0)
569 nng_cv_wake(d->cv->cv);
570 return 1;
571 }
572 prev = *pp;
573 pp = &(*pp)->next;
574 }
575 return 0;
576
577 }
578
579 static nano_dispatch_daemon *dispatch_find_idle_daemon(nano_dispatcher *d) {
580
581 for (int i = 0; i < d->outq_count; i++)
582 if (d->daemons[i].msgid == 0 && !(d->syncing && d->daemons[i].sync_gen == d->sync_generation))
583 return &d->daemons[i];
584
585 return NULL;
586
587 }
588
589 // task dispatcher -------------------------------------------------------------
590
591 static void dispatch_dispatch_tasks(nano_dispatcher *d) {
592
593 struct { int pipe; nng_msg *msg; } batch[32];
594 int nsends;
595
596 do {
597 nsends = 0;
598 nng_mtx_lock(d->cv->mtx);
599
600 while (d->inq_head && nsends < 32) {
601 nano_dispatch_task *t = d->inq_head;
602
603 nano_dispatch_daemon *dd = dispatch_find_idle_daemon(d);
604 if (dd == NULL)
605 break;
606
607 size_t len = nng_msg_len(t->msg);
608 batch[nsends].pipe = dd->pipe;
609 batch[nsends].msg = t->msg;
610 nsends++;
611
612 t->msg = NULL;
613 d->queued_bytes -= len;
614 dd->ctx = t->ctx;
615 dd->msgid = t->msgid;
616 d->executing++;
617
618 if (t->is_sync) {
619 dd->sync_gen = d->sync_generation;
620 d->syncing = 1;
621 } else if (d->syncing) {
622 d->syncing = 0;
623 d->sync_generation++;
624 }
625
626 dispatch_dequeue(d);
627 }
628
629 if (d->limit_bytes > 0 && nsends > 0)
630 nng_cv_wake(d->cv->cv);
631
632 nng_mtx_unlock(d->cv->mtx);
633
634 for (int i = 0; i < nsends; i++) {
635 if (dispatch_send_msg_to_daemon(d, batch[i].pipe, batch[i].msg) != 0)
636 nng_msg_free(batch[i].msg);
637 }
638
639 } while (nsends == 32);
640
641 }
642
643 // main event loop -------------------------------------------------------------
644
645 static int dispatch_wait_cv(nano_dispatcher *d, int *host_ready,
646 int *daemon_ready, int *monitor_count) {
647
648 nng_mtx *mtx = d->cv->mtx;
649 nng_cv *cv = d->cv->cv;
650 nano_monitor *m = d->monitor;
651 int stop;
652
653 nng_mtx_lock(mtx);
654 while (d->cv->condition == 0 && d->cv->flag >= 0)
655 nng_cv_wait(cv);
656 stop = d->cv->flag < 0;
657 d->cv->condition = 0;
658 *host_ready = d->host_recv_ready;
659 *daemon_ready = d->daemon_recv_ready;
660 d->host_recv_ready = 0;
661 d->daemon_recv_ready = 0;
662
663 int count = m->updates;
664 if (count && dispatch_ensure_pipe_events(d, count)) {
665 memcpy(d->pipe_events, m->ids, count * sizeof(int));
666 m->updates = 0;
667 *monitor_count = count;
668 } else {
669 *monitor_count = 0;
670 }
671
672 nng_mtx_unlock(mtx);
673
674 return stop;
675
676 }
677
678 static int dispatch_loop(nano_dispatcher *d) {
679
680 int host_ready, daemon_ready, monitor_events;
681
682 while (1) {
683 if (dispatch_wait_cv(d, &host_ready, &daemon_ready, &monitor_events))
684 return 0;
685
686 if (monitor_events)
687 dispatch_process_monitor(d, monitor_events);
688
689 if (host_ready) {
690 if (nng_aio_result(d->host_aio) == 0)
691 dispatch_handle_host_recv(d);
692 else
693 nng_ctx_recv(d->host_ctx, d->host_aio);
694 }
695
696 if (daemon_ready) {
697 if (nng_aio_result(d->daemon_aio) == 0)
698 dispatch_handle_daemon_recv(d);
699 else
700 nng_recv_aio(*d->poly_sock, d->daemon_aio);
701 }
702
703 if (d->inq_head)
704 dispatch_dispatch_tasks(d);
705 }
706
707 }
708
709 // shutdown --------------------------------------------------------------------
710
711 static void dispatch_shutdown(nano_dispatcher *d) {
712
713 if (d == NULL) return;
714
715 if (d->host_aio) {
716 nng_aio_stop(d->host_aio);
717 nng_aio_wait(d->host_aio);
718 }
719 if (d->daemon_aio) {
720 nng_aio_stop(d->daemon_aio);
721 nng_aio_wait(d->daemon_aio);
722 }
723
724 nng_ctx_close(d->host_ctx);
725
726 if (d->daemons) {
727 for (int i = 0; i < d->outq_count; i++)
728 if (d->daemons[i].msgid != 0)
729 nng_ctx_close(d->daemons[i].ctx);
730 }
731
732 while (d->inq_head) {
733 nano_dispatch_task *t = d->inq_head;
734 d->inq_head = t->next;
735 nng_ctx_close(t->ctx);
736 if (t->msg)
737 nng_msg_free(t->msg);
738 free(t);
739 }
740
741 free(d->daemons);
742
743 nng_aio_free(d->host_aio);
744 nng_aio_free(d->daemon_aio);
745 free(d->init_template);
746 free(d->conn_reset_buf);
747 free(d->pipe_events);
748 free(d);
749
750 }
751
752 // public entry point ----------------------------------------------------------
753
754 SEXP rnng_dispatcher_run(SEXP rep, SEXP poly, SEXP mon, SEXP reset,
755 SEXP serial, SEXP envir, SEXP next_stream_fun) {
756
757 if (NANO_PTR_CHECK(rep, nano_SocketSymbol))
758 Rf_error("`rep` is not a valid Socket");
759 if (NANO_PTR_CHECK(poly, nano_SocketSymbol))
760 Rf_error("`poly` is not a valid Socket");
761 if (NANO_PTR_CHECK(mon, nano_MonitorSymbol))
762 Rf_error("`mon` is not a valid Monitor");
763
764 SEXP call, stream;
765 PROTECT(call = Rf_lang2(next_stream_fun, envir));
766 PROTECT(stream = Rf_eval(call, R_GlobalEnv));
767
768 int xc = 2;
769 nano_dispatcher *d = calloc(1, sizeof(nano_dispatcher));
770 if (d == NULL) {
771 UNPROTECT(2);
772 goto fail;
773 }
774
775 d->rep_sock = (nng_socket *) NANO_PTR(rep);
776 d->poly_sock = (nng_socket *) NANO_PTR(poly);
777 d->monitor = (nano_monitor *) NANO_PTR(mon);
778 d->cv = d->monitor->cv;
779
780 size_t reset_len = XLENGTH(reset);
781 d->conn_reset_buf = malloc(reset_len);
782 if (d->conn_reset_buf == NULL) {
783 UNPROTECT(2);
784 goto fail;
785 }
786 memcpy(d->conn_reset_buf, DATAPTR_RO(reset), reset_len);
787 d->conn_reset_len = reset_len;
788
789 if (dispatch_prepare_init_template(d, stream, serial)) {
790 UNPROTECT(2);
791 goto fail;
792 }
793 UNPROTECT(2);
794
795 d->outq_capacity = DISPATCH_INITIAL_SIZE;
796 d->daemons = calloc(d->outq_capacity, sizeof(nano_dispatch_daemon));
797 if (d->daemons == NULL)
798 goto fail;
799
800 if ((xc = nng_aio_alloc(&d->host_aio, host_recv_cb, d)) ||
801 (xc = nng_aio_alloc(&d->daemon_aio, daemon_recv_cb, d)) ||
802 (xc = nng_ctx_open(&d->host_ctx, *d->rep_sock)))
803 goto fail;
804
805 nng_ctx_recv(d->host_ctx, d->host_aio);
806 nng_recv_aio(*d->poly_sock, d->daemon_aio);
807
808 xc = dispatch_loop(d);
809 dispatch_shutdown(d);
810
811 return Rf_ScalarInteger(xc);
812
813 fail:
814 dispatch_shutdown(d);
815 ERROR_OUT(xc);
816
817 }
818
819 // in-process dispatcher -------------------------------------------------------
820
821 typedef struct nano_dispatcher_handle_s {
822 nano_dispatcher *d;
823 nng_thread *thr;
824 nng_socket poly_sock;
825 nng_socket rep_sock;
826 nano_cv *priv_cv;
827 nano_monitor *monitor;
828 int owns_resources;
829 } nano_dispatcher_handle;
830
831 static void dispatch_thread_func(void *arg) {
832 nano_dispatcher *d = (nano_dispatcher *) arg;
833 dispatch_loop(d);
834 }
835
836 static void dispatcher_handle_release(nano_dispatcher_handle *h) {
837
838 if (!h->owns_resources) return;
839
840 nng_mtx_lock(h->priv_cv->mtx);
841 h->priv_cv->flag = -1;
842 nng_cv_wake(h->priv_cv->cv);
843 nng_mtx_unlock(h->priv_cv->mtx);
844
845 nng_thread_destroy(h->thr);
846 dispatch_shutdown(h->d);
847 h->d = NULL;
848
849 nng_close(h->poly_sock);
850 nng_close(h->rep_sock);
851
852 if (h->monitor) {
853 free(h->monitor->ids);
854 free(h->monitor);
855 }
856 free(h->priv_cv);
857 h->owns_resources = 0;
858
859 }
860
861 static void dispatcher_handle_finalizer(SEXP xptr) {
862
863 if (NANO_PTR(xptr) == NULL) return;
864
865 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(xptr);
866 dispatcher_handle_release(h);
867 free(h);
868
869 }
870
871 int dispatch_cancel_direct(void *handle, int id) {
872
873 nano_dispatcher_handle *h = (nano_dispatcher_handle *) handle;
874 nano_dispatcher *d = h->d;
875 if (d == NULL)
876 return 0;
877
878 int found = 0;
879 int pipe = 0;
880
881 nng_mtx_lock(d->cv->mtx);
882
883 for (int i = 0; i < d->outq_count; i++) {
884 if (d->daemons[i].msgid == id) {
885 pipe = d->daemons[i].pipe;
886 found = 1;
887 break;
888 }
889 }
890 if (!found)
891 found = dispatch_cancel_inq(d, id);
892
893 nng_mtx_unlock(d->cv->mtx);
894
895 if (pipe)
896 dispatch_send_to_daemon(d, pipe, NULL, 0);
897
898 return found;
899
900 }
901
902 SEXP rnng_dispatcher_start(SEXP url, SEXP disp_url, SEXP tls,
903 SEXP serial, SEXP stream,
904 SEXP capacity, SEXP cvar) {
905
906 int xc;
907 nng_listener listener = NNG_LISTENER_INITIALIZER;
908 nano_dispatcher_handle *h = NULL;
909 nano_dispatcher *d = NULL;
910 nano_cv *priv = NULL;
911
912 h = calloc(1, sizeof(nano_dispatcher_handle));
913 if (h == NULL) { xc = 2; goto fail; }
914
915 d = calloc(1, sizeof(nano_dispatcher));
916 if (d == NULL) { xc = 2; goto fail; }
917 h->d = d;
918
919 // Private CV sharing mutex/cv with shared CV
920 nano_cv *shared = (nano_cv *) NANO_PTR(cvar);
921 priv = calloc(1, sizeof(nano_cv));
922 if (priv == NULL) { xc = 2; goto fail; }
923 priv->mtx = shared->mtx;
924 priv->cv = shared->cv;
925 h->priv_cv = priv;
926 d->cv = priv;
927 if (capacity == R_NilValue) {
928 d->limit_bytes = 0;
929 } else {
930 double mb = Rf_asReal(capacity);
931 d->limit_bytes = (R_FINITE(mb) && mb > 0.0) ? (size_t) (mb * 1e6) : 0;
932 }
933
934 // POLY socket for daemon connections
935 if ((xc = nng_pair1_open_poly(&h->poly_sock)))
936 goto fail;
937
938 d->poly_sock = &h->poly_sock;
939
940 // Monitor on the POLY socket
941 const int n = 8;
942 nano_monitor *monitor = calloc(1, sizeof(nano_monitor));
943 if (monitor == NULL) { xc = 2; goto fail; }
944 monitor->ids = calloc(n, sizeof(int));
945 if (monitor->ids == NULL) { free(monitor); xc = 2; goto fail; }
946 monitor->size = n;
947 monitor->cv = priv;
948 h->monitor = monitor;
949 d->monitor = monitor;
950
951 if ((xc = nng_pipe_notify(h->poly_sock, NNG_PIPE_EV_ADD_POST, pipe_cb_monitor, monitor)))
952 goto fail;
953 if ((xc = nng_pipe_notify(h->poly_sock, NNG_PIPE_EV_REM_POST, pipe_cb_monitor, monitor)))
954 goto fail;
955
956 // Listen for daemon connections
957 const char *url_str = CHAR(STRING_ELT(url, 0));
958 if (TYPEOF(tls) != NILSXP && !NANO_PTR_CHECK(tls, nano_TlsSymbol)) {
959 nng_tls_config *cfg = (nng_tls_config *) NANO_PTR(tls);
960 if ((xc = nng_listener_create(&listener, h->poly_sock, url_str)) ||
961 (xc = nng_listener_set_ptr(listener, NNG_OPT_TLS_CONFIG, cfg)) ||
962 (xc = nng_listener_start(listener, 0)))
963 goto fail;
964 } else {
965 if ((xc = nng_listen(h->poly_sock, url_str, &listener, 0)))
966 goto fail;
967 }
968
969 // REP socket dials into the host's inproc:// REQ socket
970 if ((xc = nng_rep0_open(&h->rep_sock)))
971 goto fail;
972 d->rep_sock = &h->rep_sock;
973
974 const char *disp_url_str = CHAR(STRING_ELT(disp_url, 0));
975 if ((xc = nng_dial(h->rep_sock, disp_url_str, NULL, 0)))
976 goto fail;
977
978 // Serialize mk_error(19) for conn_reset_buf
979 SEXP err;
980 PROTECT(err = mk_error(19));
981 nano_buf reset_buf;
982 nano_serialize(&reset_buf, err, R_NilValue, 0);
983 UNPROTECT(1);
984 d->conn_reset_buf = reset_buf.buf;
985 d->conn_reset_len = reset_buf.cur;
986
987 // Prepare init template
988 if (dispatch_prepare_init_template(d, stream, serial)) { xc = 2; goto fail; }
989
990 // Allocate daemon array
991 d->outq_capacity = DISPATCH_INITIAL_SIZE;
992 d->daemons = calloc(d->outq_capacity, sizeof(nano_dispatch_daemon));
993 if (d->daemons == NULL) { xc = 2; goto fail; }
994
995 // Allocate AIOs and open host context
996 if ((xc = nng_aio_alloc(&d->host_aio, host_recv_cb, d)) ||
997 (xc = nng_aio_alloc(&d->daemon_aio, daemon_recv_cb, d)) ||
998 (xc = nng_ctx_open(&d->host_ctx, *d->rep_sock)))
999 goto fail;
1000
1001 // Start initial receive operations
1002 nng_ctx_recv(d->host_ctx, d->host_aio);
1003 nng_recv_aio(*d->poly_sock, d->daemon_aio);
1004
1005 // Create the dispatcher thread
1006 if ((xc = nng_thread_create(&h->thr, dispatch_thread_func, d)))
1007 goto fail;
1008
1009 h->owns_resources = 1;
1010
1011 // Build external pointer with finalizer
1012 SEXP xptr;
1013 PROTECT(xptr = R_MakeExternalPtr(h, nano_ThreadSymbol, R_NilValue));
1014 R_RegisterCFinalizerEx(xptr, dispatcher_handle_finalizer, TRUE);
1015
1016 // Attach resolved listener URL as attribute
1017 SEXP resolved_url = url;
1018 nng_url *up;
1019 if (nng_url_parse(&up, url_str) == 0) {
1020 if (up->u_port != NULL && up->u_port[0] == '0' && up->u_port[1] == '\0') {
1021 int port;
1022 if (nng_listener_get_int(listener, NNG_OPT_TCP_BOUND_PORT, &port) == 0)
1023 resolved_url = nano_url_with_port(up, port);
1024 }
1025 nng_url_free(up);
1026 }
1027 Rf_setAttrib(xptr, nano_UrlSymbol, resolved_url);
1028
1029 UNPROTECT(1);
1030 return xptr;
1031
1032 fail:
1033 if (d) {
1034 if (d->daemon_aio) { nng_aio_stop(d->daemon_aio); nng_aio_free(d->daemon_aio); }
1035 if (d->host_aio) { nng_aio_stop(d->host_aio); nng_aio_free(d->host_aio); }
1036 free(d->daemons);
1037 free(d->init_template);
1038 free(d->conn_reset_buf);
1039 free(d->pipe_events);
1040 free(d);
1041 }
1042 if (h) {
1043 nng_close(h->rep_sock);
1044 nng_close(h->poly_sock);
1045 if (h->monitor) { free(h->monitor->ids); free(h->monitor); }
1046 free(h);
1047 }
1048 free(priv);
1049 ERROR_OUT(xc);
1050
1051 }
1052
1053 SEXP rnng_dispatcher_stop(SEXP disp) {
1054
1055 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol))
1056 return R_NilValue;
1057
1058 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1059
1060 dispatcher_handle_release(h);
1061
1062 NANO_SET_TAG(disp, R_NilValue);
1063
1064 return R_NilValue;
1065
1066 }
1067
1068 SEXP rnng_dispatcher_wait(SEXP disp, SEXP n) {
1069
1070 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol))
1071 return R_NilValue;
1072
1073 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1074 nano_dispatcher *d = h->d;
1075 const int target = nano_integer(n);
1076 nng_cv *cv = d->cv->cv;
1077 nng_mtx *mtx = d->cv->mtx;
1078
1079 nng_mtx_lock(mtx);
1080 while (d->outq_count < target && d->cv->flag >= 0) {
1081 nng_time time = nng_clock() + 400;
1082 nng_cv_until(cv, time);
1083 nng_mtx_unlock(mtx);
1084 R_CheckUserInterrupt();
1085 nng_mtx_lock(mtx);
1086 }
1087 nng_mtx_unlock(mtx);
1088
1089 return R_NilValue;
1090
1091 }
1092
1093 SEXP rnng_dispatcher_info(SEXP disp) {
1094
1095 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol))
1096 return Rf_allocVector(INTSXP, 5);
1097
1098 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1099 nano_dispatcher *d = h->d;
1100
1101 int result[5];
1102 nng_mtx_lock(d->cv->mtx);
1103 result[0] = d->outq_count;
1104 result[1] = d->connections;
1105 result[2] = d->inq_count;
1106 result[3] = d->executing;
1107 result[4] = d->count - d->inq_count - d->executing;
1108 nng_mtx_unlock(d->cv->mtx);
1109
1110 SEXP out = PROTECT(Rf_allocVector(INTSXP, 5));
1111 memcpy(NANO_DATAPTR(out), result, sizeof(result));
1112 UNPROTECT(1);
1113
1114 return out;
1115
1116 }
1117
1118 SEXP rnng_dispatcher_capacity(SEXP disp) {
1119
1120 static const char *names[] = {"used", "peak", "capacity", ""};
1121 SEXP out = PROTECT(Rf_mkNamed(REALSXP, names));
1122 double *p = REAL(out);
1123
1124 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol)) {
1125 p[0] = NA_REAL;
1126 p[1] = NA_REAL;
1127 p[2] = NA_REAL;
1128 UNPROTECT(1);
1129 return out;
1130 }
1131
1132 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1133 nano_dispatcher *d = h->d;
1134
1135 size_t queued, peak, limit;
1136 nng_mtx_lock(d->cv->mtx);
1137 queued = d->queued_bytes;
1138 peak = d->peak_queued_bytes;
1139 limit = d->limit_bytes;
1140 nng_mtx_unlock(d->cv->mtx);
1141
1142 p[0] = (double) queued / 1e6;
1143 p[1] = (double) peak / 1e6;
1144 p[2] = limit > 0 ? (double) limit / 1e6 : NA_REAL;
1145 UNPROTECT(1);
1146
1147 return out;
1148
1149 }
1150
1151 SEXP rnng_dispatcher_gate(SEXP disp) {
1152
1153 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol))
1154 return R_NilValue;
1155
1156 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1157 nano_dispatcher *d = h->d;
1158
1159 if (d->limit_bytes > 0) {
1160 nng_mtx_lock(d->cv->mtx);
1161 while (d->queued_bytes >= d->limit_bytes) {
1162 nng_time time = nng_clock() + 400;
1163 nng_cv_until(d->cv->cv, time);
1164 nng_mtx_unlock(d->cv->mtx);
1165 R_CheckUserInterrupt();
1166 nng_mtx_lock(d->cv->mtx);
1167 }
1168 nng_mtx_unlock(d->cv->mtx);
1169 }
1170
1171 return Rf_ScalarLogical(1);
1172
1173 }
1174
1175 SEXP rnng_dispatcher_try_gate(SEXP disp) {
1176
1177 if (NANO_PTR_CHECK(disp, nano_ThreadSymbol))
1178 return R_NilValue;
1179
1180 nano_dispatcher_handle *h = (nano_dispatcher_handle *) NANO_PTR(disp);
1181 nano_dispatcher *d = h->d;
1182
1183 int allowed = 1;
1184 if (d->limit_bytes > 0) {
1185 nng_mtx_lock(d->cv->mtx);
1186 allowed = d->queued_bytes < d->limit_bytes;
1187 nng_mtx_unlock(d->cv->mtx);
1188 }
1189
1190 return Rf_ScalarLogical(allowed);
1191
1192 }
1193