pingora_core/apps/mod.rs
1// Copyright 2025 Cloudflare, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The abstraction and implementation interface for service application logic
16
17pub mod http_app;
18pub mod prometheus_http_app;
19
20use crate::server::ShutdownWatch;
21use async_trait::async_trait;
22use log::{debug, error};
23use std::future::poll_fn;
24use std::sync::Arc;
25
26use crate::protocols::http::v2::server;
27use crate::protocols::http::ServerSession;
28use crate::protocols::Digest;
29use crate::protocols::Stream;
30use crate::protocols::ALPN;
31
32// https://datatracker.ietf.org/doc/html/rfc9113#section-3.4
33const H2_PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
34
35#[async_trait]
36/// This trait defines the interface of a transport layer (TCP or TLS) application.
37pub trait ServerApp {
38 /// Whenever a new connection is established, this function will be called with the established
39 /// [`Stream`] object provided.
40 ///
41 /// The application can do whatever it wants with the `session`.
42 ///
43 /// After processing the `session`, if the `session`'s connection is reusable, This function
44 /// can return it to the service by returning `Some(session)`. The returned `session` will be
45 /// fed to another [`Self::process_new()`] for another round of processing.
46 /// If not reusable, `None` should be returned.
47 ///
48 /// The `shutdown` argument will change from `false` to `true` when the server receives a
49 /// signal to shutdown. This argument allows the application to react accordingly.
50 async fn process_new(
51 self: &Arc<Self>,
52 mut session: Stream,
53 // TODO: make this ShutdownWatch so that all task can await on this event
54 shutdown: &ShutdownWatch,
55 ) -> Option<Stream>;
56
57 /// This callback will be called once after the service stops listening to its endpoints.
58 async fn cleanup(&self) {}
59}
60#[non_exhaustive]
61#[derive(Default)]
62/// HTTP Server options that control how the server handles some transport types.
63pub struct HttpServerOptions {
64 /// Use HTTP/2 for plaintext.
65 pub h2c: bool,
66}
67
68#[derive(Debug, Clone)]
69pub struct HttpPersistentSettings {
70 keepalive_timeout: Option<u64>,
71}
72
73impl HttpPersistentSettings {
74 pub fn for_session(session: &ServerSession) -> Self {
75 HttpPersistentSettings {
76 keepalive_timeout: session.get_keepalive(),
77 }
78 }
79
80 pub fn apply_to_session(&self, session: &mut ServerSession) {
81 session.set_keepalive(self.keepalive_timeout);
82 }
83}
84
85#[derive(Debug)]
86pub struct ReusedHttpStream {
87 stream: Stream,
88 persistent_settings: Option<HttpPersistentSettings>,
89}
90
91impl ReusedHttpStream {
92 pub fn new(stream: Stream, persistent_settings: Option<HttpPersistentSettings>) -> Self {
93 ReusedHttpStream {
94 stream,
95 persistent_settings,
96 }
97 }
98
99 pub fn consume(self) -> (Stream, Option<HttpPersistentSettings>) {
100 (self.stream, self.persistent_settings)
101 }
102}
103
104/// This trait defines the interface of an HTTP application.
105#[async_trait]
106pub trait HttpServerApp {
107 /// Similar to the [`ServerApp`], this function is called whenever a new HTTP session is established.
108 ///
109 /// After successful processing, [`ServerSession::finish()`] can be called to return an optionally reusable
110 /// connection back to the service. The caller needs to make sure that the connection is in a reusable state
111 /// i.e., no error or incomplete read or write headers or bodies. Otherwise a `None` should be returned.
112 async fn process_new_http(
113 self: &Arc<Self>,
114 mut session: ServerSession,
115 // TODO: make this ShutdownWatch so that all task can await on this event
116 shutdown: &ShutdownWatch,
117 ) -> Option<ReusedHttpStream>;
118
119 /// Provide options on how HTTP/2 connection should be established. This function will be called
120 /// every time a new HTTP/2 **connection** needs to be established.
121 ///
122 /// A `None` means to use the built-in default options. See [`server::H2Options`] for more details.
123 fn h2_options(&self) -> Option<server::H2Options> {
124 None
125 }
126
127 /// Provide HTTP server options used to override default behavior. This function will be called
128 /// every time a new connection is processed.
129 ///
130 /// A `None` means no server options will be applied.
131 fn server_options(&self) -> Option<&HttpServerOptions> {
132 None
133 }
134
135 async fn http_cleanup(&self) {}
136}
137
138#[async_trait]
139impl<T> ServerApp for T
140where
141 T: HttpServerApp + Send + Sync + 'static,
142{
143 async fn process_new(
144 self: &Arc<Self>,
145 mut stream: Stream,
146 shutdown: &ShutdownWatch,
147 ) -> Option<Stream> {
148 let mut h2c = self.server_options().as_ref().map_or(false, |o| o.h2c);
149
150 // try to read h2 preface
151 if h2c {
152 let mut buf = [0u8; H2_PREFACE.len()];
153 let peeked = stream
154 .try_peek(&mut buf)
155 .await
156 .map_err(|e| {
157 // this error is normal when h1 reuse and close the connection
158 debug!("Read error while peeking h2c preface {e}");
159 e
160 })
161 .ok()?;
162 // not all streams support peeking
163 if peeked {
164 // turn off h2c (use h1) if h2 preface doesn't exist
165 h2c = buf == H2_PREFACE;
166 }
167 }
168 if h2c || matches!(stream.selected_alpn_proto(), Some(ALPN::H2)) {
169 // create a shared connection digest
170 let digest = Arc::new(Digest {
171 ssl_digest: stream.get_ssl_digest(),
172 // TODO: log h2 handshake time
173 timing_digest: stream.get_timing_digest(),
174 proxy_digest: stream.get_proxy_digest(),
175 socket_digest: stream.get_socket_digest(),
176 });
177
178 let h2_options = self.h2_options();
179 let h2_conn = server::handshake(stream, h2_options).await;
180 let mut h2_conn = match h2_conn {
181 Err(e) => {
182 error!("H2 handshake error {e}");
183 return None;
184 }
185 Ok(c) => c,
186 };
187
188 let mut shutdown = shutdown.clone();
189 loop {
190 // this loop ends when the client decides to close the h2 conn
191 // TODO: add a timeout?
192 let h2_stream = tokio::select! {
193 _ = shutdown.changed() => {
194 h2_conn.graceful_shutdown();
195 let _ = poll_fn(|cx| h2_conn.poll_closed(cx))
196 .await.map_err(|e| error!("H2 error waiting for shutdown {e}"));
197 return None;
198 }
199 h2_stream = server::HttpSession::from_h2_conn(&mut h2_conn, digest.clone()) => h2_stream
200 };
201 let h2_stream = match h2_stream {
202 Err(e) => {
203 // It is common for the client to just disconnect TCP without properly
204 // closing H2. So we don't log the errors here
205 debug!("H2 error when accepting new stream {e}");
206 return None;
207 }
208 Ok(s) => s?, // None means the connection is ready to be closed
209 };
210 let app = self.clone();
211 let shutdown = shutdown.clone();
212 pingora_runtime::current_handle().spawn(async move {
213 // Note, `PersistentSettings` not currently relevant for h2
214 app.process_new_http(ServerSession::new_http2(h2_stream), &shutdown)
215 .await;
216 });
217 }
218 } else {
219 // No ALPN or ALPN::H1 and h2c was not configured, fallback to HTTP/1.1
220 let mut session = ServerSession::new_http1(stream);
221 if *shutdown.borrow() {
222 // stop downstream from reusing if this service is shutting down soon
223 session.set_keepalive(None);
224 } else {
225 // default 60s
226 session.set_keepalive(Some(60));
227 }
228
229 let mut result = self.process_new_http(session, shutdown).await;
230 while let Some((stream, persistent_settings)) = result.map(|r| r.consume()) {
231 let mut session = ServerSession::new_http1(stream);
232 if let Some(persistent_settings) = persistent_settings {
233 persistent_settings.apply_to_session(&mut session);
234 }
235 if *shutdown.borrow() {
236 // stop downstream from reusing if this service is shutting down soon
237 session.set_keepalive(None);
238 }
239
240 result = self.process_new_http(session, shutdown).await;
241 }
242 }
243 None
244 }
245
246 async fn cleanup(&self) {
247 self.http_cleanup().await;
248 }
249}