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
//! Registration with Ockam Hub, and forwarding to local workers.
#![deny(missing_docs)]

use crate::{Context, Message, OckamError};
use core::time::Duration;
use ockam_core::compat::sync::Arc;
use ockam_core::compat::{
    boxed::Box,
    string::{String, ToString},
    vec::Vec,
};
use ockam_core::{
    Address, AllowAll, AllowSourceAddress, Any, Decodable, DenyAll, Mailbox, Mailboxes,
    OutgoingAccessControl, Result, Route, Routed, Worker,
};
use ockam_node::{DelayedEvent, WorkerBuilder};
use serde::{Deserialize, Serialize};
use tracing::{debug, info};

/// Information about a remotely forwarded worker.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, 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
    }
}

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

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

    /// Create and start static RemoteForwarder at predefined address with given Ockam Hub route
    pub async fn create_static(
        ctx: &Context,
        hub_route: impl Into<Route>,
        alias: impl Into<String>,
        outgoing_access_control: impl OutgoingAccessControl,
    ) -> Result<RemoteForwarderInfo> {
        let main_address = Address::random_tagged("RemoteForwarder.static.main");
        let heartbeat_address = Address::random_tagged("RemoteForwarder.static.heartbeat");

        let address = Address::random_tagged("RemoteForwarder.static.child");
        let mut child_ctx = ctx
            .new_detached_with_mailboxes(Mailboxes::main(
                address,
                Arc::new(AllowSourceAddress(main_address.clone())),
                Arc::new(DenyAll),
            ))
            .await?;

        let registration_route = hub_route
            .into()
            .modify()
            .append("static_forwarding_service")
            .into();

        let heartbeat = DelayedEvent::create(ctx, heartbeat_address.clone(), vec![]).await?;
        let heartbeat_source_address = heartbeat.address();
        let forwarder = Self::new(
            main_address.clone(),
            heartbeat_address.clone(),
            registration_route,
            alias.into(),
            child_ctx.address(),
            Some(heartbeat),
            Duration::from_secs(5),
        );

        debug!("Starting static RemoteForwarder at {}", &heartbeat_address);

        let mailboxes = Mailboxes::new(
            Mailbox::new(
                main_address,
                Arc::new(AllowAll), // Messages should have the same return_route, we check for that in `handle_message`
                Arc::new(outgoing_access_control),
            ),
            vec![Mailbox::new(
                heartbeat_address,
                Arc::new(AllowSourceAddress(heartbeat_source_address)),
                Arc::new(DenyAll),
            )],
        );
        WorkerBuilder::with_mailboxes(mailboxes, forwarder)
            .start(ctx)
            .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 route
    pub async fn create(
        ctx: &Context,
        hub_route: impl Into<Route>,
        outgoing_access_control: impl OutgoingAccessControl,
    ) -> Result<RemoteForwarderInfo> {
        let main_address = Address::random_tagged("RemoteForwarder.ephemeral.main");
        let heartbeat_address = Address::random_tagged("RemoteForwarder.ephemeral.heartbeat");
        let address = Address::random_tagged("RemoteForwarder.ephemeral.child");

        let mut child_ctx = ctx
            .new_detached_with_mailboxes(Mailboxes::main(
                address,
                Arc::new(AllowSourceAddress(main_address.clone())),
                Arc::new(DenyAll),
            ))
            .await?;

        let registration_route = hub_route
            .into()
            .modify()
            .append("forwarding_service")
            .into();

        let forwarder = Self::new(
            main_address.clone(),
            heartbeat_address.clone(),
            registration_route,
            "register".to_string(),
            child_ctx.address(),
            None,
            Duration::from_secs(10),
        );

        debug!("Starting ephemeral RemoteForwarder at {}", &main_address);
        // FIXME: @ac
        let mailboxes = Mailboxes::main(
            main_address,
            Arc::new(AllowAll), // Messages should have the same return_route, we check for that in `handle_message`
            Arc::new(outgoing_access_control),
        );
        WorkerBuilder::with_mailboxes(mailboxes, forwarder)
            .start(ctx)
            .await?;

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

        Ok(resp)
    }

    /// Create and start new static RemoteForwarder without heart beats
    // This is a temporary kind of RemoteForwarder that will only run on
    // rust nodes (hence the `forwarding_service` addr to create static forwarders).
    // We will use it while we don't have heartbeats implemented on rust nodes.
    pub async fn create_static_without_heartbeats(
        ctx: &Context,
        hub_route: impl Into<Route>,
        alias: impl Into<String>,
        outgoing_access_control: impl OutgoingAccessControl,
    ) -> Result<RemoteForwarderInfo> {
        let main_address = Address::random_tagged("RemoteForwarder.static_w/o_heartbeats.main");
        let heartbeat_address =
            Address::random_tagged("RemoteForwarder.static_w/o_heartbeats.heartbeat");
        let address = Address::random_tagged("RemoteForwarder.static_w/o_heartbeats.child");
        let mut child_ctx = ctx
            .new_detached_with_mailboxes(Mailboxes::main(
                address,
                Arc::new(AllowSourceAddress(main_address.clone())),
                Arc::new(DenyAll),
            ))
            .await?;

        let registration_route = hub_route
            .into()
            .modify()
            .append("forwarding_service")
            .into();

        let forwarder = Self::new(
            main_address.clone(),
            heartbeat_address.clone(),
            registration_route,
            alias.into(),
            child_ctx.address(),
            None,
            Duration::from_secs(10),
        );

        debug!(
            "Starting static RemoteForwarder without heartbeats at {}",
            &main_address
        );
        // FIXME: @ac
        let mailboxes = Mailboxes::new(
            Mailbox::new(
                main_address,
                Arc::new(AllowAll), // Messages should have the same return_route, we check for that in `handle_message`
                Arc::new(outgoing_access_control),
            ),
            vec![],
        );
        WorkerBuilder::with_mailboxes(mailboxes, forwarder)
            .start(ctx)
            .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.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.heartbeat_address {
            ctx.send_from_address(
                self.registration_route.clone(),
                self.registration_payload.clone(),
                self.main_address.clone(),
            )
            .await?;

            if let Some(heartbeat) = &mut self.heartbeat {
                heartbeat.schedule(self.heartbeat_interval).await?;
            }

            return Ok(());
        }

        // FIXME: @ac check that return address is the same
        // We are the final recipient of the message because it's registration response for our Worker
        if msg.onward_route().recipient()? == self.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 = match route.clone().recipient()?.to_string().strip_prefix("0#") {
                    Some(addr) => addr.to_string(),
                    None => return Err(OckamError::InvalidHubResponse.into()),
                };

                ctx.send_from_address(
                    callback_address,
                    RemoteForwarderInfo {
                        forwarding_route: route,
                        remote_address: address,
                        worker_address: ctx.address(),
                    },
                    self.main_address.clone(),
                )
                .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_from_address(message, self.main_address.clone())
                .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_core::route;
    use ockam_transport_tcp::TcpTransport;
    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() {
            c
        } else {
            ctx.stop().await?;
            return Ok(());
        };

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

        let tcp = TcpTransport::create(ctx).await?;
        let node_in_hub = tcp.connect(cloud_address).await?;

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

        let resp = ctx
            .send_and_receive::<_, _, String>(
                route![node_in_hub, remote_info.remote_address(), "echoer"],
                "Hello".to_string(),
            )
            .await?;

        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() {
            c
        } else {
            ctx.stop().await?;
            return Ok(());
        };

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

        let tcp = TcpTransport::create(ctx).await?;

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

        let resp = ctx
            .send_and_receive::<_, _, String>(
                route![node_in_hub, "forward_to_alias", "echoer"],
                "Hello".to_string(),
            )
            .await?;

        assert_eq!(resp, "Hello");

        ctx.stop().await
    }
}