iroh-n0des 0.10.0

p2p quic connections dialed by public key
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
use std::{
    str::FromStr,
    sync::{Arc, RwLock},
};

use anyhow::{Result, anyhow, ensure};
use iroh::{Endpoint, EndpointAddr, EndpointId, endpoint::ConnectError};
use iroh_metrics::{MetricsGroup, Registry, encoding::Encoder};
#[cfg(feature = "tickets")]
use iroh_tickets::Ticket;
use irpc_iroh::IrohLazyRemoteConnection;
use n0_error::StackResultExt;
use n0_future::{task::AbortOnDropHandle, time::Duration};
use rcan::Rcan;
use tokio::sync::oneshot;
use tracing::{debug, trace, warn};
use uuid::Uuid;

#[cfg(feature = "net_diagnostics")]
use crate::net_diagnostics::{DiagnosticsReport, checks::run_diagnostics};
#[cfg(feature = "net_diagnostics")]
use crate::protocol::PutNetworkDiagnostics;
#[cfg(feature = "tickets")]
use crate::protocol::{GetTicket, ListTickets, PublishTicket, TicketData, UnpublishTicket};
use crate::{
    api_secret::ApiSecret,
    caps::Caps,
    protocol::{ALPN, Auth, N0desClient, Ping, Pong, PutMetrics, RemoteError},
};

/// Client is the main handle for interacting with n0des. It communicates with
/// n0des entirely through an iroh endpoint, and is configured through a builder.
/// Client requires either an Ssh Key or [`ApiSecret`]
///
/// ```no_run
/// use iroh_n0des::Client;
///
/// async fn build_client() -> anyhow::Result<()> {
///     let endpoint = iroh::Endpoint::bind().await?;
///
///     // needs N0DES_API_SECRET set to an environment variable
///     // client will now push endpoint metrics to n0des.
///     let client = Client::builder(&endpoint)
///         .api_secret_from_str("MY_API_SECRET")?
///         .build()
///         .await;
///
///     Ok(())
/// }
/// ```
///
/// [`ApiSecret`]: crate::api_secret::ApiSecret
#[derive(Debug, Clone)]
pub struct Client {
    // owned clone of the endpoint for diagnostics, and for connection restarts on actor close
    #[allow(dead_code)]
    endpoint: Endpoint,
    message_channel: tokio::sync::mpsc::Sender<ClientActorMessage>,
    _actor_task: Arc<AbortOnDropHandle<()>>,
}

/// ClientBuilder provides configures and builds a n0des client, typically
/// created with [`Client::builder`]
pub struct ClientBuilder {
    #[allow(dead_code)]
    cap_expiry: Duration,
    cap: Option<Rcan<Caps>>,
    endpoint: Endpoint,
    metrics_interval: Option<Duration>,
    remote: Option<EndpointAddr>,
    registry: Registry,
}

const DEFAULT_CAP_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24 * 30); // 1 month
pub const API_SECRET_ENV_VAR_NAME: &str = "N0DES_API_SECRET";

impl ClientBuilder {
    pub fn new(endpoint: &Endpoint) -> Self {
        let mut registry = Registry::default();
        registry.register_all(endpoint.metrics());

        Self {
            cap: None,
            cap_expiry: DEFAULT_CAP_EXPIRY,
            endpoint: endpoint.clone(),
            metrics_interval: Some(Duration::from_secs(10)),
            remote: None,
            registry,
        }
    }

    /// Register a metrics group to forward to n0des
    ///
    /// The default registered metrics uses only the endpoint
    pub fn register_metrics_group(mut self, metrics_group: Arc<dyn MetricsGroup>) -> Self {
        self.registry.register(metrics_group);
        self
    }

    /// Set the metrics collection interval
    ///
    /// Defaults to enabled, every 60 seconds.
    pub fn metrics_interval(mut self, interval: Duration) -> Self {
        self.metrics_interval = Some(interval);
        self
    }

    /// Disable metrics collection.
    pub fn disable_metrics_interval(mut self) -> Self {
        self.metrics_interval = None;
        self
    }

    /// Check N0DES_API_SECRET environment variable for a valid API secret
    pub fn api_secret_from_env(self) -> Result<Self> {
        let ticket = ApiSecret::from_env_var(API_SECRET_ENV_VAR_NAME)?;
        self.api_secret(ticket)
    }

    /// set client API secret from an encoded string
    pub fn api_secret_from_str(self, secret_key: &str) -> Result<Self> {
        let key = ApiSecret::from_str(secret_key).context("invalid n0des api secret")?;
        self.api_secret(key)
    }

    /// Use a shared secret & remote n0des endpoint ID contained within a ticket
    /// to construct a n0des client. The resulting client will have "Client"
    /// capabilities.
    ///
    /// API secrets include remote details within them, and will set both the
    /// remote and rcan values on the builder
    pub fn api_secret(mut self, ticket: ApiSecret) -> Result<Self> {
        let local_id = self.endpoint.id();
        let rcan = crate::caps::create_api_token_from_secret_key(
            ticket.secret,
            local_id,
            self.cap_expiry,
            Caps::for_shared_secret(),
        )?;

        self.remote = Some(ticket.remote);
        self.rcan(rcan)
    }

    /// Loads the private ssh key from the given path, and creates the needed capability.
    #[cfg(feature = "ssh-key")]
    pub async fn ssh_key_from_file<P: AsRef<std::path::Path>>(self, path: P) -> Result<Self> {
        let file_content = tokio::fs::read_to_string(path).await?;
        let private_key = ssh_key::PrivateKey::from_openssh(&file_content)?;

        self.ssh_key(&private_key)
    }

    /// Creates the capability from the provided private ssh key.
    #[cfg(feature = "ssh-key")]
    pub fn ssh_key(mut self, key: &ssh_key::PrivateKey) -> Result<Self> {
        let local_id = self.endpoint.id();
        let rcan = crate::caps::create_api_token_from_ssh_key(
            key,
            local_id,
            self.cap_expiry,
            Caps::all(),
        )?;
        self.cap.replace(rcan);

        Ok(self)
    }

    /// Sets the rcan directly.
    pub fn rcan(mut self, cap: Rcan<Caps>) -> Result<Self> {
        ensure!(
            EndpointId::from_verifying_key(*cap.audience()) == self.endpoint.id(),
            "invalid audience"
        );
        self.cap.replace(cap);
        Ok(self)
    }

    /// Sets the remote to dial, must be provided either directly by calling
    /// this method, or through calling the api_secret builder methods.
    pub fn remote(mut self, remote: impl Into<EndpointAddr>) -> Self {
        self.remote = Some(remote.into());
        self
    }

    /// Create a new client, connected to the provide service node
    #[must_use = "dropping the client will silently cancel all client tasks"]
    pub async fn build(self) -> Result<Client, BuildError> {
        debug!("starting iroh-n0des client");
        let remote = self.remote.ok_or(BuildError::MissingRemote)?;
        let capabilities = self.cap.ok_or(BuildError::MissingCapability)?;

        let conn = IrohLazyRemoteConnection::new(self.endpoint.clone(), remote, ALPN.to_vec());
        let client = N0desClient::boxed(conn);

        let (tx, rx) = tokio::sync::mpsc::channel(1);
        let metrics_task = AbortOnDropHandle::new(n0_future::task::spawn(
            ClientActor {
                capabilities,
                client,
                session_id: Uuid::new_v4(),
                authorized: false,
                interval_metrics_enabled: self.metrics_interval.is_some(),
            }
            .run(self.registry, self.metrics_interval, rx),
        ));

        Ok(Client {
            endpoint: self.endpoint,
            message_channel: tx,
            _actor_task: Arc::new(metrics_task),
        })
    }
}

#[derive(thiserror::Error, Debug)]
pub enum BuildError {
    #[error("Missing remote endpoint to dial")]
    MissingRemote,
    #[error("Missing capability")]
    MissingCapability,
    #[error("Unauthorized")]
    Unauthorized,
    #[error("Remote error: {0}")]
    Remote(#[from] RemoteError),
    #[error("Rpc connection error: {0}")]
    Rpc(irpc::Error),
    #[error("Connection error: {0}")]
    Connect(ConnectError),
}

impl From<irpc::Error> for BuildError {
    fn from(value: irpc::Error) -> Self {
        match value {
            irpc::Error::Request {
                source:
                    irpc::RequestError::Connection {
                        source: iroh::endpoint::ConnectionError::ApplicationClosed(frame),
                        ..
                    },
                ..
            } if frame.error_code == 401u32.into() => Self::Unauthorized,
            value => Self::Rpc(value),
        }
    }
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Remote error: {0}")]
    Remote(#[from] RemoteError),
    #[error("Connection error: {0}")]
    Rpc(#[from] irpc::Error),
    #[error(transparent)]
    Other(#[from] anyhow::Error),
}

impl Client {
    pub fn builder(endpoint: &Endpoint) -> ClientBuilder {
        ClientBuilder::new(endpoint)
    }

    /// Pings the remote node.
    pub async fn ping(&self) -> Result<Pong, Error> {
        let (tx, rx) = oneshot::channel();
        self.message_channel
            .send(ClientActorMessage::Ping { done: tx })
            .await
            .map_err(|_| Error::Other(anyhow!("sending ping request")))?;

        rx.await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?
            .map_err(Error::Remote)
    }

    /// immediately send a single dump of metrics to n0des. It's not necessary
    /// to call this function if you're using a non-zero metrics interval,
    /// which will automatically propagate metrics on the set interval for you
    pub async fn push_metrics(&self) -> Result<(), Error> {
        let (tx, rx) = oneshot::channel();
        self.message_channel
            .send(ClientActorMessage::SendMetrics { done: tx })
            .await
            .map_err(|_| Error::Other(anyhow!("sending metrics")))?;

        rx.await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?
            .map_err(Error::Remote)
    }

    /// Grant capabilities to a remote endpoint. Creates a signed RCAN token
    /// and sends it to n0des for storage. The remote can then use this token
    /// when dialing back to authorize its requests.
    #[cfg(feature = "client_host")]
    pub async fn grant_capability(
        &self,
        remote_id: EndpointId,
        caps: impl IntoIterator<Item = impl Into<crate::caps::Cap>>,
    ) -> Result<(), Error> {
        let cap = crate::caps::create_grant_token(
            self.endpoint.secret_key().clone(),
            remote_id,
            DEFAULT_CAP_EXPIRY,
            Caps::new(caps),
        )
        .map_err(Error::Other)?;

        let (tx, rx) = oneshot::channel();
        self.message_channel
            .send(ClientActorMessage::GrantCap {
                cap: Box::new(cap),
                done: tx,
            })
            .await
            .map_err(|_| Error::Other(anyhow!("granting capability")))?;

        rx.await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?
    }

    /// run local network status diagnostics, optionally uploading the results
    #[cfg(feature = "net_diagnostics")]
    pub async fn net_diagnostics(&self, send: bool) -> Result<DiagnosticsReport, Error> {
        let report = run_diagnostics(&self.endpoint).await?;
        if send {
            let (tx, rx) = oneshot::channel();
            self.message_channel
                .send(ClientActorMessage::PutNetworkDiagnostics {
                    done: tx,
                    report: Box::new(report.clone()),
                })
                .await
                .map_err(|_| Error::Other(anyhow!("sending network diagnostics report")))?;

            let _ = rx
                .await
                .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?;
        }

        Ok(report)
    }

    /// Publish a [ticket] to n0des so others can find it by calling fetch_tickets.
    /// Publishing uses n0des to act as a signaling server,e.
    /// This API is intentionally designed around tickets to encourage using
    /// more than one signaling mechanism, like QR codes, sharing action sheets,
    /// copy-paste, etc. Publishing to n0des should give a smooth happy-path
    /// experience when two nodes are online, while the ticket format will still
    /// work if they can be shared by other means.
    ///
    /// Tickets are unique by {endpoint, name, type}. This means its possible to
    /// have multiple tickets with the same name, but from different endpoints.
    ///
    /// A ticket will remain published as long as the endpoint that published
    /// is online. Stale tickets be pruned within 4 metrics collection intervals
    /// of an endpoint going offline.
    ///
    /// Tickets cannot be published if a metrics collection interval is disabled,
    /// because n0des uses metrics publishing as a keepalive for ticket records
    ///
    /// [ticket]: https://docs.rs/iroh-tickets
    #[cfg(feature = "tickets")]
    pub async fn publish_ticket<T: Ticket>(&self, name: String, ticket: T) -> Result<(), Error> {
        let ticket_kind = T::KIND.to_string();
        let ticket_bytes = ticket.to_bytes();
        let (tx, rx) = oneshot::channel();

        self.message_channel
            .send(ClientActorMessage::PublishTicket {
                name,
                ticket_kind,
                ticket_bytes,
                done: tx,
            })
            .await
            .map_err(|_| Error::Other(anyhow!("publishing ticket")))?;

        rx.await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?
    }

    /// Remove a ticket from n0des that an endpoint has published. Ticket name
    /// and type must match to work, returns true if a ticket was actually
    /// removed.
    #[cfg(feature = "tickets")]
    pub async fn unpublish_ticket<T: Ticket>(&self, name: String) -> Result<bool, Error> {
        let ticket_kind = T::KIND.to_string();
        let (tx, rx) = oneshot::channel();

        self.message_channel
            .send(ClientActorMessage::UnpublishTicket {
                name,
                ticket_kind,
                done: tx,
            })
            .await
            .map_err(|_| Error::Other(anyhow!("publishing ticket")))?;

        rx.await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))?
    }

    /// Get a ticket from n0des by name.
    #[cfg(feature = "tickets")]
    pub async fn fetch_ticket<T: Ticket>(
        &self,
        name: String,
    ) -> Result<Option<PublishedTicket<T>>, Error> {
        let (tx, rx) = oneshot::channel();
        self.message_channel
            .send(ClientActorMessage::FetchTicket {
                name,
                ticket_kind: T::KIND.to_string(),
                done: tx,
            })
            .await
            .map_err(|_| Error::Other(anyhow!("fetching ticket")))?;

        let res = rx
            .await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))??;

        match res {
            Some(td) => {
                let ticket = T::from_bytes(&td.ticket_bytes).map_err(|e| {
                    Error::Other(anyhow!("parsing n0des ticket get response: {:?}", e))
                })?;

                Ok(Some(PublishedTicket {
                    name: td.name,
                    ticket,
                }))
            }
            None => Ok(None),
        }
    }

    /// List tickets published to n0des.
    #[cfg(feature = "tickets")]
    pub async fn fetch_tickets<T: Ticket>(
        &self,
        offset: u32,
        limit: u32,
    ) -> Result<Vec<PublishedTicket<T>>, Error> {
        let (tx, rx) = oneshot::channel();
        self.message_channel
            .send(ClientActorMessage::FetchTickets {
                offset,
                limit,
                ticket_kind: T::KIND.to_string(),
                done: tx,
            })
            .await
            .map_err(|_| Error::Other(anyhow!("fetching tickets")))?;

        let tickets = rx
            .await
            .map_err(|e| Error::Other(anyhow!("response on internal channel: {:?}", e)))??
            .iter()
            .map(|td| {
                let ticket = T::from_bytes(&td.ticket_bytes).map_err(|e| {
                    Error::Other(anyhow!("parsing n0des tickets list response: {:?}", e))
                })?;
                Ok::<PublishedTicket<T>, Error>(PublishedTicket {
                    name: td.name.clone(),
                    ticket,
                })
            })
            .collect::<Result<Vec<PublishedTicket<T>>, _>>()?;

        Ok(tickets)
    }
}

enum ClientActorMessage {
    SendMetrics {
        done: oneshot::Sender<Result<(), RemoteError>>,
    },
    Ping {
        done: oneshot::Sender<Result<Pong, RemoteError>>,
    },
    // GrantCap is used by the `client_host` feature flag
    #[allow(dead_code)]
    GrantCap {
        // boxed to avoid large enum variants
        cap: Box<Rcan<Caps>>,
        done: oneshot::Sender<Result<(), Error>>,
    },
    #[cfg(feature = "net_diagnostics")]
    PutNetworkDiagnostics {
        report: Box<DiagnosticsReport>,
        done: oneshot::Sender<Result<(), Error>>,
    },
    #[cfg(feature = "tickets")]
    PublishTicket {
        name: String,
        ticket_kind: String,
        ticket_bytes: Vec<u8>,
        done: oneshot::Sender<Result<(), Error>>,
    },
    #[cfg(feature = "tickets")]
    UnpublishTicket {
        name: String,
        ticket_kind: String,
        done: oneshot::Sender<Result<bool, Error>>,
    },
    #[cfg(feature = "tickets")]
    FetchTicket {
        name: String,
        ticket_kind: String,
        done: oneshot::Sender<Result<Option<TicketData>, Error>>,
    },
    #[cfg(feature = "tickets")]
    FetchTickets {
        offset: u32,
        limit: u32,
        ticket_kind: String,
        done: oneshot::Sender<Result<Vec<TicketData>, Error>>,
    },
}

/// PublishedTicket is the item type returned by n0des when listing tickets
#[cfg(feature = "tickets")]
#[derive(Debug)]
pub struct PublishedTicket<T: Ticket> {
    pub name: String,
    pub ticket: T,
}

struct ClientActor {
    capabilities: Rcan<Caps>,
    client: N0desClient,
    session_id: Uuid,
    authorized: bool,
    #[allow(dead_code)]
    interval_metrics_enabled: bool,
}

impl ClientActor {
    async fn run(
        mut self,
        registry: Registry,
        interval: Option<Duration>,
        mut inbox: tokio::sync::mpsc::Receiver<ClientActorMessage>,
    ) {
        let registry = Arc::new(RwLock::new(registry));
        let mut encoder = Encoder::new(registry);
        let mut metrics_timer = interval.map(|interval| n0_future::time::interval(interval));
        trace!("starting client actor");
        loop {
            trace!("client actor tick");
            tokio::select! {
                biased;
                Some(msg) = inbox.recv() => {
                    match msg {
                        ClientActorMessage::Ping{ done } => {
                            let res = self.send_ping().await;
                            if let Err(err) = done.send(res) {
                                debug!("failed to send ping: {:#?}", err);
                                self.authorized = false;
                            }
                        },
                        ClientActorMessage::SendMetrics{ done } => {
                            trace!("sending metrics manually triggered");
                            let res = self.send_metrics(&mut encoder).await;
                            if let Err(err) = done.send(res) {
                                debug!("failed to push metrics: {:#?}", err);
                                self.authorized = false;
                            }
                        }
                        ClientActorMessage::GrantCap{ cap, done } => {
                            let res = self.grant_cap(*cap).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to grant capability: {:#?}", err);
                            }
                        }
                        #[cfg(feature = "net_diagnostics")]
                        ClientActorMessage::PutNetworkDiagnostics{ report, done } => {
                            let res = self.put_network_diagnostics(*report).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to publish network diagnostics: {:#?}", err);
                            }
                        }
                        #[cfg(feature = "tickets")]
                        ClientActorMessage::PublishTicket{ name, ticket_kind, ticket_bytes, done } => {
                            let res = self.tickets_publish(name, ticket_kind, ticket_bytes).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to publish ticket: {:#?}", err);
                            }
                        }
                        #[cfg(feature = "tickets")]
                        ClientActorMessage::UnpublishTicket{ name, ticket_kind, done } => {
                            let res = self.tickets_unpublish(name, ticket_kind).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to unpublish ticket: {:#?}", err);
                            }
                        }
                        #[cfg(feature = "tickets")]
                        ClientActorMessage::FetchTicket{ name, ticket_kind, done } => {
                            let res = self.ticket_fetch(name, ticket_kind).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to fetch tickets: {:#?}", err);
                            }
                        }
                        #[cfg(feature = "tickets")]
                        ClientActorMessage::FetchTickets{ done, ticket_kind, offset, limit } => {
                            let res = self.tickets_fetch(ticket_kind, offset, limit).await;
                            if let Err(err) = done.send(res) {
                                warn!("failed to fetch tickets: {:#?}", err);
                            }
                        }
                    }
                }
                _ = async {
                    if let Some(ref mut timer) = metrics_timer {
                        timer.tick().await;
                    } else {
                        std::future::pending::<()>().await;
                    }
                } => {
                    trace!("metrics send tick");
                    if let Err(err) = self.send_metrics(&mut encoder).await {
                        debug!("failed to push metrics: {:#?}", err);
                        self.authorized = false;
                    }
                },
            }
        }
    }

    // sends an authorization request to the server
    async fn auth(&mut self) -> Result<(), RemoteError> {
        if self.authorized {
            return Ok(());
        }
        trace!("client authorizing");
        self.client
            .rpc(Auth {
                caps: self.capabilities.clone(),
            })
            .await
            .inspect_err(|e| debug!("authorization failed: {:?}", e))
            .map_err(|e| RemoteError::AuthError(e.to_string()))?;
        self.authorized = true;
        Ok(())
    }

    async fn send_ping(&mut self) -> Result<Pong, RemoteError> {
        trace!("client actor send ping");
        self.auth().await?;

        let req = rand::random();
        self.client
            .rpc(Ping { req_id: req })
            .await
            .inspect_err(|e| warn!("rpc ping error: {e}"))
            .map_err(|_| RemoteError::InternalServerError)
    }

    async fn send_metrics(&mut self, encoder: &mut Encoder) -> Result<(), RemoteError> {
        trace!("client actor send metrics");
        self.auth().await?;

        let update = encoder.export();
        // let delta = update_delta(&self.latest_ackd_update, &update);
        let req = PutMetrics {
            session_id: self.session_id,
            update,
        };

        self.client
            .rpc(req)
            .await
            .map_err(|_| RemoteError::InternalServerError)??;

        Ok(())
    }

    async fn grant_cap(&mut self, cap: Rcan<Caps>) -> Result<(), Error> {
        trace!("client actor grant capability");
        self.auth().await?;

        self.client
            .rpc(crate::protocol::GrantCap { cap })
            .await
            .map_err(|_| RemoteError::InternalServerError)??;

        Ok(())
    }

    #[cfg(feature = "net_diagnostics")]
    async fn put_network_diagnostics(
        &mut self,
        report: crate::net_diagnostics::DiagnosticsReport,
    ) -> Result<(), Error> {
        trace!("client actor publish network diagnostics");
        self.auth().await?;

        let req = PutNetworkDiagnostics { report };

        self.client
            .rpc(req)
            .await
            .map_err(|_| RemoteError::InternalServerError)??;

        Ok(())
    }

    #[cfg(feature = "tickets")]
    async fn tickets_publish(
        &mut self,
        name: String,
        ticket_kind: String,
        ticket_bytes: Vec<u8>,
    ) -> Result<(), Error> {
        if !self.interval_metrics_enabled {
            return Err(Error::Other(anyhow!(
                "a metrics interval is required to publish tickets"
            )));
        }
        trace!("client actor tickets publish");
        self.auth().await?;

        let req_id = rand::random();
        self.client
            .rpc(PublishTicket {
                req_id,
                name,
                ticket_kind,
                ticket: ticket_bytes,
            })
            .await??;
        Ok(())
    }

    #[cfg(feature = "tickets")]
    async fn tickets_unpublish(
        &mut self,
        name: String,
        ticket_kind: String,
    ) -> Result<bool, Error> {
        trace!("client actor tickets unpublish");
        self.auth().await?;

        let req_id = rand::random();
        let res = self
            .client
            .rpc(UnpublishTicket {
                req_id,
                name,
                ticket_kind,
            })
            .await??;
        Ok(res)
    }

    #[cfg(feature = "tickets")]
    async fn ticket_fetch(
        &mut self,
        name: String,
        ticket_kind: String,
    ) -> Result<Option<TicketData>, Error> {
        trace!("client actor tickets fetch");
        self.auth().await?;

        let req_id = rand::random();
        let tickets = self
            .client
            .rpc(GetTicket {
                req_id,
                name,
                ticket_kind,
            })
            .await??;
        Ok(tickets)
    }

    #[cfg(feature = "tickets")]
    async fn tickets_fetch(
        &mut self,
        ticket_kind: String,
        offset: u32,
        limit: u32,
    ) -> Result<Vec<TicketData>, Error> {
        trace!("client actor tickets fetch");
        self.auth().await?;

        let req_id = rand::random();
        let tickets = self
            .client
            .rpc(ListTickets {
                req_id,
                ticket_kind,
                offset,
                limit,
            })
            .await??;
        Ok(tickets)
    }
}

#[cfg(test)]
mod tests {
    use iroh::{Endpoint, EndpointAddr, SecretKey};
    use temp_env_vars::temp_env_vars;

    use crate::{
        Client,
        api_secret::ApiSecret,
        caps::{Cap, Caps},
        client::API_SECRET_ENV_VAR_NAME,
    };

    #[tokio::test]
    #[temp_env_vars]
    async fn test_api_key_from_env() {
        // construct
        let mut rng = rand::rng();
        let shared_secret = SecretKey::generate(&mut rng);
        let fake_endpoint_id = SecretKey::generate(&mut rng).public();
        let api_secret = ApiSecret::new(shared_secret.clone(), fake_endpoint_id);
        unsafe {
            std::env::set_var(API_SECRET_ENV_VAR_NAME, api_secret.to_string());
        };

        let endpoint = Endpoint::empty_builder(iroh::RelayMode::Disabled)
            .bind()
            .await
            .unwrap();

        let builder = Client::builder(&endpoint).api_secret_from_env().unwrap();

        let fake_endpoint_addr: EndpointAddr = fake_endpoint_id.into();
        assert_eq!(builder.remote, Some(fake_endpoint_addr));

        // Compare capability fields individually to avoid flaky timestamp
        // mismatches between the builder's rcan and a freshly-created one.
        let cap = builder.cap.as_ref().expect("expected capability to be set");
        assert_eq!(cap.capability(), &Caps::new([Cap::Client]));
        assert_eq!(cap.audience(), &endpoint.id().as_verifying_key());
        assert_eq!(cap.issuer(), &shared_secret.public().as_verifying_key());
    }

    /// Assert that disabling metrics interval can manually send metrics without
    /// panicking. Metrics sending itself is expected to fail.
    #[tokio::test]
    async fn test_no_metrics_interval() {
        let mut rng = rand::rng();
        let shared_secret = SecretKey::generate(&mut rng);
        let fake_endpoint_id = SecretKey::generate(&mut rng).public();
        let api_secret = ApiSecret::new(shared_secret.clone(), fake_endpoint_id);

        let endpoint = Endpoint::empty_builder(iroh::RelayMode::Disabled)
            .bind()
            .await
            .unwrap();

        let client = Client::builder(&endpoint)
            .disable_metrics_interval()
            .api_secret(api_secret)
            .unwrap()
            .build()
            .await
            .unwrap();

        let err = client.push_metrics().await;
        assert!(err.is_err());
    }
}