Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 10 additions & 31 deletions crates/op-rbuilder/src/builder/cancellation.rs
Original file line number Diff line number Diff line change
@@ -1,29 +1,12 @@
use std::sync::{
Arc,
atomic::{AtomicU8, Ordering},
};
use std::sync::{Arc, OnceLock};
use tokio_util::sync::CancellationToken;

const REASON_NONE: u8 = 0;

/// Why a payload job was cancelled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub(crate) enum CancellationReason {
Resolved = 1,
NewFcu = 2,
Deadline = 3,
}

impl CancellationReason {
fn from_u8(v: u8) -> Option<Self> {
match v {
1 => Some(Self::Resolved),
2 => Some(Self::NewFcu),
3 => Some(Self::Deadline),
_ => None,
}
}
Resolved,
NewFcu,
Deadline,
}

/// Structured cancellation for a single payload building job.
Expand All @@ -37,26 +20,22 @@ impl CancellationReason {
#[derive(Clone)]
pub(crate) struct PayloadJobCancellation {
token: CancellationToken,
reason: Arc<AtomicU8>,
reason: Arc<OnceLock<CancellationReason>>,
}

impl PayloadJobCancellation {
/// Creates a new `PayloadJobCancellation` with the token uncancelled.
pub(crate) fn new() -> Self {
Self {
token: CancellationToken::new(),
reason: Arc::new(AtomicU8::new(REASON_NONE)),
reason: Arc::new(OnceLock::new()),
}
}

fn cancel_with(&self, reason: CancellationReason) {
// First writer wins. If already set, the original reason is preserved.
let _ = self.reason.compare_exchange(
REASON_NONE,
reason as u8,
Ordering::AcqRel,
Ordering::Acquire,
);
// OnceLock ensures that the first writer wins. If already set, the
// original reason is preserved.
let _ = self.reason.set(reason);
self.token.cancel();
}

Expand Down Expand Up @@ -109,7 +88,7 @@ impl PayloadJobCancellation {

/// Returns the reason this job was cancelled, or `None` if not cancelled.
pub(crate) fn reason(&self) -> Option<CancellationReason> {
CancellationReason::from_u8(self.reason.load(Ordering::Acquire))
self.reason.get().copied()
}
}

Expand Down
Loading