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
extern crate backtrace;
extern crate crossbeam_channel;
#[allow(unused_imports)]
#[macro_use]
extern crate detach;
extern crate holochain_tracing;
#[macro_use]
extern crate lazy_static;
extern crate lock_api;
extern crate nanoid;
extern crate parking_lot;
#[macro_use]
extern crate shrinkwraprs;

#[macro_use]
extern crate log;

mod ghost_mutex;
pub use ghost_mutex::*;

#[macro_use]
pub mod ghost_test_harness;

mod backtwrap;
pub use backtwrap::{Backtwrap, BacktwrapCaptureStrategy};

#[derive(Shrinkwrap, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[shrinkwrap(mutable)]
pub struct WorkWasDone(pub bool);

impl From<bool> for WorkWasDone {
    fn from(b: bool) -> Self {
        WorkWasDone(b)
    }
}

impl From<WorkWasDone> for bool {
    fn from(d: WorkWasDone) -> Self {
        d.0
    }
}

impl WorkWasDone {
    pub fn or(&self, w: WorkWasDone) -> WorkWasDone {
        WorkWasDone(w.0 || self.0)
    }
}

#[derive(Shrinkwrap, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[shrinkwrap(mutable)]
pub struct RequestId(pub String);

impl RequestId {
    pub fn new() -> Self {
        Self::with_prefix("")
    }

    pub fn with_prefix(prefix: &str) -> Self {
        Self(format!("{}{}", prefix, nanoid::simple()))
    }
}

impl From<String> for RequestId {
    fn from(s: String) -> Self {
        RequestId(s)
    }
}

impl From<RequestId> for String {
    fn from(r: RequestId) -> Self {
        r.0
    }
}

mod ghost_error;
pub use ghost_error::{ErrorKind, GhostError, GhostResult};

mod ghost_tracker;
pub use ghost_tracker::{
    GhostCallback, GhostCallbackData, GhostTracker, GhostTrackerBookmarkOptions,
    GhostTrackerBuilder,
};

mod ghost_channel;
pub use ghost_channel::{
    create_ghost_channel, GhostCanTrack, GhostContextEndpoint, GhostEndpoint, GhostMessage,
    GhostTrackRequestOptions,
};

mod ghost_actor;
pub use ghost_actor::{GhostActor, GhostParentWrapper, GhostParentWrapperDyn};

pub mod prelude {
    pub use super::{
        create_ghost_channel, ghost_error::ErrorKind, GhostActor, GhostCallback, GhostCallbackData,
        GhostCanTrack, GhostContextEndpoint, GhostEndpoint, GhostError, GhostMessage, GhostMutex,
        GhostMutexGuard, GhostParentWrapper, GhostParentWrapperDyn, GhostResult,
        GhostTrackRequestOptions, GhostTracker, GhostTrackerBookmarkOptions, WorkWasDone,
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use detach::prelude::*;
    use holochain_tracing::test_span;

    type FakeError = String;

    #[allow(dead_code)]
    mod dht_protocol {
        #[derive(Debug)]
        pub enum RequestToChild {
            ResolveAddressForId { id: String },
        }

        #[derive(Debug)]
        pub struct ResolveAddressForIdData {
            pub address: String,
        }

        #[derive(Debug)]
        pub enum RequestToChildResponse {
            ResolveAddressForId(ResolveAddressForIdData),
        }

        #[derive(Debug)]
        pub enum RequestToParent {}

        #[derive(Debug)]
        pub enum RequestToParentResponse {}
    }

    struct RrDht {
        endpoint_parent: Option<
            GhostEndpoint<
                dht_protocol::RequestToChild,
                dht_protocol::RequestToChildResponse,
                dht_protocol::RequestToParent,
                dht_protocol::RequestToParentResponse,
                FakeError,
            >,
        >,
        endpoint_self: Detach<
            GhostContextEndpoint<
                RrDht,
                dht_protocol::RequestToParent,
                dht_protocol::RequestToParentResponse,
                dht_protocol::RequestToChild,
                dht_protocol::RequestToChildResponse,
                FakeError,
            >,
        >,
    }

    impl RrDht {
        pub fn new() -> Self {
            let (endpoint_parent, endpoint_self) = create_ghost_channel();
            Self {
                endpoint_parent: Some(endpoint_parent),
                endpoint_self: Detach::new(
                    endpoint_self
                        .as_context_endpoint_builder()
                        .request_id_prefix("dht_to_parent")
                        .build(),
                ),
            }
        }
    }

    impl
        GhostActor<
            dht_protocol::RequestToParent,
            dht_protocol::RequestToParentResponse,
            dht_protocol::RequestToChild,
            dht_protocol::RequestToChildResponse,
            FakeError,
        > for RrDht
    {
        fn take_parent_endpoint(
            &mut self,
        ) -> Option<
            GhostEndpoint<
                dht_protocol::RequestToChild,
                dht_protocol::RequestToChildResponse,
                dht_protocol::RequestToParent,
                dht_protocol::RequestToParentResponse,
                FakeError,
            >,
        > {
            std::mem::replace(&mut self.endpoint_parent, None)
        }

        fn process_concrete(&mut self) -> GhostResult<WorkWasDone> {
            detach_run!(&mut self.endpoint_self, |cs| cs.process(self))?;

            for mut msg in self.endpoint_self.as_mut().drain_messages() {
                match msg.take_message().expect("exists") {
                    dht_protocol::RequestToChild::ResolveAddressForId { id } => {
                        println!("dht got ResolveAddressForId {}", id);
                        msg.respond(Ok(
                            dht_protocol::RequestToChildResponse::ResolveAddressForId(
                                dht_protocol::ResolveAddressForIdData {
                                    address: "wss://yada".to_string(),
                                },
                            ),
                        ))?;
                    }
                }
            }

            Ok(false.into())
        }
    }

    type Url = String;
    type TransportError = String;

    #[allow(dead_code)]
    mod transport_protocol {
        use super::*;

        #[derive(Debug)]
        pub enum RequestToChild {
            Bind { spec: Url }, // wss://0.0.0.0:0 -> all network interfaces first available port
            Bootstrap { address: Url },
            SendMessage { address: Url, payload: Vec<u8> },
        }

        #[derive(Debug)]
        pub struct BindResultData {
            pub bound_url: String,
        }

        #[derive(Debug)]
        pub enum RequestToChildResponse {
            Bind(BindResultData),
            Bootstrap,
            SendMessage,
        }

        #[derive(Debug)]
        pub enum RequestToParent {
            IncomingConnection { address: Url },
            ReceivedData { adress: Url, payload: Vec<u8> },
            TransportError { error: TransportError },
        }

        #[derive(Debug)]
        pub enum RequestToParentResponse {
            Allowed,    // just for testing
            Disallowed, // just for testing
        }
    }

    use transport_protocol::*;

    struct GatewayTransport {
        endpoint_parent: Option<
            GhostEndpoint<
                RequestToChild,
                RequestToChildResponse,
                RequestToParent,
                RequestToParentResponse,
                FakeError,
            >,
        >,
        endpoint_self: Detach<
            GhostContextEndpoint<
                GatewayTransport,
                RequestToParent,
                RequestToParentResponse,
                RequestToChild,
                RequestToChildResponse,
                FakeError,
            >,
        >,
        dht: Detach<
            GhostParentWrapper<
                GatewayTransport,
                dht_protocol::RequestToParent,
                dht_protocol::RequestToParentResponse,
                dht_protocol::RequestToChild,
                dht_protocol::RequestToChildResponse,
                FakeError,
                RrDht,
            >,
        >,
    }

    impl GatewayTransport {
        pub fn new() -> Self {
            let (endpoint_parent, endpoint_self) = create_ghost_channel();
            let dht = Detach::new(GhostParentWrapper::new(RrDht::new(), "to_dht"));
            Self {
                endpoint_parent: Some(endpoint_parent),
                endpoint_self: Detach::new(
                    endpoint_self
                        .as_context_endpoint_builder()
                        .request_id_prefix("gw_to_parent")
                        .build(),
                ),
                dht,
            }
        }
    }

    impl
        GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            String,
        > for GatewayTransport
    {
        fn take_parent_endpoint(
            &mut self,
        ) -> Option<
            GhostEndpoint<
                RequestToChild,
                RequestToChildResponse,
                RequestToParent,
                RequestToParentResponse,
                FakeError,
            >,
        > {
            std::mem::replace(&mut self.endpoint_parent, None)
        }

        #[allow(irrefutable_let_patterns)]
        fn process_concrete(&mut self) -> GhostResult<WorkWasDone> {
            self.endpoint_self.as_mut().request(
                test_span(),
                RequestToParent::IncomingConnection {
                    address: "test".to_string(),
                },
                Box::new(|_m: &mut GatewayTransport, r| {
                    println!("response from parent to IncomingConnection got: {:?}", r);
                    Ok(())
                }),
            )?;
            detach_run!(&mut self.dht, |dht| dht.process(self))?;
            detach_run!(&mut self.endpoint_self, |endpoint_self| endpoint_self
                .process(self))?;

            for mut msg in self.endpoint_self.as_mut().drain_messages() {
                match msg.take_message().expect("exists") {
                    RequestToChild::Bind { spec: _ } => {
                        // do some internal bind
                        // we get a bound_url
                        let bound_url = "bound_url".to_string();
                        // respond to our parent
                        msg.respond(Ok(RequestToChildResponse::Bind(BindResultData {
                            bound_url: bound_url,
                        })))?;
                    }
                    RequestToChild::Bootstrap { address: _ } => {}
                    RequestToChild::SendMessage {
                        address,
                        payload: _,
                    } => {
                        // let _request = GwDht::ResolveAddressForId { msg };
                        self.dht.as_mut().request(
                            test_span(),
                            dht_protocol::RequestToChild::ResolveAddressForId { id: address },
                            Box::new(move |_m:&mut GatewayTransport, response| {

                                // got a timeout error
                                if let GhostCallbackData::Timeout(_) = response {
                                    msg.respond(Err("Timeout".into()))?;
                                    return Ok(());
                                }

                                let response = {
                                    if let GhostCallbackData::Response(response) = response {
                                        response
                                    } else {
                                        unimplemented!();
                                    }
                                };

                                let response = match response {
                                    Err(e) => {
                                        msg.respond(Err(e))?;
                                        return Ok(());
                                    }
                                    Ok(response) => response,
                                };

                                let response = {
                                    if let dht_protocol::RequestToChildResponse::ResolveAddressForId(
                                        response,
                                    ) = response
                                    {
                                        response
                                    } else {
                                        panic!("aaah");
                                    }
                                };

                                println!("yay? {:?}", response);

                                msg.respond(Ok(RequestToChildResponse::SendMessage))?;

                                Ok(())
                            }),
                        )?;
                    }
                }
            }
            Ok(true.into())
        }
    }

    type TransportActor = Box<
        dyn GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            String,
        >,
    >;

    #[test]
    fn test_ghost_example_transport() {
        // the body of this test simulates an object that contains a actor, i.e. a parent.
        // it would usually just be another ghost_actor but here we test it out explicitly
        // so first instantiate the "child" actor

        let gw = GatewayTransport::new();

        let mut t_actor: TransportActor = Box::new(gw);
        let mut t_actor_endpoint = t_actor
            .take_parent_endpoint()
            .expect("exists")
            .as_context_endpoint_builder()
            .build::<()>();

        // allow the actor to run this actor always creates a simulated incoming
        // connection each time it processes
        t_actor.process().unwrap();

        let _ = t_actor_endpoint.process(&mut ());

        // now process any requests the actor may have made of us (as parent)
        for mut msg in t_actor_endpoint.drain_messages() {
            let payload = msg.take_message();
            println!("in drain_messages got: {:?}", payload);

            // we might allow or disallow connections for example
            let response = RequestToParentResponse::Allowed;
            msg.respond(Ok(response)).unwrap();
        }

        t_actor.process().unwrap();
        let _ = t_actor_endpoint.process(&mut ());

        // now make a request of the child,
        // to make such a request the parent would normally will also instantiate trackers so that it can
        // handle responses when they come back as callbacks.
        // here we simply watch that we got a response back as expected
        t_actor_endpoint
            .request(
                test_span(),
                RequestToChild::Bind {
                    spec: "address_to_bind_to".to_string(),
                },
                Box::new(|_: &mut (), r| {
                    println!("in callback 1, got: {:?}", r);
                    Ok(())
                }),
            )
            .unwrap();

        t_actor.process().unwrap();
        let _ = t_actor_endpoint.process(&mut ());

        t_actor_endpoint
            .request(
                test_span(),
                RequestToChild::SendMessage {
                    address: "agentId:agent_id_1".to_string(),
                    payload: b"some content".to_vec(),
                },
                Box::new(|_: &mut (), r| {
                    println!("in callback 2, got: {:?}", r);
                    Ok(())
                }),
            )
            .unwrap();

        for _x in 0..10 {
            t_actor.process().unwrap();
            let _ = t_actor_endpoint.process(&mut ());
        }
    }
}