greentic_runner_host/runner/approval_http/
mod.rs1pub mod wire;
52
53mod poller;
54#[cfg(test)]
55mod tests;
56
57use std::collections::HashMap;
58use std::sync::Arc;
59use std::time::Duration;
60
61use anyhow::{Result, anyhow, bail};
62use async_trait::async_trait;
63use greentic_types::{DispatchMode, EnvId, TenantCtx, TenantId};
64use parking_lot::Mutex;
65use secrecy::{ExposeSecret, SecretString};
66use tokio::sync::Notify;
67use tokio::time::Instant;
68use tokio_util::sync::CancellationToken;
69
70use super::dispatch_listener::SessionResumer;
71use super::remote_dispatch::{RemoteDispatch, RemoteDispatchAction, RemoteDispatchHandler};
72
73pub use wire::{
74 APPROVAL_RAIL_HEADER, APPROVAL_RAIL_USER_AGENT, APPROVAL_RAIL_VERSION, ApprovalDecisionBody,
75 ApprovalDecisionKind, ApprovalRequestBody, ApprovalWithdrawBody, WithdrawReason,
76};
77
78pub const MAX_APPROVAL_WAIT: Duration = Duration::from_secs(7 * 24 * 60 * 60);
81
82const CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
84const REQUEST_TIMEOUT: Duration = Duration::from_secs(15);
86
87#[derive(Clone)]
91pub struct ApprovalInboxTarget {
92 pub request_url: String,
94 pub decision_url: String,
96 pub withdraw_url: String,
98 pub token: String,
101 pub tenant_slug: String,
103}
104
105impl std::fmt::Debug for ApprovalInboxTarget {
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 f.debug_struct("ApprovalInboxTarget")
108 .field("request_url", &self.request_url)
109 .field("decision_url", &self.decision_url)
110 .field("withdraw_url", &self.withdraw_url)
111 .field("token", &"<redacted>")
112 .field("tenant_slug", &self.tenant_slug)
113 .finish()
114 }
115}
116
117#[derive(Debug, thiserror::Error)]
120pub enum ApprovalInboxError {
121 #[error("approval inbox needs a non-blank `{0}`")]
122 Blank(&'static str),
123 #[error(
124 "approval inbox `{0}` is not https and not loopback http; refusing to send a bearer \
125 token in cleartext"
126 )]
127 UnsafeUrl(String),
128 #[error("approval inbox has no HTTP client: {0}")]
129 Client(String),
130}
131
132#[derive(Clone, Debug)]
134pub(crate) struct Timing {
135 pub(crate) send_retry_delays: Vec<Duration>,
137 pub(crate) fast_interval: Duration,
139 pub(crate) fast_window: Duration,
141 pub(crate) slow_interval: Duration,
143 pub(crate) backoff: Duration,
145 pub(crate) max_wait: Duration,
147}
148
149impl Default for Timing {
150 fn default() -> Self {
151 Self {
152 send_retry_delays: vec![
153 Duration::from_secs(1),
154 Duration::from_secs(4),
155 Duration::from_secs(10),
156 ],
157 fast_interval: Duration::from_secs(5),
158 fast_window: Duration::from_secs(60),
159 slow_interval: Duration::from_secs(15),
160 backoff: Duration::from_secs(60),
161 max_wait: MAX_APPROVAL_WAIT,
162 }
163 }
164}
165
166pub(crate) struct Pending {
168 pub(crate) tenant: TenantCtx,
170 pub(crate) env: String,
171 pub(crate) decision_token: Option<SecretString>,
173 pub(crate) registered_at: Instant,
174 pub(crate) deadline_at: Instant,
175 pub(crate) deadline_ms: u64,
177 pub(crate) deadline_reason: WithdrawReason,
179 pub(crate) next_poll_at: Instant,
180}
181
182pub(crate) struct Inner {
183 pub(crate) request_url: String,
184 pub(crate) decision_url: url::Url,
185 pub(crate) withdraw_url: String,
186 pub(crate) token: SecretString,
187 pub(crate) tenant_slug: String,
188 pub(crate) http: reqwest::Client,
189 pub(crate) timing: Timing,
190 pub(crate) pending: Mutex<HashMap<String, Pending>>,
191 pub(crate) resumer: Mutex<Option<Arc<dyn SessionResumer>>>,
192 pub(crate) cancel: CancellationToken,
193 pub(crate) wake: Notify,
194 pub(crate) poller_started: Mutex<bool>,
195}
196
197#[derive(Clone)]
201pub struct HttpApprovalDispatcher {
202 pub(crate) inner: Arc<Inner>,
203}
204
205impl std::fmt::Debug for HttpApprovalDispatcher {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 f.debug_struct("HttpApprovalDispatcher")
208 .field("request_url", &self.inner.request_url)
209 .field("token", &"<redacted>")
210 .field("tenant_slug", &self.inner.tenant_slug)
211 .field("pending", &self.inner.pending.lock().len())
212 .finish()
213 }
214}
215
216fn required(field: &'static str, value: &str) -> Result<String, ApprovalInboxError> {
217 let trimmed = value.trim();
218 if trimmed.is_empty() {
219 return Err(ApprovalInboxError::Blank(field));
220 }
221 Ok(trimmed.to_string())
222}
223
224fn safe_url(field: &'static str, value: &str) -> Result<url::Url, ApprovalInboxError> {
226 let value = required(field, value)?;
227 let unsafe_url = || ApprovalInboxError::UnsafeUrl(value.clone());
228 let url = url::Url::parse(&value).map_err(|_| unsafe_url())?;
229 let safe = match url.scheme() {
230 "https" => url.host().is_some(),
231 "http" => match url.host() {
232 Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
233 Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
234 Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
235 None => false,
236 },
237 _ => false,
238 };
239 if safe { Ok(url) } else { Err(unsafe_url()) }
240}
241
242impl HttpApprovalDispatcher {
243 pub fn new(target: ApprovalInboxTarget) -> Result<Self, ApprovalInboxError> {
247 Self::with_timing(target, Timing::default())
248 }
249
250 pub(crate) fn with_timing(
251 target: ApprovalInboxTarget,
252 timing: Timing,
253 ) -> Result<Self, ApprovalInboxError> {
254 let request_url = safe_url("request_url", &target.request_url)?;
255 let decision_url = safe_url("decision_url", &target.decision_url)?;
256 let withdraw_url = safe_url("withdraw_url", &target.withdraw_url)?;
257 let token = required("token", &target.token)?;
258 let tenant_slug = required("tenant_slug", &target.tenant_slug)?;
259 let http = reqwest::Client::builder()
260 .timeout(REQUEST_TIMEOUT)
261 .connect_timeout(CONNECT_TIMEOUT)
262 .user_agent(APPROVAL_RAIL_USER_AGENT)
263 .build()
264 .map_err(|err| ApprovalInboxError::Client(err.to_string()))?;
265 Ok(Self {
266 inner: Arc::new(Inner {
267 request_url: request_url.to_string(),
268 decision_url,
269 withdraw_url: withdraw_url.to_string(),
270 token: SecretString::from(token),
271 tenant_slug,
272 http,
273 timing,
274 pending: Mutex::new(HashMap::new()),
275 resumer: Mutex::new(None),
276 cancel: CancellationToken::new(),
277 wake: Notify::new(),
278 poller_started: Mutex::new(false),
279 }),
280 })
281 }
282
283 pub fn attach_resumer(&self, resumer: Arc<dyn SessionResumer>) {
287 if self.inner.cancel.is_cancelled() {
288 return;
289 }
290 *self.inner.resumer.lock() = Some(resumer);
291 }
292
293 pub fn shutdown(&self) {
298 self.inner.cancel.cancel();
299 self.inner.pending.lock().clear();
300 self.inner.resumer.lock().take();
301 }
302
303 pub fn cancellation_token(&self) -> CancellationToken {
305 self.inner.cancel.clone()
306 }
307
308 pub fn pending_count(&self) -> usize {
310 self.inner.pending.lock().len()
311 }
312
313 fn authed(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
314 builder
315 .bearer_auth(self.inner.token.expose_secret())
316 .header(APPROVAL_RAIL_HEADER, APPROVAL_RAIL_VERSION)
317 }
318
319 async fn send(&self, body: &ApprovalRequestBody) -> Result<()> {
322 let delays = self.inner.timing.send_retry_delays.clone();
323 let mut last = String::new();
324 for attempt in 0..=delays.len() {
325 if attempt > 0 {
326 tokio::time::sleep(delays[attempt - 1]).await;
327 }
328 let sent = self
329 .authed(self.inner.http.post(&self.inner.request_url))
330 .json(body)
331 .send()
332 .await;
333 let response = match sent {
334 Ok(response) => response,
335 Err(error) => {
336 last = format!("transport error: {}", error.without_url());
337 continue;
338 }
339 };
340 let status = response.status();
341 if status.is_success() {
342 return Ok(());
343 }
344 let text = response.text().await.unwrap_or_default();
345 if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
346 if text.contains(wire::PENDING_CAP_CODE) {
347 bail!(
348 "approval inbox refused the request: this worker already has the maximum \
349 number of pending approvals ({})",
350 wire::PENDING_CAP_CODE
351 );
352 }
353 last = format!("HTTP {status}");
354 continue;
355 }
356 if status.is_server_error() {
357 last = format!("HTTP {status}");
358 continue;
359 }
360 bail!("approval inbox refused the request with HTTP {status}");
361 }
362 Err(anyhow!(
363 "approval inbox did not record the request after {} attempts ({last})",
364 delays.len() + 1
365 ))
366 }
367
368 fn register(&self, correlation_id: String, pending: Pending) {
369 self.inner.pending.lock().insert(correlation_id, pending);
370 self.ensure_poller();
371 self.inner.wake.notify_one();
372 }
373
374 fn ensure_poller(&self) {
375 let mut started = self.inner.poller_started.lock();
376 if *started || self.inner.cancel.is_cancelled() {
377 return;
378 }
379 *started = true;
380 tokio::spawn(poller::run(Arc::clone(&self.inner)));
381 }
382}
383
384fn effective_deadline(node_deadline_ms: Option<u64>, cap: Duration) -> (u64, WithdrawReason) {
388 let cap_ms = u64::try_from(cap.as_millis()).unwrap_or(u64::MAX);
389 match node_deadline_ms {
390 Some(ms) if ms <= cap_ms => (ms, WithdrawReason::Timeout),
391 _ => (cap_ms, WithdrawReason::PollCap),
392 }
393}
394
395#[async_trait]
396impl RemoteDispatchHandler for HttpApprovalDispatcher {
397 async fn dispatch(&self, request: RemoteDispatch) -> Result<RemoteDispatchAction> {
398 if request.runtime != crate::runner::engine::APPROVAL_RUNTIME {
399 bail!(
400 "{}.call dispatched to the approval inbox, which serves only approval.call",
401 request.runtime
402 );
403 }
404 if self.inner.cancel.is_cancelled() {
405 bail!("approval inbox is shut down; this revision is no longer serving");
406 }
407 let tenant = TenantCtx::new(
408 EnvId::try_from(request.env.as_str())
409 .map_err(|error| anyhow!("invalid env for approval dispatch: {error}"))?,
410 TenantId::try_from(request.tenant.as_str())
411 .map_err(|error| anyhow!("invalid tenant for approval dispatch: {error}"))?,
412 );
413 let (deadline_ms, deadline_reason) =
414 effective_deadline(request.deadline_ms, self.inner.timing.max_wait);
415 let body = wire::request_body(
416 &self.inner.tenant_slug,
417 &request.correlation_id,
418 &request.target,
419 &request.operation,
420 request.mode,
421 request.input,
422 deadline_ms,
423 );
424 self.send(&body).await?;
425
426 match request.mode {
427 DispatchMode::FireAndForget => Ok(RemoteDispatchAction::Dispatched),
428 DispatchMode::Await => {
429 let now = Instant::now();
430 self.register(
431 request.correlation_id.clone(),
432 Pending {
433 tenant,
434 env: request.env,
435 decision_token: request.decision_token.map(SecretString::from),
436 registered_at: now,
437 deadline_at: now + Duration::from_millis(deadline_ms),
438 deadline_ms,
439 deadline_reason,
440 next_poll_at: now + self.inner.timing.fast_interval,
441 },
442 );
443 Ok(RemoteDispatchAction::AwaitingResponse {
444 correlation_id: request.correlation_id,
445 })
446 }
447 }
448 }
449}
450
451pub(crate) fn inbox_to_install(
455 nats_connected: bool,
456 target: Option<ApprovalInboxTarget>,
457) -> Option<ApprovalInboxTarget> {
458 if nats_connected { None } else { target }
459}