acktor-ipc 1.0.3

Interprocess communication support for the acktor actor framework
Documentation
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
use std::fmt::{self, Debug};
use std::future;
use std::hash::Hash;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use futures_util::{FutureExt, TryFutureExt};
use tracing::Instrument;

use acktor::{
    Address, Message, Recipient, SendError, Sender, SenderId,
    address::{ClosedResultFuture, DoSendResult, DoSendResultFuture, SendResult, SendResultFuture},
    channel::oneshot,
};

use crate::codec::{Decode, DecodeContext, Encode, EncodeContext};
use crate::remote_actor::RemoteActorRegistry;
use crate::remote_message::RemoteMessage;
use crate::session::Session;

/// A type which is used to send messages to a remote actor.
///
/// [`Sender`] trait is implemented for this type, so it can be converted into a [`Recipient`]
/// type easily. This will allow us to store a remote address in the same place as a locals
/// address, and send messages with it without caring about the underlying transport details.
///
/// **NOTE**: user should not send a received [`RemoteAddress`] to another remote actor,
/// it is considered as a meaningless operation.
pub struct RemoteAddress {
    /// Computed once at construction, see [`RemoteAddress::new`].
    index: u64,
    /// Index of the corresponding actor in the remote node.
    remote_actor_id: u64,
    /// Address of the IPC connection session actor, used to send encoded messages to the remote
    /// actor.
    session: Address<Session>,
    /// Pre-built encode context reused for every outbound message through this address.
    encode_context: EncodeContext,
}

impl Debug for RemoteAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("RemoteAddress")
            .field(&self.session.index())
            .field(&self.remote_actor_id)
            .finish()
    }
}

impl Clone for RemoteAddress {
    #[inline]
    fn clone(&self) -> Self {
        Self {
            index: self.index,
            remote_actor_id: self.remote_actor_id,
            session: self.session.clone(),
            encode_context: self.encode_context.clone(),
        }
    }
}

impl PartialEq for RemoteAddress {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.remote_actor_id == other.remote_actor_id
            && self.session.index() == other.session.index()
    }
}

impl Eq for RemoteAddress {}

impl Hash for RemoteAddress {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.index.hash(state)
    }
}

impl RemoteAddress {
    /// High bit of the 64-bit id space, reserved to tag a [`SenderId::index`] value as
    /// remote address.
    pub const REMOTE_FLAG: u64 = 1 << 63;

    /// Constructs a new [`RemoteAddress`] with the specified remote actor index and the address
    /// of the IPC connection session actor. The `registry` is used to construct the encode
    /// context for this address.
    ///
    /// The `index` is computed by reversing the bits of `session.index()` into bits 0..62 (small
    /// session ids occupy the high bits, growing downward) and XORing with `remote_actor_id`
    /// (small ids occupy the low bits, growing upward). Bit 63 is reserved for
    /// [`REMOTE_FLAG`][Self::REMOTE_FLAG].
    ///
    /// The collision of the `index` is structurally possible but extremely unlikely in practice
    /// since it requires `remote_actor_id * session.index() > 2^63`.
    pub fn new(
        remote_actor_id: u64,
        session: Address<Session>,
        registry: RemoteActorRegistry,
    ) -> Self {
        let index = Self::REMOTE_FLAG | ((session.index().reverse_bits() >> 1) ^ remote_actor_id);
        Self {
            index,
            remote_actor_id,
            session,
            encode_context: EncodeContext::new(registry),
        }
    }

    fn decode_context(&self) -> DecodeContext {
        self.encode_context
            .create_decode_context(self.session.clone())
    }

    /// Completes when the session has been closed.
    pub fn closed(&self) -> impl Future<Output = ()> + Send {
        self.session.closed()
    }

    /// Checks if the session has been closed.
    pub fn is_closed(&self) -> bool {
        self.session.is_closed()
    }

    /// Returns the capacity of the session.
    pub fn capacity(&self) -> usize {
        self.session.capacity()
    }
}

async fn decode_and_forward<M>(
    raw_rx: oneshot::Receiver<Bytes>,
    mut tx: oneshot::Sender<M::Result>,
    decode_context: DecodeContext,
) where
    M: Message + Encode,
    M::Result: Decode,
{
    let decode_result = tokio::select! {
        result = raw_rx => match result {
            Ok(bytes) => M::Result::decode(bytes, Some(&decode_context)),
            Err(e) => {
                let _ = tx.send_err(e);
                return;
            }
        },
        // if the sender dropped the response rx, we can stop this task early
        _ = tx.closed() => return,
    };

    match decode_result {
        Ok(result) => {
            let _ = tx.send(result);
        }
        Err(e) => {
            let _ = tx.send_err(e);
        }
    }
}

impl SenderId for RemoteAddress {
    #[inline]
    fn index(&self) -> u64 {
        self.index
    }
}

impl<M> Sender<M> for RemoteAddress
where
    M: Message + Encode,
    M::Result: Decode,
{
    fn closed(&self) -> ClosedResultFuture<'_> {
        self.closed().boxed()
    }

    fn is_closed(&self) -> bool {
        self.is_closed()
    }

    fn capacity(&self) -> usize {
        self.capacity()
    }

    fn send(&self, msg: M) -> SendResultFuture<'_, M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return future::ready(Err(SendError::other(e, msg))).boxed(),
        };

        let (raw_tx, raw_rx) = oneshot::channel::<Bytes>();
        let (tx, rx) = oneshot::channel::<M::Result>();

        let decode_context = self.decode_context();

        tokio::spawn(
            async move {
                decode_and_forward::<M>(raw_rx, tx, decode_context).await;
            }
            .in_current_span(),
        );

        // this future will be resolved to Ok once the message is in the session actor's mailbox,
        // it does not guarantee the message arrives at the remote peer actor, the IPC
        // communication may fail
        self.session
            .do_send(RemoteMessage::send(
                self.remote_actor_id,
                <M as Encode>::ID,
                message_bytes,
                raw_tx,
            ))
            // error return by the sender, which means the session actor's mailbox is closed
            // before receiving the message
            .map(|result| match result {
                Ok(_) => Ok(rx),
                Err(_) => Err(SendError::Closed(msg)),
            })
            .boxed()
    }

    fn do_send(&self, msg: M) -> DoSendResultFuture<'_, M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return future::ready(Err(SendError::other(e, msg))).boxed(),
        };

        // this future will be resolved to Ok once the message is in the session actor's mailbox,
        // it does not guarantee the message arrives at the remote peer actor, the IPC
        // communication may fail
        self.session
            .do_send(RemoteMessage::do_send(
                self.remote_actor_id,
                <M as Encode>::ID,
                message_bytes,
            ))
            // error return by the sender, which means the session actor's mailbox is closed
            // before receiving the message
            .map_err(|_| SendError::Closed(msg))
            .boxed()
    }

    fn try_send(&self, msg: M) -> SendResult<M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return Err(SendError::other(e, msg)),
        };

        let (raw_tx, raw_rx) = oneshot::channel::<Bytes>();
        let (tx, rx) = oneshot::channel::<M::Result>();

        let decode_context = self.decode_context();

        tokio::spawn(
            async move {
                decode_and_forward::<M>(raw_rx, tx, decode_context).await;
            }
            .in_current_span(),
        );

        match self.session.try_do_send(RemoteMessage::send(
            self.remote_actor_id,
            <M as Encode>::ID,
            message_bytes,
            raw_tx,
        )) {
            Ok(_) => Ok(rx),
            Err(e) => match e {
                SendError::Full(_) => Err(SendError::Full(msg)),
                _ => Err(SendError::Closed(msg)),
            },
        }
    }

    fn try_do_send(&self, msg: M) -> DoSendResult<M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return Err(SendError::other(e, msg)),
        };

        self.session
            .try_do_send(RemoteMessage::do_send(
                self.remote_actor_id,
                <M as Encode>::ID,
                message_bytes,
            ))
            .map_err(|e| match e {
                SendError::Full(_) => SendError::Full(msg),
                _ => SendError::Closed(msg),
            })
    }

    fn send_timeout(&self, msg: M, timeout: Duration) -> SendResultFuture<'_, M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return future::ready(Err(SendError::other(e, msg))).boxed(),
        };

        let (raw_tx, raw_rx) = oneshot::channel::<Bytes>();
        let (tx, rx) = oneshot::channel::<M::Result>();

        let decode_context = self.decode_context();

        tokio::spawn(
            async move {
                decode_and_forward::<M>(raw_rx, tx, decode_context).await;
            }
            .in_current_span(),
        );

        // this future will be resolved to Ok once the message is in the session actor's mailbox,
        // it does not guarantee the message arrives at the remote peer actor, the IPC
        // communication may fail
        self.session
            .do_send_timeout(
                RemoteMessage::send(
                    self.remote_actor_id,
                    <M as Encode>::ID,
                    message_bytes,
                    raw_tx,
                ),
                timeout,
            )
            // error return by the sender, which means the session actor's mailbox is closed
            // before receiving the message
            .map(|result| match result {
                Ok(_) => Ok(rx),
                Err(_) => Err(SendError::Closed(msg)),
            })
            .boxed()
    }

    fn do_send_timeout(&self, msg: M, timeout: Duration) -> DoSendResultFuture<'_, M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return future::ready(Err(SendError::other(e, msg))).boxed(),
        };

        // this future will be resolved to Ok once the message is in the session actor's mailbox,
        // it does not guarantee the message arrives at the remote peer actor, the IPC
        // communication may fail
        self.session
            .do_send_timeout(
                RemoteMessage::do_send(self.remote_actor_id, <M as Encode>::ID, message_bytes),
                timeout,
            )
            // error return by the sender, which means the session actor's mailbox is closed
            // before receiving the message
            .map_err(|_| SendError::Closed(msg))
            .boxed()
    }

    fn blocking_send(&self, msg: M) -> SendResult<M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return Err(SendError::other(e, msg)),
        };

        let (raw_tx, raw_rx) = oneshot::channel::<Bytes>();
        let (tx, rx) = oneshot::channel::<M::Result>();

        let decode_context = self.decode_context();

        tokio::spawn(
            async move {
                decode_and_forward::<M>(raw_rx, tx, decode_context).await;
            }
            .in_current_span(),
        );

        match self.session.blocking_do_send(RemoteMessage::send(
            self.remote_actor_id,
            <M as Encode>::ID,
            message_bytes,
            raw_tx,
        )) {
            Ok(_) => Ok(rx),
            Err(_) => Err(SendError::Closed(msg)),
        }
    }

    fn blocking_do_send(&self, msg: M) -> DoSendResult<M> {
        let message_bytes = match msg.encode_to_bytes(Some(&self.encode_context)) {
            Ok(bytes) => bytes,
            Err(e) => return Err(SendError::other(e, msg)),
        };

        self.session
            .blocking_do_send(RemoteMessage::do_send(
                self.remote_actor_id,
                <M as Encode>::ID,
                message_bytes,
            ))
            .map_err(|_| SendError::Closed(msg))
    }
}

impl<M> From<RemoteAddress> for Recipient<M>
where
    M: Message + Encode,
    M::Result: Decode,
{
    fn from(address: RemoteAddress) -> Self {
        Recipient::new(Arc::new(address))
    }
}