ostrya_server/endpoint.rs
1//! The receive endpoint that a host mounts in its own router.
2
3use std::fmt;
4use std::ops::RangeInclusive;
5use std::sync::Arc;
6use std::time::Duration;
7
8use futures_lite::future;
9use hyper::body::{Body, Bytes};
10use hyper::{Request, Response};
11use ostrya::{ReceiveReport, Repo};
12
13use crate::body::ReceiveBody;
14use crate::error::{Error, Result};
15use crate::receive::Receive;
16use crate::receive_auth::ReceiveAuth;
17use crate::session::SessionTable;
18use crate::shutdown::Shutdown;
19
20/// The values of `parallel_uploads` that an endpoint takes.
21const PARALLEL_UPLOADS: RangeInclusive<u32> = 1..=31;
22
23/// The HTTP/2 receive window of one stream of a connection to an endpoint.
24/// The window of the connection is this value times `parallel_uploads`.
25const UPLOAD_WINDOW: u32 = 2 * 1024 * 1024;
26
27/// The options of [`ReceiveEndpoint::new`].
28///
29/// [`EndpointOptions::default`] holds the default value of each field.
30#[derive(Clone)]
31pub struct EndpointOptions {
32 /// The number of object streams that one session runs at the same time.
33 ///
34 /// `HelloReply` announces this number. The value is in `1..=31`, and the
35 /// default is 4. [`ReceiveEndpoint::h2_windows`] gives the HTTP/2
36 /// windows that follow from it.
37 pub parallel_uploads: u32,
38 /// The longest time that a session stays with no request in progress.
39 ///
40 /// It is also the longest time that a request body of a session delivers
41 /// no byte. After this time, the endpoint aborts the session. The default
42 /// is 300 seconds, and [`ReceiveEndpoint::new`] refuses zero.
43 pub session_idle_timeout: Duration,
44 /// The largest number of sessions that are open at the same time.
45 ///
46 /// The default is 16, and [`ReceiveEndpoint::new`] refuses zero.
47 pub max_sessions: usize,
48 /// The callback that gets the report of each session that committed.
49 ///
50 /// The endpoint calls it when the response body of the commit drops. If
51 /// the connection did not take the `CommitReply` frame, the report holds a
52 /// warning of the step
53 /// [`ReplyNotDelivered`](ostrya::ReceiveStep::ReplyNotDelivered). hyper
54 /// can take the frame and still fail to write it, so a reply that the
55 /// client did not get can come with no warning.
56 ///
57 /// The call runs on a task of the host, so the callback must return soon.
58 /// The default is `None`.
59 ///
60 /// In a session with hooks, the call comes after
61 /// [`ReceiveHooks::after_update`](ostrya::ReceiveHooks::after_update),
62 /// and only if `after_update` succeeds. If `after_update` returns an
63 /// error, only `after_update` gets the report.
64 /// [`SessionSetup::hooks`](crate::SessionSetup::hooks) states the other
65 /// effects of that error.
66 pub on_report: Option<Arc<dyn Fn(ReceiveReport) + Send + Sync>>,
67}
68
69/// The debug text shows `<callback>` for a report callback that is set.
70impl fmt::Debug for EndpointOptions {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 f.debug_struct("EndpointOptions")
73 .field("parallel_uploads", &self.parallel_uploads)
74 .field("session_idle_timeout", &self.session_idle_timeout)
75 .field("max_sessions", &self.max_sessions)
76 .field("on_report", &self.on_report.as_ref().map(|_| "<callback>"))
77 .finish()
78 }
79}
80
81impl Default for EndpointOptions {
82 fn default() -> EndpointOptions {
83 EndpointOptions {
84 parallel_uploads: 4,
85 session_idle_timeout: Duration::from_secs(300),
86 max_sessions: 16,
87 on_report: None,
88 }
89 }
90}
91
92/// The receive endpoint of a push, which a host mounts in its own router.
93///
94/// The endpoint serves one repository and uses the authentication `A`. It
95/// opens no listener and does no TLS. [`Server`](crate::Server) runs the
96/// same endpoint with its built-in authentication methods.
97///
98/// # Mounting
99///
100/// - [`handle`](ReceiveEndpoint::handle) takes a raw path that starts with
101/// `/_ostrya/receive/v1/`. If a host mounts the endpoint under a prefix,
102/// for example `/api/v1/push`, the host removes the prefix before the call.
103/// `Router::nest_service` of axum removes the prefix itself. The push
104/// address of a client is then `https://HOST/api/v1/push`.
105/// - The request body does not need to be `Sync`, so the body of axum fits.
106/// The response body is [`ReceiveBody`].
107/// - Run the future of [`sweep`](ReceiveEndpoint::sweep) once, in a task of
108/// its own, when the host starts. If no task runs it, no session reaches
109/// its idle timeout.
110/// - Call [`shutdown`](ReceiveEndpoint::shutdown) before the graceful
111/// shutdown of the listener.
112/// - Serve the endpoint on a dedicated listener, with a port or an SNI name
113/// of its own. A listener for other routes keeps its own windows.
114/// - On that listener, set the HTTP/2 windows of
115/// [`h2_windows`](ReceiveEndpoint::h2_windows). Set the maximum number of
116/// concurrent streams of one connection to 32, the value of the server.
117/// Both HTTP/2 settings apply only to a TLS listener that offers `h2`
118/// through ALPN, because the push client speaks HTTP/1.1 over cleartext.
119/// - The request bytes that the host did not read are at most the
120/// connection window times the number of open connections. The host grants
121/// the windows when it sets up a connection, before it authenticates a
122/// request.
123/// - The runtime backend of the crate must be the runtime of the host: the
124/// `tokio` feature for a host on tokio. Under tokio,
125/// [`handle`](ReceiveEndpoint::handle) and
126/// [`sweep`](ReceiveEndpoint::sweep) must run within a tokio runtime with
127/// the time driver enabled.
128///
129/// # Responses
130///
131/// Each request under the raw path prefix `/_ostrya/receive/v1/` is one
132/// step of a push session of [`ReceiveService`](ostrya::ReceiveService). The
133/// path is not percent-decoded.
134///
135/// - `POST session`, with a body of one `Hello` frame, opens a session. The
136/// response is 200 with the `HelloReply` frame. The header
137/// `Ostrya-Session` carries the session id: 64 lowercase hex digits of 32
138/// bytes from the random source of the operating system.
139/// - `POST session/ID/have`, with one `Have` frame, gets `HaveReply`.
140/// - `POST session/ID/objects`, with one object stream, gets
141/// `ObjectsReply`. Up to [`EndpointOptions::parallel_uploads`] of these run
142/// at the same time in one session, and one more gets `limit-exceeded`.
143/// - `POST session/ID/commit`, with one `Commit` frame, gets `CommitReply`.
144/// The commit runs in a task of its own, so a disconnect, a `DELETE`, or
145/// the idle timeout does not stop it. If the session already commits, a
146/// second `commit` gets 422 with `protocol`, and the first commit goes on.
147/// - `DELETE session/ID` ends the session and the requests of the session
148/// in flight. It gets 204 with no body and no `Content-Length`. If the
149/// session commits, the `DELETE` gets 422 with `protocol`, and the commit
150/// goes on.
151///
152/// These requests get 404 with no body:
153///
154/// - a path under the prefix that names no route
155/// - an id that is not a session of the owner of the request
156/// - a session that ended
157///
158/// A known path with another method, also `GET` and `HEAD`, gets 405 with
159/// `Allow: POST` or `Allow: DELETE`. The body of `session`, `have`, and
160/// `commit` holds one frame of at most 1 MiB. An empty body or a byte after
161/// the frame is a `protocol` error.
162///
163/// Each other response body is one frame. An error is an `Error` frame, and
164/// its code sets the status:
165///
166/// - `ref-mismatch` and `non-fast-forward` get 409.
167/// - `internal` gets 500.
168/// - Every other code gets 422.
169/// - An error of the server with no wire code gets 500 with `internal` and
170/// the text of the error.
171/// - If [`EndpointOptions::max_sessions`] sessions are open, a `session`
172/// request whose `Hello` passes its checks gets 503 with `limit-exceeded`.
173/// - If the authentication refuses a request, the request gets 401 or 403
174/// with `unauthorized`.
175///
176/// No response that the endpoint builds itself carries `Content-Type` or
177/// `Retry-After`. A refusal of the authentication carries the headers that
178/// the authentication adds to it.
179///
180/// A refusal can come before the endpoint reads the body, for example a 404
181/// or a 405. Before such a refusal, the endpoint reads and drops up to 1 MiB
182/// of the body. The time limit of this read is the idle timeout or 5
183/// seconds, whichever is shorter. On HTTP/1.1, if the body did not reach its
184/// end, the response gets `Connection: close`.
185///
186/// # Sessions
187///
188/// A failed step ends its session. The other requests of the session in
189/// flight get 422 with `protocol` and the cause.
190///
191/// If a request ends before its response, for example because the client
192/// closes the connection, its session ends too, unless the session commits.
193/// A request body can fail, for example because the client closes the
194/// connection in the middle of the body. The cause is then that of a request
195/// that ended before its response.
196///
197/// If a session has no request in progress for
198/// [`EndpointOptions::session_idle_timeout`], the endpoint aborts it. The
199/// endpoint also aborts a session with a request body that delivers no byte
200/// for that time. While the endpoint does not read a request body, that body
201/// does not count as silent. The body of a `session` request must arrive in
202/// full within the idle timeout.
203///
204/// The future of [`sweep`](ReceiveEndpoint::sweep) applies the timeout. A
205/// session that commits is never aborted. It holds its slot until the commit
206/// ends, also if the commit fails or panics.
207///
208/// [`shutdown`](ReceiveEndpoint::shutdown) aborts every session that does
209/// not commit. A `session` request after the call gets 503. A commit that
210/// runs goes on to its end.
211///
212/// The endpoint reads the repository settings once, at start. A change of
213/// the settings applies at the next start.
214///
215/// # Examples
216///
217/// A host that mounts the endpoint under the prefix `/api/v1/push`:
218///
219/// ```no_run
220/// use std::sync::Arc;
221///
222/// use hyper::body::Incoming;
223/// use hyper::{Request, Response};
224/// use ostrya_server::{ReceiveAuth, ReceiveBody, ReceiveEndpoint};
225///
226/// // Runs the idle sweep in a task of its own, once, when the host starts.
227/// fn start<A: ReceiveAuth>(endpoint: &Arc<ReceiveEndpoint<A>>) {
228/// let endpoint = endpoint.clone();
229/// drop(ostrya_rt::spawn(async move { endpoint.sweep().await }));
230/// }
231///
232/// // Removes the prefix of the host, then lets the endpoint answer.
233/// async fn route<A: ReceiveAuth>(
234/// endpoint: &ReceiveEndpoint<A>,
235/// mut req: Request<Incoming>,
236/// ) -> Response<ReceiveBody> {
237/// let path = req.uri().path().strip_prefix("/api/v1/push").unwrap_or("/");
238/// *req.uri_mut() = path.parse().expect("a path is a valid URI");
239/// endpoint.handle(req).await
240/// }
241/// ```
242pub struct ReceiveEndpoint<A: ReceiveAuth> {
243 inner: Receive<A>,
244 /// Fires at [`shutdown`](ReceiveEndpoint::shutdown), and ends
245 /// [`sweep`](ReceiveEndpoint::sweep).
246 stop: Arc<Shutdown>,
247}
248
249/// The debug text shows the options. It leaves out the repository and the
250/// authentication.
251impl<A: ReceiveAuth> fmt::Debug for ReceiveEndpoint<A> {
252 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
253 f.debug_struct("ReceiveEndpoint")
254 .field("parallel_uploads", &self.inner.parallel_uploads)
255 .field("session_idle_timeout", &self.inner.table.idle())
256 .field("max_sessions", &self.inner.table.max())
257 .finish_non_exhaustive()
258 }
259}
260
261impl<A: ReceiveAuth> ReceiveEndpoint<A> {
262 /// Creates an endpoint over `repo` with the authentication `auth`.
263 ///
264 /// # Errors
265 ///
266 /// - [`Error::Options`] if
267 /// [`parallel_uploads`](EndpointOptions::parallel_uploads) is outside
268 /// `1..=31`.
269 /// - [`Error::Options`] if
270 /// [`session_idle_timeout`](EndpointOptions::session_idle_timeout) is
271 /// zero.
272 /// - [`Error::Options`] if
273 /// [`max_sessions`](EndpointOptions::max_sessions) is zero.
274 pub fn new(repo: Repo, auth: A, options: EndpointOptions) -> Result<ReceiveEndpoint<A>> {
275 if !PARALLEL_UPLOADS.contains(&options.parallel_uploads) {
276 return Err(Error::Options(format!(
277 "parallel_uploads {} is outside {}..={}",
278 options.parallel_uploads,
279 PARALLEL_UPLOADS.start(),
280 PARALLEL_UPLOADS.end()
281 )));
282 }
283 if options.session_idle_timeout.is_zero() {
284 return Err(Error::Options("a session idle timeout of zero".into()));
285 }
286 if options.max_sessions == 0 {
287 return Err(Error::Options("a session limit of zero".into()));
288 }
289 Ok(ReceiveEndpoint {
290 inner: Receive {
291 repo,
292 auth,
293 parallel_uploads: options.parallel_uploads,
294 on_report: options.on_report,
295 table: SessionTable::new(options.max_sessions, options.session_idle_timeout),
296 },
297 stop: Arc::new(Shutdown::default()),
298 })
299 }
300
301 /// Returns the response to one request of the endpoint.
302 ///
303 /// The raw request path must start with `/_ostrya/receive/v1/`. The path
304 /// is not percent-decoded, and the endpoint ignores the query.
305 /// [Mounting](ReceiveEndpoint#mounting) states how a host removes its
306 /// prefix. [Responses](ReceiveEndpoint#responses) states the routes and
307 /// the responses.
308 ///
309 /// A request body that fails counts as a request that ended before its
310 /// response. The request gets 500 with `internal`, and its session ends.
311 ///
312 /// Under the tokio backend, the call must run within a tokio runtime
313 /// with the time driver enabled. The commit runs in a task of its own,
314 /// and the time limits use the timer. A server signer that runs the
315 /// GnuPG binaries also needs the IO driver.
316 ///
317 /// # Panics
318 ///
319 /// A panic in the commit or in a hook of the session is not caught. The
320 /// commit runs in a task of its own. The panic resumes in this call when
321 /// the call joins that task, so it panics the request task of the host.
322 ///
323 /// Over HTTP/2, hyper then resets the stream. Over HTTP/1.1, hyper closes
324 /// the connection. The session ends and frees its slot. A panic in
325 /// [`ReceiveHooks::after_update`](ostrya::ReceiveHooks::after_update)
326 /// occurs after the endpoint writes the refs.
327 ///
328 /// If the future of `handle` is dropped first, for example because the
329 /// client resets the stream, the commit task becomes detached. The
330 /// runtime then catches the panic and drops it.
331 pub async fn handle<B>(&self, req: Request<B>) -> Response<ReceiveBody>
332 where
333 B: Body<Data = Bytes> + Send + Unpin + 'static,
334 B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
335 {
336 self.inner.handle(req).await.map(ReceiveBody)
337 }
338
339 /// Aborts each session past its idle timeout, until
340 /// [`shutdown`](ReceiveEndpoint::shutdown).
341 ///
342 /// The future also aborts each session with a request body that delivered
343 /// no byte for that time. A session that commits is never aborted. After
344 /// `shutdown`, the future completes at once.
345 ///
346 /// The host runs the future once, in a task of its own, while the
347 /// endpoint serves. If no task runs it, no session reaches its idle
348 /// timeout. Under the tokio backend, the future must run within a tokio
349 /// runtime with the time driver enabled.
350 pub async fn sweep(&self) {
351 future::or(self.stop.wait(), self.inner.table.sweep()).await
352 }
353
354 /// Stops the endpoint.
355 ///
356 /// The call aborts each session that does not commit, and ends
357 /// [`sweep`](ReceiveEndpoint::sweep). A commit that runs goes on to its
358 /// end, also through the hooks of its session. A `session` request after
359 /// the call gets 503. A second call has no further effect.
360 pub fn shutdown(&self) {
361 self.stop.fire();
362 self.inner.table.close_all();
363 }
364
365 /// Returns the HTTP/2 receive windows for a connection to the endpoint.
366 ///
367 /// The first value is the window of each stream, 2 MiB. The second value
368 /// is the window of the connection: 2 MiB for each of the
369 /// [`parallel_uploads`](EndpointOptions::parallel_uploads) object streams
370 /// of a session. The request bodies of one connection hold at most this
371 /// number of bytes that the host did not read.
372 pub fn h2_windows(&self) -> (u32, u32) {
373 (UPLOAD_WINDOW, UPLOAD_WINDOW * self.inner.parallel_uploads)
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use hyper::{Method, StatusCode};
380 use ostrya::ReceivePolicy;
381 use ostrya::remote::ErrorCode;
382 use ostrya::remote::proto::{Hello, Kind, Message};
383 use ostrya_rt::block_on;
384
385 use super::*;
386 use crate::ServeOptions;
387 use crate::auth::{FileAuth, Peer};
388 use crate::body::ServeBody;
389 use crate::body::tests::frames;
390 use crate::receive::PREFIX;
391 use crate::session::tests::TmpRepo;
392
393 /// The built-in authentication with anonymous push.
394 fn anonymous() -> FileAuth {
395 let opts = ServeOptions {
396 allow_anonymous_push: true,
397 ..ServeOptions::default()
398 };
399 FileAuth::new(&opts, Arc::new(ReceivePolicy::default())).unwrap()
400 }
401
402 fn endpoint(tmp: &TmpRepo, options: EndpointOptions) -> Result<ReceiveEndpoint<FileAuth>> {
403 ReceiveEndpoint::new(tmp.repo.clone(), anonymous(), options)
404 }
405
406 #[test]
407 fn bad_options_are_refused() {
408 let tmp = TmpRepo::new("endpoint-options");
409 let cases = [
410 (
411 EndpointOptions {
412 parallel_uploads: 0,
413 ..EndpointOptions::default()
414 },
415 "parallel_uploads 0 is outside 1..=31",
416 ),
417 (
418 EndpointOptions {
419 parallel_uploads: 32,
420 ..EndpointOptions::default()
421 },
422 "parallel_uploads 32 is outside 1..=31",
423 ),
424 (
425 EndpointOptions {
426 session_idle_timeout: Duration::ZERO,
427 ..EndpointOptions::default()
428 },
429 "a session idle timeout of zero",
430 ),
431 (
432 EndpointOptions {
433 max_sessions: 0,
434 ..EndpointOptions::default()
435 },
436 "a session limit of zero",
437 ),
438 ];
439 for (options, want) in cases {
440 match endpoint(&tmp, options) {
441 Err(Error::Options(message)) => assert_eq!(message, want),
442 other => panic!("{want}: {other:?}"),
443 }
444 }
445 }
446
447 /// The window of a connection follows `parallel_uploads`, and the widest
448 /// one is less than the HTTP/2 maximum.
449 #[test]
450 fn the_h2_windows_follow_parallel_uploads() {
451 let tmp = TmpRepo::new("endpoint-windows");
452 let windows = |parallel_uploads| {
453 let options = EndpointOptions {
454 parallel_uploads,
455 ..EndpointOptions::default()
456 };
457 endpoint(&tmp, options).unwrap().h2_windows()
458 };
459 assert_eq!(windows(4), (2 << 20, 8 << 20));
460 let (_, widest) = windows(*PARALLEL_UPLOADS.end());
461 assert_eq!(widest, 62 << 20);
462 assert!(widest < 1 << 31);
463 }
464
465 /// The debug text states the options and leaves out the callback.
466 #[test]
467 fn debug_states_the_options() {
468 let tmp = TmpRepo::new("endpoint-debug");
469 let options = EndpointOptions {
470 on_report: Some(Arc::new(|_| {})),
471 ..EndpointOptions::default()
472 };
473 let text = format!("{options:?}");
474 assert!(text.contains("<callback>"), "{text}");
475 let text = format!("{:?}", endpoint(&tmp, options).unwrap());
476 assert!(text.contains("parallel_uploads: 4"), "{text}");
477 assert!(text.contains("max_sessions: 16"), "{text}");
478 assert!(text.contains("300s"), "{text}");
479 }
480
481 /// After `shutdown`, the sweep completes, a second `shutdown` does
482 /// nothing more, and a `session` request gets 503 with
483 /// `limit-exceeded`.
484 #[test]
485 fn shutdown_ends_the_sweep_and_refuses_new_sessions() {
486 let tmp = TmpRepo::new("endpoint-shutdown");
487 let ep = endpoint(&tmp, EndpointOptions::default()).unwrap();
488 block_on(async {
489 assert!(
490 future::poll_once(Box::pin(ep.sweep())).await.is_none(),
491 "the sweep runs until shutdown"
492 );
493 ep.shutdown();
494 ep.shutdown();
495 ep.sweep().await;
496 let hello = Message::Hello(Hello {
497 version: 1,
498 agent: None,
499 refs: vec!["main".into()],
500 one_way: false,
501 });
502 let mut bytes = Vec::new();
503 let body = hello.encode_body().unwrap();
504 bytes.extend_from_slice(&(body.len() as u32 + 1).to_be_bytes());
505 bytes.push(hello.kind().as_u8());
506 bytes.extend_from_slice(&body);
507 let req = Request::builder()
508 .method(Method::POST)
509 .uri(format!("{PREFIX}session"))
510 .extension(Peer {
511 tls: false,
512 cert: None,
513 })
514 .body(ServeBody::Full(Some(Bytes::from(bytes))))
515 .unwrap();
516 let response = ep.handle(req).await;
517 assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
518 let bytes = frames(response.into_body().into_serve())
519 .await
520 .unwrap()
521 .concat();
522 let reply = Message::decode(Kind::from_u8(bytes[4]).unwrap(), &bytes[5..]).unwrap();
523 let Message::Error(e) = reply else {
524 panic!("{reply:?}");
525 };
526 assert_eq!(e.code, ErrorCode::LimitExceeded);
527 });
528 }
529}