|
| 1 | +//! consistent_request.rs |
| 2 | +use std::{ |
| 3 | + sync::{ |
| 4 | + Arc, |
| 5 | + atomic::{AtomicBool, Ordering}, |
| 6 | + }, |
| 7 | + time::Duration, |
| 8 | +}; |
| 9 | + |
| 10 | +use eyre::{Result as EyreResult, bail}; |
| 11 | +use jsonrpsee::{core::BoxError, http_client::HttpBody}; |
| 12 | +use parking_lot::Mutex; |
| 13 | +use tokio::{sync::watch, task::JoinHandle}; |
| 14 | +use tracing::{error, info, warn}; |
| 15 | + |
| 16 | +use crate::{ |
| 17 | + BufferedRequest, BufferedResponse, ExecutionMode, Health, HttpClient, Probes, Response, |
| 18 | +}; |
| 19 | + |
| 20 | +/// A request manager that ensures requests are sent consistently |
| 21 | +/// across both the builder and l2 client. |
| 22 | +#[derive(Clone)] |
| 23 | +pub struct ConsistentRequest { |
| 24 | + method: String, |
| 25 | + l2_client: HttpClient, |
| 26 | + builder_client: HttpClient, |
| 27 | + has_disabled_execution_mode: Arc<AtomicBool>, |
| 28 | + req_tx: watch::Sender<Option<BufferedRequest>>, |
| 29 | + res_rx: watch::Receiver<Option<Result<BufferedResponse, BoxError>>>, |
| 30 | + probes: Arc<Probes>, |
| 31 | + execution_mode: Arc<Mutex<ExecutionMode>>, |
| 32 | +} |
| 33 | + |
| 34 | +impl ConsistentRequest { |
| 35 | + pub fn new( |
| 36 | + method: String, |
| 37 | + l2_client: HttpClient, |
| 38 | + builder_client: HttpClient, |
| 39 | + probes: Arc<Probes>, |
| 40 | + execution_mode: Arc<Mutex<ExecutionMode>>, |
| 41 | + ) -> Self { |
| 42 | + let (req_tx, mut req_rx) = watch::channel(None); |
| 43 | + let (res_tx, mut res_rx) = watch::channel(None); |
| 44 | + req_rx.mark_unchanged(); |
| 45 | + res_rx.mark_unchanged(); |
| 46 | + |
| 47 | + let has_disabled_execution_mode = Arc::new(AtomicBool::new(false)); |
| 48 | + |
| 49 | + let manager = Self { |
| 50 | + method, |
| 51 | + l2_client, |
| 52 | + builder_client, |
| 53 | + has_disabled_execution_mode, |
| 54 | + req_tx, |
| 55 | + res_rx, |
| 56 | + probes, |
| 57 | + execution_mode, |
| 58 | + }; |
| 59 | + |
| 60 | + let clone = manager.clone(); |
| 61 | + tokio::spawn(async move { |
| 62 | + let mut attempt: Option<JoinHandle<_>> = None; |
| 63 | + loop { |
| 64 | + req_rx |
| 65 | + .changed() |
| 66 | + .await |
| 67 | + .expect("channel should always be open"); |
| 68 | + |
| 69 | + if let Some(attempt) = attempt { |
| 70 | + if !attempt.is_finished() { |
| 71 | + error!( |
| 72 | + target: "proxy::call", |
| 73 | + method = clone.method, |
| 74 | + "request cancelled" |
| 75 | + ); |
| 76 | + attempt.abort(); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + let req = req_rx |
| 81 | + .borrow_and_update() |
| 82 | + .as_ref() |
| 83 | + .expect("value should always be Some") |
| 84 | + .clone(); |
| 85 | + |
| 86 | + let mut clone = clone.clone(); |
| 87 | + let res_tx_clone = res_tx.clone(); |
| 88 | + attempt = Some(tokio::spawn(async move { |
| 89 | + clone.send_with_retry_cancel_safe(req, res_tx_clone).await |
| 90 | + })); |
| 91 | + } |
| 92 | + }); |
| 93 | + |
| 94 | + manager |
| 95 | + } |
| 96 | + |
| 97 | + /// This function may be cancelled at any time from an incoming request. |
| 98 | + async fn send_with_retry_cancel_safe( |
| 99 | + &mut self, |
| 100 | + req: BufferedRequest, |
| 101 | + res_tx: watch::Sender<Option<Result<BufferedResponse, BoxError>>>, |
| 102 | + ) -> EyreResult<()> { |
| 103 | + // We send the l2 request first, because we need to avoid the situation where the |
| 104 | + // l2 fails and the builder succeeds. If this were to happen, it would be too dangerous to |
| 105 | + // return the l2 error response back to the caller, since the builder would now have an |
| 106 | + // invalid state. We can return early if the l2 request fails. Note we're specifically |
| 107 | + // spawning new tasks here to avoid any issues with cancellation. We should ensure we're |
| 108 | + // in a valid state at all await points. |
| 109 | + let mut manager = self.clone(); |
| 110 | + let res_tx_clone = res_tx.clone(); |
| 111 | + let req_clone = req.clone(); |
| 112 | + tokio::spawn(async move { manager.send_to_l2(req_clone, res_tx_clone).await }).await??; |
| 113 | + |
| 114 | + loop { |
| 115 | + let mut manager_clone = self.clone(); |
| 116 | + let req_clone = req.clone(); |
| 117 | + |
| 118 | + match tokio::spawn(async move { manager_clone.send_to_builder(req_clone).await }) |
| 119 | + .await? |
| 120 | + { |
| 121 | + Ok(_) => return Ok(()), |
| 122 | + Err(_) => tokio::time::sleep(Duration::from_millis(200)).await, |
| 123 | + } |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + async fn send_to_l2( |
| 128 | + &mut self, |
| 129 | + req: BufferedRequest, |
| 130 | + res_tx: watch::Sender<Option<Result<BufferedResponse, BoxError>>>, |
| 131 | + ) -> EyreResult<()> { |
| 132 | + let l2_res = self.l2_client.forward(req, self.method.clone()).await; |
| 133 | + match l2_res { |
| 134 | + Ok(_) => { |
| 135 | + res_tx.send(Some(l2_res))?; |
| 136 | + Ok(()) |
| 137 | + } |
| 138 | + Err(_) => { |
| 139 | + res_tx.send(Some(l2_res))?; |
| 140 | + Err(eyre::eyre!("failed to send request to L2 client")) |
| 141 | + } |
| 142 | + } |
| 143 | + } |
| 144 | + |
| 145 | + async fn send_to_builder(&mut self, req: BufferedRequest) -> EyreResult<()> { |
| 146 | + match self.builder_client.forward(req, self.method.clone()).await { |
| 147 | + Ok(_) => { |
| 148 | + if self.has_disabled_execution_mode.load(Ordering::SeqCst) { |
| 149 | + let mut mode = self.execution_mode.lock(); |
| 150 | + *mode = ExecutionMode::Enabled; |
| 151 | + drop(mode); |
| 152 | + self.has_disabled_execution_mode |
| 153 | + .store(false, Ordering::SeqCst); |
| 154 | + info!(target: "proxy::call", message = "setting execution mode to Enabled"); |
| 155 | + } |
| 156 | + Ok(()) |
| 157 | + } |
| 158 | + Err(e) => { |
| 159 | + // l2 request succeeded, but builder request failed |
| 160 | + // This state can only be recovered from if either the builder is restarted |
| 161 | + // or if a retry eventually goes through. |
| 162 | + error!(target: "proxy::call", method = self.method, "inconsistent responses from builder and L2"); |
| 163 | + let mut mode = self.execution_mode.lock(); |
| 164 | + if *mode == ExecutionMode::Enabled { |
| 165 | + *mode = ExecutionMode::Disabled; |
| 166 | + // Drop before aquiring health lock |
| 167 | + drop(mode); |
| 168 | + self.has_disabled_execution_mode |
| 169 | + .store(true, Ordering::SeqCst); |
| 170 | + warn!(target: "proxy::call", "setting execution mode to Disabled"); |
| 171 | + // This health status will likely be later set back to healthy |
| 172 | + // but this should be enough to trigger a new leader election. |
| 173 | + self.probes.set_health(Health::PartialContent); |
| 174 | + } |
| 175 | + |
| 176 | + bail!("failed to send request to builder: {e}"); |
| 177 | + } |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + // Send a request, ensuring consistent responses from both the builder and l2 client. |
| 182 | + pub async fn send(&mut self, req: BufferedRequest) -> Result<Response, BoxError> { |
| 183 | + self.req_tx.send(Some(req))?; |
| 184 | + self.res_rx.changed().await?; |
| 185 | + match self |
| 186 | + .res_rx |
| 187 | + .borrow_and_update() |
| 188 | + .as_ref() |
| 189 | + .expect("value should always be Some") |
| 190 | + { |
| 191 | + Ok(v) => Ok(v.clone().map(HttpBody::new)), |
| 192 | + Err(e) => Err(format!("error sending consistent request: {e}").into()), |
| 193 | + } |
| 194 | + } |
| 195 | +} |
0 commit comments