fidl_next_protocol/endpoints/
connection.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use core::future::Future;
6use core::mem::{ManuallyDrop, MaybeUninit, replace, take};
7use core::pin::Pin;
8use core::task::{Context, Poll, Waker};
9
10use fidl_next_codec::EncodeError;
11
12use crate::concurrency::cell::UnsafeCell;
13use crate::concurrency::future::AtomicWaker;
14use crate::concurrency::hint::unreachable_unchecked;
15use crate::concurrency::sync::Mutex;
16use crate::concurrency::sync::atomic::{AtomicUsize, Ordering};
17
18use crate::{NonBlockingTransport, ProtocolError, Transport, encode_epitaph, encode_header};
19
20pub const ORDINAL_EPITAPH: u64 = 0xffff_ffff_ffff_ffff;
21
22// Indicates that the connection has been requested to stop. Connections are
23// always stopped as they are terminated.
24const STOPPING_BIT: usize = 1 << 0;
25// Indicates that the connection has been provided a termination reason.
26const TERMINATED_BIT: usize = 1 << 1;
27const BITS_COUNT: usize = 2;
28
29// Each refcount represents a thread which is attempting to access the shared
30// part of the transport.
31const REFCOUNT: usize = 1 << BITS_COUNT;
32
33#[derive(Clone, Copy)]
34struct State(usize);
35
36impl State {
37    fn is_stopping(self) -> bool {
38        self.0 & STOPPING_BIT != 0
39    }
40
41    fn is_terminated(self) -> bool {
42        self.0 & TERMINATED_BIT != 0
43    }
44
45    fn refcount(self) -> usize {
46        self.0 >> BITS_COUNT
47    }
48}
49
50/// A wrapper around a transport which connectivity semantics.
51///
52/// The [`Transport`] trait only provides the bare minimum API surface required
53/// to send and receive data. On top of that, FIDL requires that clients and
54/// servers respect additional messaging semantics. Those semantics are provided
55/// by [`Connection`]:
56///
57/// - `Transport`s are difficult to close because they may be accessed from
58///   several threads simultaneously. `Connection`s provide a mechanism for
59///   gracefully closing transports by causing all sends to pend until the
60///   connection is terminated, and all receives to fail instead of pend.
61/// - FIDL connections may send and receive an epitaph as the final message
62///   before the underlying transport is closed. This epitaph should be provided
63///   to all sends when they fail, which requires additional coordination.
64pub struct Connection<T: Transport> {
65    // The lowest `BITS_COUNT` of this field contain flags indicating the
66    // current state of the transport. The remainder of the upper bits contain
67    // the number of threads attempting to access the `shared` field.
68    state: AtomicUsize,
69    // A thread will drop `shared` if:
70    //
71    // - the connection is dropped before being terminated, or
72    // - it set `TERMINATED_BIT` while the refcount was 0, or
73    // - it decremented the refcount to 0 while `TERMINATED_BIT` was set.
74    //
75    // These cases are handled by `drop`, `terminate`, and `with_shared`
76    // respectively.
77    shared: UnsafeCell<ManuallyDrop<T::Shared>>,
78    stop_waker: AtomicWaker,
79    // TODO: switch this to intrusive linked list in send futures
80    termination_wakers: Mutex<Vec<Waker>>,
81    // Initialized if `TERMINATED_BIT` is set.
82    termination_reason: UnsafeCell<MaybeUninit<ProtocolError<T::Error>>>,
83}
84
85unsafe impl<T: Transport> Send for Connection<T> {}
86unsafe impl<T: Transport> Sync for Connection<T> {}
87
88impl<T: Transport> Drop for Connection<T> {
89    fn drop(&mut self) {
90        self.state.with_mut(|state| {
91            let state = State(*state);
92
93            if !state.is_terminated() {
94                self.shared.with_mut(|shared| {
95                    // SAFETY: The connection was not terminated before being
96                    // dropped, so `shared` has not yet been dropped.
97                    unsafe {
98                        ManuallyDrop::drop(&mut *shared);
99                    }
100                });
101            } else {
102                self.termination_reason.with_mut(|termination_reason| {
103                    // SAFETY: The connection was terminated before being
104                    // dropped, so `termination_reason` is initialized.
105                    unsafe {
106                        MaybeUninit::assume_init_drop(&mut *termination_reason);
107                    }
108                });
109            }
110        });
111    }
112}
113
114impl<T: Transport> Connection<T> {
115    /// Creates a new connection from the shared part of a transport.
116    pub fn new(shared: T::Shared) -> Self {
117        Self {
118            state: AtomicUsize::new(0),
119            shared: UnsafeCell::new(ManuallyDrop::new(shared)),
120            stop_waker: AtomicWaker::new(),
121            termination_wakers: Mutex::new(Vec::new()),
122            termination_reason: UnsafeCell::new(MaybeUninit::uninit()),
123        }
124    }
125
126    /// # Safety
127    ///
128    /// This thread must have loaded `state` with at least `Ordering::Acquire`
129    /// and observed that `TERMINATED_BIT` was set.
130    unsafe fn get_termination_reason_unchecked(&self) -> ProtocolError<T::Error> {
131        self.termination_reason.with(|termination_reason| {
132            // SAFETY: The caller guaranteed that `state` was loaded with at
133            // least `Ordering::Acquire` ordering and observed that
134            // `TERMINATED_BIT` was set.
135            unsafe { MaybeUninit::assume_init_ref(&*termination_reason).clone() }
136        })
137    }
138
139    /// Returns the termination reason for the connection, if any.
140    pub fn get_termination_reason(&self) -> Option<ProtocolError<T::Error>> {
141        if State(self.state.load(Ordering::Acquire)).is_terminated() {
142            // SAFETY: We loaded the state with `Ordering::Acquire` and observed
143            // that `TERMINATED_BIT` was set.
144            unsafe { Some(self.get_termination_reason_unchecked()) }
145        } else {
146            None
147        }
148    }
149
150    /// # Safety
151    ///
152    /// `shared` must not have been dropped. See the documentation on `shared`
153    /// for acceptable criteria.
154    unsafe fn get_shared_unchecked(&self) -> &T::Shared {
155        self.shared.with(|shared| {
156            // SAFETY: The caller guaranteed that `shared` has not been dropped.
157            unsafe { &*shared }
158        })
159    }
160
161    fn with_shared<U>(
162        &self,
163        success: impl FnOnce(&T::Shared) -> U,
164        failure: impl FnOnce(Option<ProtocolError<T::Error>>) -> U,
165    ) -> U {
166        let pre_increment = State(self.state.fetch_add(REFCOUNT, Ordering::Acquire));
167
168        // After the refcount drops to zero (and `shared` is dropped), threads
169        // may still increment and decrement the refcount to attempt to read it.
170        // To avoid dropping `shared` more than once, we prevent the refcount
171        // from being decremented to 0 more than once after `TERMINATED_BIT` is
172        // set.
173        //
174        // We do this by having each thread check whether its increment changed
175        // the refcount from 0 to 1 while `TERMINATED_BIT` was set. If it did,
176        // the thread will not decrement that refcount, leaving it "dangling"
177        // instead. This ensures that the refcount never falls below 1 again.
178        if pre_increment.is_terminated() && pre_increment.refcount() == 0 {
179            // SAFETY: We loaded `state` with `Ordering::Acquire` and observed
180            // that `TERMINATED_BIT` was set.
181            let termination_reason = unsafe { self.get_termination_reason_unchecked() };
182            return failure(Some(termination_reason));
183        }
184
185        let mut success_result = None;
186        if !pre_increment.is_stopping() {
187            // SAFETY: Termination always sets `STOPPING_BIT`. We incremented
188            // the refcount while `STOPPING_BIT` was not set, so `shared` won't
189            // be dropped until we decrement our refcount.
190            let shared = unsafe { self.get_shared_unchecked() };
191            success_result = Some(success(shared));
192        }
193
194        let pre_decrement = State(self.state.fetch_sub(REFCOUNT, Ordering::AcqRel));
195
196        if !pre_decrement.is_stopping() {
197            success_result.unwrap()
198        } else if !pre_decrement.is_terminated() {
199            failure(None)
200        } else {
201            // The connection is terminated. If we decremented the refcount to
202            // 0, then we need to drop `shared`.
203            if pre_decrement.refcount() == 1 {
204                self.shared.with_mut(|shared| {
205                    // SAFETY: We decremented the refcount to 0 while
206                    // `TERMINATED_BIT` was set.
207                    unsafe {
208                        ManuallyDrop::drop(&mut *shared);
209                    }
210                });
211            }
212
213            // SAFETY: We loaded `state` with `Ordering::Acquire` and observed
214            // that `TERMINATED_BIT` was set.
215            let termination_reason = unsafe { self.get_termination_reason_unchecked() };
216            failure(Some(termination_reason))
217        }
218    }
219
220    pub fn send_with(
221        &self,
222        f: impl FnOnce(&mut T::SendBuffer) -> Result<(), EncodeError>,
223    ) -> Result<SendFuture<'_, T>, EncodeError> {
224        Ok(SendFuture {
225            connection: self,
226            state: self.with_shared(
227                |shared| {
228                    let mut buffer = T::acquire(shared);
229                    f(&mut buffer)?;
230                    Ok(SendFutureState::Running { future_state: T::begin_send(shared, buffer) })
231                },
232                |error| {
233                    Ok(error
234                        // Some(Error) => Terminated
235                        .map(|error| SendFutureState::Terminated { error })
236                        // None => Stopping
237                        .unwrap_or(SendFutureState::Stopping))
238                },
239            )?,
240        })
241    }
242
243    /// Sends an epitaph to the underlying transport.
244    ///
245    /// This send ignores the current state of the connection, and does not
246    /// report back any errors encountered while sending.
247    ///
248    /// # Safety
249    ///
250    /// The connection must not be terminated, and the returned future must be
251    /// completed or canceled before the connection is terminated.
252    pub unsafe fn send_epitaph(&self, error: i32) -> SendEpitaphFuture<'_, T> {
253        // SAFETY: The caller has guaranteed that the connection is not
254        // terminated, and will not be terminated until the returned future is
255        // completed or canceled. As long as the connection is not terminated,
256        // `shared` will not be dropped.
257        let shared = unsafe { self.get_shared_unchecked() };
258
259        let mut buffer = T::acquire(shared);
260        encode_header::<T>(&mut buffer, 0, ORDINAL_EPITAPH).unwrap();
261        encode_epitaph::<T>(&mut buffer, error).unwrap();
262        let future_state = T::begin_send(shared, buffer);
263
264        SendEpitaphFuture { shared, future_state }
265    }
266
267    /// Returns a new [`RecvFuture`] which receives the next message.
268    ///
269    /// # Safety
270    ///
271    /// The connection must not be terminated, and the returned future must be
272    /// completed or canceled before the connection is terminated.
273    pub unsafe fn recv<'a>(&'a self, exclusive: &'a mut T::Exclusive) -> RecvFuture<'a, T> {
274        // SAFETY: The caller has guaranteed that the connection is not
275        // terminated, and will not be terminated until the returned future is
276        // completed or canceled. As long as the connection is not terminated,
277        // `shared` will not be dropped.
278        let shared = unsafe { self.get_shared_unchecked() };
279
280        let future_state = T::begin_recv(shared, exclusive);
281        RecvFuture { connection: self, exclusive, future_state }
282    }
283
284    /// Stops the connection to wait for termination.
285    ///
286    /// This modifies the behavior of this connection's futures:
287    ///
288    /// - Polled [`SendFuture`]s will return `Poll::Pending` without calling
289    ///   [`poll_send`].
290    /// - Polled [`RecvFuture`]s will call [`poll_recv`], but will return
291    ///   `Poll::Ready` with an error when they would normally return
292    ///   `Poll::Pending`.
293    ///
294    /// [`poll_send`]: Transport::poll_send
295    /// [`poll_recv`]: Transport::poll_recv
296    pub fn stop(&self) {
297        let prev_state = State(self.state.fetch_or(STOPPING_BIT, Ordering::Relaxed));
298        if !prev_state.is_stopping() {
299            self.stop_waker.wake();
300        }
301    }
302
303    /// Terminates the connection.
304    ///
305    /// This causes this connection's futures to return `Poll::Ready` with an
306    /// error of the given termination reason.
307    ///
308    /// # Safety
309    ///
310    /// `terminate` may only be called once per connection.
311    pub unsafe fn terminate(&self, reason: ProtocolError<T::Error>) {
312        self.termination_reason.with_mut(|termination_reason| {
313            // SAFETY: The caller guaranteed that this is the only time
314            // `terminate` is called on this connection.
315            unsafe {
316                termination_reason.write(MaybeUninit::new(reason));
317            }
318        });
319        let pre_terminate =
320            State(self.state.fetch_or(STOPPING_BIT | TERMINATED_BIT, Ordering::AcqRel));
321
322        // If we set `TERMINATED_BIT` and the refcount was 0, then we need to
323        // drop `shared`.
324        if !pre_terminate.is_terminated() && pre_terminate.refcount() == 0 {
325            self.shared.with_mut(|shared| {
326                // SAFETY: We set `TERMINATED_BIT` while the refcount was 0.
327                unsafe {
328                    ManuallyDrop::drop(&mut *shared);
329                }
330            });
331        }
332
333        // Wake all of the futures waiting for a termination reason
334        let wakers = take(&mut *self.termination_wakers.lock().unwrap());
335        for waker in wakers {
336            waker.wake();
337        }
338    }
339}
340
341pub struct SendEpitaphFuture<'a, T: Transport> {
342    shared: &'a T::Shared,
343    future_state: T::SendFutureState,
344}
345
346impl<T: Transport> Future for SendEpitaphFuture<'_, T> {
347    type Output = Result<(), Option<T::Error>>;
348
349    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
350        // SAFETY: We continue to treat `self` as pinned.
351        let this = unsafe { Pin::into_inner_unchecked(self) };
352        // SAFETY: `self` is pinned, and `future_state` is a structurally-pinned
353        // field of `self`.
354        let future_state = unsafe { Pin::new_unchecked(&mut this.future_state) };
355        T::poll_send(future_state, cx, this.shared)
356    }
357}
358
359enum SendFutureState<T: Transport> {
360    Running { future_state: T::SendFutureState },
361    Stopping,
362    Terminated { error: ProtocolError<T::Error> },
363    Waiting { waker_index: usize },
364    Finished,
365}
366
367/// A future which sends an encoded message to a connection.
368#[must_use = "futures do nothing unless polled"]
369pub struct SendFuture<'a, T: Transport> {
370    connection: &'a Connection<T>,
371    state: SendFutureState<T>,
372}
373
374impl<T: Transport> SendFuture<'_, T> {
375    fn register_termination_waker(
376        &mut self,
377        cx: &mut Context<'_>,
378        waker_index: Option<usize>,
379    ) -> Poll<Result<(), ProtocolError<T::Error>>> {
380        let mut wakers = self.connection.termination_wakers.lock().unwrap();
381
382        // Re-check the state now that we're holding the lock again. This
383        // prevents us from adding wakers after termination (which would "leak"
384        // them).
385        if let Some(termination_reason) = self.connection.get_termination_reason() {
386            Poll::Ready(Err(termination_reason))
387        } else {
388            let waker = cx.waker().clone();
389            if let Some(waker_index) = waker_index {
390                // Overwrite an existing waker
391                let old_waker = replace(&mut wakers[waker_index], waker);
392
393                // Drop the old waker outside of the mutex lock
394                drop(wakers);
395                drop(old_waker);
396            } else {
397                // Insert a new waker
398                let waker_index = wakers.len();
399                wakers.push(waker);
400
401                // Update the state outside of the mutex lock. If we were
402                // running then a `T::SendFutureState` may be dropped.
403                drop(wakers);
404                self.state = SendFutureState::Waiting { waker_index };
405            }
406            Poll::Pending
407        }
408    }
409}
410
411impl<T: NonBlockingTransport> SendFuture<'_, T> {
412    /// Completes the send operation synchronously and without blocking.
413    ///
414    /// Using this method prevents transports from applying backpressure. Prefer
415    /// awaiting when possible to allow for backpressure.
416    ///
417    /// Because failed sends return immediately, `send_immediately` may observe
418    /// transport closure prematurely. This can manifest as this method
419    /// returning `Err(PeerClosed)` or `Err(Stopped)` when it should have
420    /// returned `Err(PeerClosedWithEpitaph)`. Prefer awaiting when possible for
421    /// correctness.
422    pub fn send_immediately(mut self) -> Result<(), ProtocolError<T::Error>> {
423        match replace(&mut self.state, SendFutureState::Finished) {
424            SendFutureState::Running { mut future_state } => {
425                self.connection.with_shared(
426                    |shared| {
427                        // Connection is running, try to send immediately.
428                        T::send_immediately(&mut future_state, shared).map_err(|e| {
429                            // Immediate send failed:
430                            // - `None` => `PeerClosed`
431                            // - `Some(T::Error)` => `TransportError(T::Error)`
432                            e.map_or(ProtocolError::PeerClosed, ProtocolError::TransportError)
433                        })
434                    },
435                    // Getting shared failed, but we may have a termination
436                    // reason. If we don't have one, return `Stopped`.
437                    |error| Err(error.unwrap_or(ProtocolError::Stopped)),
438                )
439            }
440            SendFutureState::Stopping | SendFutureState::Waiting { waker_index: _ } => {
441                // Try to get the termination reason. If we don't have one yet,
442                // return `Stopped`.
443                Err(self.connection.get_termination_reason().unwrap_or(ProtocolError::Stopped))
444            }
445            SendFutureState::Terminated { error } => Err(error),
446            SendFutureState::Finished => panic!("SendFuture polled after returning `Poll::Ready`"),
447        }
448    }
449}
450
451impl<T: Transport> Future for SendFuture<'_, T> {
452    type Output = Result<(), ProtocolError<T::Error>>;
453
454    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
455        // SAFETY: We continue to treat `self` as pinned.
456        let this = unsafe { Pin::into_inner_unchecked(self) };
457
458        match &this.state {
459            SendFutureState::Running { .. } => {
460                let result = this.connection.with_shared(
461                    |shared| {
462                        let SendFutureState::Running { future_state } = &mut this.state else {
463                            // SAFETY: We matched on `state` and checked that it
464                            // is Running.
465                            unsafe { unreachable_unchecked() }
466                        };
467                        // SAFETY: `self` is pinned and `future_state` is a
468                        // structurally pinned field of `self`.
469                        let future_state = unsafe { Pin::new_unchecked(future_state) };
470                        T::poll_send(future_state, cx, shared)
471                            // `Err(Some(error))` =>
472                            //   `Err(Some(TransportError(error)))`
473                            .map_err(|error| error.map(ProtocolError::TransportError))
474                    },
475                    |error| Poll::Ready(Err(error)),
476                );
477
478                let result = match result {
479                    Poll::Pending => Poll::Pending,
480                    Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
481                    Poll::Ready(Err(None)) => this.register_termination_waker(cx, None),
482                    Poll::Ready(Err(Some(error))) => Poll::Ready(Err(error)),
483                };
484
485                if result.is_ready() {
486                    this.state = SendFutureState::Finished;
487                }
488
489                result
490            }
491            SendFutureState::Stopping => this.register_termination_waker(cx, None),
492            SendFutureState::Terminated { .. } => {
493                let state = replace(&mut this.state, SendFutureState::Finished);
494                let SendFutureState::Terminated { error } = state else {
495                    // SAFETY: We just checked that our state is Terminated.
496                    unsafe { unreachable_unchecked() }
497                };
498                Poll::Ready(Err(error))
499            }
500            SendFutureState::Waiting { waker_index } => {
501                this.register_termination_waker(cx, Some(*waker_index))
502            }
503            SendFutureState::Finished => panic!("SendFuture polled after returning `Poll::Ready`"),
504        }
505    }
506}
507
508/// A future which receives an encoded message over the transport.
509#[must_use = "futures do nothing unless polled"]
510pub struct RecvFuture<'a, T: Transport> {
511    connection: &'a Connection<T>,
512    exclusive: &'a mut T::Exclusive,
513    future_state: T::RecvFutureState,
514}
515
516impl<T: Transport> Future for RecvFuture<'_, T> {
517    type Output = Result<T::RecvBuffer, ProtocolError<T::Error>>;
518
519    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
520        // SAFETY: We continue to treat `self` as pinned
521        let this = unsafe { Pin::into_inner_unchecked(self) };
522
523        // SAFETY: This future is created by `Connection::recv`. The connection
524        // will not be terminated until this is completed or canceled, and so
525        // `shared` will not be dropped.
526        let shared = unsafe { this.connection.get_shared_unchecked() };
527
528        // SAFETY: `self` is pinned, and `future_state` is a structurally-pinned
529        // field of `self`.
530        let future_state = unsafe { Pin::new_unchecked(&mut this.future_state) };
531        let termination_reason = match T::poll_recv(future_state, cx, shared, this.exclusive) {
532            Poll::Pending => {
533                // Receive didn't complete, register waker before
534                // re-checking state.
535                this.connection.stop_waker.register_by_ref(cx.waker());
536                let state = State(this.connection.state.load(Ordering::Relaxed));
537                if state.is_stopping() {
538                    // The connection is stopping. Return an error that the
539                    // connection has been stopped.
540                    ProtocolError::Stopped
541                } else {
542                    // Still running, we'll get polled again later.
543                    return Poll::Pending;
544                }
545            }
546
547            // Receive succeeded.
548            Poll::Ready(Ok(buffer)) => return Poll::Ready(Ok(buffer)),
549
550            // Normal failure: return peer closed error.
551            Poll::Ready(Err(None)) => ProtocolError::PeerClosed,
552
553            // Abnormal failure: return transport error.
554            Poll::Ready(Err(Some(error))) => ProtocolError::TransportError(error),
555        };
556
557        Poll::Ready(Err(termination_reason))
558    }
559}