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
#![deny(missing_docs)]

use crate::{route, Context, Message, OckamError};
use core::time::Duration;
use ockam_core::compat::rand::random;
use ockam_core::compat::{
    boxed::Box,
    string::{String, ToString},
    vec::Vec,
};
use ockam_core::{Address, AddressSet, Any, Decodable, Result, Route, Routed, Worker};
use ockam_node::Heartbeat;
use rand::distributions::{Distribution, Standard};
use rand::Rng;
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

/// Information about a remotely forwarded worker.
#[derive(Serialize, Deserialize, Clone, PartialEq, Debug, Message)]
pub struct RemoteForwarderInfo {
    forwarding_route: Route,
    remote_address: String,
    worker_address: Address,
}

impl RemoteForwarderInfo {
    /// Returns the forwarding route.
    pub fn forwarding_route(&self) -> &Route {
        &self.forwarding_route
    }
    /// Returns the remote address.
    pub fn remote_address(&self) -> &str {
        &self.remote_address
    }
    /// Returns the worker address.
    pub fn worker_address(&self) -> &Address {
        &self.worker_address
    }
}

/// All addresses `RemoteForwarder` is registered for
#[derive(Clone)]
struct Addresses {
    /// Address used from other node
    main_address: Address,
    /// Address used for heartbeat messages
    heartbeat_address: Address,
}

impl Distribution<Addresses> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Addresses {
        Addresses {
            main_address: rng.gen(),
            heartbeat_address: rng.gen(),
        }
    }
}

impl Addresses {
    fn into_set(self) -> AddressSet {
        vec![self.main_address, self.heartbeat_address].into()
    }
}

/// This Worker is responsible for registering on Ockam Hub and forwarding messages to local Worker
pub struct RemoteForwarder {
    addresses: Addresses,
    registration_route: Route,
    registration_payload: String,
    callback_address: Option<Address>,
    // We only use Heartbeat for static RemoteForwarder
    heartbeat: Option<Heartbeat<Vec<u8>>>,
    heartbeat_interval: Duration,
}

impl RemoteForwarder {
    fn new(
        addresses: Addresses,
        registration_route: Route,
        registration_payload: String,
        callback_address: Address,
        heartbeat: Option<Heartbeat<Vec<u8>>>,
        heartbeat_interval: Duration,
    ) -> Self {
        Self {
            addresses,
            registration_route,
            registration_payload,
            callback_address: Some(callback_address),
            heartbeat,
            heartbeat_interval,
        }
    }

    /// Create and start static RemoteForwarder at predefined address with given Ockam Hub address
    pub async fn create_static(
        ctx: &Context,
        hub_addr: impl Into<Address>,
        alias: impl Into<String>,
    ) -> Result<RemoteForwarderInfo> {
        let address: Address = random();
        let mut child_ctx = ctx.new_context(address).await?;

        let addresses: Addresses = random();

        let heartbeat = Heartbeat::create(ctx, addresses.heartbeat_address.clone(), vec![]).await?;
        let forwarder = Self::new(
            addresses.clone(),
            route![hub_addr.into(), "static_forwarding_service"],
            alias.into(),
            child_ctx.address(),
            Some(heartbeat),
            Duration::from_secs(10),
        );

        debug!(
            "Starting static RemoteForwarder at {}",
            &addresses.heartbeat_address
        );
        ctx.start_worker(addresses.into_set(), forwarder).await?;

        let resp = child_ctx
            .receive::<RemoteForwarderInfo>()
            .await?
            .take()
            .body();

        Ok(resp)
    }

    /// Create and start new ephemeral RemoteForwarder at random address with given Ockam Hub address
    pub async fn create(
        ctx: &Context,
        hub_addr: impl Into<Address>,
    ) -> Result<RemoteForwarderInfo> {
        let address: Address = random();
        let mut child_ctx = ctx.new_context(address).await?;

        let addresses: Addresses = random();

        let forwarder = Self::new(
            addresses.clone(),
            route![hub_addr.into(), "forwarding_service"],
            "register".to_string(),
            child_ctx.address(),
            None,
            Duration::from_secs(10),
        );

        debug!(
            "Starting ephemeral RemoteForwarder at {}",
            &addresses.main_address
        );
        ctx.start_worker(addresses.main_address, forwarder).await?;

        let resp = child_ctx
            .receive::<RemoteForwarderInfo>()
            .await?
            .take()
            .body();

        Ok(resp)
    }
}

#[crate::worker]
impl Worker for RemoteForwarder {
    type Context = Context;
    type Message = Any;

    async fn initialize(&mut self, ctx: &mut Self::Context) -> Result<()> {
        debug!("RemoteForwarder registration...");

        ctx.send_from_address(
            self.registration_route.clone(),
            self.registration_payload.clone(),
            self.addresses.main_address.clone(),
        )
        .await?;

        Ok(())
    }

    async fn handle_message(
        &mut self,
        ctx: &mut Context,
        msg: Routed<Self::Message>,
    ) -> Result<()> {
        // Heartbeat message, send registration message
        if msg.msg_addr() == self.addresses.heartbeat_address {
            ctx.send_from_address(
                self.registration_route.clone(),
                self.registration_payload.clone(),
                self.addresses.main_address.clone(),
            )
            .await?;

            return Ok(());
        }

        // We are the final recipient of the message because it's registration response for our Worker
        if msg.onward_route().recipient() == self.addresses.main_address {
            debug!("RemoteForwarder received service message");

            let payload =
                Vec::<u8>::decode(msg.payload()).map_err(|_| OckamError::InvalidHubResponse)?;
            let payload = String::from_utf8(payload).map_err(|_| OckamError::InvalidHubResponse)?;
            if payload != self.registration_payload {
                return Err(OckamError::InvalidHubResponse.into());
            }

            if let Some(callback_address) = self.callback_address.take() {
                let route = msg.return_route();

                info!("RemoteForwarder registered with route: {}", route);
                let address;
                if let Some(a) = route.clone().recipient().to_string().strip_prefix("0#") {
                    address = a.to_string();
                } else {
                    return Err(OckamError::InvalidHubResponse.into());
                }

                ctx.send(
                    callback_address,
                    RemoteForwarderInfo {
                        forwarding_route: route,
                        remote_address: address,
                        worker_address: ctx.address(),
                    },
                )
                .await?;
            }

            if let Some(heartbeat) = &mut self.heartbeat {
                heartbeat.schedule(self.heartbeat_interval).await?;
            }
        } else {
            debug!("RemoteForwarder received payload message");

            let mut message = msg.into_local_message();
            let transport_message = message.transport_mut();

            // Remove my address from the onward_route
            transport_message.onward_route.step()?;

            // Send the message on its onward_route
            ctx.forward(message).await?;

            // We received message from the other node, our registration is still alive, let's reset
            // heartbeat timer
            if let Some(heartbeat) = &mut self.heartbeat {
                heartbeat.schedule(self.heartbeat_interval).await?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::workers::Echoer;
    use ockam_transport_tcp::{TcpTransport, TCP};
    use std::env;

    fn get_cloud_address() -> Option<String> {
        if let Ok(v) = env::var("CLOUD_ADDRESS") {
            if !v.is_empty() {
                return Some(v);
            }
        }

        warn!("No CLOUD_ADDRESS specified, skipping the test");

        None
    }

    #[allow(non_snake_case)]
    #[ockam_macros::test]
    async fn forwarding__ephemeral_address__should_respond(ctx: &mut Context) -> Result<()> {
        let cloud_address;
        if let Some(c) = get_cloud_address() {
            cloud_address = c;
        } else {
            ctx.stop().await?;
            return Ok(());
        }

        ctx.start_worker("echoer", Echoer).await?;

        TcpTransport::create(&ctx).await?;

        let node_in_hub = (TCP, cloud_address);
        let remote_info = RemoteForwarder::create(ctx, node_in_hub.clone()).await?;

        let mut child_ctx = ctx.new_context(Address::random(0)).await?;

        child_ctx
            .send(
                route![node_in_hub, remote_info.remote_address(), "echoer"],
                "Hello".to_string(),
            )
            .await?;

        let resp = child_ctx.receive::<String>().await?.take().body();

        assert_eq!(resp, "Hello");

        ctx.stop().await
    }

    #[allow(non_snake_case)]
    #[ockam_macros::test]
    async fn forwarding__static_address__should_respond(ctx: &mut Context) -> Result<()> {
        let cloud_address;
        if let Some(c) = get_cloud_address() {
            cloud_address = c;
        } else {
            ctx.stop().await?;
            return Ok(());
        }

        ctx.start_worker("echoer", Echoer).await?;

        TcpTransport::create(&ctx).await?;

        let node_in_hub = (TCP, cloud_address);
        let _ = RemoteForwarder::create_static(ctx, node_in_hub.clone(), "alias").await?;

        let mut child_ctx = ctx.new_context(Address::random(0)).await?;

        child_ctx
            .send(
                route![node_in_hub, "forward_to_alias", "echoer"],
                "Hello".to_string(),
            )
            .await?;

        let resp = child_ctx.receive::<String>().await?.take().body();

        assert_eq!(resp, "Hello");

        ctx.stop().await
    }
}