|
| 1 | +use std::time::Duration; |
| 2 | + |
| 3 | +use futures_util::future::Either; |
| 4 | +use worker::{ |
| 5 | + event, AbortController, AbortSignal, Context, Delay, Env, Fetch, Request, Response, Result, |
| 6 | + RouteContext, Router, |
| 7 | +}; |
| 8 | + |
| 9 | +fn get_target_url(req: &Request) -> Result<String> { |
| 10 | + req.url()? |
| 11 | + .query_pairs() |
| 12 | + .find(|(k, _)| k == "url") |
| 13 | + .map(|(_, v)| v.into_owned()) |
| 14 | + .ok_or_else(|| worker::Error::RustError("Missing 'url' query param".into())) |
| 15 | +} |
| 16 | + |
| 17 | +async fn abort_immediate(req: Request, _ctx: RouteContext<()>) -> Result<Response> { |
| 18 | + let target = get_target_url(&req)?; |
| 19 | + |
| 20 | + let signal = AbortSignal::abort(); |
| 21 | + let fetch = Fetch::Url(target.parse()?); |
| 22 | + |
| 23 | + match fetch.send_with_signal(&signal).await { |
| 24 | + Ok(mut resp) => { |
| 25 | + let text = resp.text().await?; |
| 26 | + Response::ok(format!("Unexpected success: {text}")) |
| 27 | + } |
| 28 | + Err(e) => Response::ok(format!("Aborted: {e}")), |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +async fn abort_timeout(req: Request, _ctx: RouteContext<()>) -> Result<Response> { |
| 33 | + let target = get_target_url(&req)?; |
| 34 | + |
| 35 | + let timeout_ms: u64 = req |
| 36 | + .url()? |
| 37 | + .query_pairs() |
| 38 | + .find(|(k, _)| k == "timeout") |
| 39 | + .and_then(|(_, v)| v.parse().ok()) |
| 40 | + .unwrap_or(2000); |
| 41 | + |
| 42 | + let url = target.parse()?; |
| 43 | + let controller = AbortController::default(); |
| 44 | + let signal = controller.signal(); |
| 45 | + |
| 46 | + let fetch_fut = async { |
| 47 | + let mut resp = Fetch::Url(url).send_with_signal(&signal).await?; |
| 48 | + let text = resp.text().await?; |
| 49 | + Ok::<_, worker::Error>(text) |
| 50 | + }; |
| 51 | + |
| 52 | + let timeout_fut = async { |
| 53 | + Delay::from(Duration::from_millis(timeout_ms)).await; |
| 54 | + controller.abort(); |
| 55 | + }; |
| 56 | + |
| 57 | + futures_util::pin_mut!(fetch_fut); |
| 58 | + futures_util::pin_mut!(timeout_fut); |
| 59 | + |
| 60 | + match futures_util::future::select(timeout_fut, fetch_fut).await { |
| 61 | + Either::Left((_timed_out, _cancelled)) => { |
| 62 | + Response::ok(format!("Request timed out after {timeout_ms}ms")) |
| 63 | + } |
| 64 | + Either::Right((Ok(body), _)) => Response::ok(format!("Got response: {body}")), |
| 65 | + Either::Right((Err(e), _)) => Response::ok(format!("Fetch error: {e}")), |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +#[event(fetch)] |
| 70 | +pub async fn main(req: Request, env: Env, _ctx: Context) -> Result<Response> { |
| 71 | + Router::new() |
| 72 | + .get_async("/abort", abort_immediate) |
| 73 | + .get_async("/timeout", abort_timeout) |
| 74 | + .run(req, env) |
| 75 | + .await |
| 76 | +} |
0 commit comments