aurelia 0.2.0

Embeddable service mesh for Rust distributed applications.
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
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
// This file is part of the Aurelia workspace.
// SPDX-FileCopyrightText: 2026 Zivatar Limited
// SPDX-License-Identifier: Apache-2.0

use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use bytes::Bytes;
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::time::timeout;

use super::{BlobManager, BlobReceiverState};
use crate::ids::PeerMessageId;
use crate::ids::{AureliaError, ErrorId};
use crate::peering::ring_buffer::{OutboundRingBuffer, TryPushAvailable};

pub(crate) struct BlobReceiverStream {
    blob: std::sync::Arc<BlobManager>,
    stream_id: PeerMessageId,
    receiver: std::sync::Arc<BlobReceiverState>,
    current: Option<Bytes>,
    offset: usize,
    pending: Option<Pin<Box<dyn Future<Output = ReadOutcome> + Send>>>,
    runtime_handle: tokio::runtime::Handle,
}

enum ReadOutcome {
    Chunk(Bytes),
    Eof,
    Error(AureliaError),
}

async fn try_receiver_read(
    blob: &BlobManager,
    receiver: &BlobReceiverState,
    stream_id: PeerMessageId,
) -> Option<ReadOutcome> {
    if let Some(err) = receiver.error.lock().await.clone() {
        return Some(ReadOutcome::Error(err));
    }
    let ring = blob.recv_ring(stream_id).await;
    if let Some(ring) = ring {
        if let Some(chunk) = ring.take_next().await {
            receiver.notify.notify_waiters();
            return Some(ReadOutcome::Chunk(chunk));
        }
        if receiver.completed.load(std::sync::atomic::Ordering::SeqCst) && ring.is_complete().await
        {
            let _ = blob.remove_recv_stream(stream_id).await;
            blob.note_recv_complete(stream_id, receiver.completion_ttl)
                .await;
            return Some(ReadOutcome::Eof);
        }
    } else {
        if let Some(err) = receiver.error.lock().await.clone() {
            return Some(ReadOutcome::Error(err));
        }
        if receiver.completed.load(std::sync::atomic::Ordering::SeqCst) {
            return Some(ReadOutcome::Eof);
        }
    }
    None
}

async fn fail_receiver_idle(
    blob: &BlobManager,
    receiver: &BlobReceiverState,
    stream_id: PeerMessageId,
) -> ReadOutcome {
    let err = AureliaError::new(ErrorId::BlobStreamIdleTimeout);
    receiver.fail(err.clone()).await;
    let _ = blob.remove_recv_stream(stream_id).await;
    ReadOutcome::Error(err)
}

impl BlobReceiverStream {
    pub(crate) fn new(
        blob: std::sync::Arc<BlobManager>,
        stream_id: PeerMessageId,
        receiver: std::sync::Arc<BlobReceiverState>,
        runtime_handle: tokio::runtime::Handle,
    ) -> Self {
        Self {
            blob,
            stream_id,
            receiver,
            current: None,
            offset: 0,
            pending: None,
            runtime_handle,
        }
    }

    fn start_read(&mut self) {
        let blob = std::sync::Arc::clone(&self.blob);
        let receiver = std::sync::Arc::clone(&self.receiver);
        let stream_id = self.stream_id;
        let idle_timeout = receiver.idle_timeout;
        self.pending = Some(Box::pin(async move {
            loop {
                if !receiver.accepted.load(std::sync::atomic::Ordering::SeqCst) {
                    let notified = receiver.notify.notified();
                    tokio::pin!(notified);
                    if receiver.accepted.load(std::sync::atomic::Ordering::SeqCst) {
                        continue;
                    }
                    if timeout(idle_timeout, &mut notified).await.is_err() {
                        return fail_receiver_idle(&blob, &receiver, stream_id).await;
                    }
                    continue;
                }

                if let Some(outcome) = try_receiver_read(&blob, &receiver, stream_id).await {
                    return outcome;
                }
                let notified = receiver.notify.notified();
                tokio::pin!(notified);
                if let Some(outcome) = try_receiver_read(&blob, &receiver, stream_id).await {
                    return outcome;
                }
                if timeout(idle_timeout, &mut notified).await.is_err() {
                    return fail_receiver_idle(&blob, &receiver, stream_id).await;
                }
            }
        }));
    }
}

impl AsyncRead for BlobReceiverStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        loop {
            if self.current.is_some() {
                let (to_copy, chunk_len) = {
                    let Some(chunk) = self.current.as_ref() else {
                        return Poll::Ready(Err(std::io::Error::other(
                            "blob receiver missing current chunk",
                        )));
                    };
                    let start = self.offset;
                    let end = (start + buf.remaining()).min(chunk.len());
                    let len = end.saturating_sub(start);
                    if len > 0 {
                        buf.put_slice(&chunk[start..end]);
                    }
                    (len, chunk.len())
                };
                self.offset = self.offset.saturating_add(to_copy);
                if self.offset >= chunk_len {
                    self.current = None;
                    self.offset = 0;
                }
                return Poll::Ready(Ok(()));
            }

            if self.pending.is_none() {
                self.start_read();
            }

            let Some(mut pending) = self.pending.take() else {
                return Poll::Ready(Err(std::io::Error::other(
                    "blob receiver missing read future",
                )));
            };
            match pending.as_mut().poll(cx) {
                Poll::Pending => {
                    self.pending = Some(pending);
                    return Poll::Pending;
                }
                Poll::Ready(outcome) => match outcome {
                    ReadOutcome::Chunk(chunk) => {
                        self.current = Some(chunk);
                    }
                    ReadOutcome::Eof => return Poll::Ready(Ok(())),
                    ReadOutcome::Error(err) => {
                        return Poll::Ready(Err(std::io::Error::other(err.to_string())))
                    }
                },
            }
        }
    }
}

impl Drop for BlobReceiverStream {
    fn drop(&mut self) {
        let blob = std::sync::Arc::clone(&self.blob);
        let receiver = std::sync::Arc::clone(&self.receiver);
        let stream_id = self.stream_id;
        let runtime_handle = self.runtime_handle.clone();
        runtime_handle.spawn(async move {
            if receiver.completed.load(std::sync::atomic::Ordering::SeqCst) {
                return;
            }
            let err = AureliaError::new(ErrorId::PeerUnavailable);
            let _ = blob.remove_recv_stream(stream_id).await;
            blob.drop_pending_request(stream_id).await;
            receiver.fail(err).await;
        });
    }
}

pub(crate) struct BlobSenderStream {
    state: std::sync::Arc<tokio::sync::Mutex<BlobSenderState>>,
    pending: Option<PendingOp>,
    runtime_handle: tokio::runtime::Handle,
}

struct BlobSenderState {
    blob: std::sync::Arc<BlobManager>,
    stream_id: PeerMessageId,
    ring: std::sync::Arc<OutboundRingBuffer>,
    send_timeout: Duration,
    closed: bool,
}

#[derive(Clone, Copy)]
enum PendingKind {
    Capacity,
    Flush,
    Shutdown,
}

struct PendingOp {
    kind: PendingKind,
    future: Pin<Box<dyn Future<Output = Result<(), AureliaError>> + Send>>,
}

impl BlobSenderStream {
    pub(crate) fn new(
        blob: std::sync::Arc<BlobManager>,
        stream_id: PeerMessageId,
        ring: std::sync::Arc<OutboundRingBuffer>,
        send_timeout: Duration,
        runtime_handle: tokio::runtime::Handle,
    ) -> Self {
        let state = BlobSenderState {
            blob,
            stream_id,
            ring,
            send_timeout,
            closed: false,
        };
        Self {
            state: std::sync::Arc::new(tokio::sync::Mutex::new(state)),
            pending: None,
            runtime_handle,
        }
    }

    fn start_capacity_wait(&mut self) {
        let state = std::sync::Arc::clone(&self.state);
        let future = async move {
            let state = state.lock().await;
            if state.closed {
                return Err(AureliaError::new(ErrorId::PeerUnavailable));
            }
            let deadline = tokio::time::Instant::now() + state.send_timeout;
            state.ring.wait_for_capacity(deadline).await
        };
        self.pending = Some(PendingOp {
            kind: PendingKind::Capacity,
            future: Box::pin(future),
        });
    }

    fn start_flush(&mut self) {
        let state = std::sync::Arc::clone(&self.state);
        let future = async move {
            let state = state.lock().await;
            if state.closed {
                return Ok(());
            }
            let deadline = tokio::time::Instant::now() + state.send_timeout;
            state.ring.wait_for_inflight_drain(deadline).await
        };
        self.pending = Some(PendingOp {
            kind: PendingKind::Flush,
            future: Box::pin(future),
        });
    }

    fn start_shutdown(&mut self) {
        let state = std::sync::Arc::clone(&self.state);
        let future = async move {
            let mut state = state.lock().await;
            if state.closed {
                return Ok(());
            }
            state.ring.seal(state.send_timeout).await?;
            state.blob.notify_work();

            let deadline = tokio::time::Instant::now() + state.send_timeout;
            if let Err(err) = state.ring.wait_for_complete(deadline).await {
                state.cleanup().await;
                return Err(err);
            }

            state.cleanup().await;
            Ok(())
        };
        self.pending = Some(PendingOp {
            kind: PendingKind::Shutdown,
            future: Box::pin(future),
        });
    }
}

impl BlobSenderState {
    async fn cleanup(&mut self) {
        if !self.closed {
            self.blob.unregister_outbound_stream(self.stream_id).await;
            self.closed = true;
        }
    }
}

impl AsyncWrite for BlobSenderStream {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        loop {
            if let Some(pending) = self.pending.as_mut() {
                match pending.future.as_mut().poll(cx) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(result) => {
                        let kind = pending.kind;
                        self.pending = None;
                        if let Err(err) = result {
                            return Poll::Ready(Err(std::io::Error::other(err.to_string())));
                        }
                        if let PendingKind::Capacity = kind {
                            continue;
                        }
                        continue;
                    }
                }
            }

            if buf.is_empty() {
                return Poll::Ready(Ok(0));
            }
            let state = match self.state.try_lock() {
                Ok(state) => state,
                Err(_) => {
                    cx.waker().wake_by_ref();
                    return Poll::Pending;
                }
            };
            if state.closed {
                return Poll::Ready(Err(std::io::Error::other(
                    AureliaError::new(ErrorId::PeerUnavailable).to_string(),
                )));
            }
            let blob = std::sync::Arc::clone(&state.blob);
            let result = state.ring.try_push_available(buf, || blob.notify_work());
            drop(state);
            match result {
                Ok(TryPushAvailable::Accepted { bytes }) => {
                    blob.notify_work();
                    return Poll::Ready(Ok(bytes));
                }
                Ok(TryPushAvailable::Full) => {
                    self.start_capacity_wait();
                }
                Ok(TryPushAvailable::Busy) => {
                    cx.waker().wake_by_ref();
                    return Poll::Pending;
                }
                Err(err) => return Poll::Ready(Err(std::io::Error::other(err.to_string()))),
            }
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        loop {
            if let Some(pending) = self.pending.as_mut() {
                match pending.future.as_mut().poll(cx) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(result) => {
                        let kind = pending.kind;
                        self.pending = None;
                        if let Err(err) = result {
                            return Poll::Ready(Err(std::io::Error::other(err.to_string())));
                        }
                        match kind {
                            PendingKind::Flush | PendingKind::Shutdown => {
                                return Poll::Ready(Ok(()));
                            }
                            PendingKind::Capacity => continue,
                        }
                    }
                }
            }
            self.start_flush();
        }
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
        loop {
            if let Some(pending) = self.pending.as_mut() {
                match pending.future.as_mut().poll(cx) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(result) => {
                        let kind = pending.kind;
                        self.pending = None;
                        if let Err(err) = result {
                            return Poll::Ready(Err(std::io::Error::other(err.to_string())));
                        }
                        if matches!(kind, PendingKind::Shutdown) {
                            return Poll::Ready(Ok(()));
                        }
                        continue;
                    }
                }
            }
            self.start_shutdown();
        }
    }
}

impl Drop for BlobSenderStream {
    fn drop(&mut self) {
        let state = std::sync::Arc::clone(&self.state);
        let runtime_handle = self.runtime_handle.clone();
        runtime_handle.spawn(async move {
            let mut state = state.lock().await;
            if state.closed {
                return;
            }
            state.cleanup().await;
        });
    }
}