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
#![cfg(not(target_arch = "wasm32"))]

//! common provider wasmbus support
//!

pub use crate::rpc_client::make_uuid;
use crate::{
    common::{Context, Message, MessageDispatch, SendOpts},
    core::{
        HealthCheckRequest, HealthCheckResponse, HostData, Invocation, InvocationResponse,
        LinkDefinition,
    },
    error::RpcError,
    rpc_client::RpcClient,
};
use async_trait::async_trait;
use futures::future::JoinAll;
use log::{debug, error, info, trace, warn};
use serde::de::DeserializeOwned;
use std::{
    borrow::Cow,
    collections::HashMap,
    convert::Infallible,
    ops::Deref,
    sync::{Arc, Mutex as StdMutex},
    time::Duration,
};
use tokio::sync::{oneshot, RwLock};

// name of nats queue group for rpc subscription
const RPC_SUBSCRIPTION_QUEUE_GROUP: &str = "rpc";

pub type HostShutdownEvent = String;

pub trait ProviderDispatch: MessageDispatch + ProviderHandler {}
trait ProviderImpl: ProviderDispatch + Send + Sync + Clone + 'static {}

pub mod prelude {
    pub use crate::{
        common::{Context, Message, MessageDispatch, SendOpts},
        core::LinkDefinition,
        error::{RpcError, RpcResult},
        provider::{HostBridge, ProviderDispatch, ProviderHandler},
        provider_main::{
            get_host_bridge, load_host_data, provider_main, provider_run, provider_start,
        },
    };

    pub use async_trait::async_trait;
    pub use wasmbus_macros::Provider;

    #[cfg(feature = "BigInteger")]
    pub use num_bigint::BigInt as BigInteger;

    #[cfg(feature = "BigDecimal")]
    pub use bigdecimal::BigDecimal;
}

/// CapabilityProvider handling of messages from host
/// The HostBridge handles most messages and forwards the remainder to this handler
#[async_trait]
pub trait ProviderHandler: Sync {
    /// Provider should perform any operations needed for a new link,
    /// including setting up per-actor resources, and checking authorization.
    /// If the link is allowed, return true, otherwise return false to deny the link.
    /// This message is idempotent - provider must be able to handle
    /// duplicates
    #[allow(unused_variables)]
    async fn put_link(&self, ld: &LinkDefinition) -> Result<bool, RpcError> {
        Ok(true)
    }

    /// Notify the provider that the link is dropped
    #[allow(unused_variables)]
    async fn delete_link(&self, actor_id: &str) {}

    /// Perform health check. Called at regular intervals by host
    /// Default implementation always returns healthy
    #[allow(unused_variables)]
    async fn health_request(
        &self,
        arg: &HealthCheckRequest,
    ) -> Result<HealthCheckResponse, RpcError> {
        Ok(HealthCheckResponse {
            healthy: true,
            message: None,
        })
    }

    /// Handle system shutdown message
    async fn shutdown(&self) -> Result<(), Infallible> {
        Ok(())
    }
}

/// format of log message sent to main thread for output to logger
pub type LogEntry = (log::Level, String);

/// HostBridge manages the NATS connection to the host,
/// and processes subscriptions for links, health-checks, and rpc messages.
/// Callbacks from HostBridge are implemented by the provider in the [[ProviderHandler]] implementation.
///
#[derive(Clone)]
pub struct HostBridge {
    inner: Arc<HostBridgeInner>,
    host_data: HostData,
}

impl HostBridge {
    pub fn new(
        nats: crate::anats::Connection,
        host_data: &HostData,
    ) -> Result<HostBridge, RpcError> {
        let key = if host_data.is_test() {
            wascap::prelude::KeyPair::new_user()
        } else {
            wascap::prelude::KeyPair::from_seed(&host_data.invocation_seed)
                .map_err(|e| RpcError::NotInitialized(format!("key failure: {}", e)))?
        };
        let rpc_client = crate::rpc_client::RpcClient::new(
            nats,
            &host_data.lattice_rpc_prefix,
            key,
            host_data.host_id.clone(),
            None,
        );

        Ok(HostBridge {
            inner: Arc::new(HostBridgeInner {
                subs: RwLock::new(Vec::new()),
                links: RwLock::new(HashMap::new()),
                rpc_client,
                lattice_prefix: host_data.lattice_rpc_prefix.clone(),
            }),
            host_data: host_data.clone(),
        })
    }

    /// Returns the provider's public key
    pub fn provider_key(&self) -> &str {
        self.host_data.provider_key.as_str()
    }

    /// Returns the host id that launched this provider
    pub fn host_id(&self) -> &str {
        self.host_data.host_id.as_str()
    }

    /// Returns the link_name for this provider
    pub fn link_name(&self) -> &str {
        self.host_data.link_name.as_str()
    }
}

impl Deref for HostBridge {
    type Target = HostBridgeInner;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

#[doc(hidden)]
pub struct HostBridgeInner {
    subs: RwLock<Vec<crate::anats::Subscription>>,
    /// Table of actors that are bound to this provider
    /// Key is actor_id / actor public key
    links: RwLock<HashMap<String, LinkDefinition>>,
    rpc_client: crate::rpc_client::RpcClient,
    lattice_prefix: String,
}

impl HostBridge {
    /// Returns a reference to the rpc client
    fn rpc_client(&self) -> &crate::rpc_client::RpcClient {
        &self.rpc_client
    }

    /// Clear out all subscriptions
    async fn unsubscribe_all(&self) {
        let mut copy = Vec::new();
        {
            let mut sub_lock = self.subs.write().await;
            copy.append(&mut sub_lock);
        };
        // `drop`ping the Subscription doesn't close it - we need to unsubscribe
        for sub in copy.into_iter() {
            if let Err(e) = sub.close().await {
                debug!("during shutdown, failure to unsubscribe: {}", e.to_string());
            }
        }
        debug!("unsubscribed from all subscriptions");
    }

    // add subscription so we can unsubscribe_all later
    async fn add_subscription(&self, sub: crate::anats::Subscription) {
        let mut sub_lock = self.subs.write().await;
        sub_lock.push(sub);
    }

    // parse incoming subscription message
    // if it fails deserialization, we can't really respond;
    // so log the error
    fn parse_msg<T: DeserializeOwned>(
        &self,
        msg: &crate::anats::Message,
        topic: &str,
    ) -> Option<T> {
        match if self.host_data.is_test() {
            serde_json::from_slice(&msg.data).map_err(|e| RpcError::Deser(e.to_string()))
        } else {
            crate::deserialize(&msg.data)
        } {
            Ok(item) => Some(item),
            Err(e) => {
                error!("garbled data received for {}: {}", topic, e.to_string());
                None
            }
        }
    }

    /// Stores actor with link definition
    pub async fn put_link(&self, ld: LinkDefinition) {
        let mut update = self.links.write().await;
        update.insert(ld.actor_id.to_string(), ld);
    }

    /// Deletes link
    pub async fn delete_link(&self, actor_id: &str) {
        let mut update = self.links.write().await;
        update.remove(actor_id);
    }

    /// Returns true if the actor is linked
    pub async fn is_linked(&self, actor_id: &str) -> bool {
        let read = self.links.read().await;
        read.contains_key(actor_id)
    }

    /// Returns copy of LinkDefinition, or None,if the actor is not linked
    pub async fn get_link(&self, actor_id: &str) -> Option<LinkDefinition> {
        let read = self.links.read().await;
        read.get(actor_id).cloned()
    }

    /// Implement subscriber listener threads and provider callbacks
    pub async fn connect<P>(
        &'static self,
        provider: P,
        shutdown_tx: oneshot::Sender<HostShutdownEvent>,
    ) -> Result<JoinAll<tokio::task::JoinHandle<Result<(), RpcError>>>, RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        let join = futures::future::join_all(vec![
            tokio::task::spawn(self.subscribe_rpc(provider.clone())),
            tokio::task::spawn(self.subscribe_link_put(provider.clone())),
            tokio::task::spawn(self.subscribe_link_del(provider.clone())),
            tokio::task::spawn(self.subscribe_shutdown(provider.clone(), shutdown_tx)),
            tokio::task::spawn(self.subscribe_health(provider)),
        ]);
        Ok(join)
    }

    async fn subscribe_rpc<P>(&self, provider: P) -> Result<(), RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        let rpc_topic = format!(
            "wasmbus.rpc.{}.{}.{}",
            &self.lattice_prefix, &self.host_data.provider_key, self.host_data.link_name
        );

        debug!("subscribing for rpc : {}", &rpc_topic);
        let sub = self
            .rpc_client()
            .get_async()
            .unwrap() // we are only async
            .queue_subscribe(&rpc_topic, RPC_SUBSCRIPTION_QUEUE_GROUP)
            .await
            .map_err(|e| RpcError::Nats(e.to_string()))?;
        self.add_subscription(sub.clone()).await;
        let this = self.clone();
        tokio::spawn(async move {
            while let Some(msg) = sub.next().await {
                match crate::deserialize::<Invocation>(&msg.data) {
                    Ok(inv) => match this.validate_invocation(&inv).await {
                        Ok(()) => {
                            let provider = provider.clone();
                            let rpc_client = this.rpc_client().clone();
                            tokio::task::spawn(async move {
                                trace!(
                                    "RPC Invocation: op:{} from:{}",
                                    &inv.operation,
                                    &inv.origin.public_key
                                );
                                let response = match provider
                                    .dispatch(
                                        &Context {
                                            actor: Some(inv.origin.public_key.clone()),
                                            ..Default::default()
                                        },
                                        Message {
                                            method: &inv.operation,
                                            arg: Cow::from(inv.msg),
                                        },
                                    )
                                    .await
                                {
                                    Ok(msg) => InvocationResponse {
                                        invocation_id: inv.id,
                                        error: None,
                                        msg: msg.arg.to_vec(),
                                    },
                                    Err(e) => {
                                        error!(
                                            "RPC Invocation failed: op:{} from:{}: {}",
                                            &inv.operation, &inv.origin.public_key, e
                                        );
                                        InvocationResponse {
                                            invocation_id: inv.id,
                                            error: Some(e.to_string()),
                                            msg: Vec::new(),
                                        }
                                    }
                                };
                                if let Some(reply_to) = msg.reply {
                                    // Errors are published from inside the function, safe to ignore Result
                                    let _ = publish_invocation_response(
                                        &rpc_client,
                                        reply_to,
                                        response,
                                    )
                                    .await;
                                }
                            });
                        }
                        Err(s) => {
                            error!(
                                "Invocation validation failure: op:{} from:{} id:{} host:{}: {}",
                                &inv.operation, &inv.origin.public_key, &inv.id, &inv.host_id, &s
                            );
                            if let Some(reply_to) = msg.reply {
                                // Errors are published from inside the function, safe to ignore Result
                                let _ = publish_invocation_response(
                                    this.rpc_client(),
                                    reply_to,
                                    InvocationResponse {
                                        invocation_id: inv.id,
                                        error: Some(s),
                                        msg: Vec::new(),
                                    },
                                )
                                .await;
                            }
                        }
                    },
                    Err(e) => {
                        error!("Invocation deserialization failure: {}", e.to_string());
                        if let Some(reply_to) = msg.reply {
                            if let Err(e) = publish_invocation_response(
                                this.rpc_client(),
                                reply_to,
                                InvocationResponse {
                                    invocation_id: "invalid".to_string(),
                                    error: Some(format!("Corrupt invocation: {}", e)),
                                    msg: Vec::new(),
                                },
                            )
                            .await
                            {
                                error!("replying to rpc: {}", e);
                            }
                        }
                    }
                }
            }
        });
        Ok(())
    }

    pub async fn validate_invocation(&self, inv: &Invocation) -> Result<(), String> {
        let vr = wascap::jwt::validate_token::<wascap::prelude::Invocation>(&inv.encoded_claims)
            .map_err(|e| format!("{}", e))?;
        if vr.expired {
            return Err("Invocation claims token expired".into());
        }
        if !vr.signature_valid {
            return Err("Invocation claims signature invalid".into());
        }
        if vr.cannot_use_yet {
            return Err("Attempt to use invocation before claims token allows".into());
        }
        let target_url = format!("{}/{}", inv.target.url(), &inv.operation);
        let hash = crate::rpc_client::invocation_hash(
            &target_url,
            &inv.origin.url(),
            &inv.operation,
            &inv.msg,
        );
        let claims =
            wascap::prelude::Claims::<wascap::prelude::Invocation>::decode(&inv.encoded_claims)
                .map_err(|e| format!("{}", e))?;
        let inv_claims = claims
            .metadata
            .ok_or_else(|| "No wascap metadata found on claims".to_string())?;
        if inv_claims.invocation_hash != hash {
            return Err(format!(
                "Invocation hash does not match signed claims hash ({} / {})",
                inv_claims.invocation_hash, hash
            ));
        }
        if !inv.host_id.starts_with('N') && inv.host_id.len() != 56 {
            return Err(format!("Invalid host ID on invocation: '{}'", inv.host_id));
        }
        if !self.host_data.cluster_issuers.contains(&claims.issuer) {
            return Err("Issuer of this invocation is not in list of cluster issuers".into());
        }
        if inv_claims.target_url != target_url {
            return Err(format!(
                "Invocation claims and invocation target URL do not match: {} != {}",
                &inv_claims.target_url, &target_url
            ));
        }
        if inv_claims.origin_url != inv.origin.url() {
            return Err("Invocation claims and invocation origin URL do not match".into());
        }
        // verify target public key is my key
        if inv.target.public_key != self.host_data.provider_key {
            return Err(format!(
                "target key mismatch: {} != {}",
                &inv.target.public_key, &self.host_data.host_id
            ));
        }
        // verify that the sending actor is linked with this provider
        if !self.is_linked(&inv.origin.public_key).await {
            return Err(format!("unlinked actor: {}", &inv.origin.public_key));
        }
        Ok(())
    }

    async fn subscribe_shutdown<P>(
        &self,
        provider: P,
        shutdown_tx: oneshot::Sender<HostShutdownEvent>,
    ) -> Result<(), RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        let shutdown_topic = format!(
            "wasmbus.rpc.{}.{}.{}.shutdown",
            &self.lattice_prefix, &self.host_data.provider_key, self.host_data.link_name
        );
        debug!("subscribing for shutdown : {}", &shutdown_topic);
        let sub = self
            .rpc_client()
            .get_async()
            .unwrap() // we are only async
            .subscribe(&shutdown_topic)
            .await
            .map_err(|e| RpcError::Nats(e.to_string()))?;
        // TODO: there should be validation on this message, but it's not signed by host yet
        let msg = sub.next().await;

        // Shutdown messages are unsigned (see https://github.com/wasmCloud/wasmcloud-otp/issues/256)
        // so we can't verify that this came from a trusted source.
        // When the above issue is fixed, verify the source and keep looping if it's invalid.
        debug!("Received termination signal. Shutting down capability provider.");
        let (this, provider) = (self.clone(), provider.clone());
        if let Err(e) = tokio::spawn(async move {
            // Tell provider to shutdown - before we shut down nats subscriptions,
            // in case it needs to do any message passing during shutdown
            if let Err(e) = provider.shutdown().await {
                error!("during provider shutdown processing, got error: {}", e);
            }

            // drain all subscriptions except this one
            this.unsubscribe_all().await;
        })
        .await
        {
            error!("joining thread shutdown/unsubscribe task: {}", e);
        }
        // send ack to host
        if let Some(crate::anats::Message {
            reply: Some(reply_to),
            ..
        }) = msg.as_ref()
        {
            let data = b"shutting down".to_vec();
            if let Err(e) = self.rpc_client().publish(reply_to, &data).await {
                error!(
                    "failed to send shutdown response to host: {}",
                    e.to_string()
                );
            }
        }

        // unsubscribe from shutdown messages
        let _ = sub.close().await; // ignore errors

        // signal main thread to quit
        if let Err(e) = shutdown_tx.send("bye".to_string()) {
            error!("Problem shutting down:  failure to send signal: {}", e);
        }
        Ok(())
    }

    async fn subscribe_link_put<P>(&self, provider: P) -> Result<(), RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        let ldput_topic = format!(
            "wasmbus.rpc.{}.{}.{}.linkdefs.put",
            &self.lattice_prefix, &self.host_data.provider_key, &self.host_data.link_name
        );

        debug!("subscribing for link put : {}", &ldput_topic);
        let sub = self
            .rpc_client()
            .get_async()
            .unwrap() // we are only async
            .subscribe(&ldput_topic)
            .await
            .map_err(|e| RpcError::Nats(e.to_string()))?;
        self.add_subscription(sub.clone()).await;
        //let provider = provider.clone();
        let (this, provider) = (self.clone(), provider.clone());
        tokio::spawn(async move {
            // TODO(ss): do we need to pin it with stream() before iterating?
            while let Some(msg) = sub.next().await {
                if let Some(ld) = this.parse_msg::<LinkDefinition>(&msg, "link.put") {
                    if this.is_linked(&ld.actor_id).await {
                        warn!(
                            "Ignoring duplicate link put for '{}' to '{}'.",
                            &ld.actor_id, &ld.provider_id
                        );
                    } else {
                        info!("Linking '{}' with '{}'", &ld.actor_id, &ld.provider_id);
                        match provider.put_link(&ld).await {
                            Ok(true) => {
                                this.put_link(ld).await;
                            }
                            Ok(false) => {
                                // authorization failed or parameters were invalid
                                warn!("put_link denied: {}", &ld.actor_id);
                            }
                            Err(e) => {
                                error!("put_link {} failed: {}", &ld.actor_id, e.to_string());
                            }
                        }
                    }
                }
            }
        });
        Ok(())
    }

    async fn subscribe_link_del<P>(&self, provider: P) -> Result<(), RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        // Link Delete
        let link_del_topic = format!(
            "wasmbus.rpc.{}.{}.{}.linkdefs.del",
            &self.lattice_prefix, &self.host_data.provider_key, &self.host_data.link_name
        );
        debug!("subscribing for link del : {}", &link_del_topic);
        let sub = self
            .rpc_client()
            .get_async()
            .unwrap() // we are only async
            .subscribe(&link_del_topic)
            .await
            .map_err(|e| RpcError::Nats(e.to_string()))?;
        self.add_subscription(sub.clone()).await;
        let (this, provider) = (self.clone(), provider.clone());
        tokio::spawn(async move {
            while let Some(msg) = sub.next().await {
                if let Some(ld) = &this.parse_msg::<LinkDefinition>(&msg, "link.del") {
                    this.delete_link(&ld.actor_id).await;
                    // notify provider that link is deleted
                    provider.delete_link(&ld.actor_id).await;
                }
            }
        });
        Ok(())
    }

    async fn subscribe_health<P>(&self, provider: P) -> Result<(), RpcError>
    where
        P: ProviderDispatch + Send + Sync + Clone + 'static,
    {
        let topic = format!(
            "wasmbus.rpc.{}.{}.{}.health",
            &self.lattice_prefix, &self.host_data.provider_key, &self.host_data.link_name
        );

        let sub = self
            .rpc_client()
            .get_async()
            .unwrap() // we are only async
            .subscribe(&topic)
            .await
            .map_err(|e| RpcError::Nats(e.to_string()))?;
        self.add_subscription(sub.clone()).await;
        let this = self.clone();
        tokio::spawn(async move {
            while let Some(msg) = sub.next().await {
                // placeholder arg
                let arg = HealthCheckRequest {};
                let resp = match provider.health_request(&arg).await {
                    Ok(resp) => resp,
                    Err(e) => {
                        error!("error generating health check response: {}", &e.to_string());
                        HealthCheckResponse {
                            healthy: false,
                            message: Some(e.to_string()),
                        }
                    }
                };
                let buf = if this.host_data.is_test() {
                    Ok(serde_json::to_vec(&resp).unwrap())
                } else {
                    crate::serialize(&resp)
                };
                match buf {
                    Ok(t) => {
                        if let Some(reply_to) = msg.reply.as_ref() {
                            if let Err(e) = this.rpc_client().publish(reply_to, &t).await {
                                error!("failed sending health check response: {}", e.to_string());
                            }
                        }
                    }
                    Err(e) => {
                        // extremely unlikely that InvocationResponse would fail to serialize
                        error!("failed serializing HealthCheckResponse: {}", e.to_string());
                    }
                }
            }
        });
        Ok(())
    }
}

async fn publish_invocation_response(
    rpc_client: &RpcClient,
    reply_to: String,
    response: InvocationResponse,
) -> Result<(), String> {
    match crate::serialize(&response) {
        Ok(t) => {
            if let Err(e) = rpc_client.publish(&reply_to, &t).await {
                error!(
                    "failed sending rpc response to {}: {}",
                    &reply_to,
                    e.to_string()
                );
            }
        }
        Err(e) => {
            // extremely unlikely that InvocationResponse would fail to serialize
            error!("failed serializing InvocationResponse: {}", e.to_string());
        }
    }
    Ok(())
}

pub struct ProviderTransport<'send> {
    pub bridge: &'send HostBridge,
    pub ld: &'send LinkDefinition,
    timeout: StdMutex<std::time::Duration>,
}

impl<'send> ProviderTransport<'send> {
    /// constructs a ProviderTransport with the LinkDefinition and bridge.
    /// If the bridge parameter is None, the current (static) bridge is used.
    pub fn new(ld: &'send LinkDefinition, bridge: Option<&'send HostBridge>) -> Self {
        Self::new_with_timeout(ld, bridge, None)
    }

    /// constructs a ProviderTransport with the LinkDefinition, bridge,
    /// and an optional rpc timeout.
    /// If the bridge parameter is None, the current (static) bridge is used.
    pub fn new_with_timeout(
        ld: &'send LinkDefinition,
        bridge: Option<&'send HostBridge>,
        timeout: Option<std::time::Duration>,
    ) -> Self {
        #[allow(clippy::redundant_closure)]
        let bridge = bridge.unwrap_or_else(|| crate::provider_main::get_host_bridge());
        Self {
            bridge,
            ld,
            timeout: StdMutex::new(
                timeout.unwrap_or(crate::rpc_client::DEFAULT_RPC_TIMEOUT_MILLIS),
            ),
        }
    }
}

#[async_trait]
impl<'send> crate::common::Transport for ProviderTransport<'send> {
    async fn send(
        &self,
        _ctx: &Context,
        req: Message<'_>,
        _opts: Option<SendOpts>,
    ) -> std::result::Result<Vec<u8>, RpcError> {
        let origin = self.ld.provider_entity();
        let target = self.ld.actor_entity();
        let timeout = {
            if let Ok(rd) = self.timeout.lock() {
                *rd
            } else {
                // if lock is poisioned
                warn!("rpc timeout mutex error - using default value");
                crate::rpc_client::DEFAULT_RPC_TIMEOUT_MILLIS
            }
        };
        self.bridge
            .rpc_client()
            .send_timeout(origin, target, req, timeout)
            .await
    }

    fn set_timeout(&self, interval: Duration) {
        if let Ok(mut write) = self.timeout.lock() {
            *write = interval;
        } else {
            warn!("rpc timeout mutex error - unchanged")
        }
    }
}