1pub mod context_provider;
2pub mod req;
3pub mod retry;
4mod utils;
5
6use crate::context_provider::CardinalContextProvider;
7use crate::req::ReqCtx;
8use crate::retry::RetryState;
9use crate::utils::requests::{
10 compose_upstream_url, execution_context_from_request, parse_origin, rewrite_request_path,
11 set_upstream_host_headers,
12};
13use bytes::Bytes;
14use cardinal_base::context::CardinalContext;
15use cardinal_base::destinations::container::DestinationContainer;
16use cardinal_plugins::plugin_executor::CardinalPluginExecutor;
17use cardinal_plugins::request_context::RequestContext;
18use cardinal_plugins::runner::MiddlewareResult;
19use pingora::http::ResponseHeader;
20use pingora::prelude::*;
21use pingora::protocols::Digest;
22use pingora::upstreams::peer::Peer;
23use std::sync::Arc;
24use std::time::Duration;
25use tracing::{debug, error, info, warn};
26
27pub mod pingora {
28 pub use pingora::*;
29}
30
31#[derive(Debug, Clone)]
32pub enum HealthCheckStatus {
33 None,
34 Ready,
35 Unavailable {
36 status_code: u16,
37 reason: Option<String>,
38 },
39}
40
41#[derive(Clone)]
42pub struct StaticContextProvider {
43 context: Arc<CardinalContext>,
44}
45
46impl StaticContextProvider {
47 pub fn new(context: Arc<CardinalContext>) -> Self {
48 Self { context }
49 }
50}
51
52impl CardinalContextProvider for StaticContextProvider {
53 fn resolve(&self, _session: &Session, _ctx: &mut ReqCtx) -> Option<Arc<CardinalContext>> {
54 Some(self.context.clone())
55 }
56}
57
58#[async_trait::async_trait]
59impl CardinalPluginExecutor for StaticContextProvider {}
60
61pub struct CardinalProxy {
62 provider: Arc<dyn CardinalContextProvider>,
63 plugin_executor: Arc<dyn CardinalPluginExecutor>,
64}
65
66impl CardinalProxy {
67 pub fn new(context: Arc<CardinalContext>) -> Self {
68 Self::builder(context).build()
69 }
70
71 pub fn with_provider(
72 provider: Arc<dyn CardinalContextProvider>,
73 plugin_executor: Arc<dyn CardinalPluginExecutor>,
74 ) -> Self {
75 Self {
76 provider,
77 plugin_executor,
78 }
79 }
80
81 pub fn builder(context: Arc<CardinalContext>) -> CardinalProxyBuilder {
82 CardinalProxyBuilder::new(context)
83 }
84}
85
86pub struct CardinalProxyBuilder {
87 provider: Arc<dyn CardinalContextProvider>,
88 plugin_executor: Arc<dyn CardinalPluginExecutor>,
89}
90
91impl CardinalProxyBuilder {
92 pub fn new(context: Arc<CardinalContext>) -> Self {
93 Self {
94 provider: Arc::new(StaticContextProvider::new(context.clone())),
95 plugin_executor: Arc::new(StaticContextProvider::new(context)),
96 }
97 }
98
99 pub fn from_context_provider(
100 provider: Arc<dyn CardinalContextProvider>,
101 plugin_executor: Arc<dyn CardinalPluginExecutor>,
102 ) -> Self {
103 Self {
104 provider,
105 plugin_executor,
106 }
107 }
108
109 pub fn with_context_provider(
110 mut self,
111 provider: Arc<dyn CardinalContextProvider>,
112 plugin_executor: Arc<dyn CardinalPluginExecutor>,
113 ) -> Self {
114 self.provider = provider;
115 self.plugin_executor = plugin_executor;
116 self
117 }
118
119 pub fn build(self) -> CardinalProxy {
120 CardinalProxy::with_provider(self.provider, self.plugin_executor)
121 }
122}
123
124#[async_trait::async_trait]
125impl ProxyHttp for CardinalProxy {
126 type CTX = ReqCtx;
127
128 fn new_ctx(&self) -> Self::CTX {
129 self.provider.ctx()
130 }
131
132 async fn early_request_filter(&self, _session: &mut Session, _ctx: &mut Self::CTX) -> Result<()>
133 where
134 Self::CTX: Send + Sync,
135 {
136 self.provider.early_request_filter(_session, _ctx).await
137 }
138
139 async fn logging(&self, _session: &mut Session, _e: Option<&Error>, ctx: &mut Self::CTX)
140 where
141 Self::CTX: Send + Sync,
142 {
143 self.provider.logging(_session, _e, ctx);
144 }
145
146 async fn request_filter(&self, session: &mut Session, ctx: &mut Self::CTX) -> Result<bool> {
147 let path = session.req_header().uri.path().to_string();
148 info!(%path, "Request received");
149
150 match self.provider.health_check(session) {
151 HealthCheckStatus::None => {}
152 HealthCheckStatus::Ready => {
153 debug!(%path, "Health check ready");
154 let mut resp = ResponseHeader::build(200, None)?;
156 resp.insert_header("Content-Type", "text/plain")?;
157 resp.set_content_length("healthy\n".len())?;
158
159 session
161 .write_response_header(Box::new(resp), false)
162 .await?;
163 session
164 .write_response_body(Some(Bytes::from_static(b"healthy\n")), true)
165 .await?;
166
167 return Ok(true);
169 }
170 HealthCheckStatus::Unavailable {
171 status_code,
172 reason,
173 } => {
174 if let Some(reason) = reason {
175 warn!(%path, status = status_code, reason = %reason, "Health check failed");
176 } else {
177 warn!(%path, status = status_code, "Health check failed");
178 }
179 let _ = session.respond_error(status_code).await;
180 return Ok(true);
181 }
182 }
183
184 let context = match self.provider.resolve(session, ctx) {
185 Some(ctx) => ctx,
186 None => {
187 warn!(%path, "No context found for request host");
188 let _ = session.respond_error(421).await;
189 return Ok(true);
190 }
191 };
192
193 let destination_container = context
194 .get::<DestinationContainer>()
195 .await
196 .map_err(|_| Error::new_str("Destination Container is not present"))?;
197
198 let force_path = context.config.server.force_path_parameter;
199 let backend =
200 match destination_container.get_backend_for_request(session.req_header(), force_path) {
201 Some(b) => b,
202 None => {
203 warn!(%path, "No matching backend, returning 404");
204 let _ = session.respond_error(404).await;
205 return Ok(true);
206 }
207 };
208
209 let destination_name = backend.destination.name.clone();
210 let _ = set_upstream_host_headers(session, &backend);
211 info!(backend_id = %destination_name, "Routing to backend");
212
213 rewrite_request_path(session.req_header_mut(), &destination_name, force_path);
214
215 let mut request_state = RequestContext::new(
216 context.clone(),
217 backend,
218 execution_context_from_request(session),
219 self.plugin_executor.clone(),
220 );
221
222 let plugin_runner = request_state.plugin_runner.clone();
223
224 let run_filters = plugin_runner
225 .run_request_filters(session, &mut request_state)
226 .await;
227
228 let res = match run_filters {
229 Ok(filter_result) => filter_result,
230 Err(err) => {
231 error!(%err, "Error running request filters");
232 let _ = session.respond_error(500).await;
233 return Ok(true);
234 }
235 };
236
237 ctx.set_resolved_request(request_state);
238
239 match res {
240 MiddlewareResult::Continue(resp_headers) => {
241 ctx.ctx_base
242 .resolved_request
243 .as_mut()
244 .unwrap()
245 .response_headers = Some(resp_headers);
246
247 Ok(false)
248 }
249 MiddlewareResult::Responded => Ok(true),
250 }
251 }
252
253 fn fail_to_connect(
254 &self,
255 _session: &mut Session,
256 _peer: &HttpPeer,
257 ctx: &mut Self::CTX,
258 mut e: Box<Error>,
259 ) -> Box<Error> {
260 let backend_config = ctx.req_unsafe().backend.destination.retry.clone();
261 if let Some(mut retry_state) = ctx.retry_state.take() {
262 retry_state.register_attempt();
263 if retry_state.can_retry() {
264 e.set_retry(true);
265 ctx.retry_state = Some(retry_state);
266 } else {
267 ctx.retry_state = None;
268 }
269 } else if let Some(retry_config) = backend_config {
270 let mut retry_state = RetryState::from(retry_config);
271 retry_state.register_attempt();
272 if retry_state.can_retry() {
273 e.set_retry(true);
274 ctx.retry_state = Some(retry_state);
275 } else {
276 ctx.retry_state = None;
277 }
278 }
279
280 e
281 }
282
283 async fn upstream_peer(
284 &self,
285 _session: &mut Session,
286 ctx: &mut Self::CTX,
287 ) -> Result<Box<HttpPeer>> {
288 if let Some(retry_state) = ctx.retry_state.as_mut() {
289 if !retry_state.sleep_if_retry_allowed().await {
290 ctx.retry_state = None;
291 return Err(Error::new_str("Retry attempts exhausted"));
292 }
293 }
294
295 let backend = &ctx.req_unsafe().backend;
296 let (host, port, is_tls) = parse_origin(&backend.destination.url)
298 .map_err(|_| Error::new_str("Origin could not be parsed "))?;
299 let hostport = format!("{host}:{port}");
300
301 let path_and_query = _session
303 .req_header()
304 .uri
305 .path_and_query()
306 .map(|pq| pq.as_str())
307 .unwrap_or("/");
308 let upstream_url = compose_upstream_url(is_tls, &host, port, path_and_query);
309
310 info!(%upstream_url, backend_id = %&backend.destination.name, is_tls, sni = %host, "Forwarding to upstream");
311 debug!(upstream_origin = %hostport, "Connecting to upstream origin");
312
313 let mut peer = HttpPeer::new(&hostport, is_tls, host);
314 if let Some(opts) = peer.get_mut_peer_options() {
315 opts.set_http_version(2, 1);
317 if let Some(timeout) = &backend.destination.timeout {
318 opts.idle_timeout = timeout
319 .idle
320 .as_ref()
321 .map(|idle| Duration::from_millis(*idle));
322 opts.write_timeout = timeout
323 .write
324 .as_ref()
325 .map(|idle| Duration::from_millis(*idle));
326 opts.total_connection_timeout = timeout
327 .connect
328 .as_ref()
329 .map(|idle| Duration::from_millis(*idle));
330 opts.read_timeout = timeout
331 .read
332 .as_ref()
333 .map(|idle| Duration::from_millis(*idle));
334 }
335 }
336 let peer = Box::new(peer);
337 Ok(peer)
338 }
339
340 async fn connected_to_upstream(
341 &self,
342 _session: &mut Session,
343 reused: bool,
344 peer: &HttpPeer,
345 #[cfg(unix)] _fd: std::os::unix::io::RawFd,
346 #[cfg(windows)] _sock: std::os::windows::io::RawSocket,
347 _digest: Option<&Digest>,
348 ctx: &mut Self::CTX,
349 ) -> Result<()> {
350 ctx.retry_state = None;
351 let backend_id = ctx.req_unsafe().backend.destination.name.to_string();
352
353 info!(backend_id, reused, peer = %peer, "Connected to upstream");
354 Ok(())
355 }
356
357 async fn response_filter(
358 &self,
359 session: &mut Session,
360 upstream_response: &mut ResponseHeader,
361 ctx: &mut Self::CTX,
362 ) -> Result<()> {
363 if let Some(resp_headers) = ctx.req_unsafe_mut().response_headers.take() {
364 for (key, val) in resp_headers {
365 let _ = upstream_response.insert_header(key, val);
366 }
367 }
368
369 {
370 {
372 let runner = {
373 let req = ctx.req_unsafe_mut();
374 req.plugin_runner.clone()
375 };
376
377 runner
378 .run_response_filters(
379 session,
380 {
381 let req = ctx.req_unsafe_mut();
382 req
383 },
384 upstream_response,
385 )
386 .await;
387 }
388
389 ctx.set("status", upstream_response.status.as_str());
390
391 let req = ctx.req_unsafe_mut();
393
394 if !req.cardinal_context.config.server.log_upstream_response {
395 return Ok(());
396 }
397
398 let status = upstream_response.status.as_u16();
399 let location = upstream_response
400 .headers
401 .get("location")
402 .and_then(|v| v.to_str().ok())
403 .map(str::to_string);
404 let backend_id = &req.backend.destination.name;
405
406 match location {
407 Some(loc) => info!(backend_id, status, location = %loc, "Upstream responded"),
408 None => info!(backend_id, status, "Upstream responded"),
409 }
410 }
411
412 Ok(())
413 }
414}