Skip to main content

reth_engine_tree/tree/
payload_build.rs

1//! Tracking of active payload build jobs.
2
3use reth_concurrency::sync::{
4    atomic::{AtomicUsize, Ordering},
5    channel::{self, Receiver, Sender},
6};
7use std::sync::Arc;
8
9/// Tracks payload jobs that may access the current in-memory overlay.
10#[derive(Clone, Debug)]
11pub(super) struct PayloadBuildTracker {
12    active: Arc<AtomicUsize>,
13    finished_tx: Sender<()>,
14}
15
16impl PayloadBuildTracker {
17    /// Creates a tracker and a receiver notified when its active count reaches zero.
18    pub(super) fn new() -> (Self, Receiver<()>) {
19        let (finished_tx, finished_rx) = channel::bounded(1);
20        (Self { active: Arc::new(AtomicUsize::new(0)), finished_tx }, finished_rx)
21    }
22
23    /// Acquires a lease for one payload job.
24    pub(super) fn acquire(&self) -> PayloadBuildLease {
25        self.active.fetch_add(1, Ordering::AcqRel);
26        PayloadBuildLease {
27            active: Arc::clone(&self.active),
28            finished_tx: self.finished_tx.clone(),
29        }
30    }
31
32    /// Returns whether at least one payload job is active.
33    pub(super) fn is_active(&self) -> bool {
34        self.active.load(Ordering::Acquire) != 0
35    }
36}
37
38/// A lease held for the lifetime of a payload job.
39#[derive(Debug)]
40pub(super) struct PayloadBuildLease {
41    active: Arc<AtomicUsize>,
42    finished_tx: Sender<()>,
43}
44
45impl Drop for PayloadBuildLease {
46    fn drop(&mut self) {
47        let previous = self.active.fetch_sub(1, Ordering::AcqRel);
48        debug_assert!(previous > 0, "payload build lease count underflow");
49
50        if previous == 1 {
51            // The bounded channel coalesces completion notifications. The engine always checks
52            // the counter again before applying a pending handoff.
53            let _ = self.finished_tx.try_send(());
54        }
55    }
56}