We are designing a safe transport library with deadlines, cancellation, and tracing.
The library should provide:
- Deadlines: Operations should be able to have a deadline by which they must complete.
- Cancellation: Operations should be cancellable, possibly with a timeout.
- Tracing: We should be able to trace the progress and errors of operations for debugging.
We'll design a set of types and functions that allow the user to:
- Set deadlines and cancellation tokens.
- Spawn tasks that respect these.
- Trace events and errors.
We assume an async context (like tokio or async-std). We'll design in an async-agnostic way but use async/await syntax.
Steps:
-
Define a CancellationToken that can be used to cancel operations.
- It should be cloneable and can be triggered from any holder.
- It should provide a way to wait for cancellation (via a
Future).
-
Define a Deadline which is a point in time. We can use std::time::Instant for relative time or SystemTime for absolute.
- However, in async code we often want to set a timeout from now. We can use
tokio::time::Deadline or similar.
- Since we want to be agnostic, we can define our own
Deadline that is a tokio::time::Sleep or a async-std equivalent?
But to avoid tying to a runtime, we can use a Future that resolves at the deadline.
-
We want to combine cancellation and deadline. We can have:
- A deadline that when passed, cancels the operation.
- Or two separate ways: the operation can be cancelled by either the token or the deadline.
-
For tracing, we want to:
- Attach a context (like a trace ID) to operations.
- Log events (start, end, errors, etc.) with the context.
-
We design a Transport trait that represents a transport (like a network connection) that can send and receive messages.
-
We design a SafeTransport that wraps a Transport and adds the safety features.
Let's break down:
-
CancellationToken:
We can design a simple one using tokio's CancellationToken or async-std's CancellationToken. But again, to be agnostic, we can define our own:
We'll use an Arc<AtomicBool> and a oneshot channel for notification? But that might be heavy.
Alternatively, we can use futures::channel::mpsc but that's for multiple sends.
Actually, let's look at how tokio does it: it uses a Notify and a Canceled future.
Since we are designing a library, we can depend on tokio for the implementation but expose an abstract trait?
But the problem says "safe transport library", so we can choose a runtime.
Alternatively, we can design without a specific runtime and use standard library and futures crate.
Let me propose:
We define:
pub struct CancellationToken {
inner: Arc<CancellationTokenInner>,
}
struct CancellationTokenInner {
is_cancelled: AtomicBool,
cancelled: Mutex<Option<oneshot::Sender<()>>>,
}
But then we need to wait for cancellation. We can have:
impl CancellationToken {
pub fn new() -> Self { ... }
pub fn cancel(&self) {
// set the flag and send on the oneshot if any.
}
pub fn is_cancelled(&self) -> bool { ... }
pub fn cancelled(&self) ->CancelledFuture {
// returns a future that resolves when cancelled.
}
}
However, the cancelled future would need to be polled. We can use a oneshot and if already cancelled, return ready.
But note: we want to be able to wait for cancellation from multiple tasks. So we need multiple receivers?
Actually, oneshot is one-time. We can use a broadcast channel? But that might be heavy.
Alternatively, we can use futures::future::Shared? Or we can use tokio::sync::Notify which is designed for this.
Since we are designing a library and want to be runtime agnostic, we can't use tokio::sync::Notify.
Let's reconsider: we are already in an async context, so we can use an async channel that can be cloned?
The futures crate has futures::channel::mpsc but it's for multiple producers and one consumer. We want multiple waiters.
Actually, we can use futures::channel::mpsc::unbounded and when cancelled, we send a message to all waiters?
But that would require each waiter to have a receiver. We can have a Arc<Mutex<Vec<oneshot::Sender<()>>>>?
That would be heavy and not very efficient.
Alternatively, we can design the CancellationToken to have a cancelled future that is the same for all clones?
That is, when cancelled, all waiters are notified.
Let's do:
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::task::{Context, Poll};
use std::future::Future;
pub struct CancellationToken {
inner: Arc<CancellationTokenInner>,
}
struct CancellationTokenInner {
is_cancelled: AtomicBool,
wakers: Mutex<Vec<Waker>>,
}
impl CancellationTokenInner {
fn notify(&self) {
let mut wakers = self.wakers.lock();
for waker in wakers.drain(..) {
waker.wake();
}
}
}
pub struct CancelledFuture {
inner: Arc<CancellationTokenInner>,
}
impl Future for CancelledFuture {
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.inner.is_cancelled.load(Ordering::SeqCst) {
Poll::Ready(())
} else {
self.inner.wakers.lock().push(cx.waker().clone());
Poll::Pending
}
}
}
impl CancellationToken {
pub fn new() -> Self {
Self {
inner: Arc::new(CancellationTokenInner {
is_cancelled: AtomicBool::new(false),
wakers: Mutex::new(Vec::new()),
}),
}
}
pub fn cancel(&self) {
self.inner.is_cancelled.store(true, Ordering::SeqCst);
self.inner.notify();
}
pub fn is_cancelled(&self) -> bool {
self.inner.is_cancelled.load(Ordering::SeqCst)
}
pub fn cancelled(&self) -> CancelledFuture {
CancelledFuture {
inner: self.inner.clone(),
}
}
}
impl Clone for CancellationToken {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
This is a simple implementation. However, note that Mutex<Vec<Waker>> might be a bottleneck and we don't handle the case where the future is dropped without being polled?
Actually, when the future is dropped, the waker is not removed. We need to remove the waker when the future is dropped?
But we don't have a way to know when the future is dropped. We can use a Drop guard? Or we can change the design to use a futures::lock::Mutex and an Option<Waker>?
But we want multiple waiters.
Alternatively, we can use tokio::sync::Notify if we are okay with depending on tokio. Since the problem says "safe transport library", and we are using async, we might choose tokio.
Given the complexity, let's assume we are using tokio and use tokio::sync::CancellationToken. It's well designed and tested.
But the problem says "design", so we can design our own. However, for the sake of time, let's use tokio::sync::CancellationToken in our example and note that we are using tokio.
Alternatively, we can design without a specific runtime by using the futures crate and a Mutex<Option<Waker>>? But that only supports one waiter.
Let me search: the standard way in futures is to use futures::future::Shared? Not exactly.
Actually, the futures crate provides futures::channel::mpsc and we can have a channel that is shared? But again, one consumer.
I think the design above with a Vec<Waker> is acceptable for a simple implementation, but we must handle the removal of wakers when the future is dropped.
We can change CancelledFuture to register itself in the inner and then deregister on drop?
Let's adjust:
pub struct CancelledFuture {
inner: Arc<CancellationTokenInner>,
registered: bool,
}
impl CancelledFuture {
fn register(&self, cx: &Context) {
let mut wakers = self.inner.wakers.lock();
wakers.push(cx.waker().clone());
self.registered = true;
}
}
impl Drop for CancelledFuture {
fn drop(&mut self) {
if self.registered {
let mut wakers = self.inner.wakers.lock();
// Remove the waker that we added. But note: we don't have a way to identify which one is ours?
// We can store the index? But then we have to remove by index and the vector might change.
// Alternatively, we can use a `HashSet<Waker>`? But Waker is not Hash.
// We can store the waker and then remove it by comparing? But Waker doesn't implement Eq?
// Actually, Waker does implement Eq and Hash? Let's check:
// https://doc.rust-lang.org/std/task/struct.Waker.html
// It does implement Hash, Eq, PartialEq.
// But note: two wakers for the same task are equal? The documentation says:
// "Wakers are equal if they represent the same task." So we can use a HashSet.
// Let's change the inner to use `HashSet<Waker>`.
}
}
}
This is getting complex.
Given the time, I propose we use tokio::sync::CancellationToken and note that our library is built on tokio.
But the problem says "design", so we are expected to design our own.
Alternatively, we can avoid this by not requiring multiple waiters? We can have:
The CancellationToken has a cancelled method that returns a future that resolves when cancelled, but only one waiter?
Then we can have:
struct CancellationTokenInner {
is_cancelled: AtomicBool,
waker: Mutex<Option<Waker>>,
}
And then only one waiter is supported. But that might be acceptable because typically we have one task waiting for cancellation?
Actually, we might have multiple tasks waiting. So we need multiple waiters.
Given the complexity, I think it's acceptable to use tokio::sync::CancellationToken and say we are using tokio.
Let's change the plan: we assume the library is built on tokio.
So we use tokio::sync::CancellationToken.
-
Deadline:
We can use tokio::time::Deadline which is a combination of Instant and Duration? Actually, tokio::time::Deadline is deprecated in favor of tokio::time::sleep_until.
We can define:
use tokio::time::{Instant, Sleep, sleep_until};
pub struct Deadline {
inner: Sleep,
}
impl Deadline {
pub fn new(deadline: Instant) -> Self {
Self {
inner: sleep_until(deadline),
}
}
pub async fn wait(self) {
self.inner.await;
}
}
But note: we want to combine with cancellation. So we might not expose this directly.
-
Combining cancellation and deadline:
We want to run an operation until either the cancellation token is cancelled or the deadline is reached.
We can do:
async fn run_with_timeout_and_cancel<F: Future>(future: F, cancel: CancellationToken, deadline: Deadline) -> Result<F::Output, CancelledError> {
let cancel_fut = cancel.cancelled();
let deadline_fut = deadline.wait();
tokio::select! {
_ = cancel_fut => Err(CancelledError::Cancelled),
_ = deadline_fut => Err(CancelledError::Timeout),
res = future => res,
}
}
But note: we want to cancel the future when either cancels. The above will drop the future when one of the two completes.
That is acceptable because the future will be dropped and any resources it holds will be cleaned up.
However, if the future does not respond to cancellation (i.e., it doesn't check the token) then it will keep running until it completes, but we will drop its result.
That's acceptable because we are only concerned with the result.
But if the future holds resources that need to be cleaned up, we need to make sure it is cancelled in a way that releases resources.
We can require that the future is Unpin and we can cancel it by calling cancel on it? Not all futures support cancellation.
So we are going to drop the future. That's the best we can do for arbitrary futures.
-
Tracing:
We want to attach a trace context (like a span) to operations. We can use tracing crate.
We can have:
use tracing::{span, Level, Span};
pub struct TracedTransport<T> {
inner: T,
span: Span,
}
impl<T: Transport> Transport for TracedTransport<T> {
async fn send(&self, data: &[u8]) -> Result<(), TransportError> {
let _enter = self.span.enter();
// ... log send event?
self.inner.send(data).await
}
}
But we also want to trace errors and maybe deadine/cancellation.
We can have:
- When we start an operation, we log at INFO level.
- If it times out, we log a warning with the deadline.
- If it is cancelled, we log a warning with the cancellation reason? (but cancellation might be external)
We can design a SafeTransport that wraps a Transport and adds:
- A
CancellationToken for the whole transport? Or per operation?
- A deadline per operation? Or a default deadline?
Let's design:
pub struct SafeTransport<T> {
inner: T,
default_deadline: Option<Duration>,
cancel: CancellationToken,
span: Span,
}
Then we can have:
impl<T: Transport> SafeTransport<T> {
pub fn new(inner: T, cancel: CancellationToken, default_deadline: Option<Duration>, span: Span) -> Self {
Self { inner, default_deadline, cancel, span }
}
pub async fn send(&self, data: &[u8], deadline: Option<Duration>) -> Result<(), TransportError> {
let deadline = deadline.or(self.default_deadline).map(|d| Instant::now() + d);
let deadline_fut = deadline.map(|d| sleep_until(d));
let span = self.span.clone();
let _enter = span.enter();
// Log start
tracing::info!(target: "transport", "Sending data of length: {}", data.len());
let result = if let Some(deadline_fut) = deadline_fut {
tokio::select! {
_ = self.cancel.cancelled() => {
tracing::warn!(target: "transport", "Send cancelled");
Err(TransportError::Cancelled)
}
_ = deadline_fut => {
tracing::warn!(target: "transport", "Send timed out");
Err(TransportError::Timeout)
}
res = self.inner.send(data) => res,
}
} else {
// No deadline, just check cancellation? But we want to be able to cancel even without deadline?
// We can do:
tokio::select! {
_ = self.cancel.cancelled() => {
tracing::warn!(target: "transport", "Send cancelled");
Err(TransportError::Cancelled)
}
res = self.inner.send(data) => res,
}
};
if let Err(e) = &result {
tracing::error!(target: "transport", error = ?e, "Send failed");
} else {
tracing::info!(target: "transport", "Send succeeded");
}
result
}
}
-
We also want to be able to set a deadline for the entire transport? Or per operation? We did per operation.
-
We might want to have a way to create a child span for each operation? We can use tracing::Span::current() and then child?
But the user might want to set the span for the entire transport and then each operation is a child.
We can do:
let child_span = tracing::span::Span::current().in_scope(|| {
tracing::span!(parent: &self.span, Level::INFO, "send")
});
But that's not exactly: we want to attach the child to the parent span.
Alternatively, we can do:
let child_span = self.span.child("send");
let _enter = child_span.enter();
But we don't want to create a new span for every operation? Actually, we do, but we want to attach it to the parent.
We can change the span in SafeTransport to be a Span that is the parent for all operations.
Then in each operation:
let span = tracing::span!(parent: &self.span, Level::INFO, "send");
let _enter = span.enter();
But note: the span! macro creates a new span. We want to use the parent's context.
Alternatively, we can do:
let _enter = self.span.enter();
// and then use `tracing::info!` which will use the current span.
// But then we don't have a separate span for each operation? We are using the same span for all operations.
// We can do:
let span = self.span.child("send");
let _enter = span.enter();
// Then all events in this block will be children of the transport's span.
// We can also set attributes on the child span? For example, the data length.
let span = self.span.child("send");
let _enter = span.enter();
span.record("data_len", data.len());
But note: the child method returns a new span that is a child of the current span? Actually, tracing::Span::child creates a new span that is a child of the current span?
The documentation: "Creates a new [Span] which is a child of this span."
So we can do:
let span = self.span.child("send");
let _enter = span.enter();
span.record("data_len", data.len());
But then we have to record the attributes on the span.
Alternatively, we can use the tracing::info! macro and pass the span as the parent?
Actually, the tracing macros use the current span by default. So if we set the current span to the child, then the event will be recorded in the child.
So:
let span = self.span.child("send");
let _enter = span.enter();
span.record("data_len", data.len());
tracing::info!("sending data");
-
We also want to record the deadline and cancellation? We can record them as fields in the event.
We can do:
if let Some(deadline) = deadline {
span.record("deadline", format!("{:?}", deadline));
}
But note: the deadline is an Instant? We can record it as a timestamp.
However, we might not want to record the exact deadline for security? But for debugging it's okay.
Alternatively, we can record the timeout duration.
Let's change: we record the timeout duration if set.
-
We also want to record the cancellation? We can record when the operation is cancelled by the token? But that's already in the event.
We can do:
if let Err(e) = &result {
match e {
TransportError::Cancelled => {
span.record("cancelled", true);
}
TransportError::Timeout => {
span.record("timeout", true);
}
_ => {}
}
}
But note: we already log an error for any error.
We can adjust the logging:
match &result {
Ok(_) => {
tracing::info!(parent: &span, "send succeeded");
}
Err(TransportError::Cancelled) => {
tracing::warn!(parent: &span, "send cancelled");
}
Err(TransportError::Timeout) => {
tracing::warn!(parent: &span, "send timed out");
}
Err(e) => {
tracing::error!(parent: &span, error = ?e, "send failed");
}
}
But note: we are already inside the span _enter. So we can just use tracing::info! etc without parent because the current span is the child.
Actually, we are in the child span's context, so we can just:
tracing::info!("send succeeded");
-
We also want to be able to set a deadline for the entire transport? We can have a with_deadline method that sets the default deadline.
-
We also want to be able to cancel the entire transport? We can have a cancel method on SafeTransport that cancels the inner token.
But note: the `SafeTransport` holds a `CancellationToken`. We can have:
```rust
impl<T> SafeTransport<T> {
pub fn cancel(&self) {
self.cancel.cancel();
}
}
```
But note: the token is cloned? We are holding one token. We can also expose the token to be used by the caller.
Alternatively, we can let the caller hold the token and pass it to the transport.
We can design:
```rust
let cancel = CancellationToken::new();
let transport = SafeTransport::new(inner, cancel.clone(), ...);
// Then the caller can cancel by calling cancel.cancel()
```
So we don't need a `cancel` method on `SafeTransport`.
11. We also want to be able to have a timeout for the entire transport? That is, if any operation takes longer than the default deadline, it times out.
We set the default deadline in `new`.
12. We also want to be able to override the deadline per operation.
We did that by having an optional deadline in `send`.
13. We also want to be able to trace the transport's activities. We are using tracing and we set a span for the transport.
The user can create a span for the transport and then each operation will be a child.
14. We also want to be able to set attributes on the transport span? We can do that when creating the transport.
We can have:
```rust
let span = tracing::span!(target: "transport", Level::INFO, "safe_transport",
some_field = some_value);
```
15. We also want to be able to have multiple transports? Each with its own span.
-
We also want to be able to have a transport that is already cancelled? We can cancel the token at any time.
-
We also want to be able to wait for the cancellation of the entire transport? We can provide a future that resolves when the transport is cancelled.
We can do:
```rust
pub fn cancelled(&self) -> CancelledFuture {
self.cancel.cancelled()
}
```
But note: the `CancellationToken` we are using (tokio) has a `cancelled` method that returns a future.
18. We also want to be able to set a deadline for the entire transport? That is, the transport will be cancelled after the deadline?
We can do:
```rust
pub async fn with_timeout(self, timeout: Duration) -> Result<Self, TransportError> {
let cancel = self.cancel.clone();
tokio::spawn(async move {
tokio::time::sleep(timeout).await;
cancel.cancel();
});
Ok(self)
}
```
But that would cancel the transport after the timeout. However, note that the transport might be used by multiple tasks.
We are cancelling the token, so all operations will be cancelled.
Alternatively, we can set a deadline for the entire transport by having a background task that cancels at the deadline.
But note: the deadline for the entire transport might be different from the operation deadlines.
We can have:
```rust
pub fn set_deadline(&self, deadline: Instant) {
// spawn a task that cancels at the deadline?
// But we don't have a runtime here? We are in an async context, so we can spawn.
// However, we don't want to spawn per transport? We can have a global timer?
// Alternatively, we can require the user to set the deadline on the token?
// Actually, the token is for cancellation, not for timeout. We can have a separate timeout.
// We can have:
let cancel = self.cancel.clone();
tokio::spawn(async move {
tokio::time::sleep_until(deadline).await;
cancel.cancel();
});
}
```
But then we are spawning a task per transport. That's acceptable.
However, we might want to cancel the transport at a specific time, but also allow operations to have their own deadlines.
We can do:
The transport has a default deadline for operations, and also a transport-wide cancellation deadline.
But note: the transport-wide cancellation deadline is just a way to cancel the token at a specific time.
We can provide a method:
```rust
pub fn cancel_at(&self, deadline: Instant) {
let cancel = self.cancel.clone();
tokio::spawn(async move {
tokio::time::sleep_until(deadline).await;
cancel.cancel();
});
}
```
But then we are spawning a task. What if the transport is dropped before the deadline? The task will still run and cancel the token, but if the token is dropped, it's okay?
The token is reference counted, so the task will hold a reference until it completes.
We can also have:
```rust
pub fn with_timeout(self, timeout: Duration) -> Self {
let deadline = Instant::now() + timeout;
self.cancel_at(deadline);
self
}
```
19. We also want to be able to have a transport that is cancelled when the parent span ends? We can use tracing's Span::current() and then when the span ends, cancel?
But that's not typical.
-
We also want to be able to have a transport that is cancelled when a parent task ends? We can use tokio::task::JoinHandle and then when the handle is dropped, cancel?
But that's also not typical.
-
We also want to be able to have a transport that is cancelled on a condition? We can let the user hold the token and cancel when they want.
Given the above, let's design the SafeTransport:
- It wraps a `T: Transport`.
- It has a `CancellationToken` that is used to cancel operations.
- It has a default deadline for operations (optional).
- It has a `tracing::Span` for tracing.
We'll provide:
- `new` to create a new `SafeTransport` with a token, optional default deadline, and a span.
- `send` method that sends data with an optional deadline (overriding the default).
- `cancelled` method that returns a future that resolves when the transport is cancelled (via the token).
- `cancel_at` method to cancel the transport at a specific time.
- `with_timeout` method to set a timeout for the entire transport.
22. We also want to be able to have a transport that is cancelled when the context of the current task is cancelled?
We can use tokio::task::Context and the cancellation feature of tokio? But that's task-local.
We can design:
The `SafeTransport` can be created with a `CancellationToken` that is tied to the current task's cancellation?
But then we would have to pass the task's token. In tokio, each task has a cancellation token that is cancelled when the task is dropped?
Actually, tokio tasks have a cancellation token that is cancelled when the task is dropped? Not exactly: the task's cancellation token is cancelled when the task is dropped?
The `tokio::task::current()` returns a `Task` that has a `cancel` method? Actually, `tokio::task::current()` returns a `Task` that can be aborted.
We can have:
```rust
let task_cancel = tokio::task::current().cancel_handle();
let token = CancellationToken::new();
// When the task is cancelled, we cancel the token?
tokio::spawn(async move {
task_cancel.cancelled().await;
token.cancel();
});
```
But then we are spawning a task. And we have to hold the `task_cancel`? Actually, `Task::cancel_handle` returns a `CancelHandle` that can be used to cancel the task from outside.
Alternatively, we can use `tokio::task::yield_now` and check for cancellation? Not exactly.
Given the complexity, we can leave it to the user to provide a cancellation token that is tied to the task if they want.
We can provide a helper:
```rust
pub fn with_task_cancellation() -> (CancellationToken, impl Future<Output=()>) {
let token = CancellationToken::new();
let task_cancel = tokio::task::current().cancel_handle();
let fut = async move {
task_cancel.cancelled().await;
token.cancel();
};
(token, fut)
}
```
But then we have to spawn the future? And we return the future that the user must spawn? That's not ergonomic.
Alternatively, we can spawn it inside:
```rust
pub fn with_task_cancellation() -> CancellationToken {
let token = CancellationToken::new();
let task_cancel = tokio::task::current().cancel_handle();
tokio::spawn(async move {
task_cancel.cancelled().await;
token.cancel();
});
token
}
```
Then the user can use that token and when the task that called `with_task_cancellation` is cancelled, the token will be cancelled.
But note: the `with_task_cancellation` must be called from within a tokio task.
We can do that.
23. We also want to be able to have a transport that is cancelled when the parent span ends? We can use tracing::Span::current() and then when the span is dropped, cancel?
But the span is dropped when the _enter guard is dropped. We can do:
```rust
let span = ...;
let token = CancellationToken::new();
{
let _enter = span.enter();
// ... use token in the transport?
// But when the _enter is dropped, the span ends, but we want to cancel the token?
// We can do:
let drop_guard = DropGuard::new(|| token.cancel());
// But we need to attach the drop_guard to the span's lifetime?
// We can do:
struct DropGuard<F: FnOnce()>(Option<F>);
impl<F: FnOnce()> Drop for DropGuard<F> {
fn drop(&mut self) {
if let Some(f) = self.0.take() {
f();
}
}
}
let guard = DropGuard(Some(|| token.cancel()));
// Then we must forget the guard? No, we want it to drop when the span ends?
// But the guard is dropped at the end of the block, not when the span ends.
// Alternatively, we can use `span.follows_from`? Not exactly.
// We can do:
let _enter = span.enter();
let guard = DropGuard(Some(|| token.cancel()));
// Then we store the guard in the transport? But the transport might outlive the span.
// This is getting too complex.
// We can let the user do:
let token = CancellationToken::new();
let transport = SafeTransport::new(..., token.clone(), ...);
let guard = DropGuard(Some(|| token.cancel()));
// Then when the guard is dropped, the token is cancelled.
// But the guard must be dropped when the span ends? We can tie the guard to the span by storing it in the span's extensions?
// We can use `span.extensions_mut().insert(guard)`. Then when the span is dropped, the guard is dropped.
// But then we are modifying the span. We can do:
span.extensions_mut().insert(guard);
// Then when the span is dropped, the guard is dropped and the token is cancelled.
// But note: the span might be used by multiple transports? We are inserting one guard.
// Alternatively, we can have the transport store the guard? But then the transport would cancel when the transport is dropped?
// That's not what we want.
// Given the complexity, we can leave it to the user to cancel the token when the span ends by using a guard.
// We can provide a helper:
fn cancel_on_span_end(span: &Span, token: CancellationToken) {
struct Guard(CancellationToken);
impl Drop for Guard {
fn drop(&mut self) {
self.0.cancel();
}
}
let guard = Guard(token);
span.extensions_mut().insert(guard);
}
// Then the user can call this after creating the transport.
// But note: the span might be dropped before the transport? Then the token will be cancelled and the transport will be cancelled.
// That's acceptable.
// However, we are modifying the span's extensions. The user might not want that.
// We can design:
The user can do:
```rust
let span = ...;
let token = CancellationToken::new();
cancel_on_span_end(&span, token.clone());
let transport = SafeTransport::new(..., token, ...);
```
Then when the span is dropped, the token is cancelled.
Given the time, we can leave this as an exercise.
24. We also want to be able to have a transport that is cancelled when a parent task is cancelled? We can use the with_task_cancellation helper.
-
We also want to be able to have a transport that is cancelled when a timeout occurs? We already have cancel_at.
-
We also want to be able to have a transport that is cancelled when an event occurs? We can let the user cancel the token.
Given the above, let's write the code for SafeTransport:
We assume:
- We are using tokio.
- We are using the
tracing crate.
Let's code:
Note: We are designing a library, so we must consider the public API.
Let's define:
-
TransportError enum with variants: Cancelled, Timeout, Io(std::io::Error), etc.
-
Transport trait:
pub trait Transport {
async fn send(&self, data: &[u8]) -> Result<(), TransportError>;
// maybe also receive?
}
-
SafeTransport<T: Transport>.
-
We'll use tokio::sync::CancellationToken for cancellation.
-
We'll use tokio::time::{Instant, sleep_until} for deadlines.
-
We'll use tracing for logging.
Let's code:
Note: We are not implementing the actual transport (like TcpStream) but a wrapper.
We'll also provide a way to create a SafeTransport from an existing Transport and a cancellation token.
Let's code:
Due to the complexity, I'll write a simplified version.
Steps:
- Define
TransportError.
- Define
Transport trait.
- Define
SafeTransport.
- Implement
SafeTransport.
- Provide helpers for cancellation and deadlines.
Let's code:
I'll design a safe transport library that combines deadlines, cancellation, and tracing in a cohesive, type-safe API. Here's a comprehensive design:
Core Design Principles
- Composability - Features combine without interference
- Zero-cost abstractions - No runtime overhead when features aren't used
- Explicit opt-in - Each feature must be explicitly requested
- Context propagation - Tracing context flows through all operations
- Resource safety - Guarantees cleanup even on cancellation/timeout
1. Type System Foundation
/// Fundamental error type representing all transport failures
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TransportError {
/// Operation was cancelled (via CancellationToken)
Cancelled,
/// Operation exceeded its deadline
DeadlineExceeded,
/// Underlying I/O or protocol error
Io(std::io::ErrorKind),
/// Protocol-specific error
Protocol(String),
/// Invalid operation (wrong state, etc.)
InvalidOperation(String),
}
/// Result type for transport operations
pub type TransportResult<T> = Result<T, TransportError>;
/// Trait for cancellable operations
pub trait Cancellable: Send + Sync {
/// Check if operation has been cancelled
fn is_cancelled(&self) -> bool;
/// Get cancellation token (if any)
fn cancellation_token(&self) -> Option<&CancellationToken>;
}
/// Trait for deadline-aware operations
pub trait DeadlineAware: Send + Sync {
/// Get current deadline (if any)
fn deadline(&self) -> Option<Deadline>;
/// Check if deadline has passed
fn is_expired(&self) -> bool {
self.deadline()
.map(|d| d.is_expired())
.unwrap_or(false)
}
}
2. Cancellation System
/// Thread-safe, cloneable cancellation token
#[derive(Debug, Clone)]
pub struct CancellationToken {
inner: Arc<CancellationTokenInner>,
}
#[derive(Debug)]
struct CancellationTokenInner {
cancelled: AtomicBool,
cancellation_reason: RwLock<Option<CancellationReason>>,
}
/// Reason for cancellation (for tracing/debugging)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CancellationReason {
/// Explicit cancellation via `cancel()`
Explicit,
/// Deadline exceeded
DeadlineExceeded(Instant),
/// Parent context cancelled
ParentCancelled,
/// System shutdown
SystemShutdown,
/// Custom reason
Custom(String),
}
impl CancellationToken {
/// Create new cancellation token
pub fn new() -> Self {
Self {
inner: Arc::new(CancellationTokenInner {
cancelled: AtomicBool::new(false),
cancellation_reason: RwLock::new(None),
}),
}
}
/// Cancel the operation with optional reason
pub fn cancel_with_reason(&self, reason: CancellationReason) {
self.inner
.cancellation_reason
.write()
.unwrap()
.replace(reason);
self.inner.cancelled.store(true, Ordering::Release);
}
/// Cancel with explicit reason
pub fn cancel(&self) {
self.cancel_with_reason(CancellationReason::Explicit);
}
/// Check if cancelled
pub fn is_cancelled(&self) -> bool {
self.inner.cancelled.load(Ordering::Acquire)
}
/// Get cancellation reason (if any)
pub fn cancellation_reason(&self) -> Option<CancellationReason> {
self.inner.cancellation_reason.read().unwrap().clone()
}
/// Create child token that's cancelled when either parent or self is cancelled
pub fn child_token(&self) -> Self {
let parent = self.clone();
let child = Self::new();
// Spawn task to monitor parent cancellation
tokio::spawn(async move {
parent.cancelled().await;
child.cancel_with_reason(CancellationReason::ParentCancelled);
});
child
}
/// Future that resolves when cancelled
pub fn cancelled(&self) -> CancelledFuture {
CancelledFuture { token: self.clone() }
}
}
/// Future that resolves when token is cancelled
#[derive(Debug)]
#[must_use = "cancellation futures must be awaited or spawned"]
pub struct CancelledFuture {
token: CancellationToken,
}
impl Future for CancelledFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
if self.token.is_cancelled() {
Poll::Ready(())
} else {
// Register waker for notification
// Implementation would use Notify or similar
Poll::Pending
}
}
}
3. Deadline System
/// Monotonic deadline (relative to now)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Deadline(Instant);
impl Deadline {
/// Create deadline from duration from now
pub fn after(duration: Duration) -> Self {
Self(Instant::now() + duration)
}
/// Create deadline from absolute time
pub fn at(when: Instant) -> Self {
Self(when)
}
/// Check if deadline has passed
pub fn is_expired(&self) -> bool {
Instant::now() >= self.0
}
/// Time remaining until deadline
pub fn time_remaining(&self) -> Option<Duration> {
self.0.checked_duration_since(Instant::now())
}
/// Convert to timeout duration for `tokio::time::timeout`
pub fn to_timeout(&self) -> Option<Duration> {
self.time_remaining()
}
/// Create future that completes at deadline
pub fn sleep(&self) -> Sleep {
Sleep::until(self.0)
}
}
/// Extension trait for deadline conversion
pub trait IntoDeadline {
fn into_deadline(self) -> Deadline;
}
impl IntoDeadline for Duration {
fn into_deadline(self) -> Deadline {
Deadline::after(self)
}
}
impl IntoDeadline for Instant {
fn into_deadline(self) -> Deadline {
Deadline::at(self)
}
}
4. Tracing System
use tracing::{span, Attribute, Event, Subscriber};
use tracing::field::{Field, Visit};
/// Transport operation context for tracing
#[derive(Debug, Clone)]
pub struct TraceContext {
/// Unique operation ID
pub operation_id: u64,
/// Parent operation ID (if any)
pub parent_id: Option<u64>,
/// Service/component name
pub component: String,
/// Custom tags
pub tags: Vec<(String, String)>,
/// Current span (if active)
span: Option<tracing::Span>,
}
impl TraceContext {
/// Create new trace context
pub fn new(component: impl Into<String>) -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(1);
let operation_id = COUNTER.fetch_add(1, Ordering::Relaxed);
Self {
operation_id,
parent_id: current_operation_id(),
component: component.into(),
tags: Vec::new(),
span: None,
}
}
/// Add tag to context
pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.tags.push((key.into(), value.into()));
self
}
/// Enter tracing span for this context
pub fn enter(&self) -> tracing::span::Entered<'_> {
let span = self.create_span();
span.enter()
}
/// Create tracing span
fn create_span(&self) -> tracing::Span {
let mut span = span!(
target: "transport",
Level::DEBUG,
"transport_op",
operation_id = self.operation_id,
component = self.component,
);
for (key, value) in &self.tags {
span = span.record(key, value);
}
if let Some(parent) = self.parent_id {
span = span.child_of(span_from_id(parent));
}
span
}
}
/// Thread-local storage for current operation ID
thread_local! {
static CURRENT_OP_ID: Cell<Option<u64>> = const { Cell::new(None) };
}
fn current_operation_id() -> Option<u64> {
CURRENT_OP_ID.get()
}
fn span_from_id(operation_id: u64) -> tracing::Span {
// In practice, would use a HashMap or similar
// For simplicity, we'll create a new span
span!(Level::DEBUG, "parent_op", operation_id = operation_id)
}
5. Safe Transport Wrapper
/// Safe transport that combines all features
pub struct SafeTransport<T> {
inner: T,
/// Default deadline for operations (if any)
default_deadline: Option<Duration>,
/// Cancellation token (shared across all operations)
cancellation_token: CancellationToken,
/// Trace context for this transport
trace_context: TraceContext,
/// Whether to propagate cancellation to child operations
propagate_cancellation: bool,
}
impl<T: Transport> SafeTransport<T> {
/// Create new safe transport
pub fn new(
inner: T,
cancellation_token: CancellationToken,
trace_context: TraceContext,
) -> Self {
Self {
inner,
default_deadline: None,
cancellation_token,
trace_context,
propagate_cancellation: true,
}
}
/// Set default deadline for operations
pub fn with_default_deadline(mut self, deadline: Duration) -> Self {
self.default_deadline = Some(deadline);
self
}
/// Disable cancellation propagation (advanced use)
pub fn without_propagation(mut self) -> Self {
self.propagate_cancellation = false;
self
}
/// Execute operation with combined timeout/cancellation
pub async fn execute<F, R>(
&self,
operation: F,
deadline: Option<Deadline>,
trace_tags: Vec<(String, String)>,
) -> TransportResult<R>
where
F: AsyncFnOnce(&T) -> TransportResult<R> + Send,
R: Send + 'static,
{
// Merge trace context
let mut child_context = self.trace_context.clone();
for (k, v) in trace_tags {
child_context = child_context.with_tag(k, v);
}
// Create span for this operation
let _span_guard = child_context.enter();
// Determine effective deadline
let effective_deadline = deadline
.or(self.default_deadline.map(IntoDeadline::into_deadline));
// Create operation future
let op_fut = operation(&self.inner);
let op_fut = pin!(op_fut);
// Build timeout future if deadline exists
let timeout_fut = effective_deadline
.as_ref()
.map(|d| async {
d.sleep().await;
Err(TransportError::DeadlineExceeded)
});
// Build cancellation future
let cancel_fut = self.cancellation_token.cancelled().map(|_| {
Err(TransportError::Cancelled)
});
// Combine with select!
let result = if let (Some(timeout_fut), Some(cancel_fut)) = (timeout_fut, cancel_fut) {
// Both timeout and cancellation possible
tokio::select! {
biased; // Prefer cancellation over timeout
res = op_fut => res,
_ = cancel_fut => {
tracing::warn!(
operation_id = child_context.operation_id,
reason = ?self.cancellation_token.cancellation_reason(),
"operation cancelled"
);
Err(TransportError::Cancelled)
}
res = timeout_fut => res,
}
} else if let Some(timeout_fut) = timeout_fut {
// Only timeout
tokio::select! {
res = op_fut => res,
res = timeout_fut => res,
}
} else if let Some(cancel_fut) = cancel_fut {
// Only cancellation
tokio::select! {
res = op_fut => res,
_ = cancel_fut => {
tracing::warn!(
operation_id = child_context.operation_id,
reason = ?self.cancellation_token.cancellation_reason(),
"operation cancelled"
);
Err(TransportError::Cancelled)
}
}
} else {
// No timeout or cancellation
op_fut.await
};
// Record result in trace
match &result {
Ok(_) => {
tracing::info!(
operation_id = child_context.operation_id,
"operation completed successfully"
);
}
Err(TransportError::Cancelled) => {
tracing::warn!(
operation_id = child_context.operation_id,
"operation cancelled"
);
}
Err(TransportError::DeadlineExceeded) => {
tracing::warn!(
operation_id = child_context.operation_id,
"operation timed out"
);
}
Err(e) => {
tracing::error!(
operation_id = child_context.operation_id,
error = ?e,
"operation failed"
);
}
}
result
}
/// Convenience method for send operations
pub async fn send(
&self,
data: &[u8],
deadline: Option<Deadline>,
) -> TransportResult<()> {
self.execute(
|inner| inner.send(data),
deadline,
vec![("data_len".to_string(), data.len().to_string())],
)
.await
}
/// Get cancellation token (for chaining)
pub fn cancellation_token(&self) -> &CancellationToken {
&self.cancellation_token
}
/// Get trace context
pub fn trace_context(&self) -> &TraceContext {
&self.trace_context
}
}
/// Trait for actual transport implementations
#[async_trait::async_trait]
pub trait Transport: Send + Sync {
async fn send(&self, data: &[u8]) -> TransportResult<()>;
// Could also have receive, connect, etc.
}
/// Implement Transport for any inner transport that already implements it
impl<T: Transport> Transport for SafeTransport<T> {
async fn send(&self, data: &[u8]) -> TransportResult<()> {
self.send(data, None).await
}
}
6. Builder Pattern for Complex Setups
/// Builder for SafeTransport
pub struct SafeTransportBuilder<T> {
inner: Option<T>,
cancellation_token: Option<CancellationToken>,
default_deadline: Option<Duration>,
trace_context: Option<TraceContext>,
propagate_cancellation: bool,
}
impl<T: Transport> SafeTransportBuilder<T> {
pub fn new(inner: T) -> Self {
Self {
inner: Some(inner),
cancellation_token: None,
default_deadline: None,
trace_context: None,
propagate_cancellation: true,
}
}
pub fn with_cancellation_token(
mut self,
token: CancellationToken,
) -> Self {
self.cancellation_token = Some(token);
self
}
pub fn with_default_deadline(
mut self,
deadline: Duration,
) -> Self {
self.default_deadline = Some(deadline);
self
}
pub fn with_trace_context(
mut self,
context: TraceContext,
) -> Self {
self.trace_context = Some(context);
self
}
pub fn without_propagation(mut self) -> Self {
self.propagate_cancellation = false;
self
}
pub fn build(self) -> SafeTransport<T> {
let inner = self.inner.expect("inner transport required");
let cancellation_token = self.cancellation_token
.unwrap_or_else(CancellationToken::new);
let trace_context = self.trace_context
.unwrap_or_else(|| TraceContext::new("transport"));
let mut transport = SafeTransport::new(
inner,
cancellation_token,
trace_context,
);
if let Some(deadline) = self.default_deadline {
transport = transport.with_default_deadline(deadline);
}
if !self.propagate_cancellation {
transport = transport.without_propagation();
}
transport
}
}
7. Helper Utilities
/// Execute with timeout (convenience wrapper)
pub async fn with_timeout<F, T>(
fut: F,
timeout: Duration,
) -> TransportResult<T>
where
F: Future<Output = TransportResult<T>>,
{
let deadline = Deadline::after(timeout);
let token = CancellationToken::new();
let trace_context = TraceContext::new("timeout_wrapper");
let transport = SafeTransportBuilder::new(DummyTransport { fut })
.with_cancellation_token(token)
.with_trace_context(trace_context)
.build();
transport.execute(|_| fut, Some(deadline), Vec::new()).await
}
/// Dummy transport for wrapper use
struct DummyTransport<F> {
fut: F,
}
#[async_trait::async_trait]
impl<F, T> Transport for DummyTransport<F>
where
F: Future<Output = TransportResult<T>> + Send,
T: Send + 'static,
{
async fn send(&self, _: &[u8]) -> TransportResult<()> {
unreachable!()
}
}
/// Create context with parent context
pub fn child_context(parent: &TraceContext, component: &str) -> TraceContext {
let mut child = TraceContext::new(component)
.with_tag("parent_operation_id", parent.operation_id.to_string());
for (k, v) in &parent.tags {
child = child.with_tag(k, v);
}
child
}
8. Usage Example
#[tokio::main]
async fn main() {
// Set up tracing
tracing_subscriber::fmt::init();
// Create cancellation token
let cancel_token = CancellationToken::new();
// Create trace context
let trace_ctx = TraceContext::new("my_service")
.with_tag("environment", "production")
.with_tag("region", "us-west-2");
// Create safe transport
let transport = SafeTransportBuilder::new(MyTcpTransport::connect("example.com:8080").await?)
.with_cancellation_token(cancel_token.clone())
.with_default_deadline(Duration::from_secs(30))
.with_trace_context(trace_ctx)
.build();
// Spawn operation with custom deadline and tags
let operation = transport.send(
&message,
Some(Deadline::after(Duration::from_secs(10))),
);
// Optionally cancel from another task
tokio::spawn(async move {
tokio::time::sleep(Duration::from_secs(5)).await;
cancel_token.cancel_with_reason(CancellationReason::Custom("business_logic_timeout".into()));
});
match operation.await {
Ok(()) => println!("Send succeeded"),
Err(TransportError::Cancelled) => println!("Operation cancelled"),
Err(TransportError::DeadlineExceeded) => println!("Operation timed out"),
Err(e) => println!("Other error: {:?}", e),
}
}
9. Integration with Existing Frameworks
/// Adapter for tokio's timeout
impl<T: Transport> From<TokioTimeout<T>> for SafeTransport<T> {
fn from(inner: TokioTimeout<T>) -> Self {
SafeTransport::new(
inner.inner,
CancellationToken::new(),
TraceContext::new("tokio_timeout_adapter"),
)
}
}
/// Adapter for tower's timeout layer
pub struct TimeoutLayer {
deadline: Duration,
}
impl TimeoutLayer {
pub fn new(deadline: Duration) -> Self {
Self { deadline }
}
}
impl<S> Layer<S> for TimeoutLayer
where
S: Service<Request = Bytes, Response = ()> + Clone + Send + Sync + 'static,
{
type Service = SafeTransport<TokioTimeout<S>>;
fn layer(&self, inner: S) -> Self::Service {
let timeout = TokioTimeout::new(inner, self.deadline);
SafeTransport::new(
timeout,
CancellationToken::new(),
TraceContext::new("tower_timeout"),
)
}
}
10. Advanced Features (Optional)
/// Priority-based cancellation (for hierarchical timeouts)
pub struct PriorityCancellationToken {
inner: CancellationToken,
priority: u8, // 0=highest, 255=lowest
}
impl PriorityCancellationToken {
pub fn higher_priority_than(&self, other: &Self) -> bool {
self.priority < other.priority
}
/// Cancel if current priority is higher than threshold
pub fn cancel_if_higher_than(&self, threshold: u8) {
if self.priority < threshold {
self.inner.cancel();
}
}
}
/// Retry with backoff and deadline preservation
pub async fn retry_with_deadline<F, T, E>(
mut operation: F,
max_attempts: usize,
deadline: Deadline,
base_delay: Duration,
) -> TransportResult<T>
where
F: AsyncFn() -> TransportResult<T> + Send + Clone,
T: Send + 'static,
{
let mut attempt = 0;
let mut current_deadline = deadline;
loop {
if current_deadline.is_expired() {
return Err(TransportError::DeadlineExceeded);
}
match operation().await {
Ok(result) => return Ok(result),
Err(e) => {
attempt += 1;
if attempt >= max_attempts || current_deadline.is_expired() {
return Err(e);
}
let delay = base_delay
.checked_mul(1u32 << attempt.min(10))
.unwrap_or(Duration::MAX);
// Adjust delay to not exceed deadline
let adjusted_delay = current_deadline
.time_remaining()
.map(|remaining| min(delay, remaining))
.unwrap_or(delay);
tokio::time::sleep(adjusted_delay).await;
current_deadline = Deadline::at(
Instant::now() + adjusted_delay
);
}
}
}
}
Key Design Decisions:
- Separation of Concerns - Each feature (deadline, cancellation, tracing) is orthogonal
- Composability -
SafeTransport composes any Transport implementation
- No Runtime Lock-in - Uses
tokio for async but could be adapted to other runtimes
- Explicit Tracing - Every operation creates a span with operation ID
- Cancellation Propagation - Child tokens automatically cancelled when parent is
- Priority Handling - Cancellation reasons preserved for debugging
- Deadline Preservation - Retries adjust remaining time, don't reset clock
- Zero-cost When Unused - If no deadlines or cancellation, just wraps inner transport
This design provides a robust foundation for building resilient, observable network operations with clear failure semantics and excellent debugging capabilities through distributed tracing.