asterism-zenoh 0.1.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
@@ -18,7 +25,10 @@
18
25
  * thread. Session#poll only checks the connection: receiving needs no poll.
19
26
  *
20
27
  * The GVL is released while zenoh-c may wait: opening a session (connecting
21
- * to the router), put, get, liveliness_get and close.
28
+ * to the router), put, get, liveliness_get and close. A session may be used
29
+ * from several Ruby threads: the calls that hold the GVL are serialized by
30
+ * it, the ones without it by the session's op_lock, and closing marks the
31
+ * session closed for Ruby (with the GVL held) before zenoh-c drops it.
22
32
  *
23
33
  * Losing the connection (same rules as the mruby gem): a client session is
24
34
  * closed when it has no router left, a peer session that only connects when
@@ -56,9 +66,12 @@
56
66
 
57
67
  static VALUE mAsterism, mZenoh, eZenohError;
58
68
  static VALUE cSession, cSubscriber, cWatch, cQueryable, cQuery, cGet, cToken;
69
+ static VALUE cAdvSubscriber, cPublisher, cAdvPublisher, cQuerier, cKeyExpr, cTimestamp;
70
+ static VALUE cMatchingListener, cEventListener;
59
71
  static ID id_attachment, id_target, id_consolidation, id_complete, id_mode, id_listen;
60
- static ID id_iv_session, id_iv_key;
61
- 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;
62
75
  static ID id_none, id_latest, id_monotonic, id_auto;
63
76
 
64
77
  /* ------------------------------------------------------------- channels */
@@ -199,17 +212,16 @@ static void zch_on_sample(z_loaned_sample_t *sample, void *ctx) {
199
212
  pthread_mutex_unlock(&c->lock);
200
213
  }
201
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. */
202
217
  static void zch_on_reply(z_loaned_reply_t *reply, void *ctx) {
203
218
  zch *c = (zch *)ctx;
204
- if (!z_reply_is_ok(reply)) {
205
- atomic_fetch_add(&c->errors, 1);
206
- return;
207
- }
219
+ bool ok = z_reply_is_ok(reply);
208
220
  pthread_mutex_lock(&c->lock);
209
221
  zch_make_room(c);
210
222
  z_closure_reply_call(z_loan(c->tx.reply), reply);
211
223
  atomic_fetch_add(&c->queued, 1);
212
- atomic_fetch_add(&c->received, 1);
224
+ atomic_fetch_add(ok ? &c->received : &c->errors, 1);
213
225
  pthread_mutex_unlock(&c->lock);
214
226
  }
215
227
 
@@ -284,6 +296,18 @@ static VALUE zrb_str_from_view(const z_loaned_string_t *s) {
284
296
  return rb_utf8_str_new(z_string_data(s), (long)z_string_len(s));
285
297
  }
286
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
+
287
311
  static VALUE zrb_key_str(const z_loaned_keyexpr_t *ke) {
288
312
  z_view_string_t ks;
289
313
  z_keyexpr_as_view_string(ke, &ks);
@@ -389,22 +413,46 @@ typedef struct zrb_session zrb_session;
389
413
  typedef struct zrb_sub zrb_sub;
390
414
  typedef struct zrb_qable zrb_qable;
391
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
+ };
392
432
 
393
433
  struct zrb_session {
394
434
  z_owned_session_t session;
395
435
  pthread_mutex_t op_lock; /* calls made without the GVL, and close */
396
- bool open;
436
+ bool open; /* Ruby's view; changed only with the GVL held */
437
+ bool live; /* the zenoh-c session exists; changed under op_lock */
397
438
  bool peer; /* peer mode (otherwise client) */
398
439
  bool listening; /* peer mode with a listener: stays open without peers */
399
440
  zrb_sub *subs; /* live subscribers and liveliness watches */
400
441
  zrb_qable *qables;
401
442
  zrb_token *tokens;
443
+ zrb_ent *ents; /* the rest (0.3.0) */
402
444
  };
403
445
 
446
+ typedef enum { ZSUB_PLAIN, ZSUB_LIVELINESS, ZSUB_ADVANCED } zsub_type;
447
+
404
448
  struct zrb_sub {
405
- 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;
406
453
  bool declared;
407
454
  bool liveliness;
455
+ zsub_type type;
408
456
  zrb_session *owner; /* NULL once detached */
409
457
  zrb_sub *next;
410
458
  zch *ch;
@@ -434,1027 +482,3579 @@ typedef struct {
434
482
  bool live;
435
483
  } zrb_query;
436
484
 
437
- /* ----------------------------------------------------------- subscriber */
485
+ /* ----------------------------------------------- entities (0.3.0 list) */
438
486
 
439
- static void zrb_sub_detach(zrb_sub *s) {
440
- if (s->declared) {
441
- z_drop(z_move(s->sub));
442
- 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
+ }
443
513
  }
444
- if (s->owner != NULL) {
445
- zrb_sub **pp = &s->owner->subs;
514
+ if (e->owner != NULL) {
515
+ zrb_ent **pp = &e->owner->ents;
446
516
  while (*pp != NULL) {
447
- if (*pp == s) {
448
- *pp = s->next;
517
+ if (*pp == e) {
518
+ *pp = e->next;
449
519
  break;
450
520
  }
451
521
  pp = &(*pp)->next;
452
522
  }
453
- s->owner = NULL;
454
- s->next = NULL;
523
+ e->owner = NULL;
524
+ e->next = NULL;
455
525
  }
456
526
  }
457
527
 
458
- static void zrb_sub_free(void *p) {
459
- zrb_sub *s = (zrb_sub *)p;
460
- zrb_sub_detach(s);
461
- zch_unref(s->ch);
462
- xfree(s);
463
- }
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;
464
549
 
465
- 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;
466
561
 
467
- static const rb_data_type_t zrb_sub_type = {
468
- "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
+ }
469
576
 
470
- static zrb_sub *zrb_sub_get(VALUE self) {
471
- zrb_sub *s;
472
- TypedData_Get_Struct(self, zrb_sub, &zrb_sub_type, s);
473
- 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;
474
591
  }
475
592
 
476
- /* Take out what is pending now, oldest first. Values that arrive while the
477
- * block runs are left for the next call. */
478
- static VALUE zrb_sub_each_pending(VALUE self) {
479
- zrb_sub *s = zrb_sub_get(self);
480
- bool collect = !rb_block_given_p();
481
- VALUE out = collect ? rb_ary_new() : Qnil;
482
- long taken = 0;
483
- unsigned todo = atomic_load(&s->ch->queued);
484
- while (todo > 0) {
485
- todo--;
486
- z_owned_sample_t sm;
487
- if (zch_take_sample(s->ch, &sm) != Z_OK) {
488
- break;
489
- }
490
- const z_loaned_sample_t *l = z_loan(sm);
491
- VALUE vals[3];
492
- int n;
493
- vals[0] = zrb_key_str(z_sample_keyexpr(l));
494
- if (s->liveliness) {
495
- /* A token appearing is a PUT, one going away a DELETE. */
496
- vals[1] = (z_sample_kind(l) == Z_SAMPLE_KIND_PUT) ? Qtrue : Qfalse;
497
- n = 2;
498
- } else {
499
- vals[1] = zrb_str_from_bytes(z_sample_payload(l));
500
- vals[2] = zrb_attachment_value(z_sample_attachment(l));
501
- n = 3;
502
- }
503
- z_drop(z_move(sm));
504
- taken++;
505
- if (collect) {
506
- rb_ary_push(out, rb_ary_new_from_values(n, vals));
507
- } else {
508
- rb_yield_values2(n, vals);
509
- }
593
+ static void zevq_unref(zevq *q) {
594
+ if (q == NULL || atomic_fetch_sub(&q->refs, 1) != 1) {
595
+ return;
510
596
  }
511
- 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);
512
605
  }
513
606
 
514
- static VALUE zrb_sub_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->queued)); }
515
- static VALUE zrb_sub_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_sub_get(self)->ch->received)); }
516
- 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
+ }
517
612
 
518
- static VALUE zrb_sub_close(VALUE self) {
519
- zrb_sub_detach(zrb_sub_get(self));
520
- 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);
521
617
  }
522
618
 
523
- 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
+ }
524
646
 
525
- /* ------------------------------------------------------------ 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
+ }
526
660
 
527
- static void zrb_qable_detach(zrb_qable *q) {
528
- /* Unanswered queries first: their final replies go out while the
529
- * session can still carry them. */
530
- zch_finish_queries(q->ch);
531
- if (q->declared) {
532
- z_drop(z_move(q->qable));
533
- 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';
534
666
  }
535
- if (q->owner != NULL) {
536
- zrb_qable **pp = &q->owner->qables;
537
- while (*pp != NULL) {
538
- if (*pp == q) {
539
- *pp = q->next;
540
- break;
541
- }
542
- 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));
543
684
  }
544
- q->owner = NULL;
545
- q->next = NULL;
685
+ e->nstrs = n;
546
686
  }
687
+ z_drop(z_move(*arr));
547
688
  }
548
689
 
549
- static void zrb_qable_free(void *p) {
550
- zrb_qable *q = (zrb_qable *)p;
551
- zrb_qable_detach(q);
552
- zch_unref(q->ch);
553
- 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);
554
697
  }
555
698
 
556
- 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
+ }
557
719
 
558
- static const rb_data_type_t zrb_qable_type = {
559
- "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
+ }
560
728
 
561
- static zrb_qable *zrb_qable_get(VALUE self) {
562
- zrb_qable *q;
563
- TypedData_Get_Struct(self, zrb_qable, &zrb_qable_type, q);
564
- 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);
565
736
  }
566
737
 
567
- /* ---------------------------------------------------------------- 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
+ }
568
746
 
569
- static void zrb_query_finish(zrb_query *zq) {
570
- if (zq->live) {
571
- z_drop(z_move(zq->query));
572
- 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));
573
752
  }
753
+ zevq_push((zevq *)ctx, e);
574
754
  }
575
755
 
576
- static void zrb_query_free(void *p) {
577
- zrb_query *zq = (zrb_query *)p;
578
- zrb_query_finish(zq);
579
- 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);
580
763
  }
581
764
 
582
- 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
+ }
583
774
 
584
- static const rb_data_type_t zrb_query_type = {
585
- "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
+ }
586
786
 
587
- static zrb_query *zrb_query_get(VALUE self) {
588
- zrb_query *zq;
589
- TypedData_Get_Struct(self, zrb_query, &zrb_query_type, zq);
590
- 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);
591
794
  }
592
795
 
593
- static zrb_query *zrb_query_get_live(VALUE self) {
594
- zrb_query *zq = zrb_query_get(self);
595
- if (!zq->live) {
596
- 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"));
597
816
  }
598
- return zq;
817
+ return Qnil;
599
818
  }
600
819
 
601
- /* Wraps the query (moved in) in a Query object. */
602
- static VALUE zrb_query_wrap(z_owned_query_t *q) {
603
- zrb_query *zq;
604
- VALUE obj = TypedData_Make_Struct(cQuery, zrb_query, &zrb_query_type, zq);
605
- zq->query = *q;
606
- zq->live = true;
607
- z_internal_query_null(q);
608
- return obj;
820
+ static VALUE zrb_reliability_sym(int r) {
821
+ return ID2SYM(rb_intern(r == Z_RELIABILITY_BEST_EFFORT ? "best_effort" : "reliable"));
609
822
  }
610
823
 
611
- 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
+ }
612
831
 
613
- static VALUE zrb_query_yield_ensure(VALUE obj) {
614
- 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
+ }
615
872
  return Qnil;
616
873
  }
617
874
 
618
- /* qa.each_pending { |q| ... } -> Integer (queries taken). Each query is
619
- * finished when the block returns (also when it raises).
620
- * qa.each_pending -> Array of Query; each stays open until Query#finish or
621
- * garbage collection. */
622
- static VALUE zrb_qable_each_pending(VALUE self) {
623
- 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) {
624
877
  bool collect = !rb_block_given_p();
625
878
  VALUE out = collect ? rb_ary_new() : Qnil;
626
879
  long taken = 0;
627
- unsigned todo = atomic_load(&q->ch->queued);
880
+ unsigned todo = atomic_load(&q->queued);
628
881
  while (todo > 0) {
629
882
  todo--;
630
- z_owned_query_t oq;
631
- if (zch_take_query(q->ch, &oq) != Z_OK) {
883
+ zev *e = zevq_take(q);
884
+ if (e == NULL) {
632
885
  break;
633
886
  }
634
- VALUE obj = zrb_query_wrap(&oq);
887
+ VALUE v = zev_to_ruby(q->kind, e, event);
888
+ zev_free(e);
635
889
  taken++;
636
890
  if (collect) {
637
- rb_ary_push(out, obj);
891
+ rb_ary_push(out, v);
638
892
  } else {
639
- rb_ensure(zrb_query_yield_body, obj, zrb_query_yield_ensure, obj);
893
+ rb_yield(v);
640
894
  }
641
895
  }
642
896
  return collect ? out : LONG2NUM(taken);
643
897
  }
644
898
 
645
- static VALUE zrb_qable_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->queued)); }
646
- static VALUE zrb_qable_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->received)); }
647
- static VALUE zrb_qable_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_qable_get(self)->ch->dropped)); }
899
+ /* ------------------------------------------------------------ options */
648
900
 
649
- static VALUE zrb_qable_close(VALUE self) {
650
- zrb_qable_detach(zrb_qable_get(self));
651
- 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;
652
938
  }
653
939
 
654
- 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
+ }
655
948
 
656
- static VALUE zrb_query_key(VALUE self) {
657
- zrb_query *zq = zrb_query_get_live(self);
658
- 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;
659
962
  }
660
963
 
661
- static VALUE zrb_query_params(VALUE self) {
662
- zrb_query *zq = zrb_query_get_live(self);
663
- z_view_string_t ps;
664
- z_query_parameters(z_loan(zq->query), &ps);
665
- 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;
666
974
  }
667
975
 
668
- static VALUE zrb_query_payload(VALUE self) {
669
- zrb_query *zq = zrb_query_get_live(self);
670
- const z_loaned_bytes_t *b = z_query_payload(z_loan(zq->query));
671
- if (b == NULL) {
672
- 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;
673
980
  }
674
- 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;
675
986
  }
676
987
 
677
- static VALUE zrb_query_attachment(VALUE self) {
678
- zrb_query *zq = zrb_query_get_live(self);
679
- 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;
680
1001
  }
681
1002
 
682
- /* q.reply(payload, attachment: nil) / q.reply(key, payload, attachment: nil)
683
- * -> nil. The key defaults to the query's key; it must match the query's key
684
- * expression. May be called more than once before the query is finished. */
685
- static VALUE zrb_query_reply(int argc, VALUE *argv, VALUE self) {
686
- VALUE a1, a2 = Qnil, opts = Qnil;
687
- int n = rb_scan_args(argc, argv, "11:", &a1, &a2, &opts);
688
- VALUE kw[1] = {Qundef};
689
- if (!NIL_P(opts)) {
690
- 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;
691
1006
  }
692
- VALUE att = zrb_kw_attachment(kw[0]);
693
- zrb_query *zq = zrb_query_get_live(self);
694
- VALUE key_v = (n == 1) ? Qnil : a1;
695
- VALUE payload = (n == 1) ? a1 : a2;
696
- if (!RB_TYPE_P(payload, T_STRING)) {
697
- 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);
698
1009
  }
699
- z_view_keyexpr_t ke;
700
- const z_loaned_keyexpr_t *kp;
701
- if (NIL_P(key_v)) {
702
- kp = z_query_keyexpr(z_loan(zq->query));
703
- } else {
704
- zrb_view_key(&ke, StringValueCStr(key_v));
705
- 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;
706
1023
  }
707
- z_query_reply_options_t ro;
708
- z_query_reply_options_default(&ro);
709
- z_owned_bytes_t att_bytes;
710
- if (!NIL_P(att)) {
711
- zrb_bytes_from_str(&att_bytes, att, "attachment");
712
- 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]);
713
1028
  }
714
- z_owned_bytes_t bytes;
715
- if (z_bytes_copy_from_buf(&bytes, (const uint8_t *)RSTRING_PTR(payload), (size_t)RSTRING_LEN(payload)) != Z_OK) {
716
- if (!NIL_P(att)) {
717
- 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;
718
1082
  }
719
- rb_raise(eZenohError, "cannot allocate the payload");
720
1083
  }
721
- z_result_t ret = z_query_reply(z_loan(zq->query), kp, z_move(bytes), &ro);
722
- if (ret != Z_OK) {
723
- 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;
724
1091
  }
725
- 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;
726
1097
  }
727
1098
 
728
- static VALUE zrb_query_finish_m(VALUE self) {
729
- zrb_query_finish(zrb_query_get(self));
730
- 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;
731
1109
  }
732
1110
 
733
- static VALUE zrb_query_finished_p(VALUE self) { return zrb_query_get(self)->live ? Qfalse : Qtrue; }
1111
+ /* ---------------------------------------------------------- timestamps */
734
1112
 
735
- /* ------------------------------------------------------------------ get */
1113
+ typedef struct {
1114
+ z_timestamp_t ts;
1115
+ } zrb_ts;
736
1116
 
737
- static void zrb_get_free(void *p) {
738
- zrb_get *g = (zrb_get *)p;
739
- zch_unref(g->ch); /* zenoh-c may still hold it until the get finishes */
740
- 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;
741
1129
  }
742
1130
 
743
- 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
+ }
744
1136
 
745
- 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)); }
746
1140
 
747
- static zrb_get *zrb_get_get(VALUE self) {
748
- zrb_get *g;
749
- TypedData_Get_Struct(self, zrb_get, &zrb_get_type, g);
750
- 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);
751
1144
  }
752
1145
 
753
- static VALUE zrb_get_new(zrb_get **out) {
754
- zrb_get *g;
755
- VALUE obj = TypedData_Make_Struct(cGet, zrb_get, &zrb_get_type, g);
756
- g->ch = zch_new(ZCH_REPLY, ZRB_DEFAULT_DEPTH);
757
- *out = g;
758
- 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);
759
1151
  }
760
1152
 
761
- /* g.each_reply { |key, payload, attachment| ... } -> Integer; without a
762
- * block, Array of [key, payload, attachment]. Error replies are counted
763
- * (errors), not yielded. */
764
- static VALUE zrb_get_each_reply(VALUE self) {
765
- zrb_get *g = zrb_get_get(self);
766
- bool collect = !rb_block_given_p();
767
- VALUE out = collect ? rb_ary_new() : Qnil;
768
- long taken = 0;
769
- unsigned todo = atomic_load(&g->ch->queued);
770
- while (todo > 0) {
771
- todo--;
772
- z_owned_reply_t r;
773
- if (zch_take_reply(g->ch, &r) != Z_OK) {
774
- break;
775
- }
776
- VALUE vals[3];
777
- const z_loaned_sample_t *sm = z_reply_ok(z_loan(r));
778
- vals[0] = zrb_key_str(z_sample_keyexpr(sm));
779
- vals[1] = zrb_str_from_bytes(z_sample_payload(sm));
780
- vals[2] = zrb_attachment_value(z_sample_attachment(sm));
781
- z_drop(z_move(r));
782
- taken++;
783
- if (collect) {
784
- rb_ary_push(out, rb_ary_new_from_values(3, vals));
785
- } else {
786
- 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);
787
1167
  }
788
1168
  }
789
- return collect ? out : LONG2NUM(taken);
1169
+ return INT2FIX(0);
790
1170
  }
791
1171
 
792
- static VALUE zrb_get_done_p(VALUE self) { return atomic_load(&zrb_get_get(self)->ch->done) ? Qtrue : Qfalse; }
793
- static VALUE zrb_get_pending(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->queued)); }
794
- static VALUE zrb_get_received(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->received)); }
795
- static VALUE zrb_get_dropped(VALUE self) { return UINT2NUM(atomic_load(&zrb_get_get(self)->ch->dropped)); }
796
- 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
+ }
797
1176
 
798
- /* ---------------------------------------------------------------- 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
+ }
799
1180
 
800
- static void zrb_token_detach(zrb_token *t) {
801
- if (t->declared) {
802
- z_drop(z_move(t->token));
803
- t->declared = false;
804
- }
805
- if (t->owner != NULL) {
806
- zrb_token **pp = &t->owner->tokens;
807
- while (*pp != NULL) {
808
- if (*pp == t) {
809
- *pp = t->next;
810
- break;
811
- }
812
- pp = &(*pp)->next;
813
- }
814
- t->owner = NULL;
815
- t->next = NULL;
816
- }
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));
817
1187
  }
818
1188
 
819
- static void zrb_token_free(void *p) {
820
- zrb_token *t = (zrb_token *)p;
821
- zrb_token_detach(t);
822
- 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);
823
1216
  }
824
1217
 
825
- 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
+ }
826
1246
 
827
- static const rb_data_type_t zrb_token_type = {
828
- "Asterism::Zenoh::LivelinessToken", {NULL, zrb_token_free, zrb_token_size}, NULL, NULL, 0};
1247
+ /* -------------------------------------------------------- key expressions */
829
1248
 
830
- static zrb_token *zrb_token_get(VALUE self) {
831
- zrb_token *t;
832
- TypedData_Get_Struct(self, zrb_token, &zrb_token_type, t);
833
- 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
+ }
834
1262
  }
835
1263
 
836
- static VALUE zrb_token_close(VALUE self) {
837
- zrb_token_detach(zrb_token_get(self));
838
- 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);
839
1269
  }
840
1270
 
841
- 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); }
842
1272
 
843
- /* -------------------------------------------------------------- session */
1273
+ static const rb_data_type_t zrb_ke_type = {"Asterism::Zenoh::KeyExpr", {NULL, zrb_ke_free, zrb_ke_size}, NULL, NULL, 0};
844
1274
 
845
- /* Undeclares everything the session still has. Holds the GVL (the lists
846
- * are only touched with it). */
847
- static void zrb_session_detach_all(zrb_session *z) {
848
- while (z->qables != NULL) {
849
- 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;
850
1278
  }
851
- while (z->tokens != NULL) {
852
- 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);
853
1290
  }
854
- while (z->subs != NULL) {
855
- 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;
856
1302
  }
1303
+ zrb_owned_key(out, StringValueCStr(v));
857
1304
  }
858
1305
 
859
- /* Closes the zenoh-c session. Without the GVL when called from Ruby
860
- * methods (it waits for zenoh's tasks), with it from the GC. */
861
- static void *zrb_session_close_nogvl(void *p) {
862
- zrb_session *z = (zrb_session *)p;
863
- pthread_mutex_lock(&z->op_lock);
864
- if (z->open) {
865
- z->open = false;
866
- z_close(z_loan_mut(z->session), NULL);
867
- 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));
868
1311
  }
869
- pthread_mutex_unlock(&z->op_lock);
870
- return NULL;
1312
+ StringValueCStr(v);
1313
+ return v;
871
1314
  }
872
1315
 
873
- static void zrb_session_shutdown(zrb_session *z, bool with_gvl_release) {
874
- zrb_session_detach_all(z);
875
- if (!z->open) {
876
- 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);
877
1334
  }
878
- if (with_gvl_release) {
879
- 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));
880
1339
  } else {
881
- 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
+ }
882
1346
  }
1347
+ return zrb_ke_wrap_owned(&ke);
883
1348
  }
884
1349
 
885
- static void zrb_session_free(void *p) {
886
- zrb_session *z = (zrb_session *)p;
887
- zrb_session_shutdown(z, false);
888
- pthread_mutex_destroy(&z->op_lock);
889
- 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;
890
1354
  }
891
1355
 
892
- 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)); }
893
1357
 
894
- static const rb_data_type_t zrb_session_type = {
895
- "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
+ }
896
1363
 
897
- static zrb_session *zrb_session_get(VALUE self) {
898
- zrb_session *z;
899
- TypedData_Get_Struct(self, zrb_session, &zrb_session_type, z);
900
- 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;
901
1367
  }
902
1368
 
903
- static void zrb_count_zid(const z_id_t *id, void *ctx) {
904
- (void)id;
905
- (*(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;
906
1372
  }
907
1373
 
908
- /* Routers (client) or peers (peer mode) connected now. */
909
- static int zrb_session_links(zrb_session *z) {
910
- int n = 0;
911
- z_owned_closure_zid_t cb;
912
- z_closure(&cb, zrb_count_zid, NULL, &n);
913
- if (z->peer) {
914
- z_info_peers_zid(z_loan(z->session), z_move(cb));
915
- } else {
916
- 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"));
917
1385
  }
918
- return n;
1386
+ return Qnil;
919
1387
  }
920
1388
 
921
- /* Close the session when its connection can no longer carry it (see the
922
- * comment at the top). Returns true when the session is (now) closed. */
923
- static bool zrb_session_check_link(zrb_session *z) {
924
- if (!z->open) {
925
- return true;
926
- }
927
- if (z_session_is_closed(z_loan(z->session))) {
928
- zrb_session_shutdown(z, true);
929
- return true;
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;
930
1392
  }
931
- if (z->peer && z->listening) {
932
- return false;
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;
933
1396
  }
934
- if (zrb_session_links(z) == 0) {
935
- zrb_session_shutdown(z, true);
936
- return true;
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;
1399
+ }
1400
+
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");
937
1410
  }
938
- return false;
1411
+ return zrb_ke_wrap_owned(&out);
939
1412
  }
940
1413
 
941
- static zrb_session *zrb_session_get_open(VALUE self) {
942
- zrb_session *z = zrb_session_get(self);
943
- if (zrb_session_check_link(z)) {
944
- rb_raise(eZenohError, "session is closed");
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);
945
1421
  }
946
- return z;
1422
+ return zrb_ke_wrap_owned(&out);
947
1423
  }
948
1424
 
949
- /* A JSON5 string literal of s (for the configuration). */
950
- static VALUE zrb_json_str(const char *s) {
951
- VALUE out = rb_str_new_cstr("\"");
952
- for (const char *p = s; *p; p++) {
953
- if (*p == '"' || *p == '\\') {
954
- rb_str_cat(out, "\\", 1);
955
- }
956
- rb_str_cat(out, p, 1);
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;
1431
+ }
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);
957
1442
  }
958
- rb_str_cat(out, "\"", 1);
1443
+ rb_str_set_len(out, (long)len);
959
1444
  return out;
960
1445
  }
961
1446
 
962
- static bool zrb_config_set(z_owned_config_t *config, const char *key, const char *json5) {
963
- return zc_config_insert_json5(z_loan_mut(*config), key, json5) == Z_OK;
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;
964
1451
  }
965
1452
 
966
- typedef struct {
967
- zrb_session *z;
968
- z_owned_config_t config;
969
- z_result_t ret;
970
- } zrb_open_args;
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);
971
2661
 
972
- static void *zrb_open_nogvl(void *p) {
973
- zrb_open_args *a = (zrb_open_args *)p;
974
- a->ret = z_open(&a->z->session, z_move(a->config), NULL);
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). */
2831
+ typedef struct {
2832
+ zrb_session *z;
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 */
2849
+ z_result_t ret;
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);
975
2894
  return NULL;
976
2895
  }
977
2896
 
978
- /* Asterism::Zenoh::Session.open(locator = nil, mode: :client, listen: nil) -> Session
979
- * - client: connects to the router at locator.
980
- * - peer: connects to the peer at locator (if given) and/or listens on
981
- * listen (e.g. "tcp/0.0.0.0:7447"). At least one of them is needed.
982
- * Raises Asterism::Zenoh::Error when the session cannot be opened (no
983
- * router or peer answered within CONNECT_TIMEOUT_MS). */
984
- static VALUE zrb_session_s_open(int argc, VALUE *argv, VALUE klass) {
985
- VALUE locator_v = Qnil, opts = Qnil;
986
- rb_scan_args(argc, argv, "01:", &locator_v, &opts);
987
- VALUE kw[2] = {Qundef, Qundef};
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;
988
3183
  if (!NIL_P(opts)) {
989
- ID ids[2] = {id_mode, id_listen};
990
- rb_get_kwargs(opts, ids, 0, 2, kw);
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
+ }
991
3189
  }
992
- bool peer = false;
993
- if (kw[0] != Qundef && !NIL_P(kw[0])) {
994
- ID mode = zrb_sym_id(kw[0]);
995
- if (mode == id_peer) {
996
- peer = true;
997
- } else if (mode != id_client) {
998
- rb_raise(rb_eArgError, "mode must be :client or :peer");
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");
999
3222
  }
1000
3223
  }
1001
- const char *locator = NIL_P(locator_v) ? NULL : StringValueCStr(locator_v);
1002
- VALUE listen_v = (kw[1] == Qundef) ? Qnil : kw[1];
1003
- const char *listen = NIL_P(listen_v) ? NULL : StringValueCStr(listen_v);
1004
- if (!peer && listen != NULL) {
1005
- rb_raise(rb_eArgError, "listen needs mode: :peer");
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
+ }
1006
3246
  }
1007
- if (locator == NULL && listen == NULL) {
1008
- rb_raise(rb_eArgError, "a locator (or, for a peer, listen:) is needed");
3247
+ ao.publisher_detection = RTEST(extra[2]);
3248
+
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());
1009
3263
  }
3264
+ return zrb_pub_wrap(self, z, p, obj, key_str);
3265
+ }
1010
3266
 
1011
- zrb_session *z;
1012
- VALUE obj = TypedData_Make_Struct(klass, zrb_session, &zrb_session_type, z);
1013
- pthread_mutex_init(&z->op_lock, NULL);
3267
+ static const char *const zrb_pput_kw[] = {"attachment", "encoding", "timestamp"};
1014
3268
 
1015
- /* The configuration mirrors the mruby gem's zenoh-pico build: no
1016
- * scouting (the locator is given), a connect-only peer does not listen,
1017
- * and the session fails to open when nobody answers in time. */
1018
- zrb_open_args a;
1019
- a.z = z;
1020
- if (z_config_default(&a.config) != Z_OK) {
1021
- rb_raise(eZenohError, "cannot create the configuration");
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;
1022
3286
  }
1023
- char num[32];
1024
- snprintf(num, sizeof(num), "%d", ZRB_CONNECT_TIMEOUT_MS);
1025
- bool ok = zrb_config_set(&a.config, "mode", peer ? "\"peer\"" : "\"client\"") &&
1026
- zrb_config_set(&a.config, "scouting/multicast/enabled", "false") &&
1027
- zrb_config_set(&a.config, "scouting/gossip/enabled", "false") &&
1028
- zrb_config_set(&a.config, "connect/timeout_ms", num) &&
1029
- zrb_config_set(&a.config, "connect/exit_on_failure", "true");
1030
- if (ok) {
1031
- snprintf(num, sizeof(num), "%d", ZRB_SEND_TIMEOUT_MS * 1000);
1032
- ok = zrb_config_set(&a.config, "transport/link/tx/queue/congestion_control/block/wait_before_close", num);
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);
1033
3291
  }
1034
- if (ok && locator != NULL) {
1035
- VALUE ep = rb_str_concat(rb_str_concat(rb_str_new_cstr("["), zrb_json_str(locator)), rb_str_new_cstr("]"));
1036
- ok = zrb_config_set(&a.config, "connect/endpoints", StringValueCStr(ep));
3292
+ if (!NIL_P(o.encoding)) {
3293
+ po->encoding = z_move(s.enc);
1037
3294
  }
1038
- if (ok) {
1039
- if (listen != NULL) {
1040
- VALUE ep = rb_str_concat(rb_str_concat(rb_str_new_cstr("["), zrb_json_str(listen)), rb_str_new_cstr("]"));
1041
- ok = zrb_config_set(&a.config, "listen/endpoints", StringValueCStr(ep));
1042
- } else {
1043
- ok = zrb_config_set(&a.config, "listen/endpoints", "[]");
1044
- }
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;
1045
3316
  }
1046
- if (!ok) {
1047
- z_drop(z_move(a.config));
1048
- rb_raise(eZenohError, "invalid locator");
3317
+ po->timestamp = zrb_send_timestamp(&s, o.timestamp);
3318
+ zrb_send_run(&s, "delete");
3319
+ return Qnil;
3320
+ }
3321
+
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());
1049
3330
  }
1050
- rb_thread_call_without_gvl(zrb_open_nogvl, &a, RUBY_UBF_IO, NULL);
1051
- if (a.ret != Z_OK) {
1052
- rb_raise(eZenohError, "cannot open a session to %s (%d)", locator != NULL ? locator : listen, (int)a.ret);
3331
+ return st.matching ? Qtrue : Qfalse;
3332
+ }
3333
+
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");
1053
3371
  }
1054
- z->open = true;
1055
- z->peer = peer;
1056
- z->listening = (listen != NULL);
3372
+ if (zrb_session_check_link(q->ent.owner)) {
3373
+ rb_raise(eZenohError, "session is closed");
3374
+ }
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;
3400
+ }
3401
+ if (o.priority >= 0) {
3402
+ qo.priority = (z_priority_t)o.priority;
3403
+ }
3404
+ if (o.express >= 0) {
3405
+ qo.is_express = o.express;
3406
+ }
3407
+ if (o.accept_replies >= 0) {
3408
+ qo.accept_replies = (z_reply_keyexpr_t)o.accept_replies;
3409
+ }
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);
1057
3422
  return obj;
1058
3423
  }
1059
3424
 
1060
3425
  typedef struct {
1061
3426
  zrb_session *z;
1062
- z_owned_keyexpr_t key;
1063
- z_owned_bytes_t payload;
1064
- 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;
1065
3434
  z_result_t ret;
1066
- } zrb_put_args;
3435
+ } zrb_qget_args;
1067
3436
 
1068
- static void *zrb_put_nogvl(void *p) {
1069
- 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;
1070
3439
  pthread_mutex_lock(&a->z->op_lock);
1071
- if (a->z->open) {
1072
- a->ret = z_put(z_loan(a->z->session), z_loan(a->key), z_move(a->payload), &a->opts);
1073
- } else {
3440
+ if (!a->z->live) {
1074
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);
1075
3446
  }
1076
3447
  pthread_mutex_unlock(&a->z->op_lock);
3448
+ z_drop(z_move(a->cb));
1077
3449
  return NULL;
1078
3450
  }
1079
3451
 
1080
- /* session.put(key, payload, attachment: nil) -> nil */
1081
- static VALUE zrb_session_put(int argc, VALUE *argv, VALUE self) {
1082
- VALUE key_v, payload, opts = Qnil;
1083
- rb_scan_args(argc, argv, "2:", &key_v, &payload, &opts);
1084
- VALUE kw[1] = {Qundef};
1085
- if (!NIL_P(opts)) {
1086
- rb_get_kwargs(opts, &id_attachment, 0, 1, kw);
1087
- }
1088
- const char *key = StringValueCStr(key_v);
1089
- StringValue(payload);
1090
- VALUE att = zrb_kw_attachment(kw[0]);
1091
- zrb_session *z = zrb_session_get_open(self);
3452
+ static const char *const zrb_qget_kw[] = {"attachment", "encoding"};
1092
3453
 
1093
- zrb_put_args a;
1094
- a.z = z;
1095
- a.ret = Z_OK;
1096
- zrb_owned_key(&a.key, key);
1097
- if (z_bytes_copy_from_buf(&a.payload, (const uint8_t *)RSTRING_PTR(payload), (size_t)RSTRING_LEN(payload)) !=
1098
- Z_OK) {
1099
- z_drop(z_move(a.key));
1100
- 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");
1101
3463
  }
1102
- z_put_options_default(&a.opts);
1103
- z_owned_bytes_t att_bytes;
1104
- if (!NIL_P(att)) {
1105
- if (z_bytes_copy_from_buf(&att_bytes, (const uint8_t *)RSTRING_PTR(att), (size_t)RSTRING_LEN(att)) != Z_OK) {
1106
- z_drop(z_move(a.payload));
1107
- z_drop(z_move(a.key));
1108
- rb_raise(eZenohError, "cannot allocate the attachment");
1109
- }
1110
- 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);
1111
3478
  }
1112
- rb_thread_call_without_gvl(zrb_put_nogvl, &a, RUBY_UBF_IO, NULL);
1113
- z_drop(z_move(a.key));
1114
- if (zrb_session_check_link(z)) {
1115
- 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");
1116
3500
  }
1117
3501
  if (a.ret != Z_OK) {
1118
- rb_raise(eZenohError, "put failed (%d)", (int)a.ret);
3502
+ rb_raise(eZenohError, "get failed (%d)", (int)a.ret);
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());
1119
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);
1120
3520
  return Qnil;
1121
3521
  }
1122
3522
 
1123
- static VALUE zrb_sub_new(VALUE self, zrb_session *z, VALUE key_v, long depth, bool liveliness) {
1124
- const char *key = StringValueCStr(key_v);
1125
- z_view_keyexpr_t ke;
1126
- zrb_view_key(&ke, key);
3523
+ static VALUE zrb_querier_closed_p(VALUE self) { return zrb_querier_get(self)->ent.declared ? Qfalse : Qtrue; }
1127
3524
 
1128
- zrb_sub *s;
1129
- VALUE obj = TypedData_Make_Struct(liveliness ? cWatch : cSubscriber, zrb_sub, &zrb_sub_type, s);
1130
- s->liveliness = liveliness;
1131
- s->ch = zch_new(ZCH_SAMPLE, (uint32_t)depth);
3525
+ /* ------------------------------------------------------------ listeners */
1132
3526
 
1133
- z_owned_closure_sample_t cb;
1134
- zch_closure_sample(s->ch, &cb);
1135
- z_result_t ret;
1136
- if (liveliness) {
1137
- /* history: the tokens alive now are reported first, as appearing. */
1138
- z_liveliness_subscriber_options_t lo;
1139
- z_liveliness_subscriber_options_default(&lo);
1140
- lo.history = true;
1141
- ret = z_liveliness_declare_subscriber(z_loan(z->session), &s->sub, z_loan(ke), z_move(cb), &lo);
1142
- } else {
1143
- /* Remote samples only: zenoh-pico (the mruby gem) does not deliver a
1144
- * session's own puts to its own subscribers either. */
1145
- z_subscriber_options_t so;
1146
- z_subscriber_options_default(&so);
1147
- so.allowed_origin = Z_LOCALITY_REMOTE;
1148
- ret = z_declare_subscriber(z_loan(z->session), &s->sub, z_loan(ke), z_move(cb), &so);
1149
- }
1150
- if (ret != Z_OK) {
1151
- 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;
1152
3556
  }
1153
- s->declared = true;
1154
- s->owner = z;
1155
- s->next = z->subs;
1156
- z->subs = s;
1157
- zrb_hold_session(obj, self, key_v);
1158
- return obj;
1159
3557
  }
1160
3558
 
1161
- /* session.subscribe(key, depth = 16) -> Subscriber */
1162
- static VALUE zrb_session_subscribe(int argc, VALUE *argv, VALUE self) {
1163
- VALUE key_v, depth_v = Qnil;
1164
- rb_scan_args(argc, argv, "11", &key_v, &depth_v);
1165
- long depth = zrb_check_depth(depth_v);
1166
- StringValueCStr(key_v);
1167
- zrb_session *z = zrb_session_get_open(self);
1168
- 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);
1169
3564
  }
1170
3565
 
1171
- /* session.liveliness_watch(key, depth = 16) -> LivelinessWatch */
1172
- static VALUE zrb_session_liveliness_watch(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, 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;
1179
3574
  }
1180
3575
 
1181
- /* session.queryable(key, depth = 16, complete: false) -> Queryable */
1182
- static VALUE zrb_session_queryable(int argc, VALUE *argv, VALUE self) {
1183
- VALUE key_v, depth_v = Qnil, opts = Qnil;
1184
- rb_scan_args(argc, argv, "11:", &key_v, &depth_v, &opts);
1185
- VALUE kw[1] = {Qundef};
1186
- if (!NIL_P(opts)) {
1187
- rb_get_kwargs(opts, &id_complete, 0, 1, kw);
1188
- }
1189
- 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) {
1190
3577
  long depth = zrb_check_depth(depth_v);
1191
- const char *key = StringValueCStr(key_v);
1192
- zrb_session *z = zrb_session_get_open(self);
1193
- z_view_keyexpr_t ke;
1194
- zrb_view_key(&ke, key);
1195
-
1196
- zrb_qable *q;
1197
- VALUE obj = TypedData_Make_Struct(cQueryable, zrb_qable, &zrb_qable_type, q);
1198
- q->ch = zch_new(ZCH_QUERY, (uint32_t)depth);
1199
- z_owned_closure_query_t cb;
1200
- zch_closure_query(q->ch, &cb);
1201
- z_queryable_options_t qo;
1202
- z_queryable_options_default(&qo);
1203
- qo.complete = complete;
1204
- /* Remote queries only, as with zenoh-pico (Asterism answers calls to
1205
- * its own objects in place). */
1206
- qo.allowed_origin = Z_LOCALITY_REMOTE;
1207
- z_result_t ret = z_declare_queryable(z_loan(z->session), &q->qable, z_loan(ke), z_move(cb), &qo);
1208
- if (ret != Z_OK) {
1209
- rb_raise(eZenohError, "cannot declare a queryable on %s (%d)", key, (int)ret);
1210
- }
1211
- q->declared = true;
1212
- q->owner = z;
1213
- q->next = z->qables;
1214
- z->qables = q;
1215
- 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;
1216
3583
  return obj;
1217
3584
  }
1218
3585
 
1219
- static z_query_target_t zrb_get_target(VALUE v) {
1220
- if (v == Qundef || NIL_P(v)) {
1221
- return Z_QUERY_TARGET_ALL;
1222
- }
1223
- ID t = zrb_sym_id(v);
1224
- if (t == id_all) {
1225
- return Z_QUERY_TARGET_ALL;
1226
- }
1227
- if (t == id_all_complete) {
1228
- return Z_QUERY_TARGET_ALL_COMPLETE;
1229
- }
1230
- if (t == id_best_matching) {
1231
- return Z_QUERY_TARGET_BEST_MATCHING;
1232
- }
1233
- rb_raise(rb_eArgError, "target must be :all, :all_complete or :best_matching");
1234
- 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);
1235
3589
  }
1236
3590
 
1237
- static z_query_consolidation_t zrb_get_consolidation(VALUE v) {
1238
- if (v == Qundef || NIL_P(v)) {
1239
- return z_query_consolidation_none();
1240
- }
1241
- ID c = zrb_sym_id(v);
1242
- if (c == id_none) {
1243
- return z_query_consolidation_none();
1244
- }
1245
- if (c == id_latest) {
1246
- return z_query_consolidation_latest();
1247
- }
1248
- if (c == id_monotonic) {
1249
- return z_query_consolidation_monotonic();
1250
- }
1251
- if (c == id_auto) {
1252
- 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());
1253
3622
  }
1254
- rb_raise(rb_eArgError, "consolidation must be :none, :latest, :monotonic or :auto");
1255
- return z_query_consolidation_none(); /* not reached */
3623
+ zrb_lst_linked(obj, l, p->ent.owner, self);
3624
+ return obj;
1256
3625
  }
1257
3626
 
1258
- typedef struct {
1259
- zrb_session *z;
1260
- z_owned_keyexpr_t key;
1261
- char *params; /* malloc'd copy, or NULL */
1262
- bool liveliness;
1263
- z_owned_closure_reply_t cb;
1264
- z_get_options_t opts;
1265
- z_liveliness_get_options_t lopts;
1266
- z_result_t ret;
1267
- } 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
+ }
1268
3642
 
1269
- static void *zrb_get_nogvl(void *p) {
1270
- zrb_get_args *a = (zrb_get_args *)p;
1271
- pthread_mutex_lock(&a->z->op_lock);
1272
- if (a->z->open) {
1273
- if (a->liveliness) {
1274
- a->ret = z_liveliness_get(z_loan(a->z->session), z_loan(a->key), z_move(a->cb), &a->lopts);
1275
- } else {
1276
- a->ret = z_get(z_loan(a->z->session), z_loan(a->key), a->params != NULL ? a->params : "", z_move(a->cb),
1277
- &a->opts);
1278
- }
1279
- } else {
1280
- 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);
1281
3647
  }
1282
- pthread_mutex_unlock(&a->z->op_lock);
1283
- /* A closure that was not taken (the session was closed) is dropped
1284
- * here, which releases the channel's reference. */
1285
- z_drop(z_move(a->cb));
1286
- return NULL;
3648
+ return kw[0] != Qundef && RTEST(kw[0]);
1287
3649
  }
1288
3650
 
1289
- static VALUE zrb_run_get(VALUE self, zrb_session *z, zrb_get_args *a, VALUE obj, VALUE key_v, const char *what) {
1290
- rb_thread_call_without_gvl(zrb_get_nogvl, a, RUBY_UBF_IO, NULL);
1291
- z_drop(z_move(a->key));
1292
- free(a->params);
1293
- if (zrb_session_check_link(z)) {
1294
- 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());
1295
3670
  }
1296
- if (a->ret != Z_OK) {
1297
- 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());
1298
3693
  }
1299
- zrb_hold_session(obj, self, key_v);
3694
+ zrb_lst_linked(obj, l, z, self);
1300
3695
  return obj;
1301
3696
  }
1302
3697
 
1303
- /* session.get(key, timeout_ms = 2000, params = nil, payload = nil,
1304
- * attachment: nil, target: :all, consolidation: :none) -> Get.
1305
- * Returns at once; the replies come in on zenoh's threads. */
1306
- static VALUE zrb_session_get_m(int argc, VALUE *argv, VALUE self) {
1307
- VALUE key_v, timeout_v = Qnil, params_v = Qnil, payload = Qnil, opts = Qnil;
1308
- rb_scan_args(argc, argv, "13:", &key_v, &timeout_v, &params_v, &payload, &opts);
1309
- 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};
1310
3714
  if (!NIL_P(opts)) {
1311
- ID ids[3] = {id_attachment, id_target, id_consolidation};
1312
- 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);
1313
3718
  }
1314
- const char *key = StringValueCStr(key_v);
1315
- long timeout_ms = zrb_check_timeout(timeout_v);
1316
- const char *params = NIL_P(params_v) ? NULL : StringValueCStr(params_v);
1317
- if (!NIL_P(payload) && !RB_TYPE_P(payload, T_STRING)) {
1318
- 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]);
1319
3763
  }
1320
- VALUE att = zrb_kw_attachment(kw[0]);
1321
- z_query_target_t target = zrb_get_target(kw[1]);
1322
- 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);
1323
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);
1324
3771
 
1325
- zrb_get_args a;
1326
- memset(&a, 0, sizeof(a));
1327
- a.z = z;
1328
- zrb_owned_key(&a.key, key);
1329
- zrb_get *g;
1330
- VALUE obj = zrb_get_new(&g);
1331
- z_get_options_default(&a.opts);
1332
- a.opts.timeout_ms = (uint64_t)timeout_ms;
1333
- a.opts.target = target;
1334
- a.opts.consolidation = consolidation;
1335
- /* Remote queryables only, as with zenoh-pico. */
1336
- a.opts.allowed_destination = Z_LOCALITY_REMOTE;
1337
- z_owned_bytes_t bytes;
1338
- z_owned_bytes_t att_bytes;
1339
- if (!NIL_P(payload)) {
1340
- zrb_bytes_from_str(&bytes, payload, "payload");
1341
- 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());
1342
3781
  }
1343
- if (!NIL_P(att)) {
1344
- zrb_bytes_from_str(&att_bytes, att, "attachment");
1345
- 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");
1346
3794
  }
1347
- if (params != NULL) {
1348
- a.params = strdup(params);
3795
+ if (zrb_session_check_link(s->owner)) {
3796
+ rb_raise(eZenohError, "session is closed");
1349
3797
  }
1350
- zch_closure_reply(g->ch, &a.cb);
1351
- return zrb_run_get(self, z, &a, obj, key_v, "get");
3798
+ return s;
1352
3799
  }
1353
3800
 
1354
- /* session.liveliness(key) -> LivelinessToken */
1355
- static VALUE zrb_session_liveliness(VALUE self, VALUE key_v) {
1356
- const char *key = StringValueCStr(key_v);
1357
- zrb_session *z = zrb_session_get_open(self);
1358
- z_view_keyexpr_t ke;
1359
- zrb_view_key(&ke, key);
1360
- zrb_token *t;
1361
- VALUE obj = TypedData_Make_Struct(cToken, zrb_token, &zrb_token_type, t);
1362
- 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);
1363
3844
  if (ret != Z_OK) {
1364
- 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());
1365
3846
  }
1366
- t->declared = true;
1367
- t->owner = z;
1368
- t->next = z->tokens;
1369
- z->tokens = t;
1370
- 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);
1371
3853
  return obj;
1372
3854
  }
1373
3855
 
1374
- /* session.liveliness_get(key, timeout_ms = 2000) -> Get */
1375
- static VALUE zrb_session_liveliness_get(int argc, VALUE *argv, VALUE self) {
1376
- VALUE key_v, timeout_v = Qnil;
1377
- rb_scan_args(argc, argv, "11", &key_v, &timeout_v);
1378
- const char *key = StringValueCStr(key_v);
1379
- long timeout_ms = zrb_check_timeout(timeout_v);
1380
- zrb_session *z = zrb_session_get_open(self);
3856
+ /* ------------------------------------------------- session information */
1381
3857
 
1382
- zrb_get_args a;
1383
- memset(&a, 0, sizeof(a));
1384
- a.z = z;
1385
- a.liveliness = true;
1386
- zrb_owned_key(&a.key, key);
1387
- zrb_get *g;
1388
- VALUE obj = zrb_get_new(&g);
1389
- z_liveliness_get_options_default(&a.lopts);
1390
- a.lopts.timeout_ms = (uint64_t)timeout_ms;
1391
- zch_closure_reply(g->ch, &a.cb);
1392
- 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;
1393
3868
  }
1394
3869
 
1395
- /* session.poll(steps = 8) -> true while the session is open, false once
1396
- * closed (by close, or because the connection was lost). zenoh-c receives
1397
- * on its own threads, so this only checks the connection; steps is
1398
- * accepted for the mruby gem's signature. Never waits. */
1399
- static VALUE zrb_session_poll(int argc, VALUE *argv, VALUE self) {
1400
- VALUE steps_v = Qnil;
1401
- rb_scan_args(argc, argv, "01", &steps_v);
1402
- if (!NIL_P(steps_v)) {
1403
- 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;
1404
3888
  }
1405
- return zrb_session_check_link(zrb_session_get(self)) ? Qfalse : Qtrue;
3889
+ c->ids[c->n++] = *id;
3890
+ pthread_mutex_unlock(&c->lock);
1406
3891
  }
1407
3892
 
1408
- static VALUE zrb_session_closed_p(VALUE self) {
1409
- 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;
1410
3915
  }
1411
3916
 
1412
- static VALUE zrb_session_close(VALUE self) {
1413
- zrb_session_shutdown(zrb_session_get(self), true);
1414
- 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;
1415
3932
  }
1416
3933
 
1417
- /* session.zid -> String: this session's Zenoh ID in hex. */
1418
- 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) {
1419
3936
  zrb_session *z = zrb_session_get_open(self);
1420
- z_id_t id = z_info_zid(z_loan(z->session));
1421
- z_owned_string_t str;
1422
- z_id_to_string(&id, &str);
1423
- VALUE out = zrb_str_from_view(z_loan(str));
1424
- 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);
1425
3945
  return out;
1426
3946
  }
1427
3947
 
1428
- /* session.peers -> Integer: connected peers (peer mode), or routers (1
1429
- * normally) for a client session; 0 once closed. */
1430
- static VALUE zrb_session_peers(VALUE self) {
1431
- zrb_session *z = zrb_session_get(self);
1432
- if (zrb_session_check_link(z)) {
1433
- 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");
1434
3954
  }
1435
- return INT2FIX(zrb_session_links(z));
3955
+ return zrb_ts_wrap(&ts);
1436
3956
  }
1437
3957
 
1438
- /* The default of zenoh-c's transport/unicast/max_sessions (MAX_PEERS). */
1439
- static long zrb_default_max_sessions(void) {
1440
- long n = -1;
1441
- z_owned_config_t c;
1442
- if (z_config_default(&c) != Z_OK) {
1443
- 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());
1444
3974
  }
1445
- z_owned_string_t s;
1446
- if (zc_config_get_from_str(z_loan(c), "transport/unicast/max_sessions", &s) == Z_OK) {
1447
- char buf[32];
1448
- size_t len = z_string_len(z_loan(s));
1449
- if (len < sizeof(buf)) {
1450
- memcpy(buf, z_string_data(z_loan(s)), len);
1451
- buf[len] = '\0';
1452
- 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);
1453
4024
  }
1454
- z_drop(z_move(s));
1455
4025
  }
1456
- z_drop(z_move(c));
1457
- 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;
1458
4058
  }
1459
4059
 
1460
4060
  /* ----------------------------------------------------------------- init */
@@ -1478,8 +4078,15 @@ void Init_asterism_zenoh(void) {
1478
4078
  id_listen = rb_intern("listen");
1479
4079
  id_iv_session = rb_intern("@session");
1480
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");
1481
4087
  id_client = rb_intern("client");
1482
4088
  id_peer = rb_intern("peer");
4089
+ id_router = rb_intern("router");
1483
4090
  id_all = rb_intern("all");
1484
4091
  id_all_complete = rb_intern("all_complete");
1485
4092
  id_best_matching = rb_intern("best_matching");
@@ -1492,6 +4099,19 @@ void Init_asterism_zenoh(void) {
1492
4099
  zrb_no_new(cSession);
1493
4100
  rb_define_singleton_method(cSession, "open", zrb_session_s_open, -1);
1494
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);
1495
4115
  rb_define_method(cSession, "subscribe", zrb_session_subscribe, -1);
1496
4116
  rb_define_method(cSession, "get", zrb_session_get_m, -1);
1497
4117
  rb_define_method(cSession, "queryable", zrb_session_queryable, -1);
@@ -1517,6 +4137,91 @@ void Init_asterism_zenoh(void) {
1517
4137
  rb_define_method(both[i], "close", zrb_sub_close, 0);
1518
4138
  rb_define_method(both[i], "closed?", zrb_sub_closed_p, 0);
1519
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);
1520
4225
 
1521
4226
  cQueryable = rb_define_class_under(mZenoh, "Queryable", rb_cObject);
1522
4227
  zrb_no_new(cQueryable);
@@ -1534,12 +4239,16 @@ void Init_asterism_zenoh(void) {
1534
4239
  rb_define_method(cQuery, "payload", zrb_query_payload, 0);
1535
4240
  rb_define_method(cQuery, "attachment", zrb_query_attachment, 0);
1536
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);
1537
4245
  rb_define_method(cQuery, "finish", zrb_query_finish_m, 0);
1538
4246
  rb_define_method(cQuery, "finished?", zrb_query_finished_p, 0);
1539
4247
 
1540
4248
  cGet = rb_define_class_under(mZenoh, "Get", rb_cObject);
1541
4249
  zrb_no_new(cGet);
1542
4250
  rb_define_method(cGet, "each_reply", zrb_get_each_reply, 0);
4251
+ rb_define_method(cGet, "each_result", zrb_get_each_result, 0);
1543
4252
  rb_define_method(cGet, "done?", zrb_get_done_p, 0);
1544
4253
  rb_define_method(cGet, "pending", zrb_get_pending, 0);
1545
4254
  rb_define_method(cGet, "received", zrb_get_received, 0);