Skip to main content

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`], which makes no promise of `Sync`.
107/// - The endpoint is `Send + Sync` and has no `Clone`. A host shares it in an
108///   `Arc`.
109/// - Run the future of [`sweep`](ReceiveEndpoint::sweep) once, in a task of
110///   its own, when the host starts. If no task runs it, no session reaches
111///   its idle timeout.
112/// - Call [`shutdown`](ReceiveEndpoint::shutdown) before the graceful
113///   shutdown of the listener.
114/// - Serve the endpoint on a dedicated listener, with a port or an SNI name
115///   of its own. A listener for other routes keeps its own windows.
116/// - On that listener, set the HTTP/2 windows of
117///   [`h2_windows`](ReceiveEndpoint::h2_windows). Set the maximum number of
118///   concurrent streams of one connection to 32, the value of the server.
119///   Both HTTP/2 settings apply only to a TLS listener that offers `h2`
120///   through ALPN, because the push client speaks HTTP/1.1 over cleartext.
121/// - The request bytes that the host did not read are at most the
122///   connection window times the number of open connections. The host grants
123///   the windows when it sets up a connection, before it authenticates a
124///   request.
125/// - The runtime backend of the crate must be the runtime of the host: the
126///   `tokio` feature for a host on tokio. Under tokio,
127///   [`handle`](ReceiveEndpoint::handle) and
128///   [`sweep`](ReceiveEndpoint::sweep) must run within a tokio runtime with
129///   the time driver enabled.
130///
131/// # Responses
132///
133/// Each request under the raw path prefix `/_ostrya/receive/v1/` is one
134/// step of a push session of [`ReceiveService`](ostrya::ReceiveService).
135/// [The receive endpoint] specifies the routes, the request bodies, the
136/// session id, the statuses, and the end of a session. [Error codes] gives
137/// the status of each wire code.
138/// [Authentication of the receive endpoint] gives the refusals of the
139/// authentication.
140///
141/// [`EndpointOptions::parallel_uploads`] is the number of `objects` requests
142/// that one session runs at the same time. One more `objects` request gets
143/// 422 with `limit-exceeded`, and the session ends.
144/// [`EndpointOptions::max_sessions`] is the number of sessions that are open
145/// at the same time. A `session` request past the limit gets 503 with
146/// `limit-exceeded`. A refusal of the authentication carries the headers
147/// that the [`ReceiveAuth`] adds to it, except `Content-Length`,
148/// `Transfer-Encoding`, and `Connection`, which the endpoint sets itself.
149///
150/// A refusal can come before the endpoint reads the body, for example a 404
151/// or a 405. Before such a refusal, the endpoint reads and drops up to 1 MiB
152/// of the body. The time limit of this read is the idle timeout or 5
153/// seconds, whichever is shorter. On HTTP/1.1 and HTTP/1.0, if the body did
154/// not reach its end, the response gets `Connection: close`.
155///
156/// # Sessions
157///
158/// If a session has no request in progress for
159/// [`EndpointOptions::session_idle_timeout`], the endpoint aborts it. The
160/// endpoint also aborts a session with a request body that delivers no byte
161/// for that time. While the endpoint does not read a request body, that body
162/// does not count as silent. The body of a `session` request must arrive in
163/// full within the idle timeout.
164///
165/// The future of [`sweep`](ReceiveEndpoint::sweep) applies the timeout. A
166/// session that commits is never aborted. It holds its slot until the commit
167/// ends, also if the commit fails or panics.
168///
169/// [`shutdown`](ReceiveEndpoint::shutdown) aborts every session that does
170/// not commit. A `session` request after the call gets 503. A commit that
171/// runs goes on to its end.
172///
173/// The endpoint reads the repository settings once, at start. A change of
174/// the settings applies at the next start.
175///
176/// [The receive endpoint]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#the-receive-endpoint
177/// [Error codes]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#error-codes
178/// [Authentication of the receive endpoint]: https://github.com/growler/ostrya/blob/main/docs/format-reference.md#authentication-of-the-receive-endpoint
179///
180/// # Examples
181///
182/// A host that mounts the endpoint under the prefix `/api/v1/push`:
183///
184/// ```no_run
185/// use std::sync::Arc;
186///
187/// use hyper::body::Incoming;
188/// use hyper::{Request, Response};
189/// use ostrya_server::{ReceiveAuth, ReceiveBody, ReceiveEndpoint};
190///
191/// // Runs the idle sweep in a task of its own, once, when the host starts.
192/// fn start<A: ReceiveAuth>(endpoint: &Arc<ReceiveEndpoint<A>>) {
193///     let endpoint = endpoint.clone();
194///     drop(ostrya_rt::spawn(async move { endpoint.sweep().await }));
195/// }
196///
197/// // Removes the prefix of the host, then lets the endpoint answer.
198/// async fn route<A: ReceiveAuth>(
199///     endpoint: &ReceiveEndpoint<A>,
200///     mut req: Request<Incoming>,
201/// ) -> Response<ReceiveBody> {
202///     let path = req.uri().path().strip_prefix("/api/v1/push").unwrap_or("/");
203///     *req.uri_mut() = path.parse().expect("a path is a valid URI");
204///     endpoint.handle(req).await
205/// }
206/// ```
207pub struct ReceiveEndpoint<A: ReceiveAuth> {
208    inner: Receive<A>,
209    /// Fires at [`shutdown`](ReceiveEndpoint::shutdown), and ends
210    /// [`sweep`](ReceiveEndpoint::sweep).
211    stop: Arc<Shutdown>,
212}
213
214/// The debug text shows the options. It leaves out the repository and the
215/// authentication.
216impl<A: ReceiveAuth> fmt::Debug for ReceiveEndpoint<A> {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.debug_struct("ReceiveEndpoint")
219            .field("parallel_uploads", &self.inner.parallel_uploads)
220            .field("session_idle_timeout", &self.inner.table.idle())
221            .field("max_sessions", &self.inner.table.max())
222            .finish_non_exhaustive()
223    }
224}
225
226impl<A: ReceiveAuth> ReceiveEndpoint<A> {
227    /// Creates an endpoint over `repo` with the authentication `auth`.
228    ///
229    /// # Errors
230    ///
231    /// - [`Error::Options`] if
232    ///   [`parallel_uploads`](EndpointOptions::parallel_uploads) is outside
233    ///   `1..=31`.
234    /// - [`Error::Options`] if
235    ///   [`session_idle_timeout`](EndpointOptions::session_idle_timeout) is
236    ///   zero.
237    /// - [`Error::Options`] if
238    ///   [`max_sessions`](EndpointOptions::max_sessions) is zero.
239    pub fn new(repo: Repo, auth: A, options: EndpointOptions) -> Result<ReceiveEndpoint<A>> {
240        if !PARALLEL_UPLOADS.contains(&options.parallel_uploads) {
241            return Err(Error::Options(format!(
242                "parallel_uploads {} is outside {}..={}",
243                options.parallel_uploads,
244                PARALLEL_UPLOADS.start(),
245                PARALLEL_UPLOADS.end()
246            )));
247        }
248        if options.session_idle_timeout.is_zero() {
249            return Err(Error::Options("a session idle timeout of zero".into()));
250        }
251        if options.max_sessions == 0 {
252            return Err(Error::Options("a session limit of zero".into()));
253        }
254        Ok(ReceiveEndpoint {
255            inner: Receive {
256                repo,
257                auth,
258                parallel_uploads: options.parallel_uploads,
259                on_report: options.on_report,
260                table: SessionTable::new(options.max_sessions, options.session_idle_timeout),
261            },
262            stop: Arc::new(Shutdown::default()),
263        })
264    }
265
266    /// Returns the authentication of the endpoint.
267    pub(crate) fn auth(&self) -> &A {
268        &self.inner.auth
269    }
270
271    /// Returns the response to one request of the endpoint.
272    ///
273    /// The raw request path must start with `/_ostrya/receive/v1/`. The path
274    /// is not percent-decoded, and the endpoint ignores the query.
275    /// [Mounting](ReceiveEndpoint#mounting) states how a host removes its
276    /// prefix. [Responses](ReceiveEndpoint#responses) links the specification
277    /// of the routes and the responses.
278    ///
279    /// A request body that fails counts as a request that ended before its
280    /// response. The request gets 500 with `internal`, and its session ends,
281    /// unless the session commits.
282    ///
283    /// Under the tokio backend, the call must run within a tokio runtime
284    /// with the time driver enabled. The commit runs in a task of its own,
285    /// and the time limits use the timer. A server signer that runs the
286    /// GnuPG binaries also needs the IO driver.
287    ///
288    /// # Panics
289    ///
290    /// A panic in the commit or in a hook of the session is not caught. The
291    /// commit runs in a task of its own. The panic resumes in this call when
292    /// the call joins that task, so it panics the request task of the host.
293    ///
294    /// Over HTTP/2, hyper then resets the stream. Over HTTP/1.1, hyper closes
295    /// the connection. The session ends and frees its slot. A panic in
296    /// [`ReceiveHooks::after_update`](ostrya::ReceiveHooks::after_update)
297    /// occurs after the endpoint writes the refs.
298    ///
299    /// If the future of `handle` is dropped first, for example because the
300    /// client resets the stream, the commit task becomes detached. The
301    /// runtime then catches the panic and drops it.
302    pub async fn handle<B>(&self, req: Request<B>) -> Response<ReceiveBody>
303    where
304        B: Body<Data = Bytes> + Send + Unpin + 'static,
305        B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
306    {
307        self.inner.handle(req).await.map(ReceiveBody)
308    }
309
310    /// Aborts each session past its idle timeout, until
311    /// [`shutdown`](ReceiveEndpoint::shutdown).
312    ///
313    /// The future also aborts each session with a request body that delivered
314    /// no byte for that time. A session that commits is never aborted. After
315    /// `shutdown`, the future completes at once.
316    ///
317    /// The host runs the future once, in a task of its own, while the
318    /// endpoint serves. If no task runs it, no session reaches its idle
319    /// timeout. Under the tokio backend, the future must run within a tokio
320    /// runtime with the time driver enabled.
321    pub async fn sweep(&self) {
322        future::or(self.stop.wait(), self.inner.table.sweep()).await
323    }
324
325    /// Stops the endpoint.
326    ///
327    /// The call aborts each session that does not commit, and ends
328    /// [`sweep`](ReceiveEndpoint::sweep). A commit that runs goes on to its
329    /// end, also through the hooks of its session. A `session` request after
330    /// the call gets 503. A second call has no further effect.
331    pub fn shutdown(&self) {
332        self.stop.fire();
333        self.inner.table.close_all();
334    }
335
336    /// Returns the HTTP/2 receive windows for a connection to the endpoint.
337    ///
338    /// The first value is the window of each stream, 2 MiB. The second value
339    /// is the window of the connection: 2 MiB for each of the
340    /// [`parallel_uploads`](EndpointOptions::parallel_uploads) object streams
341    /// of a session. The request bodies of one connection hold at most this
342    /// number of bytes that the host did not read.
343    pub fn h2_windows(&self) -> (u32, u32) {
344        (UPLOAD_WINDOW, UPLOAD_WINDOW * self.inner.parallel_uploads)
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    use hyper::{Method, StatusCode};
351    use ostrya::remote::ErrorCode;
352    use ostrya::remote::proto::{Hello, Kind, Message};
353    use ostrya_rt::block_on;
354
355    use super::*;
356    use crate::auth::{GroupAuth, Peer};
357    use crate::body::ServeBody;
358    use crate::body::tests::frames;
359    use crate::receive::PREFIX;
360    use crate::session::tests::{ANONYMOUS_PUSH, TmpRepo};
361
362    /// The built-in authentication with a group of anonymous push.
363    fn anonymous(tmp: &TmpRepo) -> GroupAuth {
364        GroupAuth::new(tmp.policies(ANONYMOUS_PUSH), false)
365    }
366
367    fn endpoint(tmp: &TmpRepo, options: EndpointOptions) -> Result<ReceiveEndpoint<GroupAuth>> {
368        ReceiveEndpoint::new(tmp.repo.clone(), anonymous(tmp), options)
369    }
370
371    #[test]
372    fn bad_options_are_refused() {
373        let tmp = TmpRepo::new("endpoint-options");
374        let cases = [
375            (
376                EndpointOptions {
377                    parallel_uploads: 0,
378                    ..EndpointOptions::default()
379                },
380                "parallel_uploads 0 is outside 1..=31",
381            ),
382            (
383                EndpointOptions {
384                    parallel_uploads: 32,
385                    ..EndpointOptions::default()
386                },
387                "parallel_uploads 32 is outside 1..=31",
388            ),
389            (
390                EndpointOptions {
391                    session_idle_timeout: Duration::ZERO,
392                    ..EndpointOptions::default()
393                },
394                "a session idle timeout of zero",
395            ),
396            (
397                EndpointOptions {
398                    max_sessions: 0,
399                    ..EndpointOptions::default()
400                },
401                "a session limit of zero",
402            ),
403        ];
404        for (options, want) in cases {
405            match endpoint(&tmp, options) {
406                Err(Error::Options(message)) => assert_eq!(message, want),
407                other => panic!("{want}: {other:?}"),
408            }
409        }
410    }
411
412    /// The window of a connection follows `parallel_uploads`, and the widest
413    /// one is less than the HTTP/2 maximum.
414    #[test]
415    fn the_h2_windows_follow_parallel_uploads() {
416        let tmp = TmpRepo::new("endpoint-windows");
417        let windows = |parallel_uploads| {
418            let options = EndpointOptions {
419                parallel_uploads,
420                ..EndpointOptions::default()
421            };
422            endpoint(&tmp, options).unwrap().h2_windows()
423        };
424        assert_eq!(windows(4), (2 << 20, 8 << 20));
425        let (_, widest) = windows(*PARALLEL_UPLOADS.end());
426        assert_eq!(widest, 62 << 20);
427        assert!(widest < 1 << 31);
428    }
429
430    /// The debug text states the options and leaves out the callback.
431    #[test]
432    fn debug_states_the_options() {
433        let tmp = TmpRepo::new("endpoint-debug");
434        let options = EndpointOptions {
435            on_report: Some(Arc::new(|_| {})),
436            ..EndpointOptions::default()
437        };
438        let text = format!("{options:?}");
439        assert!(text.contains("<callback>"), "{text}");
440        let text = format!("{:?}", endpoint(&tmp, options).unwrap());
441        assert!(text.contains("parallel_uploads: 4"), "{text}");
442        assert!(text.contains("max_sessions: 16"), "{text}");
443        assert!(text.contains("300s"), "{text}");
444    }
445
446    /// After `shutdown`, the sweep completes, a second `shutdown` does
447    /// nothing more, and a `session` request gets 503 with
448    /// `limit-exceeded`.
449    #[test]
450    fn shutdown_ends_the_sweep_and_refuses_new_sessions() {
451        let tmp = TmpRepo::new("endpoint-shutdown");
452        let ep = endpoint(&tmp, EndpointOptions::default()).unwrap();
453        block_on(async {
454            assert!(
455                future::poll_once(Box::pin(ep.sweep())).await.is_none(),
456                "the sweep runs until shutdown"
457            );
458            ep.shutdown();
459            ep.shutdown();
460            ep.sweep().await;
461            let hello = Message::Hello(Hello {
462                version: 1,
463                agent: None,
464                refs: vec!["main".into()],
465                collection: None,
466                one_way: false,
467            });
468            let mut bytes = Vec::new();
469            let body = hello.encode_body().unwrap();
470            bytes.extend_from_slice(&(body.len() as u32 + 1).to_be_bytes());
471            bytes.push(hello.kind().as_u8());
472            bytes.extend_from_slice(&body);
473            let req = Request::builder()
474                .method(Method::POST)
475                .uri(format!("{PREFIX}session"))
476                .extension(Peer {
477                    tls: false,
478                    addr: std::net::Ipv4Addr::LOCALHOST.into(),
479                    cert: None,
480                })
481                .body(ServeBody::Full(Some(Bytes::from(bytes))))
482                .unwrap();
483            let response = ep.handle(req).await;
484            assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
485            let bytes = frames(response.into_body().into_serve())
486                .await
487                .unwrap()
488                .concat();
489            let reply = Message::decode(Kind::from_u8(bytes[4]).unwrap(), &bytes[5..]).unwrap();
490            let Message::Error(e) = reply else {
491                panic!("{reply:?}");
492            };
493            assert_eq!(e.code, ErrorCode::LimitExceeded);
494        });
495    }
496}