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
use std::iter::Peekable;

use crate::{
    Message,
    system::SystemMsg,
    actor::{
        BasicActorRef, Sender,
        ActorReference
    },
    validate::{InvalidPath, validate_path}
};

/// A selection represents part of the actor heirarchy, allowing
/// messages to be sent to all actors in the selection.
/// 
/// There are several use cases where you would interact with actors
/// via a selection instead of actor references:
/// 
/// - You know the path of an actor but you don't have its `ActorRef`
/// - You want to broadcast a message to all actors within a path
/// 
/// `ActorRef` is almost always the better choice for actor interaction,
/// since messages are directly sent to the actor's mailbox without
/// any preprocessing or cloning.
/// 
/// `ActorSelection` provides flexibility for the cases where at runtime
/// the `ActorRef`s can't be known. This comes at the cost of traversing
/// part of the actor heirarchy and cloning messages.
/// 
/// A selection is anchored to an `ActorRef` and the path is relative
/// to that actor's path.
/// 
/// If a `selection.tell` results in the message being sent to zero actors,
/// the message is sent to dead letters.
#[derive(Debug)]
pub struct ActorSelection {
    anchor: BasicActorRef,
    // dl: BasicActorRef,
    path_vec: Vec<Selection>,
    path: String,
}

impl ActorSelection {
    pub fn new(anchor: BasicActorRef,
                // dl: &BasicActorRef,
                path: String) -> Result<ActorSelection, InvalidPath> {
        validate_path(&path)?;

        let path_vec: Vec<Selection> = path.split_terminator('/').map({|seg|
            match seg {
                ".." => Selection::SelectParent,
                "*" => Selection::SelectAllChildren,
                name => {
                    Selection::SelectChildName(name.to_string())
                }
            }
        }).collect();

        Ok(ActorSelection {
            anchor,
            // dl: dl.clone(),
            path_vec,
            path
        })
    }

    pub fn try_tell<Msg>(&self,
                msg: Msg,
                sender: impl Into<Option<BasicActorRef>>)
        where Msg: Message
    {
        fn walk<'a, I, Msg>(anchor: &BasicActorRef,
                            // dl: &BasicActorRef,
                            mut path_vec: Peekable<I>,
                            msg: Msg,
                            sender: &Sender,
                            path: &String)
            where I: Iterator<Item=&'a Selection>, Msg: Message
        {
            let seg = path_vec.next();

            match seg {
                Some(&Selection::SelectParent) => {
                    if path_vec.peek().is_none() {
                        let parent = anchor.parent();
                        let _ = parent.try_tell(msg, sender.clone());
                    } else {
                        walk(&anchor.parent(), path_vec, msg, sender, path);
                    }
                },
                Some(&Selection::SelectAllChildren) => {
                    for child in anchor.children() {
                        let _ = child.try_tell(msg.clone(), sender.clone());
                    }
                },
                Some(&Selection::SelectChildName(ref name)) => {
                    let child = anchor.children().filter({|c| c.name() == name}).last();
                    if path_vec.peek().is_none() && child.is_some() {
                        let _ = child.unwrap()
                            .try_tell(msg, sender.clone());
                    } else if path_vec.peek().is_some() && child.is_some() {
                        walk(&child.as_ref().unwrap(),
                            // dl,
                            path_vec,
                            msg,
                            sender,
                            path);
                    } else {
                        // todo send to deadletters?
                    }
                },
                None => {}
            }
        }

        walk(&self.anchor,
            // &self.dl,
            self.path_vec.iter().peekable(),
            msg,
            &sender.into(),
            &self.path);
    }

    pub fn sys_tell(&self,
                msg: SystemMsg,
                sender: impl Into<Option<BasicActorRef>>) {
        fn walk<'a, I>(anchor: &BasicActorRef,
                            // dl: &BasicActorRef,
                            mut path_vec: Peekable<I>,
                            msg: SystemMsg,
                            sender: &Sender,
                            path: &String)
            where I: Iterator<Item=&'a Selection>
        {
            let seg = path_vec.next();

            match seg {
                Some(&Selection::SelectParent) => {
                    if path_vec.peek().is_none() {
                        let parent = anchor.parent();
                        parent.sys_tell(msg);
                    } else {
                        walk(&anchor.parent(), path_vec, msg, sender, path);
                    }
                },
                Some(&Selection::SelectAllChildren) => {
                    for child in anchor.children() {
                        child.sys_tell(msg.clone());
                    }
                },
                Some(&Selection::SelectChildName(ref name)) => {
                    let child = anchor.children().filter({|c| c.name() == name}).last();
                    if path_vec.peek().is_none() && child.is_some() {
                        child.unwrap()
                            .sys_tell(msg);
                    } else if path_vec.peek().is_some() && child.is_some() {
                        walk(&child.as_ref().unwrap(),
                            // dl,
                            path_vec,
                            msg,
                            sender,
                            path);
                    } else {
                        // todo send to deadletters?
                    }
                },
                None => {}
            }
        }

        walk(&self.anchor,
            // &self.dl,
            self.path_vec.iter().peekable(),
            msg,
            &sender.into(),
            &self.path);
    }


}

#[derive(Debug)]
enum Selection {
    SelectParent,
    SelectChildName(String),
    SelectAllChildren,
}

pub trait ActorSelectionFactory {
    fn select(&self, path: &str) -> Result<ActorSelection, InvalidPath>;
}