Skip to main content

reth_payload_builder/
service.rs

1//! Support for building payloads.
2//!
3//! The payload builder is responsible for building payloads.
4//! Once a new payload is created, it is continuously updated.
5
6use crate::{
7    metrics::PayloadBuilderServiceMetrics, traits::PayloadJobGenerator, KeepPayloadJobAlive,
8    PayloadJob,
9};
10use alloy_consensus::BlockHeader;
11use alloy_primitives::{BlockTimestamp, B256};
12use alloy_rpc_types::engine::PayloadId;
13use futures_util::{future::FutureExt, Stream, StreamExt};
14use reth_chain_state::CanonStateNotification;
15use reth_execution_cache::SavedCache;
16use reth_payload_builder_primitives::{Events, PayloadBuilderError, PayloadEvents};
17use reth_payload_primitives::{BuiltPayload, PayloadAttributes, PayloadKind, PayloadTypes};
18use reth_primitives_traits::{FastInstant as Instant, NodePrimitives};
19use reth_trie_parallel::state_root_task::PayloadStateRootHandle;
20use std::{
21    future::Future,
22    pin::Pin,
23    sync::Arc,
24    task::{Context, Poll},
25};
26use tokio::sync::{
27    broadcast, mpsc,
28    oneshot::{self, Receiver},
29    watch,
30};
31use tokio_stream::wrappers::UnboundedReceiverStream;
32use tracing::{debug, debug_span, info, trace, warn, Span};
33
34type PayloadFuture<P> = Pin<Box<dyn Future<Output = Result<P, PayloadBuilderError>> + Send>>;
35type ResolvePayloadResult<P, Job> = (Option<PayloadFuture<P>>, Option<PayloadJobEntry<Job>>);
36
37/// A communication channel to the [`PayloadBuilderService`] that can retrieve payloads.
38///
39/// This type is intended to be used to retrieve payloads from the service (e.g. from the engine
40/// API).
41#[derive(Debug)]
42pub struct PayloadStore<T: PayloadTypes> {
43    inner: Arc<PayloadBuilderHandle<T>>,
44}
45
46impl<T> PayloadStore<T>
47where
48    T: PayloadTypes,
49{
50    /// Resolves the payload job and returns the best payload that has been built so far.
51    ///
52    /// Note: depending on the installed [`PayloadJobGenerator`], this may or may not terminate the
53    /// job, See [`PayloadJob::resolve`].
54    pub fn resolve_kind(
55        &self,
56        id: PayloadId,
57        kind: PayloadKind,
58    ) -> impl Future<Output = Option<Result<T::BuiltPayload, PayloadBuilderError>>> {
59        self.inner.resolve_kind(id, kind)
60    }
61
62    /// Resolves the payload job and returns the best payload that has been built so far.
63    pub async fn resolve(
64        &self,
65        id: PayloadId,
66    ) -> Option<Result<T::BuiltPayload, PayloadBuilderError>> {
67        self.resolve_kind(id, PayloadKind::Earliest).await
68    }
69
70    /// Returns the best payload for the given identifier.
71    ///
72    /// Note: this merely returns the best payload so far and does not resolve the job.
73    pub async fn best_payload(
74        &self,
75        id: PayloadId,
76    ) -> Option<Result<T::BuiltPayload, PayloadBuilderError>> {
77        self.inner.best_payload(id).await
78    }
79
80    /// Returns the payload timestamp associated with the given identifier.
81    ///
82    /// Note: this returns the timestamp of the payload and does not resolve the job.
83    pub async fn payload_timestamp(
84        &self,
85        id: PayloadId,
86    ) -> Option<Result<u64, PayloadBuilderError>> {
87        self.inner.payload_timestamp(id).await
88    }
89
90    /// Create a new instance
91    pub fn new(inner: PayloadBuilderHandle<T>) -> Self {
92        Self { inner: Arc::new(inner) }
93    }
94}
95
96impl<T> From<PayloadBuilderHandle<T>> for PayloadStore<T>
97where
98    T: PayloadTypes,
99{
100    fn from(inner: PayloadBuilderHandle<T>) -> Self {
101        Self::new(inner)
102    }
103}
104
105/// A communication channel to the [`PayloadBuilderService`].
106///
107/// This is the API used to create new payloads and to get the current state of existing ones.
108#[derive(Debug)]
109pub struct PayloadBuilderHandle<T: PayloadTypes> {
110    /// Sender half of the message channel to the [`PayloadBuilderService`].
111    to_service: mpsc::UnboundedSender<PayloadServiceCommand<T>>,
112}
113
114impl<T: PayloadTypes> PayloadBuilderHandle<T> {
115    /// Creates a new payload builder handle for the given channel.
116    ///
117    /// Note: this is only used internally by the [`PayloadBuilderService`] to manage the payload
118    /// building flow See [`PayloadBuilderService::poll`] for implementation details.
119    pub const fn new(to_service: mpsc::UnboundedSender<PayloadServiceCommand<T>>) -> Self {
120        Self { to_service }
121    }
122
123    /// Sends a message to the service to start building a new payload for the given payload.
124    ///
125    /// Returns a receiver that will receive the payload id.
126    pub fn send_new_payload(
127        &self,
128        input: BuildNewPayload<T::PayloadAttributes>,
129    ) -> Receiver<Result<PayloadId, PayloadBuilderError>> {
130        let (tx, rx) = oneshot::channel();
131        // Fall back to the caller's span so workers stay attached to the originating Engine API
132        // request when DEBUG spans are filtered out.
133        let span = debug_span!(parent: Span::current(), "payload_job").or_current();
134        let _ =
135            self.to_service.send(PayloadServiceCommand::BuildNewPayload(input.into(), span, tx));
136        rx
137    }
138
139    /// Returns the best payload for the given identifier.
140    /// Note: this does not resolve the job if it's still in progress.
141    pub async fn best_payload(
142        &self,
143        id: PayloadId,
144    ) -> Option<Result<T::BuiltPayload, PayloadBuilderError>> {
145        let (tx, rx) = oneshot::channel();
146        self.to_service.send(PayloadServiceCommand::BestPayload(id, tx)).ok()?;
147        rx.await.ok()?
148    }
149
150    /// Resolves the payload job and returns the best payload that has been built so far.
151    ///
152    /// # Cancellation safety
153    ///
154    /// The future returned by this method is not cancellation-safe. This method sends the resolve
155    /// command before returning the future, so dropping the returned future drops the response
156    /// receiver and cancels the job identified by `id`.
157    pub fn resolve_kind(
158        &self,
159        id: PayloadId,
160        kind: PayloadKind,
161    ) -> impl Future<Output = Option<Result<T::BuiltPayload, PayloadBuilderError>>> {
162        let (tx, rx) = oneshot::channel();
163        let sent = self.to_service.send(PayloadServiceCommand::Resolve(id, kind, tx)).is_ok();
164        async move {
165            if !sent {
166                return None
167            }
168
169            match rx.await.transpose()? {
170                Ok(fut) => Some(fut.await),
171                Err(e) => Some(Err(e.into())),
172            }
173        }
174    }
175
176    /// Sends a message to the service to subscribe to payload events.
177    /// Returns a receiver that will receive them.
178    pub async fn subscribe(&self) -> Result<PayloadEvents<T>, PayloadBuilderError> {
179        let (tx, rx) = oneshot::channel();
180        let _ = self.to_service.send(PayloadServiceCommand::Subscribe(tx));
181        Ok(PayloadEvents { receiver: rx.await? })
182    }
183
184    /// Returns the payload timestamp associated with the given identifier.
185    ///
186    /// Note: this returns the timestamp of the payload and does not resolve the job.
187    pub async fn payload_timestamp(
188        &self,
189        id: PayloadId,
190    ) -> Option<Result<u64, PayloadBuilderError>> {
191        let (tx, rx) = oneshot::channel();
192        self.to_service.send(PayloadServiceCommand::PayloadTimestamp(id, tx)).ok()?;
193        rx.await.ok()?
194    }
195}
196
197impl<T> Clone for PayloadBuilderHandle<T>
198where
199    T: PayloadTypes,
200{
201    fn clone(&self) -> Self {
202        Self { to_service: self.to_service.clone() }
203    }
204}
205
206/// A service that manages payload building tasks.
207///
208/// This type is an endless future that manages the building of payloads.
209///
210/// It tracks active payloads and their build jobs that run in a worker pool.
211///
212/// By design, this type relies entirely on the [`PayloadJobGenerator`] to create new payloads and
213/// does know nothing about how to build them, it just drives their jobs to completion.
214#[derive(Debug)]
215#[must_use = "futures do nothing unless you `.await` or poll them"]
216pub struct PayloadBuilderService<Gen, St, T>
217where
218    T: PayloadTypes,
219    Gen: PayloadJobGenerator,
220    Gen::Job: PayloadJob<PayloadAttributes = T::PayloadAttributes>,
221{
222    /// The type that knows how to create new payloads.
223    generator: Gen,
224    /// All active payload jobs, each accompanied by its id and the caller's tracing span
225    /// propagated across the channel so that poll and resolve work appears as children of the
226    /// original Engine API request.
227    payload_jobs: Vec<PayloadJobEntry<Gen::Job>>,
228    /// Copy of the sender half, so new [`PayloadBuilderHandle`] can be created on demand.
229    service_tx: mpsc::UnboundedSender<PayloadServiceCommand<T>>,
230    /// Receiver half of the command channel.
231    command_rx: UnboundedReceiverStream<PayloadServiceCommand<T>>,
232    /// Metrics for the payload builder service
233    metrics: PayloadBuilderServiceMetrics,
234    /// Chain events notification stream
235    chain_events: St,
236    /// Payload events handler, used to broadcast and subscribe to payload events.
237    payload_events: broadcast::Sender<Events<T>>,
238    /// We retain latest resolved payload just to make sure that we can handle repeating
239    /// requests for it gracefully.
240    cached_payload_rx: watch::Receiver<Option<(PayloadId, BlockTimestamp, T::BuiltPayload)>>,
241    /// Sender half of the cached payload channel.
242    cached_payload_tx: watch::Sender<Option<(PayloadId, BlockTimestamp, T::BuiltPayload)>>,
243}
244
245const PAYLOAD_EVENTS_BUFFER_SIZE: usize = 20;
246
247// === impl PayloadBuilderService ===
248
249impl<Gen, St, T> PayloadBuilderService<Gen, St, T>
250where
251    T: PayloadTypes,
252    Gen: PayloadJobGenerator,
253    Gen::Job: PayloadJob<PayloadAttributes = T::PayloadAttributes>,
254    <Gen::Job as PayloadJob>::BuiltPayload: Into<T::BuiltPayload>,
255{
256    /// Creates a new payload builder service and returns the [`PayloadBuilderHandle`] to interact
257    /// with it.
258    ///
259    /// This also takes a stream of chain events that will be forwarded to the generator to apply
260    /// additional logic when new state is committed. See also
261    /// [`PayloadJobGenerator::on_new_state`].
262    pub fn new(generator: Gen, chain_events: St) -> (Self, PayloadBuilderHandle<T>) {
263        let (service_tx, command_rx) = mpsc::unbounded_channel();
264        let (payload_events, _) = broadcast::channel(PAYLOAD_EVENTS_BUFFER_SIZE);
265
266        let (cached_payload_tx, cached_payload_rx) = watch::channel(None);
267
268        let service = Self {
269            generator,
270            payload_jobs: Vec::new(),
271            service_tx,
272            command_rx: UnboundedReceiverStream::new(command_rx),
273            metrics: Default::default(),
274            chain_events,
275            payload_events,
276            cached_payload_rx,
277            cached_payload_tx,
278        };
279
280        let handle = service.handle();
281        (service, handle)
282    }
283
284    /// Returns a handle to the service.
285    pub fn handle(&self) -> PayloadBuilderHandle<T> {
286        PayloadBuilderHandle::new(self.service_tx.clone())
287    }
288
289    /// Create clone on `payload_events` sending handle that could be used by builder to produce
290    /// additional events during block building
291    pub fn payload_events_handle(&self) -> broadcast::Sender<Events<T>> {
292        self.payload_events.clone()
293    }
294
295    /// Returns true if the given payload is currently being built.
296    fn contains_payload(&self, id: PayloadId) -> bool {
297        self.payload_jobs.iter().any(|entry| entry.id == id)
298    }
299
300    /// Returns the best payload for the given identifier that has been built so far.
301    fn best_payload(&self, id: PayloadId) -> Option<Result<T::BuiltPayload, PayloadBuilderError>> {
302        let res = self
303            .payload_jobs
304            .iter()
305            .find(|entry| entry.id == id)
306            .map(|entry| entry.job.best_payload().map(|payload| payload.into()));
307        if let Some(Ok(ref best)) = res {
308            self.metrics.set_best_revenue(best.block().number(), f64::from(best.fees()));
309        }
310
311        res
312    }
313
314    /// Returns the best payload for the given identifier that has been built so far.
315    ///
316    /// If the job should be terminated, this removes it from active polling and returns it so the
317    /// caller can drop it after the response is sent.
318    fn resolve(
319        &mut self,
320        id: PayloadId,
321        kind: PayloadKind,
322    ) -> ResolvePayloadResult<T::BuiltPayload, Gen::Job> {
323        let start = Instant::now();
324        debug!(target: "payload_builder", %id, "resolving payload job");
325
326        if let Some((cached, _, payload)) = &*self.cached_payload_rx.borrow() &&
327            *cached == id
328        {
329            self.metrics.resolve_duration_seconds.record(start.elapsed());
330            return (Some(Box::pin(core::future::ready(Ok(payload.clone())))), None);
331        }
332
333        let Some(job) = self.payload_jobs.iter().position(|entry| entry.id == id) else {
334            return (None, None)
335        };
336        // Resolving may spawn empty or fallback build workers that inherit the current span, so
337        // enter the job's span instead of the service task's.
338        let span = self.payload_jobs[job].span.clone();
339        let (fut, keep_alive) = span.in_scope(|| self.payload_jobs[job].job.resolve_kind(kind));
340        let payload_timestamp = self.payload_jobs[job].job.payload_timestamp();
341
342        let mut resolved_job =
343            (keep_alive == KeepPayloadJobAlive::No).then(|| self.payload_jobs.swap_remove(job));
344        let leases = resolved_job
345            .as_mut()
346            .map(|entry| std::mem::take(&mut entry.leases))
347            .unwrap_or_default();
348
349        // Since the fees will not be known until the payload future is resolved / awaited, we wrap
350        // the future in a new future that will update the metrics.
351        let resolved_metrics = self.metrics.clone();
352        let payload_events = self.payload_events.clone();
353        let cached_payload_tx = self.cached_payload_tx.clone();
354
355        let fut = async move {
356            let _leases = leases;
357            let res = fut.await;
358            resolved_metrics.resolve_duration_seconds.record(start.elapsed());
359            if let Ok(payload) = &res {
360                if payload_events.receiver_count() > 0 {
361                    payload_events.send(Events::BuiltPayload(payload.clone().into())).ok();
362                }
363
364                if let Ok(timestamp) = payload_timestamp {
365                    let _ = cached_payload_tx.send(Some((id, timestamp, payload.clone().into())));
366                }
367
368                resolved_metrics
369                    .set_resolved_revenue(payload.block().number(), f64::from(payload.fees()));
370            }
371            res.map(|p| p.into())
372        };
373
374        (Some(Box::pin(fut)), resolved_job)
375    }
376
377    /// Returns the payload timestamp for the given payload.
378    fn payload_timestamp(&self, id: PayloadId) -> Option<Result<u64, PayloadBuilderError>> {
379        if let Some((cached_id, timestamp, _)) = *self.cached_payload_rx.borrow() &&
380            cached_id == id
381        {
382            return Some(Ok(timestamp));
383        }
384
385        let timestamp = self
386            .payload_jobs
387            .iter()
388            .find(|entry| entry.id == id)
389            .map(|entry| entry.job.payload_timestamp());
390
391        if timestamp.is_none() {
392            trace!(target: "payload_builder", %id, "no matching payload job found to get timestamp for");
393        }
394
395        timestamp
396    }
397}
398
399impl<Gen, St, T, N> Future for PayloadBuilderService<Gen, St, T>
400where
401    T: PayloadTypes,
402    N: NodePrimitives,
403    Gen: PayloadJobGenerator + Unpin + 'static,
404    <Gen as PayloadJobGenerator>::Job: Unpin + 'static,
405    St: Stream<Item = CanonStateNotification<N>> + Send + Unpin + 'static,
406    Gen::Job: PayloadJob<PayloadAttributes = T::PayloadAttributes>,
407    <Gen::Job as PayloadJob>::BuiltPayload: Into<T::BuiltPayload>,
408{
409    type Output = ();
410
411    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
412        let this = self.get_mut();
413        loop {
414            // notify the generator of new chain events
415            while let Poll::Ready(Some(new_head)) = this.chain_events.poll_next_unpin(cx) {
416                this.generator.on_new_state(new_head);
417            }
418
419            // we poll all jobs first, so we always have the latest payload that we can report if
420            // requests
421            // we don't care about the order of the jobs, so we can just swap_remove them
422            for idx in (0..this.payload_jobs.len()).rev() {
423                let PayloadJobEntry { mut job, id, span, leases } =
424                    this.payload_jobs.swap_remove(idx);
425
426                let poll_result = {
427                    let _entered = span.enter();
428                    job.poll_unpin(cx)
429                };
430
431                match poll_result {
432                    Poll::Ready(Ok(_)) => {
433                        this.metrics.set_active_jobs(this.payload_jobs.len());
434                        trace!(target: "payload_builder", %id, "payload job finished");
435                    }
436                    Poll::Ready(Err(err)) => {
437                        warn!(target: "payload_builder",%err, ?id, "Payload builder job failed; resolving payload");
438                        this.metrics.inc_failed_jobs();
439                        this.metrics.set_active_jobs(this.payload_jobs.len());
440                    }
441                    Poll::Pending => {
442                        this.payload_jobs.push(PayloadJobEntry { job, id, span, leases });
443                    }
444                }
445            }
446
447            // marker for exit condition
448            let mut new_job = false;
449
450            // drain all requests
451            while let Poll::Ready(Some(cmd)) = this.command_rx.poll_next_unpin(cx) {
452                match cmd {
453                    PayloadServiceCommand::BuildNewPayload(input, job_span, tx) => {
454                        let id = input.payload_id();
455                        let mut res = Ok(id);
456                        let parent = input.parent_hash;
457
458                        if this.contains_payload(id) {
459                            debug!(target: "payload_builder", %id, %parent, "Payload job already in progress, ignoring.");
460                        } else {
461                            let start = Instant::now();
462                            let attributes = input.attributes.clone();
463                            // Keep a service-owned reference for generic payload jobs. Builders
464                            // that move work into detached tasks can retain their own references
465                            // from `resources` until those tasks exit.
466                            let leases = input.resources.clone_leases();
467                            let job_result = {
468                                let _entered = job_span.enter();
469                                this.generator.new_payload_job(*input, id)
470                            };
471
472                            match job_result {
473                                Ok(job) => {
474                                    this.metrics.new_job_duration_seconds.record(start.elapsed());
475                                    info!(target: "payload_builder", %id, %parent, "New payload job created");
476                                    this.metrics.inc_initiated_jobs();
477                                    new_job = true;
478                                    this.payload_jobs.push(PayloadJobEntry {
479                                        job,
480                                        id,
481                                        span: job_span,
482                                        leases,
483                                    });
484                                    this.payload_events.send(Events::Attributes(attributes)).ok();
485
486                                    // Clear stale cached payload for this id so
487                                    // resolve() never returns an outdated result
488                                    // from a previous job with the same id.
489                                    if this
490                                        .cached_payload_rx
491                                        .borrow()
492                                        .as_ref()
493                                        .is_some_and(|(cached_id, _, _)| *cached_id == id)
494                                    {
495                                        trace!(target: "payload_builder", %id, "clearing stale cached payload for reused payload id");
496                                        let _ = this.cached_payload_tx.send(None);
497                                    }
498                                }
499                                Err(err) => {
500                                    this.metrics.new_job_duration_seconds.record(start.elapsed());
501                                    this.metrics.inc_failed_jobs();
502                                    warn!(target: "payload_builder", %err, %id, "Failed to create payload builder job");
503                                    res = Err(err);
504                                }
505                            }
506                        }
507
508                        let _ = tx.send(res);
509                    }
510                    PayloadServiceCommand::BestPayload(id, tx) => {
511                        let _ = tx.send(this.best_payload(id));
512                    }
513                    PayloadServiceCommand::PayloadTimestamp(id, tx) => {
514                        let timestamp = this.payload_timestamp(id);
515                        let _ = tx.send(timestamp);
516                    }
517                    PayloadServiceCommand::Resolve(id, strategy, tx) => {
518                        let (payload_fut, resolved_job) = this.resolve(id, strategy);
519                        let _ = tx.send(payload_fut);
520
521                        if let Some(entry) = resolved_job {
522                            debug!(target: "payload_builder", id = %entry.id, "terminated resolved job");
523                        }
524                    }
525                    PayloadServiceCommand::Subscribe(tx) => {
526                        let new_rx = this.payload_events.subscribe();
527                        let _ = tx.send(new_rx);
528                    }
529                }
530            }
531
532            if !new_job {
533                return Poll::Pending
534            }
535        }
536    }
537}
538
539/// Message type for the [`PayloadBuilderService`].
540#[derive(derive_more::Debug)]
541pub enum PayloadServiceCommand<T: PayloadTypes> {
542    /// Start building a new payload.
543    ///
544    /// Carries the caller's [`Span`] so the service can parent payload-building work under the
545    /// originating Engine API trace.
546    ///
547    /// The sender receives the id of the started payload job. Answering with
548    /// [`PayloadBuilderError::InvalidAttributes`] rejects the payload attributes; any other error,
549    /// or dropping the sender, is reported to the CL as an internal error.
550    BuildNewPayload(
551        Box<BuildNewPayload<T::PayloadAttributes>>,
552        Span,
553        oneshot::Sender<Result<PayloadId, PayloadBuilderError>>,
554    ),
555    /// Get the best payload so far
556    BestPayload(PayloadId, oneshot::Sender<Option<Result<T::BuiltPayload, PayloadBuilderError>>>),
557    /// Get the payload timestamp for the given payload
558    PayloadTimestamp(PayloadId, oneshot::Sender<Option<Result<u64, PayloadBuilderError>>>),
559    /// Resolve the payload and return the payload
560    Resolve(
561        PayloadId,
562        /* kind: */ PayloadKind,
563        #[debug(skip)] oneshot::Sender<Option<PayloadFuture<T::BuiltPayload>>>,
564    ),
565    /// Payload service events
566    Subscribe(oneshot::Sender<broadcast::Receiver<Events<T>>>),
567}
568
569/// A request to build a new payload.
570#[derive(Debug)]
571pub struct BuildNewPayload<T> {
572    /// The attributes for the new payload
573    pub attributes: T,
574    /// The parent hash of the new payload
575    pub parent_hash: B256,
576    /// Resources loaned to the payload builder for this job.
577    pub resources: PayloadBuilderResources,
578}
579
580impl<T: PayloadAttributes> BuildNewPayload<T> {
581    /// Returns the payload id for the new payload.
582    pub fn payload_id(&self) -> PayloadId {
583        self.attributes.payload_id(&self.parent_hash)
584    }
585}
586
587/// Resources loaned to a payload builder job by the engine.
588#[derive(Debug, Default)]
589pub struct PayloadBuilderResources {
590    /// Optional execution cache to use for the payload.
591    ///
592    /// Only provided if `--engine.share-execution-cache-with-payload-builder` is enabled.
593    execution_cache: Option<SavedCache>,
594    /// Optional handle to a background state-root task.
595    state_root_handle: Option<PayloadStateRootHandle>,
596    /// Lifecycle leases retained by the service or by detached payload build tasks.
597    leases: Vec<PayloadBuilderLease>,
598}
599
600impl PayloadBuilderResources {
601    /// Creates a new payload builder resource bundle.
602    pub const fn new(
603        execution_cache: Option<SavedCache>,
604        state_root_handle: Option<PayloadStateRootHandle>,
605    ) -> Self {
606        Self { execution_cache, state_root_handle, leases: Vec::new() }
607    }
608
609    /// Adds a lease for this payload build.
610    pub fn with_lease(mut self, lease: PayloadBuilderLease) -> Self {
611        self.leases.push(lease);
612        self
613    }
614
615    /// Returns the loaned execution cache, if any.
616    pub const fn execution_cache(&self) -> Option<&SavedCache> {
617        self.execution_cache.as_ref()
618    }
619
620    /// Takes the loaned execution cache, if any.
621    pub const fn take_execution_cache(&mut self) -> Option<SavedCache> {
622        self.execution_cache.take()
623    }
624
625    /// Returns the loaned state-root task handle, if any.
626    pub const fn state_root_handle(&self) -> Option<&PayloadStateRootHandle> {
627        self.state_root_handle.as_ref()
628    }
629
630    /// Takes the loaned state-root task handle, if any.
631    pub const fn take_state_root_handle(&mut self) -> Option<PayloadStateRootHandle> {
632        self.state_root_handle.take()
633    }
634
635    /// Takes lifecycle leases for a payload job that owns detached work.
636    pub fn take_leases(&mut self) -> Vec<PayloadBuilderLease> {
637        std::mem::take(&mut self.leases)
638    }
639
640    /// Clones lifecycle leases for the payload builder service to retain.
641    fn clone_leases(&self) -> Vec<PayloadBuilderLease> {
642        self.leases.clone()
643    }
644}
645
646/// Keeps a loaned resource active until the last lease clone is dropped.
647#[derive(Clone)]
648pub struct PayloadBuilderLease {
649    _lease: Arc<dyn Send + Sync>,
650}
651
652impl PayloadBuilderLease {
653    /// Wraps a lease that releases its resource when the last clone is dropped.
654    pub fn new(lease: impl Send + Sync + 'static) -> Self {
655        Self { _lease: Arc::new(lease) }
656    }
657}
658
659impl std::fmt::Debug for PayloadBuilderLease {
660    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
661        f.debug_struct("PayloadBuilderLease").finish_non_exhaustive()
662    }
663}
664
665/// An active payload job and its service metadata.
666#[derive(Debug)]
667struct PayloadJobEntry<Job> {
668    job: Job,
669    id: PayloadId,
670    span: Span,
671    leases: Vec<PayloadBuilderLease>,
672}
673
674#[cfg(test)]
675mod tests {
676    use super::*;
677    use crate::test_utils::test_payload_service;
678    use alloy_primitives::Address;
679    use reth_ethereum_engine_primitives::{EthEngineTypes, EthPayloadAttributes};
680    use std::sync::atomic::{AtomicBool, Ordering};
681
682    struct DropProbe(Arc<AtomicBool>);
683
684    impl Drop for DropProbe {
685        fn drop(&mut self) {
686            self.0.store(true, Ordering::Release);
687        }
688    }
689
690    #[test]
691    fn payload_builder_lease_is_held_until_resolve_finishes() {
692        tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
693            let (service, handle) = test_payload_service::<EthEngineTypes>();
694            let service = tokio::spawn(service);
695            let dropped = Arc::new(AtomicBool::new(false));
696            let lease = PayloadBuilderLease::new(DropProbe(Arc::clone(&dropped)));
697            let input = BuildNewPayload {
698                attributes: EthPayloadAttributes {
699                    timestamp: 1,
700                    prev_randao: B256::ZERO,
701                    suggested_fee_recipient: Address::ZERO,
702                    withdrawals: None,
703                    parent_beacon_block_root: None,
704                    slot_number: None,
705                    ..Default::default()
706                },
707                parent_hash: B256::ZERO,
708                resources: PayloadBuilderResources::default().with_lease(lease),
709            };
710
711            let id = handle.send_new_payload(input).await.unwrap().unwrap();
712            assert!(!dropped.load(Ordering::Acquire));
713
714            handle.resolve_kind(id, PayloadKind::Earliest).await.unwrap().unwrap();
715            assert!(dropped.load(Ordering::Acquire));
716            service.abort();
717        });
718    }
719}