asterism-zenoh 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,14 @@
5
5
  * (ruby-asterism/picoruby-asterism-zenoh, over zenoh-pico): sessions
6
6
  * (client, or peer with an optional listener), put / subscribe, get /
7
7
  * queryable (query and reply), liveliness tokens and watches, attachments,
8
- * Session#zid. Code written for one runs on the other.
8
+ * Session#zid. Code written for one runs on the other. 0.3.0 adds, for
9
+ * CRuby only, the configuration, scouting, delete, declared publishers and
10
+ * queriers, matching status, the fields of samples and replies, error and
11
+ * delete replies, encodings, timestamps, key expressions, the advanced
12
+ * publisher / subscriber, transport and link events and the log
13
+ * (docs/feature_coverage.md). They receive in the same way: what zenoh-c's
14
+ * callbacks get is copied into a queue (a channel, or a zevq for small
15
+ * events) and Ruby takes it out by polling.
9
16
  *
10
17
  * Threading model: zenoh-c runs the protocol on its own threads and calls
11
18
  * the callbacks below from them. No callback touches Ruby (no GVL, no Ruby
@@ -59,9 +66,12 @@
59
66
 
60
67
  static VALUE mAsterism, mZenoh, eZenohError;
61
68
  static VALUE cSession, cSubscriber, cWatch, cQueryable, cQuery, cGet, cToken;
69
+ static VALUE cAdvSubscriber, cPublisher, cAdvPublisher, cQuerier, cKeyExpr, cTimestamp;
70
+ static VALUE cMatchingListener, cEventListener;
62
71
  static ID id_attachment, id_target, id_consolidation, id_complete, id_mode, id_listen;
63
- static ID id_iv_session, id_iv_key;
64
- static ID id_client, id_peer, id_all, id_all_complete, id_best_matching;
72
+ static ID id_config, id_config_file, id_scouting, id_history, id_new;
73
+ static ID id_iv_session, id_iv_key, id_iv_parent;
74
+ static ID id_client, id_peer, id_router, id_all, id_all_complete, id_best_matching;
65
75
  static ID id_none, id_latest, id_monotonic, id_auto;
66
76
 
67
77
  /* ------------------------------------------------------------- channels */
@@ -202,17 +212,16 @@ static void zch_on_sample(z_loaned_sample_t *sample, void *ctx) {
202
212
  pthread_mutex_unlock(&c->lock);
203
213
  }
204
214
 
215
+ /* Error replies are queued too (each_result returns them; each_reply skips
216
+ * them). They are counted in errors, the others in received. */
205
217
  static void zch_on_reply(z_loaned_reply_t *reply, void *ctx) {
206
218
  zch *c = (zch *)ctx;
207
- if (!z_reply_is_ok(reply)) {
208
- atomic_fetch_add(&c->errors, 1);
209
- return;
210
- }
219
+ bool ok = z_reply_is_ok(reply);
211
220
  pthread_mutex_lock(&c->lock);
212
221
  zch_make_room(c);
213
222
  z_closure_reply_call(z_loan(c->tx.reply), reply);
214
223
  atomic_fetch_add(&c->queued, 1);
215
- atomic_fetch_add(&c->received, 1);
224
+ atomic_fetch_add(ok ? &c->received : &c->errors, 1);
216
225
  pthread_mutex_unlock(&c->lock);
217
226
  }
218
227
 
@@ -287,6 +296,18 @@ static VALUE zrb_str_from_view(const z_loaned_string_t *s) {
287
296
  return rb_utf8_str_new(z_string_data(s), (long)z_string_len(s));
288
297
  }
289
298
 
299
+ /* zenoh-c's text for the last error on this thread (": ..."), or "". Read
300
+ * right after the failing call: the next call that can fail replaces it. */
301
+ static VALUE zrb_last_error(void) {
302
+ z_view_string_t s;
303
+ zc_get_last_error(&s);
304
+ size_t n = z_string_len(z_loan(s));
305
+ if (n == 0) {
306
+ return rb_str_new_cstr("");
307
+ }
308
+ return rb_sprintf(": %.*s", (int)n, z_string_data(z_loan(s)));
309
+ }
310
+
290
311
  static VALUE zrb_key_str(const z_loaned_keyexpr_t *ke) {
291
312
  z_view_string_t ks;
292
313
  z_keyexpr_as_view_string(ke, &ks);
@@ -392,6 +413,22 @@ typedef struct zrb_session zrb_session;
392
413
  typedef struct zrb_sub zrb_sub;
393
414
  typedef struct zrb_qable zrb_qable;
394
415
  typedef struct zrb_token zrb_token;
416
+ typedef struct zrb_ent zrb_ent;
417
+
418
+ /* The entities added in 0.3.0 (publishers, queriers, listeners, declared
419
+ * key expressions) share one list of the session. undeclare drops the
420
+ * zenoh-c object; order says when the session undeclares it on close
421
+ * (listeners first, declared key expressions last). */
422
+ enum { ZENT_LISTENER = 0, ZENT_ENTITY = 1, ZENT_KEYEXPR = 2 };
423
+
424
+ struct zrb_ent {
425
+ zrb_session *owner; /* NULL once detached */
426
+ zrb_ent *next;
427
+ int order;
428
+ bool declared;
429
+ bool gvl_free_use; /* used without the GVL: undeclared under op_lock */
430
+ void (*undeclare)(zrb_ent *e);
431
+ };
395
432
 
396
433
  struct zrb_session {
397
434
  z_owned_session_t session;
@@ -403,12 +440,19 @@ struct zrb_session {
403
440
  zrb_sub *subs; /* live subscribers and liveliness watches */
404
441
  zrb_qable *qables;
405
442
  zrb_token *tokens;
443
+ zrb_ent *ents; /* the rest (0.3.0) */
406
444
  };
407
445
 
446
+ typedef enum { ZSUB_PLAIN, ZSUB_LIVELINESS, ZSUB_ADVANCED } zsub_type;
447
+
408
448
  struct zrb_sub {
409
- z_owned_subscriber_t sub;
449
+ union {
450
+ z_owned_subscriber_t sub; /* plain and liveliness */
451
+ ze_owned_advanced_subscriber_t adv;
452
+ } u;
410
453
  bool declared;
411
454
  bool liveliness;
455
+ zsub_type type;
412
456
  zrb_session *owner; /* NULL once detached */
413
457
  zrb_sub *next;
414
458
  zch *ch;
@@ -438,1033 +482,3579 @@ typedef struct {
438
482
  bool live;
439
483
  } zrb_query;
440
484
 
441
- /* ----------------------------------------------------------- subscriber */
485
+ /* ----------------------------------------------- entities (0.3.0 list) */
442
486
 
443
- static void zrb_sub_detach(zrb_sub *s) {
444
- if (s->declared) {
445
- z_drop(z_move(s->sub));
446
- s->declared = false;
487
+ static void zrb_ent_link(zrb_ent *e, zrb_session *z, int order, bool gvl_free_use, void (*undeclare)(zrb_ent *)) {
488
+ e->owner = z;
489
+ e->order = order;
490
+ e->declared = true;
491
+ e->gvl_free_use = gvl_free_use;
492
+ e->undeclare = undeclare;
493
+ e->next = z->ents;
494
+ z->ents = e;
495
+ }
496
+
497
+ /* Undeclares the entity (once) and takes it off its session's list. With
498
+ * the GVL held. An entity that other threads use without the GVL
499
+ * (publishers, queriers) is undeclared under the session's op_lock, so a
500
+ * put in progress finishes first. */
501
+ static void zrb_ent_detach(zrb_ent *e) {
502
+ if (e->declared) {
503
+ zrb_session *z = e->owner;
504
+ bool lock = e->gvl_free_use && z != NULL;
505
+ if (lock) {
506
+ pthread_mutex_lock(&z->op_lock);
507
+ }
508
+ e->undeclare(e);
509
+ e->declared = false;
510
+ if (lock) {
511
+ pthread_mutex_unlock(&z->op_lock);
512
+ }
447
513
  }
448
- if (s->owner != NULL) {
449
- zrb_sub **pp = &s->owner->subs;
514
+ if (e->owner != NULL) {
515
+ zrb_ent **pp = &e->owner->ents;
450
516
  while (*pp != NULL) {
451
- if (*pp == s) {
452
- *pp = s->next;
517
+ if (*pp == e) {
518
+ *pp = e->next;
453
519
  break;
454
520
  }
455
521
  pp = &(*pp)->next;
456
522
  }
457
- s->owner = NULL;
458
- s->next = NULL;
523
+ e->owner = NULL;
524
+ e->next = NULL;
459
525
  }
460
526
  }
461
527
 
462
- static void zrb_sub_free(void *p) {
463
- zrb_sub *s = (zrb_sub *)p;
464
- zrb_sub_detach(s);
465
- zch_unref(s->ch);
466
- xfree(s);
467
- }
528
+ /* -------------------------------------------------------- event queues */
529
+
530
+ /* Small events (matching status, transports and links, missed samples,
531
+ * scouting answers) copied out of zenoh-c's callbacks into plain C memory.
532
+ * Same rules as the channels: the callbacks never touch Ruby, a full queue
533
+ * drops its oldest entry, Ruby takes the entries out by polling. */
534
+ typedef enum { ZEV_MATCHING, ZEV_TRANSPORT, ZEV_LINK, ZEV_MISS, ZEV_HELLO } zev_kind;
535
+
536
+ typedef struct zev {
537
+ struct zev *next;
538
+ bool flag; /* matching status; added (not removed) for transports / links */
539
+ z_id_t zid;
540
+ uint32_t eid, nb;
541
+ int whatami;
542
+ bool qos, multicast, streamed, has_reliability;
543
+ int reliability;
544
+ uint16_t mtu;
545
+ char *src, *dst, *group, *auth;
546
+ char **strs; /* interfaces of a link, locators of a hello */
547
+ size_t nstrs;
548
+ } zev;
468
549
 
469
- static size_t zrb_sub_size(const void *p) { return sizeof(zrb_sub); }
550
+ typedef struct {
551
+ zev_kind kind;
552
+ pthread_mutex_t lock;
553
+ zev *head, *tail;
554
+ uint32_t depth;
555
+ atomic_uint queued;
556
+ atomic_uint received;
557
+ atomic_uint dropped;
558
+ atomic_bool done;
559
+ atomic_int refs;
560
+ } zevq;
470
561
 
471
- static const rb_data_type_t zrb_sub_type = {
472
- "Asterism::Zenoh::Subscriber", {NULL, zrb_sub_free, zrb_sub_size}, NULL, NULL, 0};
562
+ static void zev_free(zev *e) {
563
+ if (e == NULL) {
564
+ return;
565
+ }
566
+ free(e->src);
567
+ free(e->dst);
568
+ free(e->group);
569
+ free(e->auth);
570
+ for (size_t i = 0; i < e->nstrs; i++) {
571
+ free(e->strs[i]);
572
+ }
573
+ free(e->strs);
574
+ free(e);
575
+ }
473
576
 
474
- static zrb_sub *zrb_sub_get(VALUE self) {
475
- zrb_sub *s;
476
- TypedData_Get_Struct(self, zrb_sub, &zrb_sub_type, s);
477
- return s;
577
+ static zevq *zevq_new(zev_kind kind, uint32_t depth) {
578
+ zevq *q = (zevq *)calloc(1, sizeof(zevq));
579
+ if (q == NULL) {
580
+ rb_raise(rb_eNoMemError, "cannot allocate an event queue");
581
+ }
582
+ q->kind = kind;
583
+ q->depth = depth;
584
+ pthread_mutex_init(&q->lock, NULL);
585
+ atomic_init(&q->queued, 0);
586
+ atomic_init(&q->received, 0);
587
+ atomic_init(&q->dropped, 0);
588
+ atomic_init(&q->done, false);
589
+ atomic_init(&q->refs, 1);
590
+ return q;
478
591
  }
479
592
 
480
- /* Take out what is pending now, oldest first. Values that arrive while the
481
- * block runs are left for the next call. */
482
- static VALUE zrb_sub_each_pending(VALUE self) {
483
- zrb_sub *s = zrb_sub_get(self);
484
- bool collect = !rb_block_given_p();
485
- VALUE out = collect ? rb_ary_new() : Qnil;
486
- long taken = 0;
487
- unsigned todo = atomic_load(&s->ch->queued);
488
- while (todo > 0) {
489
- todo--;
490
- z_owned_sample_t sm;
491
- if (zch_take_sample(s->ch, &sm) != Z_OK) {
492
- break;
493
- }
494
- const z_loaned_sample_t *l = z_loan(sm);
495
- VALUE vals[3];
496
- int n;
497
- vals[0] = zrb_key_str(z_sample_keyexpr(l));
498
- if (s->liveliness) {
499
- /* A token appearing is a PUT, one going away a DELETE. */
500
- vals[1] = (z_sample_kind(l) == Z_SAMPLE_KIND_PUT) ? Qtrue : Qfalse;
501
- n = 2;
502
- } else {
503
- vals[1] = zrb_str_from_bytes(z_sample_payload(l));
504
- vals[2] = zrb_attachment_value(z_sample_attachment(l));
505
- n = 3;
506
- }
507
- z_drop(z_move(sm));
508
- taken++;
509
- if (collect) {
510
- rb_ary_push(out, rb_ary_new_from_values(n, vals));
511
- } else {
512
- rb_yield_values2(n, vals);
513
- }
593
+ static void zevq_unref(zevq *q) {
594
+ if (q == NULL || atomic_fetch_sub(&q->refs, 1) != 1) {
595
+ return;
514
596
  }
515
- return collect ? out : LONG2NUM(taken);
597
+ zev *e = q->head;
598
+ while (e != NULL) {
599
+ zev *n = e->next;
600
+ zev_free(e);
601
+ e = n;
602
+ }
603
+ pthread_mutex_destroy(&q->lock);
604
+ free(q);
516
605
  }
517
606
 
518
- static VALUE zrb_sub_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->queued)); }
519
- static VALUE zrb_sub_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->received)); }
520
- static VALUE zrb_sub_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->dropped)); }
607
+ /* The context of a closure handed to zenoh-c holds a reference. */
608
+ static zevq *zevq_ref(zevq *q) {
609
+ atomic_fetch_add(&q->refs, 1);
610
+ return q;
611
+ }
521
612
 
522
- static VALUE zrb_sub_close(VALUE self) {
523
- zrb_sub_detach(zrb_sub_get(self));
524
- return Qnil;
613
+ static void zevq_on_drop(void *ctx) {
614
+ zevq *q = (zevq *)ctx;
615
+ atomic_store(&q->done, true);
616
+ zevq_unref(q);
525
617
  }
526
618
 
527
- static VALUE zrb_sub_closed_p(VALUE self) { return zrb_sub_get(self)->declared ? Qfalse : Qtrue; }
619
+ /* From zenoh's threads (or, for the snapshots, the calling one). */
620
+ static void zevq_push(zevq *q, zev *e) {
621
+ if (e == NULL) {
622
+ return;
623
+ }
624
+ pthread_mutex_lock(&q->lock);
625
+ if (atomic_load(&q->queued) >= q->depth && q->head != NULL) {
626
+ zev *old = q->head;
627
+ q->head = old->next;
628
+ if (q->head == NULL) {
629
+ q->tail = NULL;
630
+ }
631
+ zev_free(old);
632
+ atomic_fetch_sub(&q->queued, 1);
633
+ atomic_fetch_add(&q->dropped, 1);
634
+ }
635
+ e->next = NULL;
636
+ if (q->tail != NULL) {
637
+ q->tail->next = e;
638
+ } else {
639
+ q->head = e;
640
+ }
641
+ q->tail = e;
642
+ atomic_fetch_add(&q->queued, 1);
643
+ atomic_fetch_add(&q->received, 1);
644
+ pthread_mutex_unlock(&q->lock);
645
+ }
528
646
 
529
- /* ------------------------------------------------------------ queryable */
647
+ static zev *zevq_take(zevq *q) {
648
+ pthread_mutex_lock(&q->lock);
649
+ zev *e = q->head;
650
+ if (e != NULL) {
651
+ q->head = e->next;
652
+ if (q->head == NULL) {
653
+ q->tail = NULL;
654
+ }
655
+ atomic_fetch_sub(&q->queued, 1);
656
+ }
657
+ pthread_mutex_unlock(&q->lock);
658
+ return e;
659
+ }
530
660
 
531
- static void zrb_qable_detach(zrb_qable *q) {
532
- /* Unanswered queries first: their final replies go out while the
533
- * session can still carry them. */
534
- zch_finish_queries(q->ch);
535
- if (q->declared) {
536
- z_drop(z_move(q->qable));
537
- q->declared = false;
661
+ static char *zev_strdup_n(const char *s, size_t n) {
662
+ char *out = (char *)malloc(n + 1);
663
+ if (out != NULL) {
664
+ memcpy(out, s, n);
665
+ out[n] = '\0';
538
666
  }
539
- if (q->owner != NULL) {
540
- zrb_qable **pp = &q->owner->qables;
541
- while (*pp != NULL) {
542
- if (*pp == q) {
543
- *pp = q->next;
544
- break;
545
- }
546
- pp = &(*pp)->next;
667
+ return out;
668
+ }
669
+
670
+ /* Copies an owned string out (and drops it). */
671
+ static char *zev_take_string(z_owned_string_t *s) {
672
+ char *out = zev_strdup_n(z_string_data(z_loan(*s)), z_string_len(z_loan(*s)));
673
+ z_drop(z_move(*s));
674
+ return out;
675
+ }
676
+
677
+ static void zev_take_strings(zev *e, z_owned_string_array_t *arr) {
678
+ size_t n = z_string_array_len(z_loan(*arr));
679
+ e->strs = (char **)calloc(n > 0 ? n : 1, sizeof(char *));
680
+ if (e->strs != NULL) {
681
+ for (size_t i = 0; i < n; i++) {
682
+ const z_loaned_string_t *s = z_string_array_get(z_loan(*arr), i);
683
+ e->strs[i] = zev_strdup_n(z_string_data(s), z_string_len(s));
547
684
  }
548
- q->owner = NULL;
549
- q->next = NULL;
685
+ e->nstrs = n;
550
686
  }
687
+ z_drop(z_move(*arr));
551
688
  }
552
689
 
553
- static void zrb_qable_free(void *p) {
554
- zrb_qable *q = (zrb_qable *)p;
555
- zrb_qable_detach(q);
556
- zch_unref(q->ch);
557
- xfree(q);
690
+ static zev *zev_new(void) { return (zev *)calloc(1, sizeof(zev)); }
691
+
692
+ static void zev_fill_transport(zev *e, const z_loaned_transport_t *t) {
693
+ e->zid = z_transport_zid(t);
694
+ e->whatami = (int)z_transport_whatami(t);
695
+ e->qos = z_transport_is_qos(t);
696
+ e->multicast = z_transport_is_multicast(t);
558
697
  }
559
698
 
560
- static size_t zrb_qable_size(const void *p) { return sizeof(zrb_qable); }
699
+ static void zev_fill_link(zev *e, const z_loaned_link_t *l) {
700
+ z_owned_string_t s;
701
+ e->zid = z_link_zid(l);
702
+ z_link_src(l, &s);
703
+ e->src = zev_take_string(&s);
704
+ z_link_dst(l, &s);
705
+ e->dst = zev_take_string(&s);
706
+ z_link_group(l, &s);
707
+ e->group = zev_take_string(&s);
708
+ z_link_auth_identifier(l, &s);
709
+ e->auth = zev_take_string(&s);
710
+ e->mtu = z_link_mtu(l);
711
+ e->streamed = z_link_is_streamed(l);
712
+ z_reliability_t rel;
713
+ e->has_reliability = z_link_reliability(l, &rel);
714
+ e->reliability = (int)rel;
715
+ z_owned_string_array_t arr;
716
+ z_link_interfaces(l, &arr);
717
+ zev_take_strings(e, &arr);
718
+ }
561
719
 
562
- static const rb_data_type_t zrb_qable_type = {
563
- "Asterism::Zenoh::Queryable", {NULL, zrb_qable_free, zrb_qable_size}, NULL, NULL, 0};
720
+ /* The callbacks (zenoh's threads; no Ruby). */
721
+ static void zev_on_matching(const z_matching_status_t *st, void *ctx) {
722
+ zev *e = zev_new();
723
+ if (e != NULL) {
724
+ e->flag = st->matching;
725
+ }
726
+ zevq_push((zevq *)ctx, e);
727
+ }
564
728
 
565
- static zrb_qable *zrb_qable_get(VALUE self) {
566
- zrb_qable *q;
567
- TypedData_Get_Struct(self, zrb_qable, &zrb_qable_type, q);
568
- return q;
729
+ static void zev_on_transport_event(z_loaned_transport_event_t *ev, void *ctx) {
730
+ zev *e = zev_new();
731
+ if (e != NULL) {
732
+ e->flag = (z_transport_event_kind(ev) == Z_SAMPLE_KIND_PUT);
733
+ zev_fill_transport(e, z_transport_event_transport(ev));
734
+ }
735
+ zevq_push((zevq *)ctx, e);
569
736
  }
570
737
 
571
- /* ---------------------------------------------------------------- query */
738
+ static void zev_on_transport(z_loaned_transport_t *t, void *ctx) {
739
+ zev *e = zev_new();
740
+ if (e != NULL) {
741
+ e->flag = true;
742
+ zev_fill_transport(e, t);
743
+ }
744
+ zevq_push((zevq *)ctx, e);
745
+ }
572
746
 
573
- static void zrb_query_finish(zrb_query *zq) {
574
- if (zq->live) {
575
- z_drop(z_move(zq->query));
576
- zq->live = false;
747
+ static void zev_on_link_event(z_loaned_link_event_t *ev, void *ctx) {
748
+ zev *e = zev_new();
749
+ if (e != NULL) {
750
+ e->flag = (z_link_event_kind(ev) == Z_SAMPLE_KIND_PUT);
751
+ zev_fill_link(e, z_link_event_link(ev));
577
752
  }
753
+ zevq_push((zevq *)ctx, e);
578
754
  }
579
755
 
580
- static void zrb_query_free(void *p) {
581
- zrb_query *zq = (zrb_query *)p;
582
- zrb_query_finish(zq);
583
- xfree(zq);
756
+ static void zev_on_link(z_loaned_link_t *l, void *ctx) {
757
+ zev *e = zev_new();
758
+ if (e != NULL) {
759
+ e->flag = true;
760
+ zev_fill_link(e, l);
761
+ }
762
+ zevq_push((zevq *)ctx, e);
584
763
  }
585
764
 
586
- static size_t zrb_query_size(const void *p) { return sizeof(zrb_query); }
765
+ static void zev_on_miss(const ze_miss_t *m, void *ctx) {
766
+ zev *e = zev_new();
767
+ if (e != NULL) {
768
+ e->zid = z_entity_global_id_zid(&m->source);
769
+ e->eid = z_entity_global_id_eid(&m->source);
770
+ e->nb = m->nb;
771
+ }
772
+ zevq_push((zevq *)ctx, e);
773
+ }
587
774
 
588
- static const rb_data_type_t zrb_query_type = {
589
- "Asterism::Zenoh::Query", {NULL, zrb_query_free, zrb_query_size}, NULL, NULL, 0};
775
+ static void zev_on_hello(z_loaned_hello_t *h, void *ctx) {
776
+ zev *e = zev_new();
777
+ if (e != NULL) {
778
+ e->zid = z_hello_zid(h);
779
+ e->whatami = (int)z_hello_whatami(h);
780
+ z_owned_string_array_t arr;
781
+ z_hello_locators(h, &arr);
782
+ zev_take_strings(e, &arr);
783
+ }
784
+ zevq_push((zevq *)ctx, e);
785
+ }
590
786
 
591
- static zrb_query *zrb_query_get(VALUE self) {
592
- zrb_query *zq;
593
- TypedData_Get_Struct(self, zrb_query, &zrb_query_type, zq);
594
- return zq;
787
+ /* --------------------------------------------------- values for Ruby */
788
+
789
+ /* The value classes are Ruby (lib/asterism/zenoh/values.rb). */
790
+ static VALUE zrb_value_class(const char *name) { return rb_const_get(mZenoh, rb_intern(name)); }
791
+
792
+ static VALUE zrb_new_value(const char *klass, VALUE hash) {
793
+ return rb_class_new_instance_kw(1, &hash, zrb_value_class(klass), RB_PASS_KEYWORDS);
595
794
  }
596
795
 
597
- static zrb_query *zrb_query_get_live(VALUE self) {
598
- zrb_query *zq = zrb_query_get(self);
599
- if (!zq->live) {
600
- rb_raise(eZenohError, "the query is finished");
796
+ static void zrb_hset(VALUE h, const char *key, VALUE v) { rb_hash_aset(h, ID2SYM(rb_intern(key)), v); }
797
+
798
+ static VALUE zrb_zid_value(const z_id_t *id) {
799
+ z_owned_string_t str;
800
+ z_id_to_string(id, &str);
801
+ VALUE out = zrb_str_from_view(z_loan(str));
802
+ z_drop(z_move(str));
803
+ return out;
804
+ }
805
+
806
+ static VALUE zrb_cstr_or_nil(const char *s) { return s == NULL ? Qnil : rb_utf8_str_new_cstr(s); }
807
+
808
+ static VALUE zrb_whatami_sym(int w) {
809
+ switch (w) {
810
+ case Z_WHATAMI_ROUTER:
811
+ return ID2SYM(rb_intern("router"));
812
+ case Z_WHATAMI_PEER:
813
+ return ID2SYM(rb_intern("peer"));
814
+ case Z_WHATAMI_CLIENT:
815
+ return ID2SYM(rb_intern("client"));
601
816
  }
602
- return zq;
817
+ return Qnil;
603
818
  }
604
819
 
605
- /* Wraps the query (moved in) in a Query object. */
606
- static VALUE zrb_query_wrap(z_owned_query_t *q) {
607
- zrb_query *zq;
608
- VALUE obj = TypedData_Make_Struct(cQuery, zrb_query, &zrb_query_type, zq);
609
- zq->query = *q;
610
- zq->live = true;
611
- z_internal_query_null(q);
612
- return obj;
820
+ static VALUE zrb_reliability_sym(int r) {
821
+ return ID2SYM(rb_intern(r == Z_RELIABILITY_BEST_EFFORT ? "best_effort" : "reliable"));
613
822
  }
614
823
 
615
- static VALUE zrb_query_yield_body(VALUE obj) { return rb_yield(obj); }
824
+ static VALUE zrb_strs_value(const zev *e) {
825
+ VALUE a = rb_ary_new_capa((long)e->nstrs);
826
+ for (size_t i = 0; i < e->nstrs; i++) {
827
+ rb_ary_push(a, zrb_cstr_or_nil(e->strs[i]));
828
+ }
829
+ return a;
830
+ }
616
831
 
617
- static VALUE zrb_query_yield_ensure(VALUE obj) {
618
- zrb_query_finish(zrb_query_get(obj));
832
+ /* event: true for a listener (adds kind), false for a snapshot. */
833
+ static VALUE zev_to_ruby(zev_kind kind, const zev *e, bool event) {
834
+ VALUE h = rb_hash_new();
835
+ switch (kind) {
836
+ case ZEV_MATCHING:
837
+ return e->flag ? Qtrue : Qfalse;
838
+ case ZEV_TRANSPORT:
839
+ if (event) {
840
+ zrb_hset(h, "kind", ID2SYM(rb_intern(e->flag ? "added" : "removed")));
841
+ }
842
+ zrb_hset(h, "zid", zrb_zid_value(&e->zid));
843
+ zrb_hset(h, "whatami", zrb_whatami_sym(e->whatami));
844
+ zrb_hset(h, "qos", e->qos ? Qtrue : Qfalse);
845
+ zrb_hset(h, "multicast", e->multicast ? Qtrue : Qfalse);
846
+ return zrb_new_value(event ? "TransportEvent" : "Transport", h);
847
+ case ZEV_LINK:
848
+ if (event) {
849
+ zrb_hset(h, "kind", ID2SYM(rb_intern(e->flag ? "added" : "removed")));
850
+ }
851
+ zrb_hset(h, "zid", zrb_zid_value(&e->zid));
852
+ zrb_hset(h, "src", zrb_cstr_or_nil(e->src));
853
+ zrb_hset(h, "dst", zrb_cstr_or_nil(e->dst));
854
+ zrb_hset(h, "mtu", UINT2NUM(e->mtu));
855
+ zrb_hset(h, "streamed", e->streamed ? Qtrue : Qfalse);
856
+ zrb_hset(h, "reliability", e->has_reliability ? zrb_reliability_sym(e->reliability) : Qnil);
857
+ zrb_hset(h, "interfaces", zrb_strs_value(e));
858
+ zrb_hset(h, "group", (e->group && *e->group) ? zrb_cstr_or_nil(e->group) : Qnil);
859
+ zrb_hset(h, "auth_identifier", (e->auth && *e->auth) ? zrb_cstr_or_nil(e->auth) : Qnil);
860
+ return zrb_new_value(event ? "LinkEvent" : "Link", h);
861
+ case ZEV_MISS:
862
+ zrb_hset(h, "source_zid", zrb_zid_value(&e->zid));
863
+ zrb_hset(h, "source_eid", UINT2NUM(e->eid));
864
+ zrb_hset(h, "count", UINT2NUM(e->nb));
865
+ return zrb_new_value("Miss", h);
866
+ case ZEV_HELLO:
867
+ zrb_hset(h, "zid", zrb_zid_value(&e->zid));
868
+ zrb_hset(h, "whatami", zrb_whatami_sym(e->whatami));
869
+ zrb_hset(h, "locators", zrb_strs_value(e));
870
+ return zrb_new_value("Hello", h);
871
+ }
619
872
  return Qnil;
620
873
  }
621
874
 
622
- /* qa.each_pending { |q| ... } -> Integer (queries taken). Each query is
623
- * finished when the block returns (also when it raises).
624
- * qa.each_pending -> Array of Query; each stays open until Query#finish or
625
- * garbage collection. */
626
- static VALUE zrb_qable_each_pending(VALUE self) {
627
- zrb_qable *q = zrb_qable_get(self);
875
+ /* Takes what is queued now, oldest first; yields each, or returns them. */
876
+ static VALUE zevq_each_pending(zevq *q, bool event) {
628
877
  bool collect = !rb_block_given_p();
629
878
  VALUE out = collect ? rb_ary_new() : Qnil;
630
879
  long taken = 0;
631
- unsigned todo = atomic_load(&q->ch->queued);
880
+ unsigned todo = atomic_load(&q->queued);
632
881
  while (todo > 0) {
633
882
  todo--;
634
- z_owned_query_t oq;
635
- if (zch_take_query(q->ch, &oq) != Z_OK) {
883
+ zev *e = zevq_take(q);
884
+ if (e == NULL) {
636
885
  break;
637
886
  }
638
- VALUE obj = zrb_query_wrap(&oq);
887
+ VALUE v = zev_to_ruby(q->kind, e, event);
888
+ zev_free(e);
639
889
  taken++;
640
890
  if (collect) {
641
- rb_ary_push(out, obj);
891
+ rb_ary_push(out, v);
642
892
  } else {
643
- rb_ensure(zrb_query_yield_body, obj, zrb_query_yield_ensure, obj);
893
+ rb_yield(v);
644
894
  }
645
895
  }
646
896
  return collect ? out : LONG2NUM(taken);
647
897
  }
648
898
 
649
- static VALUE zrb_qable_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->queued)); }
650
- static VALUE zrb_qable_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->received)); }
651
- static VALUE zrb_qable_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->dropped)); }
899
+ /* ------------------------------------------------------------ options */
652
900
 
653
- static VALUE zrb_qable_close(VALUE self) {
654
- zrb_qable_detach(zrb_qable_get(self));
655
- return Qnil;
901
+ /* Keyword arguments of the calls that send (put, delete, publishers,
902
+ * replies, queriers). -1: not given (zenoh-c's default). */
903
+ typedef struct {
904
+ VALUE attachment; /* nil or String */
905
+ VALUE encoding; /* nil or String */
906
+ VALUE timestamp; /* nil, true or a Timestamp */
907
+ VALUE payload; /* nil or String */
908
+ int priority;
909
+ int congestion_control;
910
+ int express;
911
+ int reliability;
912
+ int destination;
913
+ int accept_replies;
914
+ VALUE target, consolidation, timeout;
915
+ bool has_target, has_consolidation, has_timeout;
916
+ } zrb_opts;
917
+
918
+ static int zrb_priority_arg(VALUE v) {
919
+ if (RB_INTEGER_TYPE_P(v)) {
920
+ int p = NUM2INT(v);
921
+ if (p < Z_PRIORITY_REAL_TIME || p > Z_PRIORITY_BACKGROUND) {
922
+ rb_raise(rb_eArgError, "priority must be 1..7");
923
+ }
924
+ return p;
925
+ }
926
+ static const char *const names[] = {"real_time", "interactive_high", "interactive_low", "data_high",
927
+ "data", "data_low", "background"};
928
+ ID id = zrb_sym_id(v);
929
+ for (int i = 0; i < 7; i++) {
930
+ if (id == rb_intern(names[i])) {
931
+ return i + 1;
932
+ }
933
+ }
934
+ rb_raise(rb_eArgError,
935
+ "priority must be :real_time, :interactive_high, :interactive_low, :data_high, :data, :data_low, "
936
+ ":background or 1..7");
937
+ return 0;
656
938
  }
657
939
 
658
- static VALUE zrb_qable_closed_p(VALUE self) { return zrb_qable_get(self)->declared ? Qfalse : Qtrue; }
940
+ static VALUE zrb_priority_sym(int p) {
941
+ static const char *const names[] = {"real_time", "interactive_high", "interactive_low", "data_high",
942
+ "data", "data_low", "background"};
943
+ if (p < 1 || p > 7) {
944
+ return Qnil;
945
+ }
946
+ return ID2SYM(rb_intern(names[p - 1]));
947
+ }
659
948
 
660
- static VALUE zrb_query_key(VALUE self) {
661
- zrb_query *zq = zrb_query_get_live(self);
662
- return zrb_key_str(z_query_keyexpr(z_loan(zq->query)));
949
+ static int zrb_cc_arg(VALUE v) {
950
+ ID id = zrb_sym_id(v);
951
+ if (id == rb_intern("drop")) {
952
+ return Z_CONGESTION_CONTROL_DROP;
953
+ }
954
+ if (id == rb_intern("block")) {
955
+ return Z_CONGESTION_CONTROL_BLOCK;
956
+ }
957
+ if (id == rb_intern("block_first")) {
958
+ return Z_CONGESTION_CONTROL_BLOCK_FIRST;
959
+ }
960
+ rb_raise(rb_eArgError, "congestion_control must be :drop, :block or :block_first");
961
+ return 0;
663
962
  }
664
963
 
665
- static VALUE zrb_query_params(VALUE self) {
666
- zrb_query *zq = zrb_query_get_live(self);
667
- z_view_string_t ps;
668
- z_query_parameters(z_loan(zq->query), &ps);
669
- return zrb_str_from_view(z_loan(ps));
964
+ static VALUE zrb_cc_sym(int c) {
965
+ switch (c) {
966
+ case Z_CONGESTION_CONTROL_BLOCK:
967
+ return ID2SYM(rb_intern("block"));
968
+ case Z_CONGESTION_CONTROL_DROP:
969
+ return ID2SYM(rb_intern("drop"));
970
+ case Z_CONGESTION_CONTROL_BLOCK_FIRST:
971
+ return ID2SYM(rb_intern("block_first"));
972
+ }
973
+ return Qnil;
670
974
  }
671
975
 
672
- static VALUE zrb_query_payload(VALUE self) {
673
- zrb_query *zq = zrb_query_get_live(self);
674
- const z_loaned_bytes_t *b = z_query_payload(z_loan(zq->query));
675
- if (b == NULL) {
676
- return rb_str_new(NULL, 0);
976
+ static int zrb_reliability_arg(VALUE v) {
977
+ ID id = zrb_sym_id(v);
978
+ if (id == rb_intern("reliable")) {
979
+ return Z_RELIABILITY_RELIABLE;
677
980
  }
678
- return zrb_str_from_bytes(b);
981
+ if (id == rb_intern("best_effort")) {
982
+ return Z_RELIABILITY_BEST_EFFORT;
983
+ }
984
+ rb_raise(rb_eArgError, "reliability must be :reliable or :best_effort");
985
+ return 0;
679
986
  }
680
987
 
681
- static VALUE zrb_query_attachment(VALUE self) {
682
- zrb_query *zq = zrb_query_get_live(self);
683
- return zrb_attachment_value(z_query_attachment(z_loan(zq->query)));
988
+ static int zrb_locality_arg(VALUE v) {
989
+ ID id = zrb_sym_id(v);
990
+ if (id == rb_intern("any")) {
991
+ return Z_LOCALITY_ANY;
992
+ }
993
+ if (id == rb_intern("remote")) {
994
+ return Z_LOCALITY_REMOTE;
995
+ }
996
+ if (id == rb_intern("session_local")) {
997
+ return Z_LOCALITY_SESSION_LOCAL;
998
+ }
999
+ rb_raise(rb_eArgError, "allowed_destination must be :any, :remote or :session_local");
1000
+ return 0;
684
1001
  }
685
1002
 
686
- /* q.reply(payload, attachment: nil) / q.reply(key, payload, attachment: nil)
687
- * -> nil. The key defaults to the query's key; it must match the query's key
688
- * expression. May be called more than once before the query is finished. */
689
- static VALUE zrb_query_reply(int argc, VALUE *argv, VALUE self) {
690
- VALUE a1, a2 = Qnil, opts = Qnil;
691
- int n = rb_scan_args(argc, argv, "11:", &a1, &a2, &opts);
692
- VALUE kw[1] = {Qundef};
693
- if (!NIL_P(opts)) {
694
- rb_get_kwargs(opts, &id_attachment, 0, 1, kw);
1003
+ static VALUE zrb_str_or_nil_arg(VALUE v, const char *what) {
1004
+ if (v == Qundef || NIL_P(v)) {
1005
+ return Qnil;
695
1006
  }
696
- VALUE att = zrb_kw_attachment(kw[0]);
697
- zrb_query *zq = zrb_query_get_live(self);
698
- VALUE key_v = (n == 1) ? Qnil : a1;
699
- VALUE payload = (n == 1) ? a1 : a2;
700
- if (!RB_TYPE_P(payload, T_STRING)) {
701
- rb_raise(rb_eTypeError, "payload must be a String");
1007
+ if (!RB_TYPE_P(v, T_STRING)) {
1008
+ rb_raise(rb_eTypeError, "%s must be a String or nil", what);
702
1009
  }
703
- z_view_keyexpr_t ke;
704
- const z_loaned_keyexpr_t *kp;
705
- if (NIL_P(key_v)) {
706
- kp = z_query_keyexpr(z_loan(zq->query));
707
- } else {
708
- zrb_view_key(&ke, StringValueCStr(key_v));
709
- kp = z_loan(ke);
1010
+ return v;
1011
+ }
1012
+
1013
+ static bool zrb_is_timestamp(VALUE v);
1014
+
1015
+ /* names: the keywords the call accepts (unknown ones raise ArgumentError). */
1016
+ static void zrb_opts_parse(VALUE hash, const char *const *names, int n, zrb_opts *o) {
1017
+ o->attachment = o->encoding = o->timestamp = o->payload = Qnil;
1018
+ o->priority = o->congestion_control = o->express = o->reliability = o->destination = o->accept_replies = -1;
1019
+ o->target = o->consolidation = o->timeout = Qnil;
1020
+ o->has_target = o->has_consolidation = o->has_timeout = false;
1021
+ if (NIL_P(hash)) {
1022
+ return;
710
1023
  }
711
- z_query_reply_options_t ro;
712
- z_query_reply_options_default(&ro);
713
- z_owned_bytes_t att_bytes;
714
- if (!NIL_P(att)) {
715
- zrb_bytes_from_str(&att_bytes, att, "attachment");
716
- ro.attachment = z_move(att_bytes);
1024
+ ID ids[16];
1025
+ VALUE kw[16];
1026
+ for (int i = 0; i < n; i++) {
1027
+ ids[i] = rb_intern(names[i]);
717
1028
  }
718
- z_owned_bytes_t bytes;
719
- if (z_bytes_copy_from_buf(&bytes, (const uint8_t *)RSTRING_PTR(payload), (size_t)RSTRING_LEN(payload)) != Z_OK) {
720
- if (!NIL_P(att)) {
721
- z_drop(z_move(att_bytes));
1029
+ rb_get_kwargs(hash, ids, 0, n, kw);
1030
+ for (int i = 0; i < n; i++) {
1031
+ VALUE v = kw[i];
1032
+ if (v == Qundef) {
1033
+ continue;
1034
+ }
1035
+ const char *k = names[i];
1036
+ if (strcmp(k, "attachment") == 0) {
1037
+ o->attachment = zrb_kw_attachment(v);
1038
+ } else if (strcmp(k, "payload") == 0) {
1039
+ o->payload = zrb_str_or_nil_arg(v, "payload");
1040
+ } else if (strcmp(k, "encoding") == 0) {
1041
+ if (!NIL_P(v)) {
1042
+ o->encoding = rb_String(v);
1043
+ }
1044
+ } else if (strcmp(k, "timestamp") == 0) {
1045
+ if (NIL_P(v) || v == Qfalse) {
1046
+ o->timestamp = Qnil;
1047
+ } else if (v == Qtrue || zrb_is_timestamp(v)) {
1048
+ o->timestamp = v;
1049
+ } else {
1050
+ rb_raise(rb_eTypeError, "timestamp must be true, nil or an Asterism::Zenoh::Timestamp");
1051
+ }
1052
+ } else if (NIL_P(v)) {
1053
+ /* nil: zenoh-c's default */
1054
+ } else if (strcmp(k, "priority") == 0) {
1055
+ o->priority = zrb_priority_arg(v);
1056
+ } else if (strcmp(k, "congestion_control") == 0) {
1057
+ o->congestion_control = zrb_cc_arg(v);
1058
+ } else if (strcmp(k, "express") == 0) {
1059
+ o->express = RTEST(v) ? 1 : 0;
1060
+ } else if (strcmp(k, "reliability") == 0) {
1061
+ o->reliability = zrb_reliability_arg(v);
1062
+ } else if (strcmp(k, "allowed_destination") == 0) {
1063
+ o->destination = zrb_locality_arg(v);
1064
+ } else if (strcmp(k, "accept_replies") == 0) {
1065
+ ID id = zrb_sym_id(v);
1066
+ if (id == rb_intern("any")) {
1067
+ o->accept_replies = Z_REPLY_KEYEXPR_ANY;
1068
+ } else if (id == rb_intern("matching_query")) {
1069
+ o->accept_replies = Z_REPLY_KEYEXPR_MATCHING_QUERY;
1070
+ } else {
1071
+ rb_raise(rb_eArgError, "accept_replies must be :matching_query or :any");
1072
+ }
1073
+ } else if (strcmp(k, "target") == 0) {
1074
+ o->target = v;
1075
+ o->has_target = true;
1076
+ } else if (strcmp(k, "consolidation") == 0) {
1077
+ o->consolidation = v;
1078
+ o->has_consolidation = true;
1079
+ } else if (strcmp(k, "timeout_ms") == 0) {
1080
+ o->timeout = v;
1081
+ o->has_timeout = true;
722
1082
  }
723
- rb_raise(eZenohError, "cannot allocate the payload");
724
1083
  }
725
- z_result_t ret = z_query_reply(z_loan(zq->query), kp, z_move(bytes), &ro);
726
- if (ret != Z_OK) {
727
- rb_raise(eZenohError, "reply failed (%d)", (int)ret);
1084
+ }
1085
+
1086
+ /* ----------------------------------------------------------- encodings */
1087
+
1088
+ static VALUE zrb_encoding_value(const z_loaned_encoding_t *e) {
1089
+ if (e == NULL) {
1090
+ return Qnil;
728
1091
  }
729
- return Qnil;
1092
+ z_owned_string_t s;
1093
+ z_encoding_to_string(e, &s);
1094
+ VALUE out = zrb_str_from_view(z_loan(s));
1095
+ z_drop(z_move(s));
1096
+ return out;
730
1097
  }
731
1098
 
732
- static VALUE zrb_query_finish_m(VALUE self) {
733
- zrb_query_finish(zrb_query_get(self));
734
- return Qnil;
1099
+ /* An owned encoding from a String (already checked). false when there is
1100
+ * none to send. */
1101
+ static bool zrb_encoding_make(z_owned_encoding_t *out, VALUE str) {
1102
+ if (NIL_P(str)) {
1103
+ return false;
1104
+ }
1105
+ if (z_encoding_from_str(out, StringValueCStr(str)) != Z_OK) {
1106
+ rb_raise(rb_eArgError, "invalid encoding: %" PRIsVALUE, str);
1107
+ }
1108
+ return true;
735
1109
  }
736
1110
 
737
- static VALUE zrb_query_finished_p(VALUE self) { return zrb_query_get(self)->live ? Qfalse : Qtrue; }
1111
+ /* ---------------------------------------------------------- timestamps */
738
1112
 
739
- /* ------------------------------------------------------------------ get */
1113
+ typedef struct {
1114
+ z_timestamp_t ts;
1115
+ } zrb_ts;
740
1116
 
741
- static void zrb_get_free(void *p) {
742
- zrb_get *g = (zrb_get *)p;
743
- zch_unref(g->ch); /* zenoh-c may still hold it until the get finishes */
744
- xfree(g);
1117
+ static size_t zrb_ts_size(const void *p) { return sizeof(zrb_ts); }
1118
+
1119
+ static const rb_data_type_t zrb_ts_type = {
1120
+ "Asterism::Zenoh::Timestamp", {NULL, RUBY_TYPED_DEFAULT_FREE, zrb_ts_size}, NULL, NULL, RUBY_TYPED_FREE_IMMEDIATELY};
1121
+
1122
+ static bool zrb_is_timestamp(VALUE v) { return rb_typeddata_is_kind_of(v, &zrb_ts_type); }
1123
+
1124
+ static VALUE zrb_ts_wrap(const z_timestamp_t *ts) {
1125
+ zrb_ts *t;
1126
+ VALUE obj = TypedData_Make_Struct(cTimestamp, zrb_ts, &zrb_ts_type, t);
1127
+ t->ts = *ts;
1128
+ return obj;
745
1129
  }
746
1130
 
747
- static size_t zrb_get_size(const void *p) { return sizeof(zrb_get); }
1131
+ static zrb_ts *zrb_ts_get(VALUE self) {
1132
+ zrb_ts *t;
1133
+ TypedData_Get_Struct(self, zrb_ts, &zrb_ts_type, t);
1134
+ return t;
1135
+ }
748
1136
 
749
- static const rb_data_type_t zrb_get_type = {"Asterism::Zenoh::Get", {NULL, zrb_get_free, zrb_get_size}, NULL, NULL, 0};
1137
+ /* NTP64 of zenoh's HLC: seconds since the UNIX epoch in the upper 32 bits,
1138
+ * the fraction of a second in the lower 32. */
1139
+ static VALUE zrb_ts_ntp64(VALUE self) { return ULL2NUM(z_timestamp_ntp64_time(&zrb_ts_get(self)->ts)); }
750
1140
 
751
- static zrb_get *zrb_get_get(VALUE self) {
752
- zrb_get *g;
753
- TypedData_Get_Struct(self, zrb_get, &zrb_get_type, g);
754
- return g;
1141
+ static VALUE zrb_ts_id(VALUE self) {
1142
+ z_id_t id = z_timestamp_id(&zrb_ts_get(self)->ts);
1143
+ return zrb_zid_value(&id);
755
1144
  }
756
1145
 
757
- static VALUE zrb_get_new(zrb_get **out) {
758
- zrb_get *g;
759
- VALUE obj = TypedData_Make_Struct(cGet, zrb_get, &zrb_get_type, g);
760
- g->ch = zch_new(ZCH_REPLY, ZRB_DEFAULT_DEPTH);
761
- *out = g;
762
- return obj;
1146
+ static VALUE zrb_ts_to_time(VALUE self) {
1147
+ uint64_t t = z_timestamp_ntp64_time(&zrb_ts_get(self)->ts);
1148
+ time_t sec = (time_t)(t >> 32);
1149
+ long nsec = (long)(((t & 0xffffffffULL) * 1000000000ULL) >> 32);
1150
+ return rb_time_nano_new(sec, nsec);
763
1151
  }
764
1152
 
765
- /* g.each_reply { |key, payload, attachment| ... } -> Integer; without a
766
- * block, Array of [key, payload, attachment]. Error replies are counted
767
- * (errors), not yielded. */
768
- static VALUE zrb_get_each_reply(VALUE self) {
769
- zrb_get *g = zrb_get_get(self);
770
- bool collect = !rb_block_given_p();
771
- VALUE out = collect ? rb_ary_new() : Qnil;
772
- long taken = 0;
773
- unsigned todo = atomic_load(&g->ch->queued);
774
- while (todo > 0) {
775
- todo--;
776
- z_owned_reply_t r;
777
- if (zch_take_reply(g->ch, &r) != Z_OK) {
778
- break;
779
- }
780
- VALUE vals[3];
781
- const z_loaned_sample_t *sm = z_reply_ok(z_loan(r));
782
- vals[0] = zrb_key_str(z_sample_keyexpr(sm));
783
- vals[1] = zrb_str_from_bytes(z_sample_payload(sm));
784
- vals[2] = zrb_attachment_value(z_sample_attachment(sm));
785
- z_drop(z_move(r));
786
- taken++;
787
- if (collect) {
788
- rb_ary_push(out, rb_ary_new_from_values(3, vals));
789
- } else {
790
- rb_yield_values2(3, vals);
1153
+ static VALUE zrb_ts_cmp(VALUE self, VALUE other) {
1154
+ if (!zrb_is_timestamp(other)) {
1155
+ return Qnil;
1156
+ }
1157
+ const z_timestamp_t *a = &zrb_ts_get(self)->ts, *b = &zrb_ts_get(other)->ts;
1158
+ uint64_t ta = z_timestamp_ntp64_time(a), tb = z_timestamp_ntp64_time(b);
1159
+ if (ta != tb) {
1160
+ return INT2FIX(ta < tb ? -1 : 1);
1161
+ }
1162
+ z_id_t ia = z_timestamp_id(a), ib = z_timestamp_id(b);
1163
+ /* LSB first: compare from the most significant byte. */
1164
+ for (int i = 15; i >= 0; i--) {
1165
+ if (ia.id[i] != ib.id[i]) {
1166
+ return INT2FIX(ia.id[i] < ib.id[i] ? -1 : 1);
791
1167
  }
792
1168
  }
793
- return collect ? out : LONG2NUM(taken);
1169
+ return INT2FIX(0);
794
1170
  }
795
1171
 
796
- static VALUE zrb_get_done_p(VALUE self) { return atomic_load(&zrb_get_get(self)->ch->done) ? Qtrue : Qfalse; }
797
- static VALUE zrb_get_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->queued)); }
798
- static VALUE zrb_get_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->received)); }
799
- static VALUE zrb_get_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->dropped)); }
800
- static VALUE zrb_get_errors(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->errors)); }
1172
+ static VALUE zrb_ts_eql(VALUE self, VALUE other) {
1173
+ VALUE c = zrb_ts_cmp(self, other);
1174
+ return (!NIL_P(c) && FIX2INT(c) == 0) ? Qtrue : Qfalse;
1175
+ }
801
1176
 
802
- /* ---------------------------------------------------------------- token */
1177
+ static VALUE zrb_ts_hash(VALUE self) {
1178
+ return rb_funcall(rb_ary_new_from_args(2, zrb_ts_ntp64(self), zrb_ts_id(self)), rb_intern("hash"), 0);
1179
+ }
803
1180
 
804
- static void zrb_token_detach(zrb_token *t) {
805
- if (t->declared) {
806
- z_drop(z_move(t->token));
807
- t->declared = false;
808
- }
809
- if (t->owner != NULL) {
810
- zrb_token **pp = &t->owner->tokens;
811
- while (*pp != NULL) {
812
- if (*pp == t) {
813
- *pp = t->next;
814
- break;
815
- }
816
- pp = &(*pp)->next;
817
- }
818
- t->owner = NULL;
819
- t->next = NULL;
820
- }
1181
+ /* "<ntp64>/<id>" as zenoh prints it, with the time in seconds. */
1182
+ static VALUE zrb_ts_to_s(VALUE self) {
1183
+ VALUE t = zrb_ts_to_time(self);
1184
+ VALUE iso = rb_funcall(rb_funcall(t, rb_intern("utc"), 0), rb_intern("strftime"), 1,
1185
+ rb_str_new_cstr("%Y-%m-%dT%H:%M:%S.%9NZ"));
1186
+ return rb_sprintf("%" PRIsVALUE "/%" PRIsVALUE, iso, zrb_ts_id(self));
821
1187
  }
822
1188
 
823
- static void zrb_token_free(void *p) {
824
- zrb_token *t = (zrb_token *)p;
825
- zrb_token_detach(t);
826
- xfree(t);
1189
+ static VALUE zrb_ts_inspect(VALUE self) { return rb_sprintf("#<Asterism::Zenoh::Timestamp %" PRIsVALUE ">", zrb_ts_to_s(self)); }
1190
+
1191
+ /* -------------------------------------------------------------- samples */
1192
+
1193
+ /* A sample as an Asterism::Zenoh::Sample (key, payload, attachment, kind,
1194
+ * encoding, timestamp, priority, congestion_control, express,
1195
+ * reliability, source_zid). */
1196
+ static VALUE zrb_sample_value(const z_loaned_sample_t *s) {
1197
+ VALUE h = rb_hash_new();
1198
+ zrb_hset(h, "key", zrb_key_str(z_sample_keyexpr(s)));
1199
+ zrb_hset(h, "payload", zrb_str_from_bytes(z_sample_payload(s)));
1200
+ zrb_hset(h, "attachment", zrb_attachment_value(z_sample_attachment(s)));
1201
+ zrb_hset(h, "kind", ID2SYM(rb_intern(z_sample_kind(s) == Z_SAMPLE_KIND_DELETE ? "delete" : "put")));
1202
+ zrb_hset(h, "encoding", zrb_encoding_value(z_sample_encoding(s)));
1203
+ const z_timestamp_t *ts = z_sample_timestamp(s);
1204
+ zrb_hset(h, "timestamp", ts != NULL ? zrb_ts_wrap(ts) : Qnil);
1205
+ zrb_hset(h, "priority", zrb_priority_sym((int)z_sample_priority(s)));
1206
+ zrb_hset(h, "congestion_control", zrb_cc_sym((int)z_sample_congestion_control(s)));
1207
+ zrb_hset(h, "express", z_sample_express(s) ? Qtrue : Qfalse);
1208
+ zrb_hset(h, "reliability", zrb_reliability_sym((int)z_sample_reliability(s)));
1209
+ const z_source_info_t *si = z_sample_source_info(s);
1210
+ if (si != NULL) {
1211
+ z_entity_global_id_t gid = z_source_info_id(si);
1212
+ z_id_t zid = z_entity_global_id_zid(&gid);
1213
+ zrb_hset(h, "source_zid", zrb_zid_value(&zid));
1214
+ }
1215
+ return zrb_new_value("Sample", h);
827
1216
  }
828
1217
 
829
- static size_t zrb_token_size(const void *p) { return sizeof(zrb_token); }
1218
+ /* A reply as an Asterism::Zenoh::Reply: an answer (the sample's fields)
1219
+ * or an error (error: true, payload and encoding of the error). */
1220
+ static VALUE zrb_reply_value(const z_loaned_reply_t *r) {
1221
+ VALUE h = rb_hash_new();
1222
+ if (z_reply_is_ok(r)) {
1223
+ const z_loaned_sample_t *s = z_reply_ok(r);
1224
+ zrb_hset(h, "key", zrb_key_str(z_sample_keyexpr(s)));
1225
+ zrb_hset(h, "payload", zrb_str_from_bytes(z_sample_payload(s)));
1226
+ zrb_hset(h, "attachment", zrb_attachment_value(z_sample_attachment(s)));
1227
+ zrb_hset(h, "kind", ID2SYM(rb_intern(z_sample_kind(s) == Z_SAMPLE_KIND_DELETE ? "delete" : "put")));
1228
+ zrb_hset(h, "encoding", zrb_encoding_value(z_sample_encoding(s)));
1229
+ const z_timestamp_t *ts = z_sample_timestamp(s);
1230
+ zrb_hset(h, "timestamp", ts != NULL ? zrb_ts_wrap(ts) : Qnil);
1231
+ zrb_hset(h, "error", Qfalse);
1232
+ } else {
1233
+ const z_loaned_reply_err_t *e = z_reply_err(r);
1234
+ zrb_hset(h, "key", Qnil);
1235
+ zrb_hset(h, "payload", zrb_str_from_bytes(z_reply_err_payload(e)));
1236
+ zrb_hset(h, "encoding", zrb_encoding_value(z_reply_err_encoding(e)));
1237
+ zrb_hset(h, "error", Qtrue);
1238
+ }
1239
+ z_entity_global_id_t gid;
1240
+ if (z_reply_replier_id(r, &gid)) {
1241
+ z_id_t zid = z_entity_global_id_zid(&gid);
1242
+ zrb_hset(h, "replier_zid", zrb_zid_value(&zid));
1243
+ }
1244
+ return zrb_new_value("Reply", h);
1245
+ }
830
1246
 
831
- static const rb_data_type_t zrb_token_type = {
832
- "Asterism::Zenoh::LivelinessToken", {NULL, zrb_token_free, zrb_token_size}, NULL, NULL, 0};
1247
+ /* -------------------------------------------------------- key expressions */
833
1248
 
834
- static zrb_token *zrb_token_get(VALUE self) {
835
- zrb_token *t;
836
- TypedData_Get_Struct(self, zrb_token, &zrb_token_type, t);
837
- return t;
1249
+ typedef struct {
1250
+ zrb_ent ent; /* declared ones only */
1251
+ z_owned_keyexpr_t ke; /* always valid */
1252
+ z_owned_keyexpr_t decl; /* valid while ent.declared */
1253
+ } zrb_ke;
1254
+
1255
+ static void zrb_ke_undeclare(zrb_ent *e) {
1256
+ zrb_ke *k = (zrb_ke *)e;
1257
+ if (e->owner != NULL && e->owner->live) {
1258
+ z_undeclare_keyexpr(z_loan(e->owner->session), z_move(k->decl));
1259
+ } else {
1260
+ z_drop(z_move(k->decl));
1261
+ }
838
1262
  }
839
1263
 
840
- static VALUE zrb_token_close(VALUE self) {
841
- zrb_token_detach(zrb_token_get(self));
842
- return Qnil;
1264
+ static void zrb_ke_free(void *p) {
1265
+ zrb_ke *k = (zrb_ke *)p;
1266
+ zrb_ent_detach(&k->ent);
1267
+ z_drop(z_move(k->ke));
1268
+ xfree(k);
843
1269
  }
844
1270
 
845
- static VALUE zrb_token_closed_p(VALUE self) { return zrb_token_get(self)->declared ? Qfalse : Qtrue; }
1271
+ static size_t zrb_ke_size(const void *p) { return sizeof(zrb_ke); }
846
1272
 
847
- /* -------------------------------------------------------------- session */
1273
+ static const rb_data_type_t zrb_ke_type = {"Asterism::Zenoh::KeyExpr", {NULL, zrb_ke_free, zrb_ke_size}, NULL, NULL, 0};
848
1274
 
849
- /* Undeclares everything the session still has. Holds the GVL (the lists
850
- * are only touched with it). */
851
- static void zrb_session_detach_all(zrb_session *z) {
852
- while (z->qables != NULL) {
853
- zrb_qable_detach(z->qables); /* unlinks itself */
1275
+ static zrb_ke *zrb_ke_of(VALUE v) {
1276
+ if (!rb_typeddata_is_kind_of(v, &zrb_ke_type)) {
1277
+ return NULL;
854
1278
  }
855
- while (z->tokens != NULL) {
856
- zrb_token_detach(z->tokens);
1279
+ return (zrb_ke *)RTYPEDDATA_DATA(v);
1280
+ }
1281
+
1282
+ static const z_loaned_keyexpr_t *zrb_ke_loan(zrb_ke *k) { return k->ent.declared ? z_loan(k->decl) : z_loan(k->ke); }
1283
+
1284
+ /* A key argument (String or KeyExpr) as a loaned key expression; view is
1285
+ * the storage for a String. */
1286
+ static const z_loaned_keyexpr_t *zrb_key_loan(VALUE v, z_view_keyexpr_t *view) {
1287
+ zrb_ke *k = zrb_ke_of(v);
1288
+ if (k != NULL) {
1289
+ return zrb_ke_loan(k);
857
1290
  }
858
- while (z->subs != NULL) {
859
- zrb_sub_detach(z->subs);
1291
+ zrb_view_key(view, StringValueCStr(v));
1292
+ return z_loan(*view);
1293
+ }
1294
+
1295
+ /* An owned copy of a key argument, for calls without the GVL. A declared
1296
+ * KeyExpr keeps its declaration. */
1297
+ static void zrb_key_owned(VALUE v, z_owned_keyexpr_t *out) {
1298
+ zrb_ke *k = zrb_ke_of(v);
1299
+ if (k != NULL) {
1300
+ z_keyexpr_clone(out, zrb_ke_loan(k));
1301
+ return;
860
1302
  }
1303
+ zrb_owned_key(out, StringValueCStr(v));
861
1304
  }
862
1305
 
863
- /* Closes the zenoh-c session. Without the GVL when called from Ruby
864
- * methods (it waits for zenoh's tasks), with it from the GC. */
865
- static void *zrb_session_close_nogvl(void *p) {
866
- zrb_session *z = (zrb_session *)p;
867
- pthread_mutex_lock(&z->op_lock);
868
- if (z->live) {
869
- z->live = false;
870
- z_close(z_loan_mut(z->session), NULL);
871
- z_drop(z_move(z->session));
1306
+ /* The key argument as a String (to keep on the Ruby objects). */
1307
+ static VALUE zrb_key_string(VALUE v) {
1308
+ zrb_ke *k = zrb_ke_of(v);
1309
+ if (k != NULL) {
1310
+ return zrb_key_str(z_loan(k->ke));
872
1311
  }
873
- pthread_mutex_unlock(&z->op_lock);
874
- return NULL;
1312
+ StringValueCStr(v);
1313
+ return v;
875
1314
  }
876
1315
 
877
- static void zrb_session_shutdown(zrb_session *z, bool with_gvl_release) {
878
- zrb_session_detach_all(z);
879
- if (!z->open) {
880
- return;
1316
+ static VALUE zrb_ke_wrap_owned(z_owned_keyexpr_t *ke) {
1317
+ zrb_ke *k;
1318
+ VALUE obj = TypedData_Make_Struct(cKeyExpr, zrb_ke, &zrb_ke_type, k);
1319
+ k->ke = *ke;
1320
+ z_internal_keyexpr_null(ke);
1321
+ z_internal_keyexpr_null(&k->decl);
1322
+ return obj;
1323
+ }
1324
+
1325
+ /* KeyExpr.new(str, autocanonize: false). Raises ArgumentError for a key
1326
+ * expression that is not valid (or not canonical, without autocanonize). */
1327
+ static VALUE zrb_ke_s_new(int argc, VALUE *argv, VALUE klass) {
1328
+ VALUE str, opts = Qnil;
1329
+ rb_scan_args(argc, argv, "1:", &str, &opts);
1330
+ VALUE kw[1] = {Qundef};
1331
+ if (!NIL_P(opts)) {
1332
+ ID ids[1] = {rb_intern("autocanonize")};
1333
+ rb_get_kwargs(opts, ids, 0, 1, kw);
881
1334
  }
882
- /* Closed for Ruby before the GVL is released: another Ruby thread that
883
- * runs while zenoh-c closes the session sees it closed and does not
884
- * touch the session any more (the calls without the GVL check live
885
- * under op_lock instead). */
886
- z->open = false;
887
- if (with_gvl_release) {
888
- rb_thread_call_without_gvl(zrb_session_close_nogvl, z, RUBY_UBF_IO, NULL);
1335
+ zrb_ke *src = zrb_ke_of(str);
1336
+ z_owned_keyexpr_t ke;
1337
+ if (src != NULL) {
1338
+ z_keyexpr_clone(&ke, z_loan(src->ke));
889
1339
  } else {
890
- zrb_session_close_nogvl(z);
1340
+ const char *s = StringValueCStr(str);
1341
+ z_result_t r = (kw[0] != Qundef && RTEST(kw[0])) ? z_keyexpr_from_str_autocanonize(&ke, s)
1342
+ : z_keyexpr_from_str(&ke, s);
1343
+ if (r != Z_OK) {
1344
+ rb_raise(rb_eArgError, "invalid key expression: %s", s);
1345
+ }
891
1346
  }
1347
+ return zrb_ke_wrap_owned(&ke);
892
1348
  }
893
1349
 
894
- static void zrb_session_free(void *p) {
895
- zrb_session *z = (zrb_session *)p;
896
- zrb_session_shutdown(z, false);
897
- pthread_mutex_destroy(&z->op_lock);
898
- xfree(z);
1350
+ static zrb_ke *zrb_ke_get(VALUE self) {
1351
+ zrb_ke *k;
1352
+ TypedData_Get_Struct(self, zrb_ke, &zrb_ke_type, k);
1353
+ return k;
899
1354
  }
900
1355
 
901
- static size_t zrb_session_size(const void *p) { return sizeof(zrb_session); }
1356
+ static VALUE zrb_ke_to_s(VALUE self) { return zrb_key_str(z_loan(zrb_ke_get(self)->ke)); }
902
1357
 
903
- static const rb_data_type_t zrb_session_type = {
904
- "Asterism::Zenoh::Session", {NULL, zrb_session_free, zrb_session_size}, NULL, NULL, 0};
1358
+ static VALUE zrb_ke_inspect(VALUE self) {
1359
+ zrb_ke *k = zrb_ke_get(self);
1360
+ return rb_sprintf("#<Asterism::Zenoh::KeyExpr %" PRIsVALUE "%s>", zrb_ke_to_s(self),
1361
+ k->ent.declared ? " (declared)" : "");
1362
+ }
905
1363
 
906
- static zrb_session *zrb_session_get(VALUE self) {
907
- zrb_session *z;
908
- TypedData_Get_Struct(self, zrb_session, &zrb_session_type, z);
909
- return z;
1364
+ static VALUE zrb_ke_intersects_p(VALUE self, VALUE other) {
1365
+ z_view_keyexpr_t v;
1366
+ return z_keyexpr_intersects(z_loan(zrb_ke_get(self)->ke), zrb_key_loan(other, &v)) ? Qtrue : Qfalse;
910
1367
  }
911
1368
 
912
- static void zrb_count_zid(const z_id_t *id, void *ctx) {
913
- (void)id;
914
- (*(int *)ctx)++;
1369
+ static VALUE zrb_ke_includes_p(VALUE self, VALUE other) {
1370
+ z_view_keyexpr_t v;
1371
+ return z_keyexpr_includes(z_loan(zrb_ke_get(self)->ke), zrb_key_loan(other, &v)) ? Qtrue : Qfalse;
915
1372
  }
916
1373
 
917
- /* Routers (client) or peers (peer mode) connected now. */
918
- static int zrb_session_links(zrb_session *z) {
919
- int n = 0;
920
- z_owned_closure_zid_t cb;
921
- z_closure(&cb, zrb_count_zid, NULL, &n);
922
- if (z->peer) {
923
- z_info_peers_zid(z_loan(z->session), z_move(cb));
924
- } else {
925
- z_info_routers_zid(z_loan(z->session), z_move(cb));
1374
+ static VALUE zrb_ke_relation_to(VALUE self, VALUE other) {
1375
+ z_view_keyexpr_t v;
1376
+ switch (z_keyexpr_relation_to(z_loan(zrb_ke_get(self)->ke), zrb_key_loan(other, &v))) {
1377
+ case Z_KEYEXPR_INTERSECTION_LEVEL_DISJOINT:
1378
+ return ID2SYM(rb_intern("disjoint"));
1379
+ case Z_KEYEXPR_INTERSECTION_LEVEL_INTERSECTS:
1380
+ return ID2SYM(rb_intern("intersects"));
1381
+ case Z_KEYEXPR_INTERSECTION_LEVEL_INCLUDES:
1382
+ return ID2SYM(rb_intern("includes"));
1383
+ case Z_KEYEXPR_INTERSECTION_LEVEL_EQUALS:
1384
+ return ID2SYM(rb_intern("equals"));
926
1385
  }
927
- return n;
1386
+ return Qnil;
928
1387
  }
929
1388
 
930
- /* Close the session when its connection can no longer carry it (see the
931
- * comment at the top). Returns true when the session is (now) closed. */
932
- static bool zrb_session_check_link(zrb_session *z) {
933
- if (!z->open) {
934
- return true;
935
- }
936
- if (z_session_is_closed(z_loan(z->session))) {
937
- zrb_session_shutdown(z, true);
938
- return true;
939
- }
940
- if (z->peer && z->listening) {
941
- return false;
1389
+ static VALUE zrb_ke_eq(VALUE self, VALUE other) {
1390
+ if (zrb_ke_of(other) == NULL && !RB_TYPE_P(other, T_STRING)) {
1391
+ return Qfalse;
942
1392
  }
943
- if (zrb_session_links(z) == 0) {
944
- zrb_session_shutdown(z, true);
945
- return true;
1393
+ z_view_keyexpr_t v;
1394
+ if (RB_TYPE_P(other, T_STRING) && z_view_keyexpr_from_str(&v, StringValueCStr(other)) != Z_OK) {
1395
+ return Qfalse;
946
1396
  }
947
- return false;
1397
+ const z_loaned_keyexpr_t *o = RB_TYPE_P(other, T_STRING) ? z_loan(v) : z_loan(zrb_ke_of(other)->ke);
1398
+ return z_keyexpr_equals(z_loan(zrb_ke_get(self)->ke), o) ? Qtrue : Qfalse;
948
1399
  }
949
1400
 
950
- static zrb_session *zrb_session_get_open(VALUE self) {
951
- zrb_session *z = zrb_session_get(self);
952
- if (zrb_session_check_link(z)) {
953
- rb_raise(eZenohError, "session is closed");
1401
+ static VALUE zrb_ke_hash(VALUE self) { return LONG2NUM((long)rb_str_hash(zrb_ke_to_s(self))); }
1402
+
1403
+ /* ke.join(other) -> KeyExpr: "a/b" join "c/d" is "a/b/c/d" (canonized). */
1404
+ static VALUE zrb_ke_join(VALUE self, VALUE other) {
1405
+ z_view_keyexpr_t v;
1406
+ const z_loaned_keyexpr_t *o = zrb_key_loan(other, &v);
1407
+ z_owned_keyexpr_t out;
1408
+ if (z_keyexpr_join(&out, z_loan(zrb_ke_get(self)->ke), o) != Z_OK) {
1409
+ rb_raise(rb_eArgError, "cannot join the key expressions");
954
1410
  }
955
- return z;
1411
+ return zrb_ke_wrap_owned(&out);
956
1412
  }
957
1413
 
958
- /* A JSON5 string literal of s (for the configuration). */
959
- static VALUE zrb_json_str(const char *s) {
960
- VALUE out = rb_str_new_cstr("\"");
961
- for (const char *p = s; *p; p++) {
962
- if (*p == '"' || *p == '\\') {
963
- rb_str_cat(out, "\\", 1);
964
- }
965
- rb_str_cat(out, p, 1);
1414
+ /* ke.concat(str) -> KeyExpr: the string appended as it is ("a/b" concat
1415
+ * "c" is "a/bc"); the result must be a valid key expression. */
1416
+ static VALUE zrb_ke_concat(VALUE self, VALUE str) {
1417
+ StringValue(str);
1418
+ z_owned_keyexpr_t out;
1419
+ if (z_keyexpr_concat(&out, z_loan(zrb_ke_get(self)->ke), RSTRING_PTR(str), (size_t)RSTRING_LEN(str)) != Z_OK) {
1420
+ rb_raise(rb_eArgError, "cannot concatenate %" PRIsVALUE, str);
966
1421
  }
967
- rb_str_cat(out, "\"", 1);
968
- return out;
1422
+ return zrb_ke_wrap_owned(&out);
969
1423
  }
970
1424
 
971
- static bool zrb_config_set(z_owned_config_t *config, const char *key, const char *json5) {
972
- return zc_config_insert_json5(z_loan_mut(*config), key, json5) == Z_OK;
1425
+ static VALUE zrb_ke_declared_p(VALUE self) { return zrb_ke_get(self)->ent.declared ? Qtrue : Qfalse; }
1426
+
1427
+ /* Undeclares a declared key expression (it stays usable as a plain one). */
1428
+ static VALUE zrb_ke_undeclare_m(VALUE self) {
1429
+ zrb_ent_detach(&zrb_ke_get(self)->ent);
1430
+ return Qnil;
973
1431
  }
974
1432
 
1433
+ /* KeyExpr.canonize(str) -> String in canonical form (for example two
1434
+ * "**" chunks in a row become one, a lone "$*" chunk becomes "*").
1435
+ * Raises ArgumentError when it cannot be made one. */
1436
+ static VALUE zrb_ke_s_canonize(VALUE klass, VALUE str) {
1437
+ VALUE out = rb_str_dup(StringValue(str));
1438
+ size_t len = (size_t)RSTRING_LEN(out);
1439
+ rb_str_modify(out);
1440
+ if (z_keyexpr_canonize(RSTRING_PTR(out), &len) != Z_OK) {
1441
+ rb_raise(rb_eArgError, "invalid key expression: %" PRIsVALUE, str);
1442
+ }
1443
+ rb_str_set_len(out, (long)len);
1444
+ return out;
1445
+ }
1446
+
1447
+ /* KeyExpr.valid?(str): a key expression in canonical form. */
1448
+ static VALUE zrb_ke_s_valid_p(VALUE klass, VALUE str) {
1449
+ StringValue(str);
1450
+ return z_keyexpr_is_canon(RSTRING_PTR(str), (size_t)RSTRING_LEN(str)) == Z_OK ? Qtrue : Qfalse;
1451
+ }
1452
+
1453
+ /* ----------------------------------------------------------- subscriber */
1454
+
1455
+ static void zrb_sub_detach(zrb_sub *s) {
1456
+ if (s->declared) {
1457
+ if (s->type == ZSUB_ADVANCED) {
1458
+ z_drop(z_move(s->u.adv));
1459
+ } else {
1460
+ z_drop(z_move(s->u.sub));
1461
+ }
1462
+ s->declared = false;
1463
+ }
1464
+ if (s->owner != NULL) {
1465
+ zrb_sub **pp = &s->owner->subs;
1466
+ while (*pp != NULL) {
1467
+ if (*pp == s) {
1468
+ *pp = s->next;
1469
+ break;
1470
+ }
1471
+ pp = &(*pp)->next;
1472
+ }
1473
+ s->owner = NULL;
1474
+ s->next = NULL;
1475
+ }
1476
+ }
1477
+
1478
+ static void zrb_sub_free(void *p) {
1479
+ zrb_sub *s = (zrb_sub *)p;
1480
+ zrb_sub_detach(s);
1481
+ zch_unref(s->ch);
1482
+ xfree(s);
1483
+ }
1484
+
1485
+ static size_t zrb_sub_size(const void *p) { return sizeof(zrb_sub); }
1486
+
1487
+ static const rb_data_type_t zrb_sub_type = {
1488
+ "Asterism::Zenoh::Subscriber", {NULL, zrb_sub_free, zrb_sub_size}, NULL, NULL, 0};
1489
+
1490
+ static zrb_sub *zrb_sub_get(VALUE self) {
1491
+ zrb_sub *s;
1492
+ TypedData_Get_Struct(self, zrb_sub, &zrb_sub_type, s);
1493
+ return s;
1494
+ }
1495
+
1496
+ /* Take out what is pending now, oldest first. Values that arrive while the
1497
+ * block runs are left for the next call. */
1498
+ static VALUE zrb_sub_each_pending(VALUE self) {
1499
+ zrb_sub *s = zrb_sub_get(self);
1500
+ bool collect = !rb_block_given_p();
1501
+ VALUE out = collect ? rb_ary_new() : Qnil;
1502
+ long taken = 0;
1503
+ unsigned todo = atomic_load(&s->ch->queued);
1504
+ while (todo > 0) {
1505
+ todo--;
1506
+ z_owned_sample_t sm;
1507
+ if (zch_take_sample(s->ch, &sm) != Z_OK) {
1508
+ break;
1509
+ }
1510
+ const z_loaned_sample_t *l = z_loan(sm);
1511
+ VALUE vals[3];
1512
+ int n;
1513
+ vals[0] = zrb_key_str(z_sample_keyexpr(l));
1514
+ if (s->liveliness) {
1515
+ /* A token appearing is a PUT, one going away a DELETE. */
1516
+ vals[1] = (z_sample_kind(l) == Z_SAMPLE_KIND_PUT) ? Qtrue : Qfalse;
1517
+ n = 2;
1518
+ } else {
1519
+ vals[1] = zrb_str_from_bytes(z_sample_payload(l));
1520
+ vals[2] = zrb_attachment_value(z_sample_attachment(l));
1521
+ n = 3;
1522
+ }
1523
+ z_drop(z_move(sm));
1524
+ taken++;
1525
+ if (collect) {
1526
+ rb_ary_push(out, rb_ary_new_from_values(n, vals));
1527
+ } else {
1528
+ rb_yield_values2(n, vals);
1529
+ }
1530
+ }
1531
+ return collect ? out : LONG2NUM(taken);
1532
+ }
1533
+
1534
+ /* sub.each_sample { |sample| ... } -> Integer; without a block, Array of
1535
+ * Asterism::Zenoh::Sample (the payload with kind, encoding, timestamp,
1536
+ * priority and the other fields). Takes from the same queue as
1537
+ * each_pending. */
1538
+ static VALUE zrb_sub_each_sample(VALUE self) {
1539
+ zrb_sub *s = zrb_sub_get(self);
1540
+ bool collect = !rb_block_given_p();
1541
+ VALUE out = collect ? rb_ary_new() : Qnil;
1542
+ long taken = 0;
1543
+ unsigned todo = atomic_load(&s->ch->queued);
1544
+ while (todo > 0) {
1545
+ todo--;
1546
+ z_owned_sample_t sm;
1547
+ if (zch_take_sample(s->ch, &sm) != Z_OK) {
1548
+ break;
1549
+ }
1550
+ VALUE v = zrb_sample_value(z_loan(sm));
1551
+ z_drop(z_move(sm));
1552
+ taken++;
1553
+ if (collect) {
1554
+ rb_ary_push(out, v);
1555
+ } else {
1556
+ rb_yield(v);
1557
+ }
1558
+ }
1559
+ return collect ? out : LONG2NUM(taken);
1560
+ }
1561
+
1562
+ static VALUE zrb_sub_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->queued)); }
1563
+ static VALUE zrb_sub_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->received)); }
1564
+ static VALUE zrb_sub_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->dropped)); }
1565
+
1566
+ static VALUE zrb_sub_close(VALUE self) {
1567
+ zrb_sub_detach(zrb_sub_get(self));
1568
+ return Qnil;
1569
+ }
1570
+
1571
+ static VALUE zrb_sub_closed_p(VALUE self) { return zrb_sub_get(self)->declared ? Qfalse : Qtrue; }
1572
+
1573
+ /* ------------------------------------------------------------ queryable */
1574
+
1575
+ static void zrb_qable_detach(zrb_qable *q) {
1576
+ /* Unanswered queries first: their final replies go out while the
1577
+ * session can still carry them. */
1578
+ zch_finish_queries(q->ch);
1579
+ if (q->declared) {
1580
+ z_drop(z_move(q->qable));
1581
+ q->declared = false;
1582
+ }
1583
+ if (q->owner != NULL) {
1584
+ zrb_qable **pp = &q->owner->qables;
1585
+ while (*pp != NULL) {
1586
+ if (*pp == q) {
1587
+ *pp = q->next;
1588
+ break;
1589
+ }
1590
+ pp = &(*pp)->next;
1591
+ }
1592
+ q->owner = NULL;
1593
+ q->next = NULL;
1594
+ }
1595
+ }
1596
+
1597
+ static void zrb_qable_free(void *p) {
1598
+ zrb_qable *q = (zrb_qable *)p;
1599
+ zrb_qable_detach(q);
1600
+ zch_unref(q->ch);
1601
+ xfree(q);
1602
+ }
1603
+
1604
+ static size_t zrb_qable_size(const void *p) { return sizeof(zrb_qable); }
1605
+
1606
+ static const rb_data_type_t zrb_qable_type = {
1607
+ "Asterism::Zenoh::Queryable", {NULL, zrb_qable_free, zrb_qable_size}, NULL, NULL, 0};
1608
+
1609
+ static zrb_qable *zrb_qable_get(VALUE self) {
1610
+ zrb_qable *q;
1611
+ TypedData_Get_Struct(self, zrb_qable, &zrb_qable_type, q);
1612
+ return q;
1613
+ }
1614
+
1615
+ /* ---------------------------------------------------------------- query */
1616
+
1617
+ static void zrb_query_finish(zrb_query *zq) {
1618
+ if (zq->live) {
1619
+ z_drop(z_move(zq->query));
1620
+ zq->live = false;
1621
+ }
1622
+ }
1623
+
1624
+ static void zrb_query_free(void *p) {
1625
+ zrb_query *zq = (zrb_query *)p;
1626
+ zrb_query_finish(zq);
1627
+ xfree(zq);
1628
+ }
1629
+
1630
+ static size_t zrb_query_size(const void *p) { return sizeof(zrb_query); }
1631
+
1632
+ static const rb_data_type_t zrb_query_type = {
1633
+ "Asterism::Zenoh::Query", {NULL, zrb_query_free, zrb_query_size}, NULL, NULL, 0};
1634
+
1635
+ static zrb_query *zrb_query_get(VALUE self) {
1636
+ zrb_query *zq;
1637
+ TypedData_Get_Struct(self, zrb_query, &zrb_query_type, zq);
1638
+ return zq;
1639
+ }
1640
+
1641
+ static zrb_query *zrb_query_get_live(VALUE self) {
1642
+ zrb_query *zq = zrb_query_get(self);
1643
+ if (!zq->live) {
1644
+ rb_raise(eZenohError, "the query is finished");
1645
+ }
1646
+ return zq;
1647
+ }
1648
+
1649
+ /* Wraps the query (moved in) in a Query object. */
1650
+ static VALUE zrb_query_wrap(z_owned_query_t *q) {
1651
+ zrb_query *zq;
1652
+ VALUE obj = TypedData_Make_Struct(cQuery, zrb_query, &zrb_query_type, zq);
1653
+ zq->query = *q;
1654
+ zq->live = true;
1655
+ z_internal_query_null(q);
1656
+ return obj;
1657
+ }
1658
+
1659
+ static VALUE zrb_query_yield_body(VALUE obj) { return rb_yield(obj); }
1660
+
1661
+ static VALUE zrb_query_yield_ensure(VALUE obj) {
1662
+ zrb_query_finish(zrb_query_get(obj));
1663
+ return Qnil;
1664
+ }
1665
+
1666
+ /* qa.each_pending { |q| ... } -> Integer (queries taken). Each query is
1667
+ * finished when the block returns (also when it raises).
1668
+ * qa.each_pending -> Array of Query; each stays open until Query#finish or
1669
+ * garbage collection. */
1670
+ static VALUE zrb_qable_each_pending(VALUE self) {
1671
+ zrb_qable *q = zrb_qable_get(self);
1672
+ bool collect = !rb_block_given_p();
1673
+ VALUE out = collect ? rb_ary_new() : Qnil;
1674
+ long taken = 0;
1675
+ unsigned todo = atomic_load(&q->ch->queued);
1676
+ while (todo > 0) {
1677
+ todo--;
1678
+ z_owned_query_t oq;
1679
+ if (zch_take_query(q->ch, &oq) != Z_OK) {
1680
+ break;
1681
+ }
1682
+ VALUE obj = zrb_query_wrap(&oq);
1683
+ taken++;
1684
+ if (collect) {
1685
+ rb_ary_push(out, obj);
1686
+ } else {
1687
+ rb_ensure(zrb_query_yield_body, obj, zrb_query_yield_ensure, obj);
1688
+ }
1689
+ }
1690
+ return collect ? out : LONG2NUM(taken);
1691
+ }
1692
+
1693
+ static VALUE zrb_qable_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->queued)); }
1694
+ static VALUE zrb_qable_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->received)); }
1695
+ static VALUE zrb_qable_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->dropped)); }
1696
+
1697
+ static VALUE zrb_qable_close(VALUE self) {
1698
+ zrb_qable_detach(zrb_qable_get(self));
1699
+ return Qnil;
1700
+ }
1701
+
1702
+ static VALUE zrb_qable_closed_p(VALUE self) { return zrb_qable_get(self)->declared ? Qfalse : Qtrue; }
1703
+
1704
+ static VALUE zrb_query_key(VALUE self) {
1705
+ zrb_query *zq = zrb_query_get_live(self);
1706
+ return zrb_key_str(z_query_keyexpr(z_loan(zq->query)));
1707
+ }
1708
+
1709
+ static VALUE zrb_query_params(VALUE self) {
1710
+ zrb_query *zq = zrb_query_get_live(self);
1711
+ z_view_string_t ps;
1712
+ z_query_parameters(z_loan(zq->query), &ps);
1713
+ return zrb_str_from_view(z_loan(ps));
1714
+ }
1715
+
1716
+ static VALUE zrb_query_payload(VALUE self) {
1717
+ zrb_query *zq = zrb_query_get_live(self);
1718
+ const z_loaned_bytes_t *b = z_query_payload(z_loan(zq->query));
1719
+ if (b == NULL) {
1720
+ return rb_str_new(NULL, 0);
1721
+ }
1722
+ return zrb_str_from_bytes(b);
1723
+ }
1724
+
1725
+ static VALUE zrb_query_attachment(VALUE self) {
1726
+ zrb_query *zq = zrb_query_get_live(self);
1727
+ return zrb_attachment_value(z_query_attachment(z_loan(zq->query)));
1728
+ }
1729
+
1730
+ /* The query's own key (key_v nil) or the given one (String or KeyExpr). */
1731
+ static const z_loaned_keyexpr_t *zrb_reply_key(zrb_query *zq, VALUE key_v, z_view_keyexpr_t *view) {
1732
+ if (NIL_P(key_v)) {
1733
+ return z_query_keyexpr(z_loan(zq->query));
1734
+ }
1735
+ return zrb_key_loan(key_v, view);
1736
+ }
1737
+
1738
+ /* A timestamp option: true makes a new one (needs the session, which the
1739
+ * query does not carry: true is only accepted where there is a session). */
1740
+ static const z_timestamp_t *zrb_opts_timestamp(VALUE v, z_timestamp_t *store, const z_loaned_session_t *session) {
1741
+ if (NIL_P(v)) {
1742
+ return NULL;
1743
+ }
1744
+ if (v == Qtrue) {
1745
+ if (session == NULL || z_timestamp_new(store, session) != Z_OK) {
1746
+ rb_raise(eZenohError, "cannot make a timestamp");
1747
+ }
1748
+ return store;
1749
+ }
1750
+ *store = zrb_ts_get(v)->ts;
1751
+ return store;
1752
+ }
1753
+
1754
+ static const char *const zrb_reply_kw[] = {"attachment", "encoding", "timestamp", "priority", "congestion_control",
1755
+ "express"};
1756
+
1757
+ /* q.reply(payload, **opts) / q.reply(key, payload, **opts) -> nil.
1758
+ * opts: attachment:, encoding: (a String such as "application/json"),
1759
+ * timestamp: (an Asterism::Zenoh::Timestamp), priority:,
1760
+ * congestion_control:, express:. The key defaults to the query's key; it
1761
+ * must match the query's key expression. May be called more than once
1762
+ * before the query is finished. */
1763
+ static VALUE zrb_query_reply(int argc, VALUE *argv, VALUE self) {
1764
+ VALUE a1, a2 = Qnil, opts = Qnil;
1765
+ int n = rb_scan_args(argc, argv, "11:", &a1, &a2, &opts);
1766
+ zrb_opts o;
1767
+ zrb_opts_parse(opts, zrb_reply_kw, 6, &o);
1768
+ if (o.timestamp == Qtrue) {
1769
+ rb_raise(rb_eArgError, "timestamp: needs a Timestamp here (session.new_timestamp)");
1770
+ }
1771
+ zrb_query *zq = zrb_query_get_live(self);
1772
+ VALUE key_v = (n == 1) ? Qnil : a1;
1773
+ VALUE payload = (n == 1) ? a1 : a2;
1774
+ if (!RB_TYPE_P(payload, T_STRING)) {
1775
+ rb_raise(rb_eTypeError, "payload must be a String");
1776
+ }
1777
+ z_view_keyexpr_t ke;
1778
+ const z_loaned_keyexpr_t *kp = zrb_reply_key(zq, key_v, &ke);
1779
+ z_timestamp_t ts;
1780
+ const z_timestamp_t *tsp = zrb_opts_timestamp(o.timestamp, &ts, NULL);
1781
+ z_query_reply_options_t ro;
1782
+ z_query_reply_options_default(&ro);
1783
+ if (o.priority >= 0) {
1784
+ ro.priority = (z_priority_t)o.priority;
1785
+ }
1786
+ if (o.congestion_control >= 0) {
1787
+ ro.congestion_control = (z_congestion_control_t)o.congestion_control;
1788
+ }
1789
+ if (o.express >= 0) {
1790
+ ro.is_express = o.express;
1791
+ }
1792
+ if (tsp != NULL) {
1793
+ ro.timestamp = &ts;
1794
+ }
1795
+ /* Nothing below raises before the reply takes the owned values. */
1796
+ z_owned_encoding_t enc;
1797
+ if (zrb_encoding_make(&enc, o.encoding)) {
1798
+ ro.encoding = z_move(enc);
1799
+ }
1800
+ z_owned_bytes_t att_bytes;
1801
+ if (!NIL_P(o.attachment)) {
1802
+ zrb_bytes_from_str(&att_bytes, o.attachment, "attachment");
1803
+ ro.attachment = z_move(att_bytes);
1804
+ }
1805
+ z_owned_bytes_t bytes;
1806
+ zrb_bytes_from_str(&bytes, payload, "payload");
1807
+ z_result_t ret = z_query_reply(z_loan(zq->query), kp, z_move(bytes), &ro);
1808
+ if (ret != Z_OK) {
1809
+ rb_raise(eZenohError, "reply failed (%d)%" PRIsVALUE, (int)ret, zrb_last_error());
1810
+ }
1811
+ return Qnil;
1812
+ }
1813
+
1814
+ /* q.reply_err(payload, encoding: nil) -> nil: an error answer; the
1815
+ * requester sees it as an error (Get#errors, each_result's error?). */
1816
+ static VALUE zrb_query_reply_err(int argc, VALUE *argv, VALUE self) {
1817
+ VALUE payload, opts = Qnil;
1818
+ rb_scan_args(argc, argv, "1:", &payload, &opts);
1819
+ static const char *const kws[] = {"encoding"};
1820
+ zrb_opts o;
1821
+ zrb_opts_parse(opts, kws, 1, &o);
1822
+ if (!RB_TYPE_P(payload, T_STRING)) {
1823
+ rb_raise(rb_eTypeError, "payload must be a String");
1824
+ }
1825
+ zrb_query *zq = zrb_query_get_live(self);
1826
+ z_query_reply_err_options_t eo;
1827
+ z_query_reply_err_options_default(&eo);
1828
+ z_owned_encoding_t enc;
1829
+ if (zrb_encoding_make(&enc, o.encoding)) {
1830
+ eo.encoding = z_move(enc);
1831
+ }
1832
+ z_owned_bytes_t bytes;
1833
+ zrb_bytes_from_str(&bytes, payload, "payload");
1834
+ z_result_t ret = z_query_reply_err(z_loan(zq->query), z_move(bytes), &eo);
1835
+ if (ret != Z_OK) {
1836
+ rb_raise(eZenohError, "reply_err failed (%d)%" PRIsVALUE, (int)ret, zrb_last_error());
1837
+ }
1838
+ return Qnil;
1839
+ }
1840
+
1841
+ /* q.reply_del(key = nil, attachment:, timestamp:, priority:,
1842
+ * congestion_control:, express:) -> nil: answers that the key was
1843
+ * deleted (a DELETE sample). */
1844
+ static VALUE zrb_query_reply_del(int argc, VALUE *argv, VALUE self) {
1845
+ VALUE key_v = Qnil, opts = Qnil;
1846
+ rb_scan_args(argc, argv, "01:", &key_v, &opts);
1847
+ static const char *const kws[] = {"attachment", "timestamp", "priority", "congestion_control", "express"};
1848
+ zrb_opts o;
1849
+ zrb_opts_parse(opts, kws, 5, &o);
1850
+ if (o.timestamp == Qtrue) {
1851
+ rb_raise(rb_eArgError, "timestamp: needs a Timestamp here (session.new_timestamp)");
1852
+ }
1853
+ zrb_query *zq = zrb_query_get_live(self);
1854
+ z_view_keyexpr_t ke;
1855
+ const z_loaned_keyexpr_t *kp = zrb_reply_key(zq, key_v, &ke);
1856
+ z_timestamp_t ts;
1857
+ const z_timestamp_t *tsp = zrb_opts_timestamp(o.timestamp, &ts, NULL);
1858
+ z_query_reply_del_options_t d;
1859
+ z_query_reply_del_options_default(&d);
1860
+ if (o.priority >= 0) {
1861
+ d.priority = (z_priority_t)o.priority;
1862
+ }
1863
+ if (o.congestion_control >= 0) {
1864
+ d.congestion_control = (z_congestion_control_t)o.congestion_control;
1865
+ }
1866
+ if (o.express >= 0) {
1867
+ d.is_express = o.express;
1868
+ }
1869
+ if (tsp != NULL) {
1870
+ d.timestamp = &ts;
1871
+ }
1872
+ z_owned_bytes_t att_bytes;
1873
+ if (!NIL_P(o.attachment)) {
1874
+ zrb_bytes_from_str(&att_bytes, o.attachment, "attachment");
1875
+ d.attachment = z_move(att_bytes);
1876
+ }
1877
+ z_result_t ret = z_query_reply_del(z_loan(zq->query), kp, &d);
1878
+ if (ret != Z_OK) {
1879
+ rb_raise(eZenohError, "reply_del failed (%d)%" PRIsVALUE, (int)ret, zrb_last_error());
1880
+ }
1881
+ return Qnil;
1882
+ }
1883
+
1884
+ /* q.encoding -> String or nil: the encoding of the query's payload. */
1885
+ static VALUE zrb_query_encoding(VALUE self) {
1886
+ zrb_query *zq = zrb_query_get_live(self);
1887
+ if (z_query_payload(z_loan(zq->query)) == NULL) {
1888
+ return Qnil;
1889
+ }
1890
+ return zrb_encoding_value(z_query_encoding(z_loan(zq->query)));
1891
+ }
1892
+
1893
+ static VALUE zrb_query_finish_m(VALUE self) {
1894
+ zrb_query_finish(zrb_query_get(self));
1895
+ return Qnil;
1896
+ }
1897
+
1898
+ static VALUE zrb_query_finished_p(VALUE self) { return zrb_query_get(self)->live ? Qfalse : Qtrue; }
1899
+
1900
+ /* ------------------------------------------------------------------ get */
1901
+
1902
+ static void zrb_get_free(void *p) {
1903
+ zrb_get *g = (zrb_get *)p;
1904
+ zch_unref(g->ch); /* zenoh-c may still hold it until the get finishes */
1905
+ xfree(g);
1906
+ }
1907
+
1908
+ static size_t zrb_get_size(const void *p) { return sizeof(zrb_get); }
1909
+
1910
+ static const rb_data_type_t zrb_get_type = {"Asterism::Zenoh::Get", {NULL, zrb_get_free, zrb_get_size}, NULL, NULL, 0};
1911
+
1912
+ static zrb_get *zrb_get_get(VALUE self) {
1913
+ zrb_get *g;
1914
+ TypedData_Get_Struct(self, zrb_get, &zrb_get_type, g);
1915
+ return g;
1916
+ }
1917
+
1918
+ static VALUE zrb_get_new(zrb_get **out) {
1919
+ zrb_get *g;
1920
+ VALUE obj = TypedData_Make_Struct(cGet, zrb_get, &zrb_get_type, g);
1921
+ g->ch = zch_new(ZCH_REPLY, ZRB_DEFAULT_DEPTH);
1922
+ *out = g;
1923
+ return obj;
1924
+ }
1925
+
1926
+ /* g.each_reply { |key, payload, attachment| ... } -> Integer; without a
1927
+ * block, Array of [key, payload, attachment]. Error replies are counted
1928
+ * (errors) and taken out, not yielded (each_result returns them). */
1929
+ static VALUE zrb_get_each_reply(VALUE self) {
1930
+ zrb_get *g = zrb_get_get(self);
1931
+ bool collect = !rb_block_given_p();
1932
+ VALUE out = collect ? rb_ary_new() : Qnil;
1933
+ long taken = 0;
1934
+ unsigned todo = atomic_load(&g->ch->queued);
1935
+ while (todo > 0) {
1936
+ todo--;
1937
+ z_owned_reply_t r;
1938
+ if (zch_take_reply(g->ch, &r) != Z_OK) {
1939
+ break;
1940
+ }
1941
+ if (!z_reply_is_ok(z_loan(r))) {
1942
+ /* Counted in errors; each_result returns them. */
1943
+ z_drop(z_move(r));
1944
+ continue;
1945
+ }
1946
+ VALUE vals[3];
1947
+ const z_loaned_sample_t *sm = z_reply_ok(z_loan(r));
1948
+ vals[0] = zrb_key_str(z_sample_keyexpr(sm));
1949
+ vals[1] = zrb_str_from_bytes(z_sample_payload(sm));
1950
+ vals[2] = zrb_attachment_value(z_sample_attachment(sm));
1951
+ z_drop(z_move(r));
1952
+ taken++;
1953
+ if (collect) {
1954
+ rb_ary_push(out, rb_ary_new_from_values(3, vals));
1955
+ } else {
1956
+ rb_yield_values2(3, vals);
1957
+ }
1958
+ }
1959
+ return collect ? out : LONG2NUM(taken);
1960
+ }
1961
+
1962
+ /* g.each_result { |reply| ... } -> Integer; without a block, Array of
1963
+ * Asterism::Zenoh::Reply. Unlike each_reply, error replies are returned
1964
+ * too (reply.error?). Takes from the same queue as each_reply. */
1965
+ static VALUE zrb_get_each_result(VALUE self) {
1966
+ zrb_get *g = zrb_get_get(self);
1967
+ bool collect = !rb_block_given_p();
1968
+ VALUE out = collect ? rb_ary_new() : Qnil;
1969
+ long taken = 0;
1970
+ unsigned todo = atomic_load(&g->ch->queued);
1971
+ while (todo > 0) {
1972
+ todo--;
1973
+ z_owned_reply_t r;
1974
+ if (zch_take_reply(g->ch, &r) != Z_OK) {
1975
+ break;
1976
+ }
1977
+ VALUE v = zrb_reply_value(z_loan(r));
1978
+ z_drop(z_move(r));
1979
+ taken++;
1980
+ if (collect) {
1981
+ rb_ary_push(out, v);
1982
+ } else {
1983
+ rb_yield(v);
1984
+ }
1985
+ }
1986
+ return collect ? out : LONG2NUM(taken);
1987
+ }
1988
+
1989
+ static VALUE zrb_get_done_p(VALUE self) { return atomic_load(&zrb_get_get(self)->ch->done) ? Qtrue : Qfalse; }
1990
+ static VALUE zrb_get_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->queued)); }
1991
+ static VALUE zrb_get_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->received)); }
1992
+ static VALUE zrb_get_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->dropped)); }
1993
+ static VALUE zrb_get_errors(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->errors)); }
1994
+
1995
+ /* ---------------------------------------------------------------- token */
1996
+
1997
+ static void zrb_token_detach(zrb_token *t) {
1998
+ if (t->declared) {
1999
+ z_drop(z_move(t->token));
2000
+ t->declared = false;
2001
+ }
2002
+ if (t->owner != NULL) {
2003
+ zrb_token **pp = &t->owner->tokens;
2004
+ while (*pp != NULL) {
2005
+ if (*pp == t) {
2006
+ *pp = t->next;
2007
+ break;
2008
+ }
2009
+ pp = &(*pp)->next;
2010
+ }
2011
+ t->owner = NULL;
2012
+ t->next = NULL;
2013
+ }
2014
+ }
2015
+
2016
+ static void zrb_token_free(void *p) {
2017
+ zrb_token *t = (zrb_token *)p;
2018
+ zrb_token_detach(t);
2019
+ xfree(t);
2020
+ }
2021
+
2022
+ static size_t zrb_token_size(const void *p) { return sizeof(zrb_token); }
2023
+
2024
+ static const rb_data_type_t zrb_token_type = {
2025
+ "Asterism::Zenoh::LivelinessToken", {NULL, zrb_token_free, zrb_token_size}, NULL, NULL, 0};
2026
+
2027
+ static zrb_token *zrb_token_get(VALUE self) {
2028
+ zrb_token *t;
2029
+ TypedData_Get_Struct(self, zrb_token, &zrb_token_type, t);
2030
+ return t;
2031
+ }
2032
+
2033
+ static VALUE zrb_token_close(VALUE self) {
2034
+ zrb_token_detach(zrb_token_get(self));
2035
+ return Qnil;
2036
+ }
2037
+
2038
+ static VALUE zrb_token_closed_p(VALUE self) { return zrb_token_get(self)->declared ? Qfalse : Qtrue; }
2039
+
2040
+ /* -------------------------------------------------------------- session */
2041
+
2042
+ /* Undeclares everything the session still has. Holds the GVL (the lists
2043
+ * are only touched with it). */
2044
+ static void zrb_session_detach_order(zrb_session *z, int order) {
2045
+ zrb_ent *e = z->ents;
2046
+ while (e != NULL) {
2047
+ zrb_ent *next = e->next;
2048
+ if (e->order == order) {
2049
+ zrb_ent_detach(e); /* unlinks itself */
2050
+ }
2051
+ e = next;
2052
+ }
2053
+ }
2054
+
2055
+ static void zrb_session_detach_all(zrb_session *z) {
2056
+ /* Listeners before what they listen to, declared key expressions after
2057
+ * everything that may use them. */
2058
+ zrb_session_detach_order(z, ZENT_LISTENER);
2059
+ zrb_session_detach_order(z, ZENT_ENTITY);
2060
+ while (z->qables != NULL) {
2061
+ zrb_qable_detach(z->qables); /* unlinks itself */
2062
+ }
2063
+ while (z->tokens != NULL) {
2064
+ zrb_token_detach(z->tokens);
2065
+ }
2066
+ while (z->subs != NULL) {
2067
+ zrb_sub_detach(z->subs);
2068
+ }
2069
+ zrb_session_detach_order(z, ZENT_KEYEXPR);
2070
+ }
2071
+
2072
+ /* Closes the zenoh-c session. Without the GVL when called from Ruby
2073
+ * methods (it waits for zenoh's tasks), with it from the GC. */
2074
+ static void *zrb_session_close_nogvl(void *p) {
2075
+ zrb_session *z = (zrb_session *)p;
2076
+ pthread_mutex_lock(&z->op_lock);
2077
+ if (z->live) {
2078
+ z->live = false;
2079
+ z_close(z_loan_mut(z->session), NULL);
2080
+ z_drop(z_move(z->session));
2081
+ }
2082
+ pthread_mutex_unlock(&z->op_lock);
2083
+ return NULL;
2084
+ }
2085
+
2086
+ static void zrb_session_shutdown(zrb_session *z, bool with_gvl_release) {
2087
+ zrb_session_detach_all(z);
2088
+ if (!z->open) {
2089
+ return;
2090
+ }
2091
+ /* Closed for Ruby before the GVL is released: another Ruby thread that
2092
+ * runs while zenoh-c closes the session sees it closed and does not
2093
+ * touch the session any more (the calls without the GVL check live
2094
+ * under op_lock instead). */
2095
+ z->open = false;
2096
+ if (with_gvl_release) {
2097
+ rb_thread_call_without_gvl(zrb_session_close_nogvl, z, RUBY_UBF_IO, NULL);
2098
+ } else {
2099
+ zrb_session_close_nogvl(z);
2100
+ }
2101
+ }
2102
+
2103
+ static void zrb_session_free(void *p) {
2104
+ zrb_session *z = (zrb_session *)p;
2105
+ zrb_session_shutdown(z, false);
2106
+ pthread_mutex_destroy(&z->op_lock);
2107
+ xfree(z);
2108
+ }
2109
+
2110
+ static size_t zrb_session_size(const void *p) { return sizeof(zrb_session); }
2111
+
2112
+ static const rb_data_type_t zrb_session_type = {
2113
+ "Asterism::Zenoh::Session", {NULL, zrb_session_free, zrb_session_size}, NULL, NULL, 0};
2114
+
2115
+ static zrb_session *zrb_session_get(VALUE self) {
2116
+ zrb_session *z;
2117
+ TypedData_Get_Struct(self, zrb_session, &zrb_session_type, z);
2118
+ return z;
2119
+ }
2120
+
2121
+ static void zrb_count_zid(const z_id_t *id, void *ctx) {
2122
+ (void)id;
2123
+ (*(int *)ctx)++;
2124
+ }
2125
+
2126
+ /* Routers (client) or peers (peer mode) connected now. */
2127
+ static int zrb_session_links(zrb_session *z) {
2128
+ int n = 0;
2129
+ z_owned_closure_zid_t cb;
2130
+ z_closure(&cb, zrb_count_zid, NULL, &n);
2131
+ if (z->peer) {
2132
+ z_info_peers_zid(z_loan(z->session), z_move(cb));
2133
+ } else {
2134
+ z_info_routers_zid(z_loan(z->session), z_move(cb));
2135
+ }
2136
+ return n;
2137
+ }
2138
+
2139
+ /* Close the session when its connection can no longer carry it (see the
2140
+ * comment at the top). Returns true when the session is (now) closed. */
2141
+ static bool zrb_session_check_link(zrb_session *z) {
2142
+ if (!z->open) {
2143
+ return true;
2144
+ }
2145
+ if (z_session_is_closed(z_loan(z->session))) {
2146
+ zrb_session_shutdown(z, true);
2147
+ return true;
2148
+ }
2149
+ if (z->peer && z->listening) {
2150
+ return false;
2151
+ }
2152
+ if (zrb_session_links(z) == 0) {
2153
+ zrb_session_shutdown(z, true);
2154
+ return true;
2155
+ }
2156
+ return false;
2157
+ }
2158
+
2159
+ static zrb_session *zrb_session_get_open(VALUE self) {
2160
+ zrb_session *z = zrb_session_get(self);
2161
+ if (zrb_session_check_link(z)) {
2162
+ rb_raise(eZenohError, "session is closed");
2163
+ }
2164
+ return z;
2165
+ }
2166
+
2167
+ /* A JSON5 string literal of s (for the configuration). */
2168
+ static VALUE zrb_json_str(const char *s) {
2169
+ VALUE out = rb_str_new_cstr("\"");
2170
+ for (const char *p = s; *p; p++) {
2171
+ if (*p == '"' || *p == '\\') {
2172
+ rb_str_cat(out, "\\", 1);
2173
+ }
2174
+ rb_str_cat(out, p, 1);
2175
+ }
2176
+ rb_str_cat(out, "\"", 1);
2177
+ return out;
2178
+ }
2179
+
2180
+ static bool zrb_config_set(z_owned_config_t *config, const char *key, const char *json5) {
2181
+ return zc_config_insert_json5(z_loan_mut(*config), key, json5) == Z_OK;
2182
+ }
2183
+
2184
+ typedef struct {
2185
+ zrb_session *z;
2186
+ z_owned_config_t config;
2187
+ z_result_t ret;
2188
+ } zrb_open_args;
2189
+
2190
+ static void *zrb_open_nogvl(void *p) {
2191
+ zrb_open_args *a = (zrb_open_args *)p;
2192
+ a->ret = z_open(&a->z->session, z_move(a->config), NULL);
2193
+ return NULL;
2194
+ }
2195
+
2196
+ /* The value at key of a configuration as JSON (a Ruby String), or nil. */
2197
+ static VALUE zrb_config_get(const z_loaned_config_t *c, const char *key) {
2198
+ z_owned_string_t s;
2199
+ if (zc_config_get_from_str(c, key, &s) != Z_OK) {
2200
+ return Qnil;
2201
+ }
2202
+ VALUE out = zrb_str_from_view(z_loan(s));
2203
+ z_drop(z_move(s));
2204
+ return out;
2205
+ }
2206
+
2207
+ /* A Ruby value as JSON text (for the config: Hash). */
2208
+ static VALUE zrb_to_json(VALUE v) {
2209
+ static bool loaded = false;
2210
+ if (!loaded) {
2211
+ rb_require("json");
2212
+ loaded = true;
2213
+ }
2214
+ return rb_funcall(rb_const_get(rb_cObject, rb_intern("JSON")), rb_intern("generate"), 1, v);
2215
+ }
2216
+
2217
+ typedef struct {
2218
+ z_owned_config_t *config;
2219
+ z_owned_config_t *dflt; /* zenoh's defaults, when the user gave a file */
2220
+ } zrb_cfg;
2221
+
2222
+ /* One of the gem's own settings: applied unless the user's file (or
2223
+ * configuration String) set that key to something other than zenoh's
2224
+ * default. */
2225
+ static bool zrb_cfg_internal(zrb_cfg *c, const char *key, const char *json5) {
2226
+ if (c->dflt != NULL) {
2227
+ VALUE mine = zrb_config_get(z_loan(*c->config), key);
2228
+ VALUE def = zrb_config_get(z_loan(*c->dflt), key);
2229
+ if (!rb_equal(mine, def)) {
2230
+ return true; /* the user's */
2231
+ }
2232
+ }
2233
+ return zrb_config_set(c->config, key, json5);
2234
+ }
2235
+
2236
+ static VALUE zrb_json_endpoints(const char *ep) {
2237
+ return rb_str_concat(rb_str_concat(rb_str_new_cstr("["), zrb_json_str(ep)), rb_str_new_cstr("]"));
2238
+ }
2239
+
2240
+ typedef struct {
2241
+ VALUE hash;
2242
+ z_owned_config_t *config;
2243
+ VALUE bad; /* the key that failed */
2244
+ } zrb_cfg_hash;
2245
+
2246
+ static int zrb_cfg_hash_i(VALUE key, VALUE val, VALUE arg) {
2247
+ zrb_cfg_hash *h = (zrb_cfg_hash *)arg;
2248
+ VALUE k = rb_obj_as_string(key);
2249
+ VALUE json = zrb_to_json(val);
2250
+ if (!zrb_config_set(h->config, StringValueCStr(k), StringValueCStr(json))) {
2251
+ h->bad = rb_sprintf("%" PRIsVALUE " = %" PRIsVALUE, k, json);
2252
+ return ST_STOP;
2253
+ }
2254
+ return ST_CONTINUE;
2255
+ }
2256
+
2257
+ static VALUE zrb_cfg_hash_body(VALUE arg) {
2258
+ zrb_cfg_hash *h = (zrb_cfg_hash *)arg;
2259
+ rb_hash_foreach(h->hash, zrb_cfg_hash_i, arg);
2260
+ return Qnil;
2261
+ }
2262
+
2263
+ /* Asterism::Zenoh::Session.open(locator = nil, mode: :client, listen: nil,
2264
+ * scouting: nil, config: nil, config_file: nil) -> Session
2265
+ * - client: connects to the router at locator.
2266
+ * - peer: connects to the peer at locator (if given) and/or listens on
2267
+ * listen (e.g. "tcp/0.0.0.0:7447").
2268
+ * - scouting: true turns multicast scouting (and gossip) on, so a peer or
2269
+ * client finds the others by itself (then no locator is needed).
2270
+ * - timestamping: true stamps every put of the session with its clock
2271
+ * (needed by an advanced publisher with a cache but no
2272
+ * sample_miss_detection; zenoh's default is on for routers only).
2273
+ * - config: a Hash of zenoh configuration keys and values
2274
+ * ({"transport/link/tls/root_ca_certificate" => "ca.pem"}; the values are
2275
+ * Ruby values, sent as JSON), or a String with a whole JSON5
2276
+ * configuration. config_file: a JSON5 configuration file.
2277
+ * What wins, lowest first: zenoh's defaults, the gem's own settings (no
2278
+ * scouting, CONNECT_TIMEOUT_MS, SEND_TIMEOUT_MS, a connecting peer does
2279
+ * not listen), the file or the configuration String, the arguments
2280
+ * (locator, mode, listen, scouting, timestamping), the config Hash.
2281
+ * Raises Asterism::Zenoh::Error when the session cannot be opened (no
2282
+ * router or peer answered within the connect timeout). */
2283
+ static VALUE zrb_session_s_open(int argc, VALUE *argv, VALUE klass) {
2284
+ VALUE locator_v = Qnil, opts = Qnil;
2285
+ rb_scan_args(argc, argv, "01:", &locator_v, &opts);
2286
+ VALUE kw[6] = {Qundef, Qundef, Qundef, Qundef, Qundef, Qundef};
2287
+ if (!NIL_P(opts)) {
2288
+ ID ids[6] = {id_mode, id_listen, id_scouting, id_config, id_config_file, rb_intern("timestamping")};
2289
+ rb_get_kwargs(opts, ids, 0, 6, kw);
2290
+ }
2291
+ int timestamping = (kw[5] == Qundef || NIL_P(kw[5])) ? -1 : (RTEST(kw[5]) ? 1 : 0);
2292
+ int mode_arg = -1; /* 0 client, 1 peer */
2293
+ if (kw[0] != Qundef && !NIL_P(kw[0])) {
2294
+ ID mode = zrb_sym_id(kw[0]);
2295
+ if (mode == id_peer) {
2296
+ mode_arg = 1;
2297
+ } else if (mode == id_client) {
2298
+ mode_arg = 0;
2299
+ } else {
2300
+ rb_raise(rb_eArgError, "mode must be :client or :peer");
2301
+ }
2302
+ }
2303
+ const char *locator = NIL_P(locator_v) ? NULL : StringValueCStr(locator_v);
2304
+ VALUE listen_v = (kw[1] == Qundef) ? Qnil : kw[1];
2305
+ const char *listen = NIL_P(listen_v) ? NULL : StringValueCStr(listen_v);
2306
+ int scouting = (kw[2] == Qundef || NIL_P(kw[2])) ? -1 : (RTEST(kw[2]) ? 1 : 0);
2307
+ VALUE config_v = (kw[3] == Qundef) ? Qnil : kw[3];
2308
+ VALUE file_v = (kw[4] == Qundef) ? Qnil : kw[4];
2309
+ VALUE config_hash = Qnil, config_str = Qnil;
2310
+ if (!NIL_P(config_v)) {
2311
+ if (RB_TYPE_P(config_v, T_HASH)) {
2312
+ config_hash = config_v;
2313
+ } else if (RB_TYPE_P(config_v, T_STRING)) {
2314
+ config_str = config_v;
2315
+ } else {
2316
+ rb_raise(rb_eTypeError, "config must be a Hash or a String (JSON5)");
2317
+ }
2318
+ }
2319
+ const char *file = NIL_P(file_v) ? NULL : StringValueCStr(file_v);
2320
+ if (file != NULL && !NIL_P(config_str)) {
2321
+ rb_raise(rb_eArgError, "config: (a String) and config_file: cannot be used together");
2322
+ }
2323
+ bool user_base = (file != NULL || !NIL_P(config_str));
2324
+ if (mode_arg != 1 && listen != NULL && !user_base && NIL_P(config_hash)) {
2325
+ rb_raise(rb_eArgError, "listen needs mode: :peer");
2326
+ }
2327
+ if (locator == NULL && listen == NULL && scouting != 1 && !user_base && NIL_P(config_hash)) {
2328
+ rb_raise(rb_eArgError, "a locator (or, for a peer, listen:) is needed");
2329
+ }
2330
+ if (!NIL_P(config_hash)) {
2331
+ zrb_to_json(Qnil); /* loads json now, before anything is allocated */
2332
+ }
2333
+
2334
+ zrb_session *z;
2335
+ VALUE obj = TypedData_Make_Struct(klass, zrb_session, &zrb_session_type, z);
2336
+ pthread_mutex_init(&z->op_lock, NULL);
2337
+
2338
+ zrb_open_args a;
2339
+ a.z = z;
2340
+ z_owned_config_t dflt;
2341
+ z_result_t cr;
2342
+ if (file != NULL) {
2343
+ cr = zc_config_from_file(&a.config, file);
2344
+ } else if (!NIL_P(config_str)) {
2345
+ cr = zc_config_from_str(&a.config, StringValueCStr(config_str));
2346
+ } else {
2347
+ cr = z_config_default(&a.config);
2348
+ }
2349
+ if (cr != Z_OK) {
2350
+ if (file != NULL) {
2351
+ rb_raise(rb_eArgError, "cannot read the configuration file %s (%d)", file, (int)cr);
2352
+ }
2353
+ rb_raise(rb_eArgError, "invalid configuration (%d)", (int)cr);
2354
+ }
2355
+ if (user_base && z_config_default(&dflt) != Z_OK) {
2356
+ z_drop(z_move(a.config));
2357
+ rb_raise(eZenohError, "cannot create the configuration");
2358
+ }
2359
+ zrb_cfg c = {&a.config, user_base ? &dflt : NULL};
2360
+
2361
+ /* Peer or client, as far as the arguments and the file say (a config
2362
+ * Hash may still change it; the mode is read back below). */
2363
+ bool peer = (mode_arg == 1);
2364
+ if (mode_arg < 0 && user_base) {
2365
+ VALUE m = zrb_config_get(z_loan(a.config), "mode");
2366
+ peer = !NIL_P(m) && rb_str_equal(m, rb_str_new_cstr("\"peer\"")) == Qtrue;
2367
+ }
2368
+
2369
+ /* The gem's own settings mirror the mruby gem's zenoh-pico build: no
2370
+ * scouting (the locator is given), a connect-only peer does not listen,
2371
+ * and the session fails to open when nobody answers in time. */
2372
+ char num[32];
2373
+ bool ok = true;
2374
+ if (mode_arg >= 0) {
2375
+ ok = zrb_config_set(&a.config, "mode", mode_arg == 1 ? "\"peer\"" : "\"client\"");
2376
+ } else {
2377
+ ok = zrb_cfg_internal(&c, "mode", "\"client\"");
2378
+ }
2379
+ if (ok && scouting >= 0) {
2380
+ ok = zrb_config_set(&a.config, "scouting/multicast/enabled", scouting ? "true" : "false") &&
2381
+ zrb_config_set(&a.config, "scouting/gossip/enabled", scouting ? "true" : "false");
2382
+ } else if (ok) {
2383
+ ok = zrb_cfg_internal(&c, "scouting/multicast/enabled", "false") &&
2384
+ zrb_cfg_internal(&c, "scouting/gossip/enabled", "false");
2385
+ }
2386
+ if (ok) {
2387
+ snprintf(num, sizeof(num), "%d", ZRB_CONNECT_TIMEOUT_MS);
2388
+ ok = zrb_cfg_internal(&c, "connect/timeout_ms", num) &&
2389
+ zrb_cfg_internal(&c, "connect/exit_on_failure", "true");
2390
+ }
2391
+ if (ok) {
2392
+ snprintf(num, sizeof(num), "%d", ZRB_SEND_TIMEOUT_MS * 1000);
2393
+ ok = zrb_cfg_internal(&c, "transport/link/tx/queue/congestion_control/block/wait_before_close", num);
2394
+ }
2395
+ if (ok && timestamping >= 0) {
2396
+ ok = zrb_config_set(&a.config, "timestamping/enabled", timestamping ? "true" : "false");
2397
+ }
2398
+ if (ok && locator != NULL) {
2399
+ VALUE ep = zrb_json_endpoints(locator);
2400
+ ok = zrb_config_set(&a.config, "connect/endpoints", StringValueCStr(ep));
2401
+ }
2402
+ if (ok) {
2403
+ if (listen != NULL) {
2404
+ VALUE ep = zrb_json_endpoints(listen);
2405
+ ok = zrb_config_set(&a.config, "listen/endpoints", StringValueCStr(ep));
2406
+ } else if (!(peer && scouting == 1)) {
2407
+ /* A scouting peer keeps zenoh's own listener, so the others can
2408
+ * connect to it. */
2409
+ ok = zrb_cfg_internal(&c, "listen/endpoints", "[]");
2410
+ }
2411
+ }
2412
+ if (user_base) {
2413
+ z_drop(z_move(dflt));
2414
+ }
2415
+ if (!ok) {
2416
+ z_drop(z_move(a.config));
2417
+ rb_raise(eZenohError, "invalid locator");
2418
+ }
2419
+ if (!NIL_P(config_hash)) {
2420
+ zrb_cfg_hash h = {config_hash, &a.config, Qnil};
2421
+ int state = 0;
2422
+ rb_protect(zrb_cfg_hash_body, (VALUE)&h, &state);
2423
+ if (state != 0 || !NIL_P(h.bad)) {
2424
+ z_drop(z_move(a.config));
2425
+ if (state != 0) {
2426
+ rb_jump_tag(state);
2427
+ }
2428
+ rb_raise(rb_eArgError, "invalid configuration: %" PRIsVALUE, h.bad);
2429
+ }
2430
+ }
2431
+
2432
+ /* What the session will be, read back from the final configuration. */
2433
+ VALUE m = zrb_config_get(z_loan(a.config), "mode");
2434
+ bool is_router = !NIL_P(m) && rb_str_equal(m, rb_str_new_cstr("\"router\"")) == Qtrue;
2435
+ peer = is_router || (!NIL_P(m) && rb_str_equal(m, rb_str_new_cstr("\"peer\"")) == Qtrue);
2436
+ VALUE lst = zrb_config_get(z_loan(a.config), "listen/endpoints");
2437
+ VALUE mc = zrb_config_get(z_loan(a.config), "scouting/multicast/enabled");
2438
+ bool listens = !NIL_P(lst) && rb_str_equal(lst, rb_str_new_cstr("[]")) != Qtrue &&
2439
+ rb_str_equal(lst, rb_str_new_cstr("{}")) != Qtrue;
2440
+ bool scouts = !NIL_P(mc) && rb_str_equal(mc, rb_str_new_cstr("true")) == Qtrue;
2441
+
2442
+ rb_thread_call_without_gvl(zrb_open_nogvl, &a, RUBY_UBF_IO, NULL);
2443
+ if (a.ret != Z_OK) {
2444
+ rb_raise(eZenohError, "cannot open a session to %s (%d)%" PRIsVALUE,
2445
+ locator != NULL ? locator : (listen != NULL ? listen : "the configured endpoints"), (int)a.ret,
2446
+ zrb_last_error());
2447
+ }
2448
+ z->open = true;
2449
+ z->live = true;
2450
+ z->peer = peer;
2451
+ /* A peer that listens (or finds the others by scouting) stays open
2452
+ * without peers; one that only connects closes when it has none. */
2453
+ z->listening = peer && (is_router || listens || scouts);
2454
+ return obj;
2455
+ }
2456
+
2457
+ static VALUE zrb_sub_new(VALUE self, zrb_session *z, VALUE key_v, long depth, bool liveliness) {
2458
+ const char *key = StringValueCStr(key_v);
2459
+ z_view_keyexpr_t ke;
2460
+ zrb_view_key(&ke, key);
2461
+
2462
+ zrb_sub *s;
2463
+ VALUE obj = TypedData_Make_Struct(liveliness ? cWatch : cSubscriber, zrb_sub, &zrb_sub_type, s);
2464
+ s->liveliness = liveliness;
2465
+ s->type = liveliness ? ZSUB_LIVELINESS : ZSUB_PLAIN;
2466
+ s->ch = zch_new(ZCH_SAMPLE, (uint32_t)depth);
2467
+
2468
+ z_owned_closure_sample_t cb;
2469
+ zch_closure_sample(s->ch, &cb);
2470
+ z_result_t ret;
2471
+ if (liveliness) {
2472
+ /* history: the tokens alive now are reported first, as appearing. */
2473
+ z_liveliness_subscriber_options_t lo;
2474
+ z_liveliness_subscriber_options_default(&lo);
2475
+ lo.history = true;
2476
+ ret = z_liveliness_declare_subscriber(z_loan(z->session), &s->u.sub, z_loan(ke), z_move(cb), &lo);
2477
+ } else {
2478
+ /* Remote samples only: zenoh-pico (the mruby gem) does not deliver a
2479
+ * session's own puts to its own subscribers either. */
2480
+ z_subscriber_options_t so;
2481
+ z_subscriber_options_default(&so);
2482
+ so.allowed_origin = Z_LOCALITY_REMOTE;
2483
+ ret = z_declare_subscriber(z_loan(z->session), &s->u.sub, z_loan(ke), z_move(cb), &so);
2484
+ }
2485
+ if (ret != Z_OK) {
2486
+ rb_raise(eZenohError, "cannot subscribe to %s (%d)%" PRIsVALUE, key, (int)ret, zrb_last_error());
2487
+ }
2488
+ s->declared = true;
2489
+ s->owner = z;
2490
+ s->next = z->subs;
2491
+ z->subs = s;
2492
+ zrb_hold_session(obj, self, key_v);
2493
+ return obj;
2494
+ }
2495
+
2496
+ /* session.subscribe(key, depth = 16) -> Subscriber */
2497
+ static VALUE zrb_session_subscribe(int argc, VALUE *argv, VALUE self) {
2498
+ VALUE key_v, depth_v = Qnil;
2499
+ rb_scan_args(argc, argv, "11", &key_v, &depth_v);
2500
+ long depth = zrb_check_depth(depth_v);
2501
+ StringValueCStr(key_v);
2502
+ zrb_session *z = zrb_session_get_open(self);
2503
+ return zrb_sub_new(self, z, key_v, depth, false);
2504
+ }
2505
+
2506
+ /* session.liveliness_watch(key, depth = 16) -> LivelinessWatch */
2507
+ static VALUE zrb_session_liveliness_watch(int argc, VALUE *argv, VALUE self) {
2508
+ VALUE key_v, depth_v = Qnil;
2509
+ rb_scan_args(argc, argv, "11", &key_v, &depth_v);
2510
+ long depth = zrb_check_depth(depth_v);
2511
+ StringValueCStr(key_v);
2512
+ zrb_session *z = zrb_session_get_open(self);
2513
+ return zrb_sub_new(self, z, key_v, depth, true);
2514
+ }
2515
+
2516
+ /* session.queryable(key, depth = 16, complete: false) -> Queryable */
2517
+ static VALUE zrb_session_queryable(int argc, VALUE *argv, VALUE self) {
2518
+ VALUE key_v, depth_v = Qnil, opts = Qnil;
2519
+ rb_scan_args(argc, argv, "11:", &key_v, &depth_v, &opts);
2520
+ VALUE kw[1] = {Qundef};
2521
+ if (!NIL_P(opts)) {
2522
+ rb_get_kwargs(opts, &id_complete, 0, 1, kw);
2523
+ }
2524
+ bool complete = (kw[0] != Qundef) && RTEST(kw[0]);
2525
+ long depth = zrb_check_depth(depth_v);
2526
+ const char *key = StringValueCStr(key_v);
2527
+ zrb_session *z = zrb_session_get_open(self);
2528
+ z_view_keyexpr_t ke;
2529
+ zrb_view_key(&ke, key);
2530
+
2531
+ zrb_qable *q;
2532
+ VALUE obj = TypedData_Make_Struct(cQueryable, zrb_qable, &zrb_qable_type, q);
2533
+ q->ch = zch_new(ZCH_QUERY, (uint32_t)depth);
2534
+ z_owned_closure_query_t cb;
2535
+ zch_closure_query(q->ch, &cb);
2536
+ z_queryable_options_t qo;
2537
+ z_queryable_options_default(&qo);
2538
+ qo.complete = complete;
2539
+ /* Remote queries only, as with zenoh-pico (Asterism answers calls to
2540
+ * its own objects in place). */
2541
+ qo.allowed_origin = Z_LOCALITY_REMOTE;
2542
+ z_result_t ret = z_declare_queryable(z_loan(z->session), &q->qable, z_loan(ke), z_move(cb), &qo);
2543
+ if (ret != Z_OK) {
2544
+ rb_raise(eZenohError, "cannot declare a queryable on %s (%d)%" PRIsVALUE, key, (int)ret, zrb_last_error());
2545
+ }
2546
+ q->declared = true;
2547
+ q->owner = z;
2548
+ q->next = z->qables;
2549
+ z->qables = q;
2550
+ zrb_hold_session(obj, self, key_v);
2551
+ return obj;
2552
+ }
2553
+
2554
+ static z_query_target_t zrb_get_target(VALUE v) {
2555
+ if (v == Qundef || NIL_P(v)) {
2556
+ return Z_QUERY_TARGET_ALL;
2557
+ }
2558
+ ID t = zrb_sym_id(v);
2559
+ if (t == id_all) {
2560
+ return Z_QUERY_TARGET_ALL;
2561
+ }
2562
+ if (t == id_all_complete) {
2563
+ return Z_QUERY_TARGET_ALL_COMPLETE;
2564
+ }
2565
+ if (t == id_best_matching) {
2566
+ return Z_QUERY_TARGET_BEST_MATCHING;
2567
+ }
2568
+ rb_raise(rb_eArgError, "target must be :all, :all_complete or :best_matching");
2569
+ return Z_QUERY_TARGET_ALL; /* not reached */
2570
+ }
2571
+
2572
+ static z_query_consolidation_t zrb_get_consolidation(VALUE v) {
2573
+ if (v == Qundef || NIL_P(v)) {
2574
+ return z_query_consolidation_none();
2575
+ }
2576
+ ID c = zrb_sym_id(v);
2577
+ if (c == id_none) {
2578
+ return z_query_consolidation_none();
2579
+ }
2580
+ if (c == id_latest) {
2581
+ return z_query_consolidation_latest();
2582
+ }
2583
+ if (c == id_monotonic) {
2584
+ return z_query_consolidation_monotonic();
2585
+ }
2586
+ if (c == id_auto) {
2587
+ return z_query_consolidation_auto();
2588
+ }
2589
+ rb_raise(rb_eArgError, "consolidation must be :none, :latest, :monotonic or :auto");
2590
+ return z_query_consolidation_none(); /* not reached */
2591
+ }
2592
+
2593
+ typedef struct {
2594
+ zrb_session *z;
2595
+ z_owned_keyexpr_t key;
2596
+ char *params; /* malloc'd copy, or NULL */
2597
+ bool liveliness;
2598
+ z_owned_closure_reply_t cb;
2599
+ z_get_options_t opts;
2600
+ z_liveliness_get_options_t lopts;
2601
+ z_result_t ret;
2602
+ } zrb_get_args;
2603
+
2604
+ static void *zrb_get_nogvl(void *p) {
2605
+ zrb_get_args *a = (zrb_get_args *)p;
2606
+ pthread_mutex_lock(&a->z->op_lock);
2607
+ if (a->z->live) {
2608
+ if (a->liveliness) {
2609
+ a->ret = z_liveliness_get(z_loan(a->z->session), z_loan(a->key), z_move(a->cb), &a->lopts);
2610
+ } else {
2611
+ a->ret = z_get(z_loan(a->z->session), z_loan(a->key), a->params != NULL ? a->params : "", z_move(a->cb),
2612
+ &a->opts);
2613
+ }
2614
+ } else {
2615
+ a->ret = Z_ESESSION_CLOSED;
2616
+ }
2617
+ pthread_mutex_unlock(&a->z->op_lock);
2618
+ /* A closure that was not taken (the session was closed) is dropped
2619
+ * here, which releases the channel's reference. */
2620
+ z_drop(z_move(a->cb));
2621
+ return NULL;
2622
+ }
2623
+
2624
+ static VALUE zrb_run_get(VALUE self, zrb_session *z, zrb_get_args *a, VALUE obj, VALUE key_v, const char *what) {
2625
+ rb_thread_call_without_gvl(zrb_get_nogvl, a, RUBY_UBF_IO, NULL);
2626
+ z_drop(z_move(a->key));
2627
+ free(a->params);
2628
+ if (zrb_session_check_link(z)) {
2629
+ rb_raise(eZenohError, "%s failed: the connection is lost (%d)", what, (int)a->ret);
2630
+ }
2631
+ if (a->ret != Z_OK) {
2632
+ rb_raise(eZenohError, "%s failed (%d)", what, (int)a->ret);
2633
+ }
2634
+ zrb_hold_session(obj, self, key_v);
2635
+ return obj;
2636
+ }
2637
+
2638
+ static const char *const zrb_get_kw[] = {"attachment", "target", "consolidation", "encoding",
2639
+ "priority", "congestion_control", "express", "accept_replies"};
2640
+
2641
+ /* session.get(key, timeout_ms = 2000, params = nil, payload = nil,
2642
+ * attachment: nil, target: :all, consolidation: :none,
2643
+ * encoding: nil, priority: nil, congestion_control: nil,
2644
+ * express: nil, accept_replies: nil) -> Get.
2645
+ * Returns at once; the replies come in on zenoh's threads. key: a String
2646
+ * or a KeyExpr. accept_replies: :matching_query (zenoh's default) or :any. */
2647
+ static VALUE zrb_session_get_m(int argc, VALUE *argv, VALUE self) {
2648
+ VALUE key_v, timeout_v = Qnil, params_v = Qnil, payload = Qnil, opts = Qnil;
2649
+ rb_scan_args(argc, argv, "13:", &key_v, &timeout_v, &params_v, &payload, &opts);
2650
+ zrb_opts o;
2651
+ zrb_opts_parse(opts, zrb_get_kw, 8, &o);
2652
+ VALUE key_str = zrb_key_string(key_v);
2653
+ long timeout_ms = zrb_check_timeout(timeout_v);
2654
+ const char *params = NIL_P(params_v) ? NULL : StringValueCStr(params_v);
2655
+ if (!NIL_P(payload) && !RB_TYPE_P(payload, T_STRING)) {
2656
+ rb_raise(rb_eTypeError, "payload must be a String");
2657
+ }
2658
+ z_query_target_t target = zrb_get_target(o.has_target ? o.target : Qnil);
2659
+ z_query_consolidation_t consolidation = zrb_get_consolidation(o.has_consolidation ? o.consolidation : Qnil);
2660
+ zrb_session *z = zrb_session_get_open(self);
2661
+
2662
+ zrb_get_args a;
2663
+ memset(&a, 0, sizeof(a));
2664
+ a.z = z;
2665
+ zrb_key_owned(key_v, &a.key);
2666
+ zrb_get *g;
2667
+ VALUE obj = zrb_get_new(&g);
2668
+ z_get_options_default(&a.opts);
2669
+ a.opts.timeout_ms = (uint64_t)timeout_ms;
2670
+ a.opts.target = target;
2671
+ a.opts.consolidation = consolidation;
2672
+ /* Remote queryables only, as with zenoh-pico. */
2673
+ a.opts.allowed_destination = Z_LOCALITY_REMOTE;
2674
+ if (o.priority >= 0) {
2675
+ a.opts.priority = (z_priority_t)o.priority;
2676
+ }
2677
+ if (o.congestion_control >= 0) {
2678
+ a.opts.congestion_control = (z_congestion_control_t)o.congestion_control;
2679
+ }
2680
+ if (o.express >= 0) {
2681
+ a.opts.is_express = o.express;
2682
+ }
2683
+ if (o.accept_replies >= 0) {
2684
+ a.opts.accept_replies = (z_reply_keyexpr_t)o.accept_replies;
2685
+ }
2686
+ z_owned_bytes_t bytes;
2687
+ z_owned_bytes_t att_bytes;
2688
+ z_owned_encoding_t enc;
2689
+ if (!NIL_P(payload)) {
2690
+ zrb_bytes_from_str(&bytes, payload, "payload");
2691
+ a.opts.payload = z_move(bytes);
2692
+ }
2693
+ if (!NIL_P(o.attachment)) {
2694
+ zrb_bytes_from_str(&att_bytes, o.attachment, "attachment");
2695
+ a.opts.attachment = z_move(att_bytes);
2696
+ }
2697
+ if (zrb_encoding_make(&enc, o.encoding)) {
2698
+ a.opts.encoding = z_move(enc);
2699
+ }
2700
+ if (params != NULL) {
2701
+ a.params = strdup(params);
2702
+ }
2703
+ zch_closure_reply(g->ch, &a.cb);
2704
+ return zrb_run_get(self, z, &a, obj, key_str, "get");
2705
+ }
2706
+
2707
+ /* session.liveliness(key) -> LivelinessToken */
2708
+ static VALUE zrb_session_liveliness(VALUE self, VALUE key_v) {
2709
+ const char *key = StringValueCStr(key_v);
2710
+ zrb_session *z = zrb_session_get_open(self);
2711
+ z_view_keyexpr_t ke;
2712
+ zrb_view_key(&ke, key);
2713
+ zrb_token *t;
2714
+ VALUE obj = TypedData_Make_Struct(cToken, zrb_token, &zrb_token_type, t);
2715
+ z_result_t ret = z_liveliness_declare_token(z_loan(z->session), &t->token, z_loan(ke), NULL);
2716
+ if (ret != Z_OK) {
2717
+ rb_raise(eZenohError, "cannot declare a liveliness token on %s (%d)%" PRIsVALUE, key, (int)ret, zrb_last_error());
2718
+ }
2719
+ t->declared = true;
2720
+ t->owner = z;
2721
+ t->next = z->tokens;
2722
+ z->tokens = t;
2723
+ zrb_hold_session(obj, self, key_v);
2724
+ return obj;
2725
+ }
2726
+
2727
+ /* session.liveliness_get(key, timeout_ms = 2000) -> Get */
2728
+ static VALUE zrb_session_liveliness_get(int argc, VALUE *argv, VALUE self) {
2729
+ VALUE key_v, timeout_v = Qnil;
2730
+ rb_scan_args(argc, argv, "11", &key_v, &timeout_v);
2731
+ const char *key = StringValueCStr(key_v);
2732
+ long timeout_ms = zrb_check_timeout(timeout_v);
2733
+ zrb_session *z = zrb_session_get_open(self);
2734
+
2735
+ zrb_get_args a;
2736
+ memset(&a, 0, sizeof(a));
2737
+ a.z = z;
2738
+ a.liveliness = true;
2739
+ zrb_owned_key(&a.key, key);
2740
+ zrb_get *g;
2741
+ VALUE obj = zrb_get_new(&g);
2742
+ z_liveliness_get_options_default(&a.lopts);
2743
+ a.lopts.timeout_ms = (uint64_t)timeout_ms;
2744
+ zch_closure_reply(g->ch, &a.cb);
2745
+ return zrb_run_get(self, z, &a, obj, key_v, "liveliness_get");
2746
+ }
2747
+
2748
+ /* session.poll(steps = 8) -> true while the session is open, false once
2749
+ * closed (by close, or because the connection was lost). zenoh-c receives
2750
+ * on its own threads, so this only checks the connection; steps is
2751
+ * accepted for the mruby gem's signature. Never waits. */
2752
+ static VALUE zrb_session_poll(int argc, VALUE *argv, VALUE self) {
2753
+ VALUE steps_v = Qnil;
2754
+ rb_scan_args(argc, argv, "01", &steps_v);
2755
+ if (!NIL_P(steps_v)) {
2756
+ NUM2LONG(steps_v);
2757
+ }
2758
+ return zrb_session_check_link(zrb_session_get(self)) ? Qfalse : Qtrue;
2759
+ }
2760
+
2761
+ static VALUE zrb_session_closed_p(VALUE self) {
2762
+ return zrb_session_check_link(zrb_session_get(self)) ? Qtrue : Qfalse;
2763
+ }
2764
+
2765
+ static VALUE zrb_session_close(VALUE self) {
2766
+ zrb_session_shutdown(zrb_session_get(self), true);
2767
+ return Qnil;
2768
+ }
2769
+
2770
+ /* session.zid -> String: this session's Zenoh ID in hex. */
2771
+ static VALUE zrb_session_zid(VALUE self) {
2772
+ zrb_session *z = zrb_session_get_open(self);
2773
+ z_id_t id = z_info_zid(z_loan(z->session));
2774
+ z_owned_string_t str;
2775
+ z_id_to_string(&id, &str);
2776
+ VALUE out = zrb_str_from_view(z_loan(str));
2777
+ z_drop(z_move(str));
2778
+ return out;
2779
+ }
2780
+
2781
+ /* session.peers -> Integer: connected peers (peer mode), or routers (1
2782
+ * normally) for a client session; 0 once closed. */
2783
+ static VALUE zrb_session_peers(VALUE self) {
2784
+ zrb_session *z = zrb_session_get(self);
2785
+ if (zrb_session_check_link(z)) {
2786
+ return INT2FIX(0);
2787
+ }
2788
+ return INT2FIX(zrb_session_links(z));
2789
+ }
2790
+
2791
+ /* The default of zenoh-c's transport/unicast/max_sessions (MAX_PEERS). */
2792
+ static long zrb_default_max_sessions(void) {
2793
+ long n = -1;
2794
+ z_owned_config_t c;
2795
+ if (z_config_default(&c) != Z_OK) {
2796
+ return n;
2797
+ }
2798
+ z_owned_string_t s;
2799
+ if (zc_config_get_from_str(z_loan(c), "transport/unicast/max_sessions", &s) == Z_OK) {
2800
+ char buf[32];
2801
+ size_t len = z_string_len(z_loan(s));
2802
+ if (len < sizeof(buf)) {
2803
+ memcpy(buf, z_string_data(z_loan(s)), len);
2804
+ buf[len] = '\0';
2805
+ n = strtol(buf, NULL, 10);
2806
+ }
2807
+ z_drop(z_move(s));
2808
+ }
2809
+ z_drop(z_move(c));
2810
+ return n;
2811
+ }
2812
+
2813
+ /* ------------------------------------------------- sending (0.3.0 path) */
2814
+
2815
+ typedef struct zrb_pub zrb_pub;
2816
+
2817
+ struct zrb_pub {
2818
+ zrb_ent ent;
2819
+ bool advanced;
2820
+ union {
2821
+ z_owned_publisher_t p;
2822
+ ze_owned_advanced_publisher_t a;
2823
+ } u;
2824
+ };
2825
+
2826
+ typedef enum { ZS_PUT, ZS_DEL, ZS_PPUT, ZS_PDEL, ZS_APUT, ZS_ADEL } zsend_op;
2827
+
2828
+ /* One put or delete, of the session or of a publisher, made without the
2829
+ * GVL. Everything owned is null until made, and dropped after the call
2830
+ * (a value zenoh-c took is left empty, so dropping it again is a no-op). */
975
2831
  typedef struct {
976
2832
  zrb_session *z;
977
- z_owned_config_t config;
2833
+ zrb_pub *pub;
2834
+ zsend_op op;
2835
+ z_owned_keyexpr_t key;
2836
+ z_owned_bytes_t payload;
2837
+ z_owned_bytes_t att;
2838
+ z_owned_encoding_t enc;
2839
+ z_timestamp_t ts;
2840
+ union {
2841
+ z_put_options_t put;
2842
+ z_delete_options_t del;
2843
+ z_publisher_put_options_t pput;
2844
+ z_publisher_delete_options_t pdel;
2845
+ ze_advanced_publisher_put_options_t aput;
2846
+ ze_advanced_publisher_delete_options_t adel;
2847
+ } o;
2848
+ bool undeclared; /* the publisher was closed */
978
2849
  z_result_t ret;
979
- } zrb_open_args;
2850
+ } zrb_send;
2851
+
2852
+ static void zrb_send_init(zrb_send *s, zrb_session *z, zrb_pub *pub, zsend_op op) {
2853
+ memset(s, 0, sizeof(*s));
2854
+ s->z = z;
2855
+ s->pub = pub;
2856
+ s->op = op;
2857
+ s->ret = Z_OK;
2858
+ z_internal_keyexpr_null(&s->key);
2859
+ z_internal_bytes_null(&s->payload);
2860
+ z_internal_bytes_null(&s->att);
2861
+ z_internal_encoding_null(&s->enc);
2862
+ }
2863
+
2864
+ static void *zrb_send_nogvl(void *p) {
2865
+ zrb_send *s = (zrb_send *)p;
2866
+ pthread_mutex_lock(&s->z->op_lock);
2867
+ if (!s->z->live) {
2868
+ s->ret = Z_ESESSION_CLOSED;
2869
+ } else if (s->pub != NULL && !s->pub->ent.declared) {
2870
+ s->undeclared = true;
2871
+ } else {
2872
+ switch (s->op) {
2873
+ case ZS_PUT:
2874
+ s->ret = z_put(z_loan(s->z->session), z_loan(s->key), z_move(s->payload), &s->o.put);
2875
+ break;
2876
+ case ZS_DEL:
2877
+ s->ret = z_delete(z_loan(s->z->session), z_loan(s->key), &s->o.del);
2878
+ break;
2879
+ case ZS_PPUT:
2880
+ s->ret = z_publisher_put(z_loan(s->pub->u.p), z_move(s->payload), &s->o.pput);
2881
+ break;
2882
+ case ZS_PDEL:
2883
+ s->ret = z_publisher_delete(z_loan(s->pub->u.p), &s->o.pdel);
2884
+ break;
2885
+ case ZS_APUT:
2886
+ s->ret = ze_advanced_publisher_put(z_loan(s->pub->u.a), z_move(s->payload), &s->o.aput);
2887
+ break;
2888
+ case ZS_ADEL:
2889
+ s->ret = ze_advanced_publisher_delete(z_loan(s->pub->u.a), &s->o.adel);
2890
+ break;
2891
+ }
2892
+ }
2893
+ pthread_mutex_unlock(&s->z->op_lock);
2894
+ return NULL;
2895
+ }
2896
+
2897
+ static void zrb_send_run(zrb_send *s, const char *what) {
2898
+ rb_thread_call_without_gvl(zrb_send_nogvl, s, RUBY_UBF_IO, NULL);
2899
+ z_drop(z_move(s->key));
2900
+ z_drop(z_move(s->payload));
2901
+ z_drop(z_move(s->att));
2902
+ z_drop(z_move(s->enc));
2903
+ if (zrb_session_check_link(s->z)) {
2904
+ rb_raise(eZenohError, "%s failed: the connection is lost (%d)", what, (int)s->ret);
2905
+ }
2906
+ if (s->undeclared) {
2907
+ rb_raise(eZenohError, "%s failed: the publisher is closed", what);
2908
+ }
2909
+ if (s->ret != Z_OK) {
2910
+ rb_raise(eZenohError, "%s failed (%d)", what, (int)s->ret);
2911
+ }
2912
+ }
2913
+
2914
+ /* The timestamp option (nil, true for a new one, or a Timestamp). */
2915
+ static z_timestamp_t *zrb_send_timestamp(zrb_send *s, VALUE v) {
2916
+ if (NIL_P(v)) {
2917
+ return NULL;
2918
+ }
2919
+ if (v == Qtrue) {
2920
+ if (z_timestamp_new(&s->ts, z_loan(s->z->session)) != Z_OK) {
2921
+ rb_raise(eZenohError, "cannot make a timestamp");
2922
+ }
2923
+ } else {
2924
+ s->ts = zrb_ts_get(v)->ts;
2925
+ }
2926
+ return &s->ts;
2927
+ }
2928
+
2929
+ /* Payload, attachment and encoding into s (after every check: only
2930
+ * allocation failures raise from here on). */
2931
+ static void zrb_send_values(zrb_send *s, VALUE payload, const zrb_opts *o) {
2932
+ if (!NIL_P(payload)) {
2933
+ zrb_bytes_from_str(&s->payload, payload, "payload");
2934
+ }
2935
+ if (!NIL_P(o->attachment)) {
2936
+ zrb_bytes_from_str(&s->att, o->attachment, "attachment");
2937
+ }
2938
+ zrb_encoding_make(&s->enc, o->encoding);
2939
+ }
2940
+
2941
+ static const char *const zrb_put_kw[] = {"attachment", "encoding", "priority", "congestion_control",
2942
+ "express", "reliability", "timestamp", "allowed_destination"};
2943
+ static const char *const zrb_del_kw[] = {"priority", "congestion_control", "express",
2944
+ "reliability", "timestamp", "allowed_destination"};
2945
+
2946
+ /* session.put(key, payload, attachment: nil, encoding: nil, priority: nil,
2947
+ * congestion_control: nil, express: nil, reliability: nil,
2948
+ * timestamp: nil, allowed_destination: nil) -> nil.
2949
+ * key: a String or a KeyExpr. encoding: a String ("application/json").
2950
+ * priority: :real_time .. :background (or 1..7), congestion_control:
2951
+ * :drop / :block / :block_first, reliability: :reliable / :best_effort,
2952
+ * timestamp: true (a new one) or a Timestamp, allowed_destination: :any /
2953
+ * :remote / :session_local. nil (or left out) is zenoh-c's default. */
2954
+ static VALUE zrb_session_put(int argc, VALUE *argv, VALUE self) {
2955
+ VALUE key_v, payload, opts = Qnil;
2956
+ rb_scan_args(argc, argv, "2:", &key_v, &payload, &opts);
2957
+ zrb_opts o;
2958
+ zrb_opts_parse(opts, zrb_put_kw, 8, &o);
2959
+ StringValue(payload);
2960
+ zrb_key_string(key_v);
2961
+ zrb_session *z = zrb_session_get_open(self);
2962
+ zrb_send s;
2963
+ zrb_send_init(&s, z, NULL, ZS_PUT);
2964
+ z_put_options_default(&s.o.put);
2965
+ s.o.put.timestamp = zrb_send_timestamp(&s, o.timestamp);
2966
+ if (o.priority >= 0) {
2967
+ s.o.put.priority = (z_priority_t)o.priority;
2968
+ }
2969
+ if (o.congestion_control >= 0) {
2970
+ s.o.put.congestion_control = (z_congestion_control_t)o.congestion_control;
2971
+ }
2972
+ if (o.express >= 0) {
2973
+ s.o.put.is_express = o.express;
2974
+ }
2975
+ if (o.reliability >= 0) {
2976
+ s.o.put.reliability = (z_reliability_t)o.reliability;
2977
+ }
2978
+ if (o.destination >= 0) {
2979
+ s.o.put.allowed_destination = (z_locality_t)o.destination;
2980
+ }
2981
+ zrb_key_owned(key_v, &s.key);
2982
+ zrb_send_values(&s, payload, &o);
2983
+ if (!NIL_P(o.attachment)) {
2984
+ s.o.put.attachment = z_move(s.att);
2985
+ }
2986
+ if (!NIL_P(o.encoding)) {
2987
+ s.o.put.encoding = z_move(s.enc);
2988
+ }
2989
+ zrb_send_run(&s, "put");
2990
+ return Qnil;
2991
+ }
2992
+
2993
+ /* session.delete(key, priority:, congestion_control:, express:,
2994
+ * reliability:, timestamp:, allowed_destination:) -> nil.
2995
+ * Subscribers get a sample of kind :delete (each_pending gives it with an
2996
+ * empty payload). */
2997
+ static VALUE zrb_session_delete(int argc, VALUE *argv, VALUE self) {
2998
+ VALUE key_v, opts = Qnil;
2999
+ rb_scan_args(argc, argv, "1:", &key_v, &opts);
3000
+ zrb_opts o;
3001
+ zrb_opts_parse(opts, zrb_del_kw, 6, &o);
3002
+ zrb_key_string(key_v);
3003
+ zrb_session *z = zrb_session_get_open(self);
3004
+ zrb_send s;
3005
+ zrb_send_init(&s, z, NULL, ZS_DEL);
3006
+ z_delete_options_default(&s.o.del);
3007
+ s.o.del.timestamp = zrb_send_timestamp(&s, o.timestamp);
3008
+ if (o.priority >= 0) {
3009
+ s.o.del.priority = (z_priority_t)o.priority;
3010
+ }
3011
+ if (o.congestion_control >= 0) {
3012
+ s.o.del.congestion_control = (z_congestion_control_t)o.congestion_control;
3013
+ }
3014
+ if (o.express >= 0) {
3015
+ s.o.del.is_express = o.express;
3016
+ }
3017
+ if (o.reliability >= 0) {
3018
+ s.o.del.reliability = (z_reliability_t)o.reliability;
3019
+ }
3020
+ if (o.destination >= 0) {
3021
+ s.o.del.allowed_destination = (z_locality_t)o.destination;
3022
+ }
3023
+ zrb_key_owned(key_v, &s.key);
3024
+ zrb_send_run(&s, "delete");
3025
+ return Qnil;
3026
+ }
3027
+
3028
+ /* ----------------------------------------------------------- publishers */
3029
+
3030
+ static void zrb_pub_undeclare(zrb_ent *e) {
3031
+ zrb_pub *p = (zrb_pub *)e;
3032
+ if (p->advanced) {
3033
+ z_drop(z_move(p->u.a));
3034
+ } else {
3035
+ z_drop(z_move(p->u.p));
3036
+ }
3037
+ }
3038
+
3039
+ static void zrb_pub_free(void *ptr) {
3040
+ zrb_pub *p = (zrb_pub *)ptr;
3041
+ zrb_ent_detach(&p->ent);
3042
+ xfree(p);
3043
+ }
3044
+
3045
+ static size_t zrb_pub_size(const void *p) { return sizeof(zrb_pub); }
3046
+
3047
+ static const rb_data_type_t zrb_pub_type = {"Asterism::Zenoh::Publisher", {NULL, zrb_pub_free, zrb_pub_size}, NULL, NULL, 0};
3048
+
3049
+ static zrb_pub *zrb_pub_get(VALUE self) {
3050
+ zrb_pub *p;
3051
+ TypedData_Get_Struct(self, zrb_pub, &zrb_pub_type, p);
3052
+ return p;
3053
+ }
3054
+
3055
+ /* The publisher, declared, with its session open. */
3056
+ static zrb_pub *zrb_pub_get_open(VALUE self) {
3057
+ zrb_pub *p = zrb_pub_get(self);
3058
+ if (!p->ent.declared) {
3059
+ rb_raise(eZenohError, "the publisher is closed");
3060
+ }
3061
+ if (zrb_session_check_link(p->ent.owner)) {
3062
+ rb_raise(eZenohError, "session is closed");
3063
+ }
3064
+ return p;
3065
+ }
3066
+
3067
+ static const char *const zrb_pub_kw[] = {"encoding", "priority", "congestion_control", "express",
3068
+ "reliability", "allowed_destination"};
3069
+
3070
+ static void zrb_pub_options(z_publisher_options_t *po, const zrb_opts *o) {
3071
+ if (o->priority >= 0) {
3072
+ po->priority = (z_priority_t)o->priority;
3073
+ }
3074
+ if (o->congestion_control >= 0) {
3075
+ po->congestion_control = (z_congestion_control_t)o->congestion_control;
3076
+ }
3077
+ if (o->express >= 0) {
3078
+ po->is_express = o->express;
3079
+ }
3080
+ if (o->reliability >= 0) {
3081
+ po->reliability = (z_reliability_t)o->reliability;
3082
+ }
3083
+ if (o->destination >= 0) {
3084
+ po->allowed_destination = (z_locality_t)o->destination;
3085
+ }
3086
+ }
3087
+
3088
+ /* A sub-option: v is nil / false (off), true (on with zenoh's defaults),
3089
+ * an Integer (for cache: the number of samples) or a Hash of the given
3090
+ * keys. Returns the Hash (or nil), raises for unknown keys. */
3091
+ static VALUE zrb_subopt_hash(VALUE v, const char *what, const char *const *keys, int n) {
3092
+ if (!RB_TYPE_P(v, T_HASH)) {
3093
+ return Qnil;
3094
+ }
3095
+ VALUE ks = rb_funcall(v, rb_intern("keys"), 0);
3096
+ for (long i = 0; i < RARRAY_LEN(ks); i++) {
3097
+ VALUE k = RARRAY_AREF(ks, i);
3098
+ bool known = false;
3099
+ if (SYMBOL_P(k)) {
3100
+ for (int j = 0; j < n; j++) {
3101
+ if (SYM2ID(k) == rb_intern(keys[j])) {
3102
+ known = true;
3103
+ }
3104
+ }
3105
+ }
3106
+ if (!known) {
3107
+ rb_raise(rb_eArgError, "unknown key in %s: %" PRIsVALUE, what, k);
3108
+ }
3109
+ }
3110
+ return v;
3111
+ }
3112
+
3113
+ static VALUE zrb_hget(VALUE h, const char *key) {
3114
+ if (NIL_P(h)) {
3115
+ return Qnil;
3116
+ }
3117
+ return rb_hash_lookup2(h, ID2SYM(rb_intern(key)), Qnil);
3118
+ }
3119
+
3120
+ static uint64_t zrb_ms_arg(VALUE v, const char *what) {
3121
+ long long ms = NUM2LL(v);
3122
+ if (ms < 0) {
3123
+ rb_raise(rb_eArgError, "%s must be 0 or more", what);
3124
+ }
3125
+ return (uint64_t)ms;
3126
+ }
3127
+
3128
+ static VALUE zrb_pub_wrap(VALUE self, zrb_session *z, zrb_pub *p, VALUE obj, VALUE key_str) {
3129
+ zrb_ent_link(&p->ent, z, ZENT_ENTITY, true, zrb_pub_undeclare);
3130
+ zrb_hold_session(obj, self, key_str);
3131
+ return obj;
3132
+ }
3133
+
3134
+ /* session.publisher(key, encoding:, priority:, congestion_control:,
3135
+ * express:, reliability:, allowed_destination:) -> Publisher */
3136
+ static VALUE zrb_session_publisher(int argc, VALUE *argv, VALUE self) {
3137
+ VALUE key_v, opts = Qnil;
3138
+ rb_scan_args(argc, argv, "1:", &key_v, &opts);
3139
+ zrb_opts o;
3140
+ zrb_opts_parse(opts, zrb_pub_kw, 6, &o);
3141
+ VALUE key_str = zrb_key_string(key_v);
3142
+ zrb_session *z = zrb_session_get_open(self);
3143
+ z_view_keyexpr_t view;
3144
+ const z_loaned_keyexpr_t *ke = zrb_key_loan(key_v, &view);
3145
+ zrb_pub *p;
3146
+ VALUE obj = TypedData_Make_Struct(cPublisher, zrb_pub, &zrb_pub_type, p);
3147
+ z_publisher_options_t po;
3148
+ z_publisher_options_default(&po);
3149
+ zrb_pub_options(&po, &o);
3150
+ z_owned_encoding_t enc;
3151
+ if (zrb_encoding_make(&enc, o.encoding)) {
3152
+ po.encoding = z_move(enc);
3153
+ }
3154
+ z_result_t ret = z_declare_publisher(z_loan(z->session), &p->u.p, ke, &po);
3155
+ if (ret != Z_OK) {
3156
+ rb_raise(eZenohError, "cannot declare a publisher on %" PRIsVALUE " (%d)%" PRIsVALUE, key_str, (int)ret, zrb_last_error());
3157
+ }
3158
+ return zrb_pub_wrap(self, z, p, obj, key_str);
3159
+ }
3160
+
3161
+ static const char *const zrb_cache_keys[] = {"max_samples", "priority", "congestion_control", "express"};
3162
+ static const char *const zrb_smd_keys[] = {"heartbeat", "heartbeat_ms"};
3163
+
3164
+ /* session.advanced_publisher(key, cache: nil, sample_miss_detection: nil,
3165
+ * publisher_detection: false, **publisher options) -> AdvancedPublisher
3166
+ * cache: N (keep the last N samples for late subscribers, the history of
3167
+ * an advanced subscriber), true (zenoh's default size) or a Hash
3168
+ * {max_samples:, priority:, congestion_control:, express:}.
3169
+ * sample_miss_detection: true or {heartbeat: :periodic / :sporadic,
3170
+ * heartbeat_ms:} (lets advanced subscribers notice and recover lost
3171
+ * samples). publisher_detection: true declares a liveliness token that
3172
+ * advanced subscribers can watch (detect_publishers). A cache without
3173
+ * sample_miss_detection orders the samples by their timestamps: the
3174
+ * session needs timestamping (Session.open(..., timestamping: true)). */
3175
+ static VALUE zrb_session_advanced_publisher(int argc, VALUE *argv, VALUE self) {
3176
+ VALUE key_v, opts = Qnil;
3177
+ rb_scan_args(argc, argv, "1:", &key_v, &opts);
3178
+ static const char *const kws[] = {"encoding", "priority", "congestion_control", "express", "reliability",
3179
+ "allowed_destination", "cache", "sample_miss_detection",
3180
+ "publisher_detection"};
3181
+ VALUE extra[3] = {Qnil, Qnil, Qnil};
3182
+ VALUE base = Qnil;
3183
+ if (!NIL_P(opts)) {
3184
+ /* Split our three keywords from the publisher's ones. */
3185
+ base = rb_hash_dup(opts);
3186
+ for (int i = 0; i < 3; i++) {
3187
+ extra[i] = rb_hash_delete(base, ID2SYM(rb_intern(kws[6 + i])));
3188
+ }
3189
+ }
3190
+ zrb_opts o;
3191
+ zrb_opts_parse(base, kws, 6, &o);
3192
+ VALUE cache_h = zrb_subopt_hash(extra[0], "cache", zrb_cache_keys, 4);
3193
+ VALUE smd_h = zrb_subopt_hash(extra[1], "sample_miss_detection", zrb_smd_keys, 2);
3194
+
3195
+ ze_advanced_publisher_options_t ao;
3196
+ ze_advanced_publisher_options_default(&ao);
3197
+ zrb_pub_options(&ao.publisher_options, &o);
3198
+ if (RTEST(extra[0])) {
3199
+ ao.cache.is_enabled = true;
3200
+ if (RB_INTEGER_TYPE_P(extra[0])) {
3201
+ long n = NUM2LONG(extra[0]);
3202
+ if (n < 1) {
3203
+ rb_raise(rb_eArgError, "cache must be 1 or more samples");
3204
+ }
3205
+ ao.cache.max_samples = (size_t)n;
3206
+ } else if (!NIL_P(cache_h)) {
3207
+ VALUE v;
3208
+ if (!NIL_P(v = zrb_hget(cache_h, "max_samples"))) {
3209
+ ao.cache.max_samples = (size_t)NUM2ULONG(v);
3210
+ }
3211
+ if (!NIL_P(v = zrb_hget(cache_h, "priority"))) {
3212
+ ao.cache.priority = (z_priority_t)zrb_priority_arg(v);
3213
+ }
3214
+ if (!NIL_P(v = zrb_hget(cache_h, "congestion_control"))) {
3215
+ ao.cache.congestion_control = (z_congestion_control_t)zrb_cc_arg(v);
3216
+ }
3217
+ if (!NIL_P(v = zrb_hget(cache_h, "express"))) {
3218
+ ao.cache.is_express = RTEST(v);
3219
+ }
3220
+ } else if (extra[0] != Qtrue) {
3221
+ rb_raise(rb_eTypeError, "cache must be an Integer, true or a Hash");
3222
+ }
3223
+ }
3224
+ if (RTEST(extra[1])) {
3225
+ ao.sample_miss_detection.is_enabled = true;
3226
+ if (!NIL_P(smd_h)) {
3227
+ VALUE v;
3228
+ if (!NIL_P(v = zrb_hget(smd_h, "heartbeat"))) {
3229
+ ID hb = zrb_sym_id(v);
3230
+ if (hb == rb_intern("periodic")) {
3231
+ ao.sample_miss_detection.heartbeat_mode = ZE_ADVANCED_PUBLISHER_HEARTBEAT_MODE_PERIODIC;
3232
+ } else if (hb == rb_intern("sporadic")) {
3233
+ ao.sample_miss_detection.heartbeat_mode = ZE_ADVANCED_PUBLISHER_HEARTBEAT_MODE_SPORADIC;
3234
+ } else if (hb == id_none) {
3235
+ ao.sample_miss_detection.heartbeat_mode = ZE_ADVANCED_PUBLISHER_HEARTBEAT_MODE_NONE;
3236
+ } else {
3237
+ rb_raise(rb_eArgError, "heartbeat must be :periodic, :sporadic or :none");
3238
+ }
3239
+ }
3240
+ if (!NIL_P(v = zrb_hget(smd_h, "heartbeat_ms"))) {
3241
+ ao.sample_miss_detection.heartbeat_period_ms = zrb_ms_arg(v, "heartbeat_ms");
3242
+ }
3243
+ } else if (extra[1] != Qtrue) {
3244
+ rb_raise(rb_eTypeError, "sample_miss_detection must be true or a Hash");
3245
+ }
3246
+ }
3247
+ ao.publisher_detection = RTEST(extra[2]);
980
3248
 
981
- static void *zrb_open_nogvl(void *p) {
982
- zrb_open_args *a = (zrb_open_args *)p;
983
- a->ret = z_open(&a->z->session, z_move(a->config), NULL);
984
- return NULL;
3249
+ VALUE key_str = zrb_key_string(key_v);
3250
+ zrb_session *z = zrb_session_get_open(self);
3251
+ z_view_keyexpr_t view;
3252
+ const z_loaned_keyexpr_t *ke = zrb_key_loan(key_v, &view);
3253
+ zrb_pub *p;
3254
+ VALUE obj = TypedData_Make_Struct(cAdvPublisher, zrb_pub, &zrb_pub_type, p);
3255
+ p->advanced = true;
3256
+ z_owned_encoding_t enc;
3257
+ if (zrb_encoding_make(&enc, o.encoding)) {
3258
+ ao.publisher_options.encoding = z_move(enc);
3259
+ }
3260
+ z_result_t ret = ze_declare_advanced_publisher(z_loan(z->session), &p->u.a, ke, &ao);
3261
+ if (ret != Z_OK) {
3262
+ rb_raise(eZenohError, "cannot declare an advanced publisher on %" PRIsVALUE " (%d)%" PRIsVALUE, key_str, (int)ret, zrb_last_error());
3263
+ }
3264
+ return zrb_pub_wrap(self, z, p, obj, key_str);
985
3265
  }
986
3266
 
987
- /* Asterism::Zenoh::Session.open(locator = nil, mode: :client, listen: nil) -> Session
988
- * - client: connects to the router at locator.
989
- * - peer: connects to the peer at locator (if given) and/or listens on
990
- * listen (e.g. "tcp/0.0.0.0:7447"). At least one of them is needed.
991
- * Raises Asterism::Zenoh::Error when the session cannot be opened (no
992
- * router or peer answered within CONNECT_TIMEOUT_MS). */
993
- static VALUE zrb_session_s_open(int argc, VALUE *argv, VALUE klass) {
994
- VALUE locator_v = Qnil, opts = Qnil;
995
- rb_scan_args(argc, argv, "01:", &locator_v, &opts);
996
- VALUE kw[2] = {Qundef, Qundef};
997
- if (!NIL_P(opts)) {
998
- ID ids[2] = {id_mode, id_listen};
999
- rb_get_kwargs(opts, ids, 0, 2, kw);
3267
+ static const char *const zrb_pput_kw[] = {"attachment", "encoding", "timestamp"};
3268
+
3269
+ /* pub.put(payload, attachment: nil, encoding: nil, timestamp: nil) -> nil */
3270
+ static VALUE zrb_pub_put(int argc, VALUE *argv, VALUE self) {
3271
+ VALUE payload, opts = Qnil;
3272
+ rb_scan_args(argc, argv, "1:", &payload, &opts);
3273
+ zrb_opts o;
3274
+ zrb_opts_parse(opts, zrb_pput_kw, 3, &o);
3275
+ StringValue(payload);
3276
+ zrb_pub *p = zrb_pub_get_open(self);
3277
+ zrb_send s;
3278
+ zrb_send_init(&s, p->ent.owner, p, p->advanced ? ZS_APUT : ZS_PPUT);
3279
+ z_publisher_put_options_t *po;
3280
+ if (p->advanced) {
3281
+ ze_advanced_publisher_put_options_default(&s.o.aput);
3282
+ po = &s.o.aput.put_options;
3283
+ } else {
3284
+ z_publisher_put_options_default(&s.o.pput);
3285
+ po = &s.o.pput;
1000
3286
  }
1001
- bool peer = false;
1002
- if (kw[0] != Qundef && !NIL_P(kw[0])) {
1003
- ID mode = zrb_sym_id(kw[0]);
1004
- if (mode == id_peer) {
1005
- peer = true;
1006
- } else if (mode != id_client) {
1007
- rb_raise(rb_eArgError, "mode must be :client or :peer");
1008
- }
3287
+ po->timestamp = zrb_send_timestamp(&s, o.timestamp);
3288
+ zrb_send_values(&s, payload, &o);
3289
+ if (!NIL_P(o.attachment)) {
3290
+ po->attachment = z_move(s.att);
1009
3291
  }
1010
- const char *locator = NIL_P(locator_v) ? NULL : StringValueCStr(locator_v);
1011
- VALUE listen_v = (kw[1] == Qundef) ? Qnil : kw[1];
1012
- const char *listen = NIL_P(listen_v) ? NULL : StringValueCStr(listen_v);
1013
- if (!peer && listen != NULL) {
1014
- rb_raise(rb_eArgError, "listen needs mode: :peer");
3292
+ if (!NIL_P(o.encoding)) {
3293
+ po->encoding = z_move(s.enc);
1015
3294
  }
1016
- if (locator == NULL && listen == NULL) {
1017
- rb_raise(rb_eArgError, "a locator (or, for a peer, listen:) is needed");
3295
+ zrb_send_run(&s, "put");
3296
+ return Qnil;
3297
+ }
3298
+
3299
+ /* pub.delete(timestamp: nil) -> nil */
3300
+ static VALUE zrb_pub_delete(int argc, VALUE *argv, VALUE self) {
3301
+ VALUE opts = Qnil;
3302
+ rb_scan_args(argc, argv, "0:", &opts);
3303
+ static const char *const kws[] = {"timestamp"};
3304
+ zrb_opts o;
3305
+ zrb_opts_parse(opts, kws, 1, &o);
3306
+ zrb_pub *p = zrb_pub_get_open(self);
3307
+ zrb_send s;
3308
+ zrb_send_init(&s, p->ent.owner, p, p->advanced ? ZS_ADEL : ZS_PDEL);
3309
+ z_publisher_delete_options_t *po;
3310
+ if (p->advanced) {
3311
+ ze_advanced_publisher_delete_options_default(&s.o.adel);
3312
+ po = &s.o.adel.delete_options;
3313
+ } else {
3314
+ z_publisher_delete_options_default(&s.o.pdel);
3315
+ po = &s.o.pdel;
1018
3316
  }
3317
+ po->timestamp = zrb_send_timestamp(&s, o.timestamp);
3318
+ zrb_send_run(&s, "delete");
3319
+ return Qnil;
3320
+ }
1019
3321
 
1020
- zrb_session *z;
1021
- VALUE obj = TypedData_Make_Struct(klass, zrb_session, &zrb_session_type, z);
1022
- pthread_mutex_init(&z->op_lock, NULL);
3322
+ /* pub.matching? -> true when at least one subscriber matches the key now. */
3323
+ static VALUE zrb_pub_matching_p(VALUE self) {
3324
+ zrb_pub *p = zrb_pub_get_open(self);
3325
+ z_matching_status_t st = {false};
3326
+ z_result_t r = p->advanced ? ze_advanced_publisher_get_matching_status(z_loan(p->u.a), &st)
3327
+ : z_publisher_get_matching_status(z_loan(p->u.p), &st);
3328
+ if (r != Z_OK) {
3329
+ rb_raise(eZenohError, "cannot get the matching status (%d)%" PRIsVALUE, (int)r, zrb_last_error());
3330
+ }
3331
+ return st.matching ? Qtrue : Qfalse;
3332
+ }
1023
3333
 
1024
- /* The configuration mirrors the mruby gem's zenoh-pico build: no
1025
- * scouting (the locator is given), a connect-only peer does not listen,
1026
- * and the session fails to open when nobody answers in time. */
1027
- zrb_open_args a;
1028
- a.z = z;
1029
- if (z_config_default(&a.config) != Z_OK) {
1030
- rb_raise(eZenohError, "cannot create the configuration");
3334
+ static VALUE zrb_pub_close(VALUE self) {
3335
+ zrb_ent_detach(&zrb_pub_get(self)->ent);
3336
+ return Qnil;
3337
+ }
3338
+
3339
+ static VALUE zrb_pub_closed_p(VALUE self) { return zrb_pub_get(self)->ent.declared ? Qfalse : Qtrue; }
3340
+
3341
+ /* ------------------------------------------------------------- queriers */
3342
+
3343
+ typedef struct {
3344
+ zrb_ent ent;
3345
+ z_owned_querier_t q;
3346
+ } zrb_querier;
3347
+
3348
+ static void zrb_querier_undeclare(zrb_ent *e) { z_drop(z_move(((zrb_querier *)e)->q)); }
3349
+
3350
+ static void zrb_querier_free(void *ptr) {
3351
+ zrb_querier *q = (zrb_querier *)ptr;
3352
+ zrb_ent_detach(&q->ent);
3353
+ xfree(q);
3354
+ }
3355
+
3356
+ static size_t zrb_querier_size(const void *p) { return sizeof(zrb_querier); }
3357
+
3358
+ static const rb_data_type_t zrb_querier_type = {
3359
+ "Asterism::Zenoh::Querier", {NULL, zrb_querier_free, zrb_querier_size}, NULL, NULL, 0};
3360
+
3361
+ static zrb_querier *zrb_querier_get(VALUE self) {
3362
+ zrb_querier *q;
3363
+ TypedData_Get_Struct(self, zrb_querier, &zrb_querier_type, q);
3364
+ return q;
3365
+ }
3366
+
3367
+ static zrb_querier *zrb_querier_get_open(VALUE self) {
3368
+ zrb_querier *q = zrb_querier_get(self);
3369
+ if (!q->ent.declared) {
3370
+ rb_raise(eZenohError, "the querier is closed");
1031
3371
  }
1032
- char num[32];
1033
- snprintf(num, sizeof(num), "%d", ZRB_CONNECT_TIMEOUT_MS);
1034
- bool ok = zrb_config_set(&a.config, "mode", peer ? "\"peer\"" : "\"client\"") &&
1035
- zrb_config_set(&a.config, "scouting/multicast/enabled", "false") &&
1036
- zrb_config_set(&a.config, "scouting/gossip/enabled", "false") &&
1037
- zrb_config_set(&a.config, "connect/timeout_ms", num) &&
1038
- zrb_config_set(&a.config, "connect/exit_on_failure", "true");
1039
- if (ok) {
1040
- snprintf(num, sizeof(num), "%d", ZRB_SEND_TIMEOUT_MS * 1000);
1041
- ok = zrb_config_set(&a.config, "transport/link/tx/queue/congestion_control/block/wait_before_close", num);
3372
+ if (zrb_session_check_link(q->ent.owner)) {
3373
+ rb_raise(eZenohError, "session is closed");
1042
3374
  }
1043
- if (ok && locator != NULL) {
1044
- VALUE ep = rb_str_concat(rb_str_concat(rb_str_new_cstr("["), zrb_json_str(locator)), rb_str_new_cstr("]"));
1045
- ok = zrb_config_set(&a.config, "connect/endpoints", StringValueCStr(ep));
3375
+ return q;
3376
+ }
3377
+
3378
+ static const char *const zrb_querier_kw[] = {"target", "consolidation", "timeout_ms", "congestion_control",
3379
+ "priority", "express", "accept_replies", "allowed_destination"};
3380
+
3381
+ /* session.querier(key, target: :all, consolidation: :none,
3382
+ * timeout_ms: 2000, congestion_control:, priority:,
3383
+ * express:, accept_replies: :matching_query,
3384
+ * allowed_destination: :remote) -> Querier.
3385
+ * A declared get: q.get(...) sends the same query again and again. */
3386
+ static VALUE zrb_session_querier(int argc, VALUE *argv, VALUE self) {
3387
+ VALUE key_v, opts = Qnil;
3388
+ rb_scan_args(argc, argv, "1:", &key_v, &opts);
3389
+ zrb_opts o;
3390
+ zrb_opts_parse(opts, zrb_querier_kw, 8, &o);
3391
+ z_querier_options_t qo;
3392
+ z_querier_options_default(&qo);
3393
+ qo.target = zrb_get_target(o.has_target ? o.target : Qnil);
3394
+ qo.consolidation = zrb_get_consolidation(o.has_consolidation ? o.consolidation : Qnil);
3395
+ qo.timeout_ms = (uint64_t)zrb_check_timeout(o.has_timeout ? o.timeout : Qnil);
3396
+ /* Remote queryables only by default, as with get. */
3397
+ qo.allowed_destination = o.destination >= 0 ? (z_locality_t)o.destination : Z_LOCALITY_REMOTE;
3398
+ if (o.congestion_control >= 0) {
3399
+ qo.congestion_control = (z_congestion_control_t)o.congestion_control;
1046
3400
  }
1047
- if (ok) {
1048
- if (listen != NULL) {
1049
- VALUE ep = rb_str_concat(rb_str_concat(rb_str_new_cstr("["), zrb_json_str(listen)), rb_str_new_cstr("]"));
1050
- ok = zrb_config_set(&a.config, "listen/endpoints", StringValueCStr(ep));
1051
- } else {
1052
- ok = zrb_config_set(&a.config, "listen/endpoints", "[]");
1053
- }
3401
+ if (o.priority >= 0) {
3402
+ qo.priority = (z_priority_t)o.priority;
1054
3403
  }
1055
- if (!ok) {
1056
- z_drop(z_move(a.config));
1057
- rb_raise(eZenohError, "invalid locator");
3404
+ if (o.express >= 0) {
3405
+ qo.is_express = o.express;
1058
3406
  }
1059
- rb_thread_call_without_gvl(zrb_open_nogvl, &a, RUBY_UBF_IO, NULL);
1060
- if (a.ret != Z_OK) {
1061
- rb_raise(eZenohError, "cannot open a session to %s (%d)", locator != NULL ? locator : listen, (int)a.ret);
3407
+ if (o.accept_replies >= 0) {
3408
+ qo.accept_replies = (z_reply_keyexpr_t)o.accept_replies;
1062
3409
  }
1063
- z->open = true;
1064
- z->live = true;
1065
- z->peer = peer;
1066
- z->listening = (listen != NULL);
3410
+ VALUE key_str = zrb_key_string(key_v);
3411
+ zrb_session *z = zrb_session_get_open(self);
3412
+ z_view_keyexpr_t view;
3413
+ const z_loaned_keyexpr_t *ke = zrb_key_loan(key_v, &view);
3414
+ zrb_querier *q;
3415
+ VALUE obj = TypedData_Make_Struct(cQuerier, zrb_querier, &zrb_querier_type, q);
3416
+ z_result_t ret = z_declare_querier(z_loan(z->session), &q->q, ke, &qo);
3417
+ if (ret != Z_OK) {
3418
+ rb_raise(eZenohError, "cannot declare a querier on %" PRIsVALUE " (%d)%" PRIsVALUE, key_str, (int)ret, zrb_last_error());
3419
+ }
3420
+ zrb_ent_link(&q->ent, z, ZENT_ENTITY, true, zrb_querier_undeclare);
3421
+ zrb_hold_session(obj, self, key_str);
1067
3422
  return obj;
1068
3423
  }
1069
3424
 
1070
3425
  typedef struct {
1071
3426
  zrb_session *z;
1072
- z_owned_keyexpr_t key;
1073
- z_owned_bytes_t payload;
1074
- z_put_options_t opts;
3427
+ zrb_querier *q;
3428
+ char *params;
3429
+ z_owned_closure_reply_t cb;
3430
+ z_owned_bytes_t payload, att;
3431
+ z_owned_encoding_t enc;
3432
+ z_querier_get_options_t opts;
3433
+ bool undeclared;
1075
3434
  z_result_t ret;
1076
- } zrb_put_args;
3435
+ } zrb_qget_args;
1077
3436
 
1078
- static void *zrb_put_nogvl(void *p) {
1079
- zrb_put_args *a = (zrb_put_args *)p;
3437
+ static void *zrb_qget_nogvl(void *p) {
3438
+ zrb_qget_args *a = (zrb_qget_args *)p;
1080
3439
  pthread_mutex_lock(&a->z->op_lock);
1081
- if (a->z->live) {
1082
- a->ret = z_put(z_loan(a->z->session), z_loan(a->key), z_move(a->payload), &a->opts);
1083
- } else {
3440
+ if (!a->z->live) {
1084
3441
  a->ret = Z_ESESSION_CLOSED;
3442
+ } else if (!a->q->ent.declared) {
3443
+ a->undeclared = true;
3444
+ } else {
3445
+ a->ret = z_querier_get(z_loan(a->q->q), a->params != NULL ? a->params : "", z_move(a->cb), &a->opts);
1085
3446
  }
1086
3447
  pthread_mutex_unlock(&a->z->op_lock);
3448
+ z_drop(z_move(a->cb));
1087
3449
  return NULL;
1088
3450
  }
1089
3451
 
1090
- /* session.put(key, payload, attachment: nil) -> nil */
1091
- static VALUE zrb_session_put(int argc, VALUE *argv, VALUE self) {
1092
- VALUE key_v, payload, opts = Qnil;
1093
- rb_scan_args(argc, argv, "2:", &key_v, &payload, &opts);
1094
- VALUE kw[1] = {Qundef};
1095
- if (!NIL_P(opts)) {
1096
- rb_get_kwargs(opts, &id_attachment, 0, 1, kw);
1097
- }
1098
- const char *key = StringValueCStr(key_v);
1099
- StringValue(payload);
1100
- VALUE att = zrb_kw_attachment(kw[0]);
1101
- zrb_session *z = zrb_session_get_open(self);
3452
+ static const char *const zrb_qget_kw[] = {"attachment", "encoding"};
1102
3453
 
1103
- zrb_put_args a;
1104
- a.z = z;
1105
- a.ret = Z_OK;
1106
- zrb_owned_key(&a.key, key);
1107
- if (z_bytes_copy_from_buf(&a.payload, (const uint8_t *)RSTRING_PTR(payload), (size_t)RSTRING_LEN(payload)) !=
1108
- Z_OK) {
1109
- z_drop(z_move(a.key));
1110
- rb_raise(eZenohError, "cannot allocate the payload");
3454
+ /* querier.get(params = nil, payload = nil, attachment: nil, encoding: nil) -> Get */
3455
+ static VALUE zrb_querier_get_m(int argc, VALUE *argv, VALUE self) {
3456
+ VALUE params_v = Qnil, payload = Qnil, opts = Qnil;
3457
+ rb_scan_args(argc, argv, "02:", &params_v, &payload, &opts);
3458
+ zrb_opts o;
3459
+ zrb_opts_parse(opts, zrb_qget_kw, 2, &o);
3460
+ const char *params = NIL_P(params_v) ? NULL : StringValueCStr(params_v);
3461
+ if (!NIL_P(payload) && !RB_TYPE_P(payload, T_STRING)) {
3462
+ rb_raise(rb_eTypeError, "payload must be a String");
1111
3463
  }
1112
- z_put_options_default(&a.opts);
1113
- z_owned_bytes_t att_bytes;
1114
- if (!NIL_P(att)) {
1115
- if (z_bytes_copy_from_buf(&att_bytes, (const uint8_t *)RSTRING_PTR(att), (size_t)RSTRING_LEN(att)) != Z_OK) {
1116
- z_drop(z_move(a.payload));
1117
- z_drop(z_move(a.key));
1118
- rb_raise(eZenohError, "cannot allocate the attachment");
1119
- }
1120
- a.opts.attachment = z_move(att_bytes);
3464
+ zrb_querier *q = zrb_querier_get_open(self);
3465
+ zrb_qget_args a;
3466
+ memset(&a, 0, sizeof(a));
3467
+ a.z = q->ent.owner;
3468
+ a.q = q;
3469
+ z_internal_bytes_null(&a.payload);
3470
+ z_internal_bytes_null(&a.att);
3471
+ z_internal_encoding_null(&a.enc);
3472
+ zrb_get *g;
3473
+ VALUE obj = zrb_get_new(&g);
3474
+ z_querier_get_options_default(&a.opts);
3475
+ if (!NIL_P(payload)) {
3476
+ zrb_bytes_from_str(&a.payload, payload, "payload");
3477
+ a.opts.payload = z_move(a.payload);
1121
3478
  }
1122
- rb_thread_call_without_gvl(zrb_put_nogvl, &a, RUBY_UBF_IO, NULL);
1123
- z_drop(z_move(a.key));
1124
- if (zrb_session_check_link(z)) {
1125
- rb_raise(eZenohError, "put failed: the connection is lost (%d)", (int)a.ret);
3479
+ if (!NIL_P(o.attachment)) {
3480
+ zrb_bytes_from_str(&a.att, o.attachment, "attachment");
3481
+ a.opts.attachment = z_move(a.att);
3482
+ }
3483
+ if (zrb_encoding_make(&a.enc, o.encoding)) {
3484
+ a.opts.encoding = z_move(a.enc);
3485
+ }
3486
+ if (params != NULL) {
3487
+ a.params = strdup(params);
3488
+ }
3489
+ zch_closure_reply(g->ch, &a.cb);
3490
+ rb_thread_call_without_gvl(zrb_qget_nogvl, &a, RUBY_UBF_IO, NULL);
3491
+ free(a.params);
3492
+ z_drop(z_move(a.payload));
3493
+ z_drop(z_move(a.att));
3494
+ z_drop(z_move(a.enc));
3495
+ if (zrb_session_check_link(a.z)) {
3496
+ rb_raise(eZenohError, "get failed: the connection is lost (%d)", (int)a.ret);
3497
+ }
3498
+ if (a.undeclared) {
3499
+ rb_raise(eZenohError, "get failed: the querier is closed");
1126
3500
  }
1127
3501
  if (a.ret != Z_OK) {
1128
- rb_raise(eZenohError, "put failed (%d)", (int)a.ret);
3502
+ rb_raise(eZenohError, "get failed (%d)", (int)a.ret);
1129
3503
  }
3504
+ rb_ivar_set(obj, id_iv_session, rb_ivar_get(self, id_iv_session));
3505
+ return obj;
3506
+ }
3507
+
3508
+ static VALUE zrb_querier_matching_p(VALUE self) {
3509
+ zrb_querier *q = zrb_querier_get_open(self);
3510
+ z_matching_status_t st = {false};
3511
+ z_result_t r = z_querier_get_matching_status(z_loan(q->q), &st);
3512
+ if (r != Z_OK) {
3513
+ rb_raise(eZenohError, "cannot get the matching status (%d)%" PRIsVALUE, (int)r, zrb_last_error());
3514
+ }
3515
+ return st.matching ? Qtrue : Qfalse;
3516
+ }
3517
+
3518
+ static VALUE zrb_querier_close(VALUE self) {
3519
+ zrb_ent_detach(&zrb_querier_get(self)->ent);
1130
3520
  return Qnil;
1131
3521
  }
1132
3522
 
1133
- static VALUE zrb_sub_new(VALUE self, zrb_session *z, VALUE key_v, long depth, bool liveliness) {
1134
- const char *key = StringValueCStr(key_v);
1135
- z_view_keyexpr_t ke;
1136
- zrb_view_key(&ke, key);
3523
+ static VALUE zrb_querier_closed_p(VALUE self) { return zrb_querier_get(self)->ent.declared ? Qfalse : Qtrue; }
1137
3524
 
1138
- zrb_sub *s;
1139
- VALUE obj = TypedData_Make_Struct(liveliness ? cWatch : cSubscriber, zrb_sub, &zrb_sub_type, s);
1140
- s->liveliness = liveliness;
1141
- s->ch = zch_new(ZCH_SAMPLE, (uint32_t)depth);
3525
+ /* ------------------------------------------------------------ listeners */
1142
3526
 
1143
- z_owned_closure_sample_t cb;
1144
- zch_closure_sample(s->ch, &cb);
1145
- z_result_t ret;
1146
- if (liveliness) {
1147
- /* history: the tokens alive now are reported first, as appearing. */
1148
- z_liveliness_subscriber_options_t lo;
1149
- z_liveliness_subscriber_options_default(&lo);
1150
- lo.history = true;
1151
- ret = z_liveliness_declare_subscriber(z_loan(z->session), &s->sub, z_loan(ke), z_move(cb), &lo);
1152
- } else {
1153
- /* Remote samples only: zenoh-pico (the mruby gem) does not deliver a
1154
- * session's own puts to its own subscribers either. */
1155
- z_subscriber_options_t so;
1156
- z_subscriber_options_default(&so);
1157
- so.allowed_origin = Z_LOCALITY_REMOTE;
1158
- ret = z_declare_subscriber(z_loan(z->session), &s->sub, z_loan(ke), z_move(cb), &so);
1159
- }
1160
- if (ret != Z_OK) {
1161
- rb_raise(eZenohError, "cannot subscribe to %s (%d)", key, (int)ret);
3527
+ typedef enum { ZLST_MATCHING, ZLST_TRANSPORT, ZLST_LINK, ZLST_MISS } zlst_type;
3528
+
3529
+ typedef struct {
3530
+ zrb_ent ent;
3531
+ zlst_type type;
3532
+ union {
3533
+ z_owned_matching_listener_t m;
3534
+ z_owned_transport_events_listener_t t;
3535
+ z_owned_link_events_listener_t l;
3536
+ ze_owned_sample_miss_listener_t s;
3537
+ } u;
3538
+ zevq *q;
3539
+ } zrb_lst;
3540
+
3541
+ static void zrb_lst_undeclare(zrb_ent *e) {
3542
+ zrb_lst *l = (zrb_lst *)e;
3543
+ switch (l->type) {
3544
+ case ZLST_MATCHING:
3545
+ z_drop(z_move(l->u.m));
3546
+ break;
3547
+ case ZLST_TRANSPORT:
3548
+ z_drop(z_move(l->u.t));
3549
+ break;
3550
+ case ZLST_LINK:
3551
+ z_drop(z_move(l->u.l));
3552
+ break;
3553
+ case ZLST_MISS:
3554
+ z_drop(z_move(l->u.s));
3555
+ break;
1162
3556
  }
1163
- s->declared = true;
1164
- s->owner = z;
1165
- s->next = z->subs;
1166
- z->subs = s;
1167
- zrb_hold_session(obj, self, key_v);
1168
- return obj;
1169
3557
  }
1170
3558
 
1171
- /* session.subscribe(key, depth = 16) -> Subscriber */
1172
- static VALUE zrb_session_subscribe(int argc, VALUE *argv, VALUE self) {
1173
- VALUE key_v, depth_v = Qnil;
1174
- rb_scan_args(argc, argv, "11", &key_v, &depth_v);
1175
- long depth = zrb_check_depth(depth_v);
1176
- StringValueCStr(key_v);
1177
- zrb_session *z = zrb_session_get_open(self);
1178
- return zrb_sub_new(self, z, key_v, depth, false);
3559
+ static void zrb_lst_free(void *p) {
3560
+ zrb_lst *l = (zrb_lst *)p;
3561
+ zrb_ent_detach(&l->ent);
3562
+ zevq_unref(l->q);
3563
+ xfree(l);
1179
3564
  }
1180
3565
 
1181
- /* session.liveliness_watch(key, depth = 16) -> LivelinessWatch */
1182
- static VALUE zrb_session_liveliness_watch(int argc, VALUE *argv, VALUE self) {
1183
- VALUE key_v, depth_v = Qnil;
1184
- rb_scan_args(argc, argv, "11", &key_v, &depth_v);
1185
- long depth = zrb_check_depth(depth_v);
1186
- StringValueCStr(key_v);
1187
- zrb_session *z = zrb_session_get_open(self);
1188
- return zrb_sub_new(self, z, key_v, depth, true);
3566
+ static size_t zrb_lst_size(const void *p) { return sizeof(zrb_lst); }
3567
+
3568
+ static const rb_data_type_t zrb_lst_type = {"Asterism::Zenoh::Listener", {NULL, zrb_lst_free, zrb_lst_size}, NULL, NULL, 0};
3569
+
3570
+ static zrb_lst *zrb_lst_get(VALUE self) {
3571
+ zrb_lst *l;
3572
+ TypedData_Get_Struct(self, zrb_lst, &zrb_lst_type, l);
3573
+ return l;
1189
3574
  }
1190
3575
 
1191
- /* session.queryable(key, depth = 16, complete: false) -> Queryable */
1192
- static VALUE zrb_session_queryable(int argc, VALUE *argv, VALUE self) {
1193
- VALUE key_v, depth_v = Qnil, opts = Qnil;
1194
- rb_scan_args(argc, argv, "11:", &key_v, &depth_v, &opts);
1195
- VALUE kw[1] = {Qundef};
1196
- if (!NIL_P(opts)) {
1197
- rb_get_kwargs(opts, &id_complete, 0, 1, kw);
1198
- }
1199
- bool complete = (kw[0] != Qundef) && RTEST(kw[0]);
3576
+ static VALUE zrb_lst_new(VALUE klass, zlst_type type, zev_kind kind, VALUE depth_v, zrb_lst **out) {
1200
3577
  long depth = zrb_check_depth(depth_v);
1201
- const char *key = StringValueCStr(key_v);
1202
- zrb_session *z = zrb_session_get_open(self);
1203
- z_view_keyexpr_t ke;
1204
- zrb_view_key(&ke, key);
1205
-
1206
- zrb_qable *q;
1207
- VALUE obj = TypedData_Make_Struct(cQueryable, zrb_qable, &zrb_qable_type, q);
1208
- q->ch = zch_new(ZCH_QUERY, (uint32_t)depth);
1209
- z_owned_closure_query_t cb;
1210
- zch_closure_query(q->ch, &cb);
1211
- z_queryable_options_t qo;
1212
- z_queryable_options_default(&qo);
1213
- qo.complete = complete;
1214
- /* Remote queries only, as with zenoh-pico (Asterism answers calls to
1215
- * its own objects in place). */
1216
- qo.allowed_origin = Z_LOCALITY_REMOTE;
1217
- z_result_t ret = z_declare_queryable(z_loan(z->session), &q->qable, z_loan(ke), z_move(cb), &qo);
1218
- if (ret != Z_OK) {
1219
- rb_raise(eZenohError, "cannot declare a queryable on %s (%d)", key, (int)ret);
1220
- }
1221
- q->declared = true;
1222
- q->owner = z;
1223
- q->next = z->qables;
1224
- z->qables = q;
1225
- zrb_hold_session(obj, self, key_v);
3578
+ zrb_lst *l;
3579
+ VALUE obj = TypedData_Make_Struct(klass, zrb_lst, &zrb_lst_type, l);
3580
+ l->type = type;
3581
+ l->q = zevq_new(kind, (uint32_t)depth);
3582
+ *out = l;
1226
3583
  return obj;
1227
3584
  }
1228
3585
 
1229
- static z_query_target_t zrb_get_target(VALUE v) {
1230
- if (v == Qundef || NIL_P(v)) {
1231
- return Z_QUERY_TARGET_ALL;
1232
- }
1233
- ID t = zrb_sym_id(v);
1234
- if (t == id_all) {
1235
- return Z_QUERY_TARGET_ALL;
1236
- }
1237
- if (t == id_all_complete) {
1238
- return Z_QUERY_TARGET_ALL_COMPLETE;
1239
- }
1240
- if (t == id_best_matching) {
1241
- return Z_QUERY_TARGET_BEST_MATCHING;
1242
- }
1243
- rb_raise(rb_eArgError, "target must be :all, :all_complete or :best_matching");
1244
- return Z_QUERY_TARGET_ALL; /* not reached */
3586
+ static void zrb_lst_linked(VALUE obj, zrb_lst *l, zrb_session *z, VALUE parent) {
3587
+ zrb_ent_link(&l->ent, z, ZENT_LISTENER, false, zrb_lst_undeclare);
3588
+ rb_ivar_set(obj, id_iv_parent, parent);
1245
3589
  }
1246
3590
 
1247
- static z_query_consolidation_t zrb_get_consolidation(VALUE v) {
1248
- if (v == Qundef || NIL_P(v)) {
1249
- return z_query_consolidation_none();
1250
- }
1251
- ID c = zrb_sym_id(v);
1252
- if (c == id_none) {
1253
- return z_query_consolidation_none();
1254
- }
1255
- if (c == id_latest) {
1256
- return z_query_consolidation_latest();
1257
- }
1258
- if (c == id_monotonic) {
1259
- return z_query_consolidation_monotonic();
1260
- }
1261
- if (c == id_auto) {
1262
- return z_query_consolidation_auto();
3591
+ /* listener.each_pending { |value| } -> Integer; without a block, an Array.
3592
+ * A MatchingListener gives true / false (a subscriber matches or not any
3593
+ * more); an EventListener gives TransportEvent, LinkEvent or Miss values. */
3594
+ static VALUE zrb_lst_each_pending(VALUE self) { return zevq_each_pending(zrb_lst_get(self)->q, true); }
3595
+ static VALUE zrb_lst_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_lst_get(self)->q->queued)); }
3596
+ static VALUE zrb_lst_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_lst_get(self)->q->received)); }
3597
+ static VALUE zrb_lst_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_lst_get(self)->q->dropped)); }
3598
+
3599
+ static VALUE zrb_lst_close(VALUE self) {
3600
+ zrb_ent_detach(&zrb_lst_get(self)->ent);
3601
+ return Qnil;
3602
+ }
3603
+
3604
+ static VALUE zrb_lst_closed_p(VALUE self) { return zrb_lst_get(self)->ent.declared ? Qfalse : Qtrue; }
3605
+
3606
+ /* pub.matching_listener(depth = 16) -> MatchingListener: each change of
3607
+ * the matching status (true when the first subscriber appears, false when
3608
+ * the last goes). Also for queriers (queryables) and advanced publishers. */
3609
+ static VALUE zrb_pub_matching_listener(int argc, VALUE *argv, VALUE self) {
3610
+ VALUE depth_v = Qnil;
3611
+ rb_scan_args(argc, argv, "01", &depth_v);
3612
+ zrb_pub *p = zrb_pub_get_open(self);
3613
+ zrb_lst *l;
3614
+ VALUE obj = zrb_lst_new(cMatchingListener, ZLST_MATCHING, ZEV_MATCHING, depth_v, &l);
3615
+ z_owned_closure_matching_status_t cb;
3616
+ z_closure_matching_status(&cb, zev_on_matching, zevq_on_drop, zevq_ref(l->q));
3617
+ z_result_t r = p->advanced
3618
+ ? ze_advanced_publisher_declare_matching_listener(z_loan(p->u.a), &l->u.m, z_move(cb))
3619
+ : z_publisher_declare_matching_listener(z_loan(p->u.p), &l->u.m, z_move(cb));
3620
+ if (r != Z_OK) {
3621
+ rb_raise(eZenohError, "cannot declare a matching listener (%d)%" PRIsVALUE, (int)r, zrb_last_error());
1263
3622
  }
1264
- rb_raise(rb_eArgError, "consolidation must be :none, :latest, :monotonic or :auto");
1265
- return z_query_consolidation_none(); /* not reached */
3623
+ zrb_lst_linked(obj, l, p->ent.owner, self);
3624
+ return obj;
1266
3625
  }
1267
3626
 
1268
- typedef struct {
1269
- zrb_session *z;
1270
- z_owned_keyexpr_t key;
1271
- char *params; /* malloc'd copy, or NULL */
1272
- bool liveliness;
1273
- z_owned_closure_reply_t cb;
1274
- z_get_options_t opts;
1275
- z_liveliness_get_options_t lopts;
1276
- z_result_t ret;
1277
- } zrb_get_args;
3627
+ static VALUE zrb_querier_matching_listener(int argc, VALUE *argv, VALUE self) {
3628
+ VALUE depth_v = Qnil;
3629
+ rb_scan_args(argc, argv, "01", &depth_v);
3630
+ zrb_querier *q = zrb_querier_get_open(self);
3631
+ zrb_lst *l;
3632
+ VALUE obj = zrb_lst_new(cMatchingListener, ZLST_MATCHING, ZEV_MATCHING, depth_v, &l);
3633
+ z_owned_closure_matching_status_t cb;
3634
+ z_closure_matching_status(&cb, zev_on_matching, zevq_on_drop, zevq_ref(l->q));
3635
+ z_result_t r = z_querier_declare_matching_listener(z_loan(q->q), &l->u.m, z_move(cb));
3636
+ if (r != Z_OK) {
3637
+ rb_raise(eZenohError, "cannot declare a matching listener (%d)%" PRIsVALUE, (int)r, zrb_last_error());
3638
+ }
3639
+ zrb_lst_linked(obj, l, q->ent.owner, self);
3640
+ return obj;
3641
+ }
1278
3642
 
1279
- static void *zrb_get_nogvl(void *p) {
1280
- zrb_get_args *a = (zrb_get_args *)p;
1281
- pthread_mutex_lock(&a->z->op_lock);
1282
- if (a->z->live) {
1283
- if (a->liveliness) {
1284
- a->ret = z_liveliness_get(z_loan(a->z->session), z_loan(a->key), z_move(a->cb), &a->lopts);
1285
- } else {
1286
- a->ret = z_get(z_loan(a->z->session), z_loan(a->key), a->params != NULL ? a->params : "", z_move(a->cb),
1287
- &a->opts);
1288
- }
1289
- } else {
1290
- a->ret = Z_ESESSION_CLOSED;
3643
+ static bool zrb_history_kw(VALUE opts) {
3644
+ VALUE kw[1] = {Qundef};
3645
+ if (!NIL_P(opts)) {
3646
+ rb_get_kwargs(opts, &id_history, 0, 1, kw);
1291
3647
  }
1292
- pthread_mutex_unlock(&a->z->op_lock);
1293
- /* A closure that was not taken (the session was closed) is dropped
1294
- * here, which releases the channel's reference. */
1295
- z_drop(z_move(a->cb));
1296
- return NULL;
3648
+ return kw[0] != Qundef && RTEST(kw[0]);
1297
3649
  }
1298
3650
 
1299
- static VALUE zrb_run_get(VALUE self, zrb_session *z, zrb_get_args *a, VALUE obj, VALUE key_v, const char *what) {
1300
- rb_thread_call_without_gvl(zrb_get_nogvl, a, RUBY_UBF_IO, NULL);
1301
- z_drop(z_move(a->key));
1302
- free(a->params);
1303
- if (zrb_session_check_link(z)) {
1304
- rb_raise(eZenohError, "%s failed: the connection is lost (%d)", what, (int)a->ret);
3651
+ /* session.transport_events(depth = 16, history: false) -> EventListener:
3652
+ * a TransportEvent (kind :added / :removed, zid, whatami, qos, multicast)
3653
+ * each time a peer or router connects or goes. history: true reports the
3654
+ * ones connected now first. */
3655
+ static VALUE zrb_session_transport_events(int argc, VALUE *argv, VALUE self) {
3656
+ VALUE depth_v = Qnil, opts = Qnil;
3657
+ rb_scan_args(argc, argv, "01:", &depth_v, &opts);
3658
+ bool history = zrb_history_kw(opts);
3659
+ zrb_session *z = zrb_session_get_open(self);
3660
+ zrb_lst *l;
3661
+ VALUE obj = zrb_lst_new(cEventListener, ZLST_TRANSPORT, ZEV_TRANSPORT, depth_v, &l);
3662
+ z_owned_closure_transport_event_t cb;
3663
+ z_closure_transport_event(&cb, zev_on_transport_event, zevq_on_drop, zevq_ref(l->q));
3664
+ z_transport_events_listener_options_t to;
3665
+ z_transport_events_listener_options_default(&to);
3666
+ to.history = history;
3667
+ z_result_t r = z_declare_transport_events_listener(z_loan(z->session), &l->u.t, z_move(cb), &to);
3668
+ if (r != Z_OK) {
3669
+ rb_raise(eZenohError, "cannot declare a transport events listener (%d)%" PRIsVALUE, (int)r, zrb_last_error());
1305
3670
  }
1306
- if (a->ret != Z_OK) {
1307
- rb_raise(eZenohError, "%s failed (%d)", what, (int)a->ret);
3671
+ zrb_lst_linked(obj, l, z, self);
3672
+ return obj;
3673
+ }
3674
+
3675
+ /* session.link_events(depth = 16, history: false) -> EventListener: a
3676
+ * LinkEvent (kind, zid, src, dst, mtu, streamed, reliability, interfaces,
3677
+ * group, auth_identifier) each time a link opens or closes. */
3678
+ static VALUE zrb_session_link_events(int argc, VALUE *argv, VALUE self) {
3679
+ VALUE depth_v = Qnil, opts = Qnil;
3680
+ rb_scan_args(argc, argv, "01:", &depth_v, &opts);
3681
+ bool history = zrb_history_kw(opts);
3682
+ zrb_session *z = zrb_session_get_open(self);
3683
+ zrb_lst *l;
3684
+ VALUE obj = zrb_lst_new(cEventListener, ZLST_LINK, ZEV_LINK, depth_v, &l);
3685
+ z_owned_closure_link_event_t cb;
3686
+ z_closure_link_event(&cb, zev_on_link_event, zevq_on_drop, zevq_ref(l->q));
3687
+ z_link_events_listener_options_t lo;
3688
+ z_link_events_listener_options_default(&lo);
3689
+ lo.history = history;
3690
+ z_result_t r = z_declare_link_events_listener(z_loan(z->session), &l->u.l, z_move(cb), &lo);
3691
+ if (r != Z_OK) {
3692
+ rb_raise(eZenohError, "cannot declare a link events listener (%d)%" PRIsVALUE, (int)r, zrb_last_error());
1308
3693
  }
1309
- zrb_hold_session(obj, self, key_v);
3694
+ zrb_lst_linked(obj, l, z, self);
1310
3695
  return obj;
1311
3696
  }
1312
3697
 
1313
- /* session.get(key, timeout_ms = 2000, params = nil, payload = nil,
1314
- * attachment: nil, target: :all, consolidation: :none) -> Get.
1315
- * Returns at once; the replies come in on zenoh's threads. */
1316
- static VALUE zrb_session_get_m(int argc, VALUE *argv, VALUE self) {
1317
- VALUE key_v, timeout_v = Qnil, params_v = Qnil, payload = Qnil, opts = Qnil;
1318
- rb_scan_args(argc, argv, "13:", &key_v, &timeout_v, &params_v, &payload, &opts);
1319
- VALUE kw[3] = {Qundef, Qundef, Qundef};
3698
+ /* ---------------------------------------------------- advanced subscriber */
3699
+
3700
+ static const char *const zrb_history_keys[] = {"max_samples", "max_age", "detect_late_publishers"};
3701
+ static const char *const zrb_recovery_keys[] = {"periodic_queries_ms", "heartbeat"};
3702
+
3703
+ /* session.advanced_subscriber(key, depth = 16, history: nil, recovery: nil,
3704
+ * subscriber_detection: false, query_timeout_ms: nil) -> AdvancedSubscriber
3705
+ * history: true or {max_samples:, max_age: (seconds), detect_late_publishers:}
3706
+ * asks the advanced publishers' caches for what they kept (late joiners get
3707
+ * the last values; ROS 2's transient local). recovery: true or
3708
+ * {periodic_queries_ms:} (or {heartbeat: true}) asks again for samples
3709
+ * that were missed. The rest is the same as subscribe. */
3710
+ static VALUE zrb_session_advanced_subscriber(int argc, VALUE *argv, VALUE self) {
3711
+ VALUE key_v, depth_v = Qnil, opts = Qnil;
3712
+ rb_scan_args(argc, argv, "11:", &key_v, &depth_v, &opts);
3713
+ VALUE kw[4] = {Qundef, Qundef, Qundef, Qundef};
1320
3714
  if (!NIL_P(opts)) {
1321
- ID ids[3] = {id_attachment, id_target, id_consolidation};
1322
- rb_get_kwargs(opts, ids, 0, 3, kw);
3715
+ ID ids[4] = {id_history, rb_intern("recovery"), rb_intern("subscriber_detection"),
3716
+ rb_intern("query_timeout_ms")};
3717
+ rb_get_kwargs(opts, ids, 0, 4, kw);
1323
3718
  }
1324
- const char *key = StringValueCStr(key_v);
1325
- long timeout_ms = zrb_check_timeout(timeout_v);
1326
- const char *params = NIL_P(params_v) ? NULL : StringValueCStr(params_v);
1327
- if (!NIL_P(payload) && !RB_TYPE_P(payload, T_STRING)) {
1328
- rb_raise(rb_eTypeError, "payload must be a String");
3719
+ long depth = zrb_check_depth(depth_v);
3720
+ ze_advanced_subscriber_options_t ao;
3721
+ ze_advanced_subscriber_options_default(&ao);
3722
+ ao.subscriber_options.allowed_origin = Z_LOCALITY_REMOTE;
3723
+ VALUE hist = kw[0] == Qundef ? Qnil : kw[0];
3724
+ VALUE rec = kw[1] == Qundef ? Qnil : kw[1];
3725
+ if (RTEST(hist)) {
3726
+ VALUE h = zrb_subopt_hash(hist, "history", zrb_history_keys, 3);
3727
+ if (NIL_P(h) && hist != Qtrue) {
3728
+ rb_raise(rb_eTypeError, "history must be true or a Hash");
3729
+ }
3730
+ ao.history.is_enabled = true;
3731
+ VALUE v;
3732
+ if (!NIL_P(v = zrb_hget(h, "max_samples"))) {
3733
+ ao.history.max_samples = (size_t)NUM2ULONG(v);
3734
+ }
3735
+ if (!NIL_P(v = zrb_hget(h, "max_age"))) {
3736
+ double s = NUM2DBL(v);
3737
+ if (s < 0) {
3738
+ rb_raise(rb_eArgError, "max_age must be 0 or more");
3739
+ }
3740
+ ao.history.max_age_ms = (uint64_t)(s * 1000.0);
3741
+ }
3742
+ if (!NIL_P(v = zrb_hget(h, "detect_late_publishers"))) {
3743
+ ao.history.detect_late_publishers = RTEST(v);
3744
+ }
3745
+ }
3746
+ if (RTEST(rec)) {
3747
+ VALUE h = zrb_subopt_hash(rec, "recovery", zrb_recovery_keys, 2);
3748
+ if (NIL_P(h) && rec != Qtrue) {
3749
+ rb_raise(rb_eTypeError, "recovery must be true or a Hash");
3750
+ }
3751
+ ao.recovery.is_enabled = true;
3752
+ VALUE v;
3753
+ if (!NIL_P(v = zrb_hget(h, "periodic_queries_ms"))) {
3754
+ ao.recovery.last_sample_miss_detection.is_enabled = true;
3755
+ ao.recovery.last_sample_miss_detection.periodic_queries_period_ms = zrb_ms_arg(v, "periodic_queries_ms");
3756
+ } else if (RTEST(zrb_hget(h, "heartbeat"))) {
3757
+ ao.recovery.last_sample_miss_detection.is_enabled = true;
3758
+ ao.recovery.last_sample_miss_detection.periodic_queries_period_ms = 0;
3759
+ }
3760
+ }
3761
+ if (kw[2] != Qundef) {
3762
+ ao.subscriber_detection = RTEST(kw[2]);
1329
3763
  }
1330
- VALUE att = zrb_kw_attachment(kw[0]);
1331
- z_query_target_t target = zrb_get_target(kw[1]);
1332
- z_query_consolidation_t consolidation = zrb_get_consolidation(kw[2]);
3764
+ if (kw[3] != Qundef && !NIL_P(kw[3])) {
3765
+ ao.query_timeout_ms = zrb_ms_arg(kw[3], "query_timeout_ms");
3766
+ }
3767
+ VALUE key_str = zrb_key_string(key_v);
1333
3768
  zrb_session *z = zrb_session_get_open(self);
3769
+ z_view_keyexpr_t view;
3770
+ const z_loaned_keyexpr_t *ke = zrb_key_loan(key_v, &view);
1334
3771
 
1335
- zrb_get_args a;
1336
- memset(&a, 0, sizeof(a));
1337
- a.z = z;
1338
- zrb_owned_key(&a.key, key);
1339
- zrb_get *g;
1340
- VALUE obj = zrb_get_new(&g);
1341
- z_get_options_default(&a.opts);
1342
- a.opts.timeout_ms = (uint64_t)timeout_ms;
1343
- a.opts.target = target;
1344
- a.opts.consolidation = consolidation;
1345
- /* Remote queryables only, as with zenoh-pico. */
1346
- a.opts.allowed_destination = Z_LOCALITY_REMOTE;
1347
- z_owned_bytes_t bytes;
1348
- z_owned_bytes_t att_bytes;
1349
- if (!NIL_P(payload)) {
1350
- zrb_bytes_from_str(&bytes, payload, "payload");
1351
- a.opts.payload = z_move(bytes);
3772
+ zrb_sub *s;
3773
+ VALUE obj = TypedData_Make_Struct(cAdvSubscriber, zrb_sub, &zrb_sub_type, s);
3774
+ s->type = ZSUB_ADVANCED;
3775
+ s->ch = zch_new(ZCH_SAMPLE, (uint32_t)depth);
3776
+ z_owned_closure_sample_t cb;
3777
+ zch_closure_sample(s->ch, &cb);
3778
+ z_result_t ret = ze_declare_advanced_subscriber(z_loan(z->session), &s->u.adv, ke, z_move(cb), &ao);
3779
+ if (ret != Z_OK) {
3780
+ rb_raise(eZenohError, "cannot declare an advanced subscriber on %" PRIsVALUE " (%d)%" PRIsVALUE, key_str, (int)ret, zrb_last_error());
1352
3781
  }
1353
- if (!NIL_P(att)) {
1354
- zrb_bytes_from_str(&att_bytes, att, "attachment");
1355
- a.opts.attachment = z_move(att_bytes);
3782
+ s->declared = true;
3783
+ s->owner = z;
3784
+ s->next = z->subs;
3785
+ z->subs = s;
3786
+ zrb_hold_session(obj, self, key_str);
3787
+ return obj;
3788
+ }
3789
+
3790
+ static zrb_sub *zrb_advsub_get_open(VALUE self) {
3791
+ zrb_sub *s = zrb_sub_get(self);
3792
+ if (s->type != ZSUB_ADVANCED || !s->declared) {
3793
+ rb_raise(eZenohError, "the subscriber is closed");
1356
3794
  }
1357
- if (params != NULL) {
1358
- a.params = strdup(params);
3795
+ if (zrb_session_check_link(s->owner)) {
3796
+ rb_raise(eZenohError, "session is closed");
1359
3797
  }
1360
- zch_closure_reply(g->ch, &a.cb);
1361
- return zrb_run_get(self, z, &a, obj, key_v, "get");
3798
+ return s;
1362
3799
  }
1363
3800
 
1364
- /* session.liveliness(key) -> LivelinessToken */
1365
- static VALUE zrb_session_liveliness(VALUE self, VALUE key_v) {
1366
- const char *key = StringValueCStr(key_v);
1367
- zrb_session *z = zrb_session_get_open(self);
1368
- z_view_keyexpr_t ke;
1369
- zrb_view_key(&ke, key);
1370
- zrb_token *t;
1371
- VALUE obj = TypedData_Make_Struct(cToken, zrb_token, &zrb_token_type, t);
1372
- z_result_t ret = z_liveliness_declare_token(z_loan(z->session), &t->token, z_loan(ke), NULL);
3801
+ /* advsub.miss_listener(depth = 16) -> EventListener of Miss (source_zid,
3802
+ * source_eid, count): samples a publisher sent that never came (needs
3803
+ * sample_miss_detection on the advanced publisher). */
3804
+ static VALUE zrb_advsub_miss_listener(int argc, VALUE *argv, VALUE self) {
3805
+ VALUE depth_v = Qnil;
3806
+ rb_scan_args(argc, argv, "01", &depth_v);
3807
+ zrb_sub *s = zrb_advsub_get_open(self);
3808
+ zrb_lst *l;
3809
+ VALUE obj = zrb_lst_new(cEventListener, ZLST_MISS, ZEV_MISS, depth_v, &l);
3810
+ ze_owned_closure_miss_t cb;
3811
+ ze_closure_miss(&cb, zev_on_miss, zevq_on_drop, zevq_ref(l->q));
3812
+ z_result_t r = ze_advanced_subscriber_declare_sample_miss_listener(z_loan(s->u.adv), &l->u.s, z_move(cb));
3813
+ if (r != Z_OK) {
3814
+ rb_raise(eZenohError, "cannot declare a sample miss listener (%d)%" PRIsVALUE, (int)r, zrb_last_error());
3815
+ }
3816
+ zrb_lst_linked(obj, l, s->owner, self);
3817
+ return obj;
3818
+ }
3819
+
3820
+ /* advsub.detect_publishers(depth = 16, history: true) -> LivelinessWatch:
3821
+ * each_pending { |key, alive| } for the advanced publishers on the key
3822
+ * (those declared with publisher_detection: true). */
3823
+ static VALUE zrb_advsub_detect_publishers(int argc, VALUE *argv, VALUE self) {
3824
+ VALUE depth_v = Qnil, opts = Qnil;
3825
+ rb_scan_args(argc, argv, "01:", &depth_v, &opts);
3826
+ VALUE kw[1] = {Qundef};
3827
+ if (!NIL_P(opts)) {
3828
+ rb_get_kwargs(opts, &id_history, 0, 1, kw);
3829
+ }
3830
+ bool history = (kw[0] == Qundef) ? true : RTEST(kw[0]);
3831
+ long depth = zrb_check_depth(depth_v);
3832
+ zrb_sub *as = zrb_advsub_get_open(self);
3833
+ zrb_sub *s;
3834
+ VALUE obj = TypedData_Make_Struct(cWatch, zrb_sub, &zrb_sub_type, s);
3835
+ s->liveliness = true;
3836
+ s->type = ZSUB_LIVELINESS;
3837
+ s->ch = zch_new(ZCH_SAMPLE, (uint32_t)depth);
3838
+ z_owned_closure_sample_t cb;
3839
+ zch_closure_sample(s->ch, &cb);
3840
+ z_liveliness_subscriber_options_t lo;
3841
+ z_liveliness_subscriber_options_default(&lo);
3842
+ lo.history = history;
3843
+ z_result_t ret = ze_advanced_subscriber_detect_publishers(z_loan(as->u.adv), &s->u.sub, z_move(cb), &lo);
1373
3844
  if (ret != Z_OK) {
1374
- rb_raise(eZenohError, "cannot declare a liveliness token on %s (%d)", key, (int)ret);
3845
+ rb_raise(eZenohError, "cannot detect publishers (%d)%" PRIsVALUE, (int)ret, zrb_last_error());
1375
3846
  }
1376
- t->declared = true;
1377
- t->owner = z;
1378
- t->next = z->tokens;
1379
- z->tokens = t;
1380
- zrb_hold_session(obj, self, key_v);
3847
+ s->declared = true;
3848
+ s->owner = as->owner;
3849
+ s->next = as->owner->subs;
3850
+ as->owner->subs = s;
3851
+ rb_ivar_set(obj, id_iv_session, rb_ivar_get(self, id_iv_session));
3852
+ rb_ivar_set(obj, id_iv_parent, self);
1381
3853
  return obj;
1382
3854
  }
1383
3855
 
1384
- /* session.liveliness_get(key, timeout_ms = 2000) -> Get */
1385
- static VALUE zrb_session_liveliness_get(int argc, VALUE *argv, VALUE self) {
1386
- VALUE key_v, timeout_v = Qnil;
1387
- rb_scan_args(argc, argv, "11", &key_v, &timeout_v);
1388
- const char *key = StringValueCStr(key_v);
1389
- long timeout_ms = zrb_check_timeout(timeout_v);
1390
- zrb_session *z = zrb_session_get_open(self);
3856
+ /* ------------------------------------------------- session information */
1391
3857
 
1392
- zrb_get_args a;
1393
- memset(&a, 0, sizeof(a));
1394
- a.z = z;
1395
- a.liveliness = true;
1396
- zrb_owned_key(&a.key, key);
1397
- zrb_get *g;
1398
- VALUE obj = zrb_get_new(&g);
1399
- z_liveliness_get_options_default(&a.lopts);
1400
- a.lopts.timeout_ms = (uint64_t)timeout_ms;
1401
- zch_closure_reply(g->ch, &a.cb);
1402
- return zrb_run_get(self, z, &a, obj, key_v, "liveliness_get");
3858
+ /* Everything queued, as an Array (a snapshot's queue). */
3859
+ static VALUE zevq_each_pending_noblock(zevq *q, bool event) {
3860
+ VALUE out = rb_ary_new();
3861
+ zev *e;
3862
+ while ((e = zevq_take(q)) != NULL) {
3863
+ VALUE v = zev_to_ruby(q->kind, e, event);
3864
+ zev_free(e);
3865
+ rb_ary_push(out, v);
3866
+ }
3867
+ return out;
1403
3868
  }
1404
3869
 
1405
- /* session.poll(steps = 8) -> true while the session is open, false once
1406
- * closed (by close, or because the connection was lost). zenoh-c receives
1407
- * on its own threads, so this only checks the connection; steps is
1408
- * accepted for the mruby gem's signature. Never waits. */
1409
- static VALUE zrb_session_poll(int argc, VALUE *argv, VALUE self) {
1410
- VALUE steps_v = Qnil;
1411
- rb_scan_args(argc, argv, "01", &steps_v);
1412
- if (!NIL_P(steps_v)) {
1413
- NUM2LONG(steps_v);
3870
+ typedef struct {
3871
+ pthread_mutex_t lock;
3872
+ z_id_t *ids;
3873
+ size_t n, cap;
3874
+ } zrb_zids;
3875
+
3876
+ static void zrb_collect_zid(const z_id_t *id, void *ctx) {
3877
+ zrb_zids *c = (zrb_zids *)ctx;
3878
+ pthread_mutex_lock(&c->lock);
3879
+ if (c->n == c->cap) {
3880
+ size_t cap = c->cap ? c->cap * 2 : 8;
3881
+ z_id_t *ids = (z_id_t *)realloc(c->ids, cap * sizeof(z_id_t));
3882
+ if (ids == NULL) {
3883
+ pthread_mutex_unlock(&c->lock);
3884
+ return;
3885
+ }
3886
+ c->ids = ids;
3887
+ c->cap = cap;
1414
3888
  }
1415
- return zrb_session_check_link(zrb_session_get(self)) ? Qfalse : Qtrue;
3889
+ c->ids[c->n++] = *id;
3890
+ pthread_mutex_unlock(&c->lock);
1416
3891
  }
1417
3892
 
1418
- static VALUE zrb_session_closed_p(VALUE self) {
1419
- return zrb_session_check_link(zrb_session_get(self)) ? Qtrue : Qfalse;
3893
+ static VALUE zrb_session_zids(VALUE self, bool routers) {
3894
+ zrb_session *z = zrb_session_get(self);
3895
+ if (zrb_session_check_link(z)) {
3896
+ return rb_ary_new();
3897
+ }
3898
+ zrb_zids c;
3899
+ memset(&c, 0, sizeof(c));
3900
+ pthread_mutex_init(&c.lock, NULL);
3901
+ z_owned_closure_zid_t cb;
3902
+ z_closure_zid(&cb, zrb_collect_zid, NULL, &c);
3903
+ if (routers) {
3904
+ z_info_routers_zid(z_loan(z->session), z_move(cb));
3905
+ } else {
3906
+ z_info_peers_zid(z_loan(z->session), z_move(cb));
3907
+ }
3908
+ VALUE out = rb_ary_new_capa((long)c.n);
3909
+ for (size_t i = 0; i < c.n; i++) {
3910
+ rb_ary_push(out, zrb_zid_value(&c.ids[i]));
3911
+ }
3912
+ free(c.ids);
3913
+ pthread_mutex_destroy(&c.lock);
3914
+ return out;
1420
3915
  }
1421
3916
 
1422
- static VALUE zrb_session_close(VALUE self) {
1423
- zrb_session_shutdown(zrb_session_get(self), true);
1424
- return Qnil;
3917
+ /* session.peer_zids / router_zids -> Array of String: the Zenoh IDs of the
3918
+ * peers / routers connected now (session.peers stays the count). */
3919
+ static VALUE zrb_session_peer_zids(VALUE self) { return zrb_session_zids(self, false); }
3920
+ static VALUE zrb_session_router_zids(VALUE self) { return zrb_session_zids(self, true); }
3921
+
3922
+ /* session.transports -> Array of Transport (zid, whatami, qos, multicast) */
3923
+ static VALUE zrb_session_transports(VALUE self) {
3924
+ zrb_session *z = zrb_session_get_open(self);
3925
+ zevq *q = zevq_new(ZEV_TRANSPORT, ZRB_MAX_DEPTH);
3926
+ z_owned_closure_transport_t cb;
3927
+ z_closure_transport(&cb, zev_on_transport, zevq_on_drop, zevq_ref(q));
3928
+ z_info_transports(z_loan(z->session), z_move(cb));
3929
+ VALUE out = zevq_each_pending_noblock(q, false);
3930
+ zevq_unref(q);
3931
+ return out;
1425
3932
  }
1426
3933
 
1427
- /* session.zid -> String: this session's Zenoh ID in hex. */
1428
- static VALUE zrb_session_zid(VALUE self) {
3934
+ /* session.links -> Array of Link (zid, src, dst, mtu, streamed, ...) */
3935
+ static VALUE zrb_session_links_m(VALUE self) {
1429
3936
  zrb_session *z = zrb_session_get_open(self);
1430
- z_id_t id = z_info_zid(z_loan(z->session));
1431
- z_owned_string_t str;
1432
- z_id_to_string(&id, &str);
1433
- VALUE out = zrb_str_from_view(z_loan(str));
1434
- z_drop(z_move(str));
3937
+ zevq *q = zevq_new(ZEV_LINK, ZRB_MAX_DEPTH);
3938
+ z_owned_closure_link_t cb;
3939
+ z_closure_link(&cb, zev_on_link, zevq_on_drop, zevq_ref(q));
3940
+ z_info_links_options_t lo;
3941
+ z_info_links_options_default(&lo);
3942
+ z_info_links(z_loan(z->session), z_move(cb), &lo);
3943
+ VALUE out = zevq_each_pending_noblock(q, false);
3944
+ zevq_unref(q);
1435
3945
  return out;
1436
3946
  }
1437
3947
 
1438
- /* session.peers -> Integer: connected peers (peer mode), or routers (1
1439
- * normally) for a client session; 0 once closed. */
1440
- static VALUE zrb_session_peers(VALUE self) {
1441
- zrb_session *z = zrb_session_get(self);
1442
- if (zrb_session_check_link(z)) {
1443
- return INT2FIX(0);
3948
+ /* session.new_timestamp -> Timestamp (from the session's clock and ID) */
3949
+ static VALUE zrb_session_new_timestamp(VALUE self) {
3950
+ zrb_session *z = zrb_session_get_open(self);
3951
+ z_timestamp_t ts;
3952
+ if (z_timestamp_new(&ts, z_loan(z->session)) != Z_OK) {
3953
+ rb_raise(eZenohError, "cannot make a timestamp");
1444
3954
  }
1445
- return INT2FIX(zrb_session_links(z));
3955
+ return zrb_ts_wrap(&ts);
1446
3956
  }
1447
3957
 
1448
- /* The default of zenoh-c's transport/unicast/max_sessions (MAX_PEERS). */
1449
- static long zrb_default_max_sessions(void) {
1450
- long n = -1;
1451
- z_owned_config_t c;
1452
- if (z_config_default(&c) != Z_OK) {
1453
- return n;
3958
+ /* session.declare_keyexpr(key) -> KeyExpr, declared on the session: the
3959
+ * key goes over the wire as a short number afterwards. Pass it to put,
3960
+ * delete, publisher, querier and the advanced ones of the same session.
3961
+ * Undeclared by KeyExpr#undeclare or when the session closes. */
3962
+ static VALUE zrb_session_declare_keyexpr(VALUE self, VALUE key_v) {
3963
+ zrb_key_string(key_v);
3964
+ zrb_session *z = zrb_session_get_open(self);
3965
+ z_view_keyexpr_t view;
3966
+ const z_loaned_keyexpr_t *ke = zrb_key_loan(key_v, &view);
3967
+ zrb_ke *k;
3968
+ VALUE obj = TypedData_Make_Struct(cKeyExpr, zrb_ke, &zrb_ke_type, k);
3969
+ z_keyexpr_clone(&k->ke, ke);
3970
+ z_internal_keyexpr_null(&k->decl);
3971
+ z_result_t r = z_declare_keyexpr(z_loan(z->session), &k->decl, ke);
3972
+ if (r != Z_OK) {
3973
+ rb_raise(eZenohError, "cannot declare the key expression (%d)%" PRIsVALUE, (int)r, zrb_last_error());
1454
3974
  }
1455
- z_owned_string_t s;
1456
- if (zc_config_get_from_str(z_loan(c), "transport/unicast/max_sessions", &s) == Z_OK) {
1457
- char buf[32];
1458
- size_t len = z_string_len(z_loan(s));
1459
- if (len < sizeof(buf)) {
1460
- memcpy(buf, z_string_data(z_loan(s)), len);
1461
- buf[len] = '\0';
1462
- n = strtol(buf, NULL, 10);
3975
+ zrb_ent_link(&k->ent, z, ZENT_KEYEXPR, true, zrb_ke_undeclare);
3976
+ rb_ivar_set(obj, id_iv_session, self);
3977
+ return obj;
3978
+ }
3979
+
3980
+ /* ------------------------------------------------------ scouting, logs */
3981
+
3982
+ typedef struct {
3983
+ z_owned_config_t config;
3984
+ z_owned_closure_hello_t cb;
3985
+ z_scout_options_t opts;
3986
+ z_result_t ret;
3987
+ } zrb_scout_args;
3988
+
3989
+ static void *zrb_scout_nogvl(void *p) {
3990
+ zrb_scout_args *a = (zrb_scout_args *)p;
3991
+ a->ret = z_scout(z_move(a->config), z_move(a->cb), &a->opts);
3992
+ return NULL;
3993
+ }
3994
+
3995
+ /* Asterism::Zenoh._scout(what, timeout_ms, config) -> Array of Hello.
3996
+ * what: the bits of z_what_t (1 router, 2 peer, 4 client). config: nil or
3997
+ * a Hash as for Session.open. Waits timeout_ms (without the GVL). The
3998
+ * Ruby wrapper is Asterism::Zenoh.scout. */
3999
+ static VALUE zrb_s_scout(VALUE mod, VALUE what_v, VALUE timeout_v, VALUE config_v) {
4000
+ int what = NUM2INT(what_v);
4001
+ if (what < 1 || what > 7) {
4002
+ rb_raise(rb_eArgError, "what must be 1..7");
4003
+ }
4004
+ long timeout = zrb_check_timeout(timeout_v);
4005
+ if (!NIL_P(config_v)) {
4006
+ Check_Type(config_v, T_HASH);
4007
+ zrb_to_json(Qnil);
4008
+ }
4009
+ zrb_scout_args a;
4010
+ if (z_config_default(&a.config) != Z_OK) {
4011
+ rb_raise(eZenohError, "cannot create the configuration");
4012
+ }
4013
+ zrb_config_set(&a.config, "scouting/multicast/enabled", "true");
4014
+ if (!NIL_P(config_v)) {
4015
+ zrb_cfg_hash h = {config_v, &a.config, Qnil};
4016
+ int state = 0;
4017
+ rb_protect(zrb_cfg_hash_body, (VALUE)&h, &state);
4018
+ if (state != 0 || !NIL_P(h.bad)) {
4019
+ z_drop(z_move(a.config));
4020
+ if (state != 0) {
4021
+ rb_jump_tag(state);
4022
+ }
4023
+ rb_raise(rb_eArgError, "invalid configuration: %" PRIsVALUE, h.bad);
1463
4024
  }
1464
- z_drop(z_move(s));
1465
4025
  }
1466
- z_drop(z_move(c));
1467
- return n;
4026
+ zevq *q = zevq_new(ZEV_HELLO, ZRB_MAX_DEPTH);
4027
+ z_closure_hello(&a.cb, zev_on_hello, zevq_on_drop, zevq_ref(q));
4028
+ z_scout_options_default(&a.opts);
4029
+ a.opts.timeout_ms = (uint64_t)timeout;
4030
+ a.opts.what = (z_what_t)what;
4031
+ rb_thread_call_without_gvl(zrb_scout_nogvl, &a, RUBY_UBF_IO, NULL);
4032
+ VALUE out = zevq_each_pending_noblock(q, false);
4033
+ zevq_unref(q);
4034
+ if (a.ret != Z_OK) {
4035
+ rb_raise(eZenohError, "scouting failed (%d)", (int)a.ret);
4036
+ }
4037
+ return out;
4038
+ }
4039
+
4040
+ /* Asterism::Zenoh.init_log(level = nil) -> nil: zenoh-c's log, written to
4041
+ * standard output (zenoh-c's own logger).
4042
+ * level: "error", "warn", "info", "debug", "trace" (or a filter such as
4043
+ * "zenoh::net=debug"); RUST_LOG, when set, wins. nil: only RUST_LOG. Once
4044
+ * per process: later calls change nothing. */
4045
+ static VALUE zrb_s_init_log(int argc, VALUE *argv, VALUE mod) {
4046
+ VALUE level = Qnil;
4047
+ rb_scan_args(argc, argv, "01", &level);
4048
+ if (NIL_P(level)) {
4049
+ zc_try_init_log_from_env();
4050
+ return Qnil;
4051
+ }
4052
+ VALUE s = rb_obj_as_string(level);
4053
+ z_result_t r = zc_init_log_from_env_or(StringValueCStr(s));
4054
+ if (r != Z_OK) {
4055
+ rb_raise(rb_eArgError, "invalid log level: %" PRIsVALUE, s);
4056
+ }
4057
+ return Qnil;
1468
4058
  }
1469
4059
 
1470
4060
  /* ----------------------------------------------------------------- init */
@@ -1488,8 +4078,15 @@ void Init_asterism_zenoh(void) {
1488
4078
  id_listen = rb_intern("listen");
1489
4079
  id_iv_session = rb_intern("@session");
1490
4080
  id_iv_key = rb_intern("@key");
4081
+ id_iv_parent = rb_intern("@parent");
4082
+ id_config = rb_intern("config");
4083
+ id_config_file = rb_intern("config_file");
4084
+ id_scouting = rb_intern("scouting");
4085
+ id_history = rb_intern("history");
4086
+ id_new = rb_intern("new");
1491
4087
  id_client = rb_intern("client");
1492
4088
  id_peer = rb_intern("peer");
4089
+ id_router = rb_intern("router");
1493
4090
  id_all = rb_intern("all");
1494
4091
  id_all_complete = rb_intern("all_complete");
1495
4092
  id_best_matching = rb_intern("best_matching");
@@ -1502,6 +4099,19 @@ void Init_asterism_zenoh(void) {
1502
4099
  zrb_no_new(cSession);
1503
4100
  rb_define_singleton_method(cSession, "open", zrb_session_s_open, -1);
1504
4101
  rb_define_method(cSession, "put", zrb_session_put, -1);
4102
+ rb_define_method(cSession, "delete", zrb_session_delete, -1);
4103
+ rb_define_method(cSession, "publisher", zrb_session_publisher, -1);
4104
+ rb_define_method(cSession, "advanced_publisher", zrb_session_advanced_publisher, -1);
4105
+ rb_define_method(cSession, "advanced_subscriber", zrb_session_advanced_subscriber, -1);
4106
+ rb_define_method(cSession, "querier", zrb_session_querier, -1);
4107
+ rb_define_method(cSession, "transport_events", zrb_session_transport_events, -1);
4108
+ rb_define_method(cSession, "link_events", zrb_session_link_events, -1);
4109
+ rb_define_method(cSession, "peer_zids", zrb_session_peer_zids, 0);
4110
+ rb_define_method(cSession, "router_zids", zrb_session_router_zids, 0);
4111
+ rb_define_method(cSession, "transports", zrb_session_transports, 0);
4112
+ rb_define_method(cSession, "links", zrb_session_links_m, 0);
4113
+ rb_define_method(cSession, "new_timestamp", zrb_session_new_timestamp, 0);
4114
+ rb_define_method(cSession, "declare_keyexpr", zrb_session_declare_keyexpr, 1);
1505
4115
  rb_define_method(cSession, "subscribe", zrb_session_subscribe, -1);
1506
4116
  rb_define_method(cSession, "get", zrb_session_get_m, -1);
1507
4117
  rb_define_method(cSession, "queryable", zrb_session_queryable, -1);
@@ -1527,6 +4137,91 @@ void Init_asterism_zenoh(void) {
1527
4137
  rb_define_method(both[i], "close", zrb_sub_close, 0);
1528
4138
  rb_define_method(both[i], "closed?", zrb_sub_closed_p, 0);
1529
4139
  }
4140
+ rb_define_method(cSubscriber, "each_sample", zrb_sub_each_sample, 0);
4141
+
4142
+ /* AdvancedSubscriber: a Subscriber with history, recovery, missed
4143
+ * samples and publisher detection. */
4144
+ cAdvSubscriber = rb_define_class_under(mZenoh, "AdvancedSubscriber", rb_cObject);
4145
+ zrb_no_new(cAdvSubscriber);
4146
+ rb_define_method(cAdvSubscriber, "each_pending", zrb_sub_each_pending, 0);
4147
+ rb_define_method(cAdvSubscriber, "each_sample", zrb_sub_each_sample, 0);
4148
+ rb_define_method(cAdvSubscriber, "pending", zrb_sub_pending, 0);
4149
+ rb_define_method(cAdvSubscriber, "received", zrb_sub_received, 0);
4150
+ rb_define_method(cAdvSubscriber, "dropped", zrb_sub_dropped, 0);
4151
+ rb_define_method(cAdvSubscriber, "close", zrb_sub_close, 0);
4152
+ rb_define_method(cAdvSubscriber, "closed?", zrb_sub_closed_p, 0);
4153
+ rb_define_method(cAdvSubscriber, "miss_listener", zrb_advsub_miss_listener, -1);
4154
+ rb_define_method(cAdvSubscriber, "detect_publishers", zrb_advsub_detect_publishers, -1);
4155
+
4156
+ /* Publisher and AdvancedPublisher share one C structure. */
4157
+ cPublisher = rb_define_class_under(mZenoh, "Publisher", rb_cObject);
4158
+ cAdvPublisher = rb_define_class_under(mZenoh, "AdvancedPublisher", rb_cObject);
4159
+ VALUE pubs[2] = {cPublisher, cAdvPublisher};
4160
+ for (int i = 0; i < 2; i++) {
4161
+ zrb_no_new(pubs[i]);
4162
+ rb_define_method(pubs[i], "put", zrb_pub_put, -1);
4163
+ rb_define_method(pubs[i], "delete", zrb_pub_delete, -1);
4164
+ rb_define_method(pubs[i], "matching?", zrb_pub_matching_p, 0);
4165
+ rb_define_method(pubs[i], "matching_listener", zrb_pub_matching_listener, -1);
4166
+ rb_define_method(pubs[i], "close", zrb_pub_close, 0);
4167
+ rb_define_method(pubs[i], "closed?", zrb_pub_closed_p, 0);
4168
+ }
4169
+
4170
+ cQuerier = rb_define_class_under(mZenoh, "Querier", rb_cObject);
4171
+ zrb_no_new(cQuerier);
4172
+ rb_define_method(cQuerier, "get", zrb_querier_get_m, -1);
4173
+ rb_define_method(cQuerier, "matching?", zrb_querier_matching_p, 0);
4174
+ rb_define_method(cQuerier, "matching_listener", zrb_querier_matching_listener, -1);
4175
+ rb_define_method(cQuerier, "close", zrb_querier_close, 0);
4176
+ rb_define_method(cQuerier, "closed?", zrb_querier_closed_p, 0);
4177
+
4178
+ cMatchingListener = rb_define_class_under(mZenoh, "MatchingListener", rb_cObject);
4179
+ cEventListener = rb_define_class_under(mZenoh, "EventListener", rb_cObject);
4180
+ VALUE lsts[2] = {cMatchingListener, cEventListener};
4181
+ for (int i = 0; i < 2; i++) {
4182
+ zrb_no_new(lsts[i]);
4183
+ rb_define_method(lsts[i], "each_pending", zrb_lst_each_pending, 0);
4184
+ rb_define_method(lsts[i], "pending", zrb_lst_pending, 0);
4185
+ rb_define_method(lsts[i], "received", zrb_lst_received, 0);
4186
+ rb_define_method(lsts[i], "dropped", zrb_lst_dropped, 0);
4187
+ rb_define_method(lsts[i], "close", zrb_lst_close, 0);
4188
+ rb_define_method(lsts[i], "closed?", zrb_lst_closed_p, 0);
4189
+ }
4190
+
4191
+ cKeyExpr = rb_define_class_under(mZenoh, "KeyExpr", rb_cObject);
4192
+ rb_undef_alloc_func(cKeyExpr);
4193
+ rb_define_singleton_method(cKeyExpr, "new", zrb_ke_s_new, -1);
4194
+ rb_define_singleton_method(cKeyExpr, "canonize", zrb_ke_s_canonize, 1);
4195
+ rb_define_singleton_method(cKeyExpr, "valid?", zrb_ke_s_valid_p, 1);
4196
+ rb_define_method(cKeyExpr, "to_s", zrb_ke_to_s, 0);
4197
+ rb_define_method(cKeyExpr, "to_str", zrb_ke_to_s, 0);
4198
+ rb_define_method(cKeyExpr, "inspect", zrb_ke_inspect, 0);
4199
+ rb_define_method(cKeyExpr, "intersects?", zrb_ke_intersects_p, 1);
4200
+ rb_define_method(cKeyExpr, "includes?", zrb_ke_includes_p, 1);
4201
+ rb_define_method(cKeyExpr, "relation_to", zrb_ke_relation_to, 1);
4202
+ rb_define_method(cKeyExpr, "join", zrb_ke_join, 1);
4203
+ rb_define_method(cKeyExpr, "concat", zrb_ke_concat, 1);
4204
+ rb_define_method(cKeyExpr, "==", zrb_ke_eq, 1);
4205
+ rb_define_method(cKeyExpr, "eql?", zrb_ke_eq, 1);
4206
+ rb_define_method(cKeyExpr, "hash", zrb_ke_hash, 0);
4207
+ rb_define_method(cKeyExpr, "declared?", zrb_ke_declared_p, 0);
4208
+ rb_define_method(cKeyExpr, "undeclare", zrb_ke_undeclare_m, 0);
4209
+
4210
+ cTimestamp = rb_define_class_under(mZenoh, "Timestamp", rb_cObject);
4211
+ zrb_no_new(cTimestamp);
4212
+ rb_include_module(cTimestamp, rb_mComparable);
4213
+ rb_define_method(cTimestamp, "ntp64", zrb_ts_ntp64, 0);
4214
+ rb_define_method(cTimestamp, "id", zrb_ts_id, 0);
4215
+ rb_define_method(cTimestamp, "to_time", zrb_ts_to_time, 0);
4216
+ rb_define_method(cTimestamp, "<=>", zrb_ts_cmp, 1);
4217
+ rb_define_method(cTimestamp, "==", zrb_ts_eql, 1);
4218
+ rb_define_method(cTimestamp, "eql?", zrb_ts_eql, 1);
4219
+ rb_define_method(cTimestamp, "hash", zrb_ts_hash, 0);
4220
+ rb_define_method(cTimestamp, "to_s", zrb_ts_to_s, 0);
4221
+ rb_define_method(cTimestamp, "inspect", zrb_ts_inspect, 0);
4222
+
4223
+ rb_define_module_function(mZenoh, "_scout", zrb_s_scout, 3);
4224
+ rb_define_module_function(mZenoh, "init_log", zrb_s_init_log, -1);
1530
4225
 
1531
4226
  cQueryable = rb_define_class_under(mZenoh, "Queryable", rb_cObject);
1532
4227
  zrb_no_new(cQueryable);
@@ -1544,12 +4239,16 @@ void Init_asterism_zenoh(void) {
1544
4239
  rb_define_method(cQuery, "payload", zrb_query_payload, 0);
1545
4240
  rb_define_method(cQuery, "attachment", zrb_query_attachment, 0);
1546
4241
  rb_define_method(cQuery, "reply", zrb_query_reply, -1);
4242
+ rb_define_method(cQuery, "reply_err", zrb_query_reply_err, -1);
4243
+ rb_define_method(cQuery, "reply_del", zrb_query_reply_del, -1);
4244
+ rb_define_method(cQuery, "encoding", zrb_query_encoding, 0);
1547
4245
  rb_define_method(cQuery, "finish", zrb_query_finish_m, 0);
1548
4246
  rb_define_method(cQuery, "finished?", zrb_query_finished_p, 0);
1549
4247
 
1550
4248
  cGet = rb_define_class_under(mZenoh, "Get", rb_cObject);
1551
4249
  zrb_no_new(cGet);
1552
4250
  rb_define_method(cGet, "each_reply", zrb_get_each_reply, 0);
4251
+ rb_define_method(cGet, "each_result", zrb_get_each_result, 0);
1553
4252
  rb_define_method(cGet, "done?", zrb_get_done_p, 0);
1554
4253
  rb_define_method(cGet, "pending", zrb_get_pending, 0);
1555
4254
  rb_define_method(cGet, "received", zrb_get_received, 0);