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
use crate::prelude::*;
use holochain_tracing::Span;

//--------------------------------------------------------------------------------------------------
// GhostParentWrapper
//---------------------------------------------------------------------------------------------------

/// helper struct that merges (on the parent side) the actual child
/// GhostActor instance, with the child's ghost channel endpoint.
/// You only have to call process() on this one struct, and it provides
/// all the request / drain_messages etc functions from GhostEndpoint.
pub struct GhostParentWrapper<
    UserData,
    RequestToParent: 'static,
    RequestToParentResponse: 'static,
    RequestToChild: 'static,
    RequestToChildResponse: 'static,
    Error: 'static + std::fmt::Debug,
    Actor: GhostActor<
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
    >,
> {
    actor: Actor,
    endpoint: GhostContextEndpoint<
        UserData,
        RequestToChild,
        RequestToChildResponse,
        RequestToParent,
        RequestToParentResponse,
        Error,
    >,
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
        Actor: GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            Error,
        >,
    >
    GhostParentWrapper<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
        Actor,
    >
{
    /// wrap a GhostActor instance and it's parent channel endpoint.
    pub fn new(mut actor: Actor, request_id_prefix: &str) -> Self {
        let endpoint = actor
            .take_parent_endpoint()
            .expect("exists")
            .as_context_endpoint_builder()
            .request_id_prefix(request_id_prefix)
            .build();
        Self { actor, endpoint }
    }
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
        Actor: GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            Error,
        >,
    >
    GhostCanTrack<
        UserData,
        RequestToChild,
        RequestToChildResponse,
        RequestToParent,
        RequestToParentResponse,
        Error,
    >
    for GhostParentWrapper<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
        Actor,
    >
{
    /// see GhostContextEndpoint::publish
    fn publish(&mut self, span: Span, payload: RequestToChild) -> GhostResult<()> {
        self.endpoint.publish(span, payload)
    }

    /// see GhostContextEndpoint::request
    fn request(
        &mut self,
        span: Span,
        payload: RequestToChild,
        cb: GhostCallback<UserData, RequestToChildResponse, Error>,
    ) -> GhostResult<()> {
        self.endpoint.request(span, payload, cb)
    }

    /// see GhostContextEndpoint::request
    fn request_options(
        &mut self,
        span: Span,
        payload: RequestToChild,
        cb: GhostCallback<UserData, RequestToChildResponse, Error>,
        options: GhostTrackRequestOptions,
    ) -> GhostResult<()> {
        self.endpoint.request_options(span, payload, cb, options)
    }

    /// see GhostContextEndpoint::drain_messages
    fn drain_messages(
        &mut self,
    ) -> Vec<GhostMessage<RequestToParent, RequestToChild, RequestToParentResponse, Error>> {
        self.endpoint.drain_messages()
    }

    /// see GhostContextEndpoint::process and GhostActor::process
    fn process(&mut self, user_data: &mut UserData) -> GhostResult<WorkWasDone> {
        let work_was_done = self.actor.process()?;
        let _endpoint_did_work = self.endpoint.process(user_data)?;
        Ok(work_was_done)
    }
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
        Actor: GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            Error,
        >,
    > std::convert::AsRef<Actor>
    for GhostParentWrapper<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
        Actor,
    >
{
    fn as_ref(&self) -> &Actor {
        &self.actor
    }
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
        Actor: GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            Error,
        >,
    > std::convert::AsMut<Actor>
    for GhostParentWrapper<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
        Actor,
    >
{
    fn as_mut(&mut self) -> &mut Actor {
        &mut self.actor
    }
}

//--------------------------------------------------------------------------------------------------
// GhostActor
//---------------------------------------------------------------------------------------------------

pub trait GhostActor<
    RequestToParent: 'static,
    RequestToParentResponse: 'static,
    RequestToChild: 'static,
    RequestToChildResponse: 'static,
    Error: 'static + std::fmt::Debug,
>
{
    /// our parent gets a reference to the parent side of our channel
    fn take_parent_endpoint(
        &mut self,
    ) -> Option<
        GhostEndpoint<
            RequestToChild,
            RequestToChildResponse,
            RequestToParent,
            RequestToParentResponse,
            Error,
        >,
    >;

    /// our parent will call this process function
    fn process(&mut self) -> GhostResult<WorkWasDone> {
        // it would be awesome if this trait level could handle things like:
        //  `self.endpoint_self.process();`
        self.process_concrete()
    }

    /// we, as a ghost actor implement this, it will get called from
    /// process after the subconscious process items have run
    fn process_concrete(&mut self) -> GhostResult<WorkWasDone> {
        Ok(false.into())
    }
}

//--------------------------------------------------------------------------------------------------
// GhostParentWrapperDyn
//---------------------------------------------------------------------------------------------------

/// same as above, but takes a trait object child
pub struct GhostParentWrapperDyn<
    UserData,
    RequestToParent: 'static,
    RequestToParentResponse: 'static,
    RequestToChild: 'static,
    RequestToChildResponse: 'static,
    Error: 'static + std::fmt::Debug,
> {
    actor: Box<
        dyn GhostActor<
            RequestToParent,
            RequestToParentResponse,
            RequestToChild,
            RequestToChildResponse,
            Error,
        >,
    >,
    endpoint: GhostContextEndpoint<
        UserData,
        RequestToChild,
        RequestToChildResponse,
        RequestToParent,
        RequestToParentResponse,
        Error,
    >,
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
    >
    GhostParentWrapperDyn<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
    >
{
    /// wrap a GhostActor instance and it's parent channel endpoint.
    pub fn new(
        mut actor: Box<
            dyn GhostActor<
                RequestToParent,
                RequestToParentResponse,
                RequestToChild,
                RequestToChildResponse,
                Error,
            >,
        >,
        request_id_prefix: &str,
    ) -> Self {
        let endpoint: GhostContextEndpoint<UserData, _, _, _, _, _> = actor
            .take_parent_endpoint()
            .expect("exists")
            .as_context_endpoint_builder()
            .request_id_prefix(request_id_prefix)
            .build();
        Self { actor, endpoint }
    }
}

impl<
        UserData,
        RequestToParent: 'static,
        RequestToParentResponse: 'static,
        RequestToChild: 'static,
        RequestToChildResponse: 'static,
        Error: 'static + std::fmt::Debug,
    >
    GhostCanTrack<
        UserData,
        RequestToChild,
        RequestToChildResponse,
        RequestToParent,
        RequestToParentResponse,
        Error,
    >
    for GhostParentWrapperDyn<
        UserData,
        RequestToParent,
        RequestToParentResponse,
        RequestToChild,
        RequestToChildResponse,
        Error,
    >
{
    /// see GhostContextEndpoint::publish
    fn publish(&mut self, span: Span, payload: RequestToChild) -> GhostResult<()> {
        self.endpoint.publish(span, payload)
    }

    /// see GhostContextEndpoint::request
    fn request(
        &mut self,
        span: Span,
        payload: RequestToChild,
        cb: GhostCallback<UserData, RequestToChildResponse, Error>,
    ) -> GhostResult<()> {
        self.endpoint.request(span, payload, cb)
    }

    fn request_options(
        &mut self,
        span: Span,
        payload: RequestToChild,
        cb: GhostCallback<UserData, RequestToChildResponse, Error>,
        options: GhostTrackRequestOptions,
    ) -> GhostResult<()> {
        self.endpoint.request_options(span, payload, cb, options)
    }

    /// see GhostContextEndpoint::drain_messages
    fn drain_messages(
        &mut self,
    ) -> Vec<GhostMessage<RequestToParent, RequestToChild, RequestToParentResponse, Error>> {
        self.endpoint.drain_messages()
    }

    /// see GhostContextEndpoint::process and GhostActor::process
    fn process(&mut self, user_data: &mut UserData) -> GhostResult<WorkWasDone> {
        let mut work_was_done = self.actor.process()?;
        work_was_done = work_was_done.or(self.endpoint.process(user_data)?);
        Ok(work_was_done)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{ghost_channel::create_ghost_channel, ghost_tracker::GhostCallbackData};
    use detach::prelude::*;
    use holochain_tracing::test_span;
    //    use predicates::prelude::*;
    type TestError = String;

    // Any actor has messages that it exchanges with it's parent
    // These are the Out message, and it has messages that come internally
    // either self-generated or (presumeably) from children
    #[derive(Debug)]
    struct TestMsgOut(String);
    #[derive(Debug, PartialEq)]
    struct TestMsgOutResponse(String);
    #[derive(Debug)]
    struct TestMsgIn(String);
    #[derive(Debug, PartialEq, Clone)]
    struct TestMsgInResponse(String);

    struct TestActor {
        endpoint_for_parent: Option<
            GhostEndpoint<TestMsgIn, TestMsgInResponse, TestMsgOut, TestMsgOutResponse, TestError>,
        >,
        endpoint_as_child: Detach<
            GhostContextEndpoint<
                TestActor,
                TestMsgOut,
                TestMsgOutResponse,
                TestMsgIn,
                TestMsgInResponse,
                TestError,
            >,
        >,
        internal_state: Vec<String>,
    }

    impl TestActor {
        pub fn new() -> Self {
            let (endpoint_parent, endpoint_self) = create_ghost_channel();
            Self {
                endpoint_for_parent: Some(endpoint_parent),
                endpoint_as_child: Detach::new(
                    endpoint_self
                        .as_context_endpoint_builder()
                        .request_id_prefix("child")
                        .build(),
                ),
                internal_state: Vec::new(),
            }
        }
    }

    impl GhostActor<TestMsgOut, TestMsgOutResponse, TestMsgIn, TestMsgInResponse, TestError>
        for TestActor
    {
        // START BOILER PLATE--------------------------

        fn take_parent_endpoint(
            &mut self,
        ) -> Option<
            GhostEndpoint<TestMsgIn, TestMsgInResponse, TestMsgOut, TestMsgOutResponse, TestError>,
        > {
            std::mem::replace(&mut self.endpoint_for_parent, None)
        }
        // END BOILER PLATE--------------------------

        // for this test actor what we do
        fn process_concrete(&mut self) -> GhostResult<WorkWasDone> {
            println!("process_concrete!");
            // START BOILER PLATE--------------------------
            // always run the endpoint process loop
            detach_run!(&mut self.endpoint_as_child, |cs| cs.process(self))?;
            // END BOILER PLATE--------------------------

            // In this test actor we simply take all the messages we get and
            // add them to our internal state.
            let mut did_work = false;
            for mut msg in self.endpoint_as_child.as_mut().drain_messages() {
                println!("process_concrete, got msg");
                let payload = match msg.take_message().expect("exists") {
                    TestMsgIn(payload) => payload,
                };
                self.internal_state.push(payload.clone());
                if msg.is_request() {
                    msg.respond(Ok(TestMsgInResponse(format!("we got: {}", payload))))?;
                };
                did_work |= true;
            }
            Ok(did_work.into())
        }
    }

    struct FakeParent {
        state: String,
    }

    #[test]
    fn test_ghost_actor() {
        // The body of this test simulates being the parent actor
        let mut fake_parent = FakeParent {
            state: "".to_string(),
        };

        // then we create the child actor
        let mut child_actor = TestActor::new();
        // get the endpoint from the child actor that we as parent will interact with
        let mut parent_endpoint: GhostContextEndpoint<
            FakeParent,
            TestMsgIn,
            TestMsgInResponse,
            TestMsgOut,
            TestMsgOutResponse,
            TestError,
        > = child_actor
            .take_parent_endpoint()
            .unwrap()
            .as_context_endpoint_builder()
            .request_id_prefix("parent")
            .build();

        let span = test_span();

        // now lets post an event from the parent
        parent_endpoint
            .publish(span, TestMsgIn("event from parent".into()))
            .unwrap();

        // now process the events on the child and watch that internal state has chaned
        assert!(child_actor.process().is_ok());
        assert_eq!(
            "\"event from parent\"",
            format!("{:?}", child_actor.internal_state[0])
        );

        // now lets try posting a request with a callback which just saves the response
        // value to the parent's statee
        let cb: GhostCallback<FakeParent, TestMsgInResponse, TestError> =
            Box::new(|parent, callback_data| {
                if let GhostCallbackData::Response(Ok(TestMsgInResponse(payload))) = callback_data {
                    parent.state = payload;
                }
                Ok(())
            });

        parent_endpoint
            .request(test_span(), TestMsgIn("event from parent".into()), cb)
            .unwrap();
        assert!(child_actor.process().is_ok());
        assert!(parent_endpoint.process(&mut fake_parent).is_ok());
        assert_eq!("we got: event from parent", fake_parent.state);
    }

    #[test]
    fn test_ghost_actor_parent_wrapper() {
        // much of the previous test is the parent creating instances of the actor
        // and taking control of the parent endpoint.  Parent wrapper implements
        // much of this work as a convenience

        let mut fake_parent = FakeParent {
            state: "".to_string(),
        };

        // create the wrapper
        let mut wrapped_child: GhostParentWrapper<
            FakeParent,
            TestMsgOut,
            TestMsgOutResponse,
            TestMsgIn,
            TestMsgInResponse,
            TestError,
            TestActor,
        > = GhostParentWrapper::new(TestActor::new(), "parent");

        // use it to publish an event via the wrapper
        wrapped_child
            .publish(test_span(), TestMsgIn("event from parent".into()))
            .unwrap();

        // process via the wrapper
        assert!(wrapped_child.process(&mut fake_parent).is_ok());

        assert_eq!(
            "\"event from parent\"",
            format!("{:?}", wrapped_child.as_ref().internal_state[0])
        )
    }
}