ostrya_remote/transport/mod.rs
1//! The endpoints, and the ssh and HTTP transports of the sessions.
2//!
3//! An [`Endpoint`] holds a remote address and the options of its transport.
4//! These calls open a session:
5//!
6//! - [`PushSession::connect`], or [`PushSession::prepare`] and then
7//! [`PreparedSession::open`], for a push to an endpoint
8//! - [`PullSession::connect`] for a pull from an endpoint
9//! - [`StreamSession::connect`] for a stream session to an [`SshAddress`]
10//!
11//! Over ssh, the session runs the ssh client as a child process, and the remote
12//! side runs the receive command or the send command. The frames of the
13//! session go over the standard input and the standard output of the child.
14//! Over HTTP, each step of a push session is one request to the server.
15
16mod http;
17mod ssh;
18
19use std::ffi::OsStr;
20use std::fmt;
21use std::time::Duration;
22
23use crate::error::{Error, Result};
24use crate::session::http::Endpoint as HttpEndpoint;
25use crate::session::{
26 PullSession, PushSession, SessionOptions, StreamSession, StreamSessionOptions,
27};
28
29pub(crate) use ssh::Transport;
30pub use ssh::{SshAddress, SshOptions, without_userinfo};
31
32/// The longest wait for a pending message after a failed write, and for the
33/// exit of the ssh client. It applies to a session that
34/// [`PushSession::connect`] or [`StreamSession::connect`] opens.
35const PENDING_READ_LIMIT: Duration = Duration::from_secs(5);
36
37/// A remote address with the options of its transport.
38///
39/// [`Endpoint::parse`] reads an address and gives the default options. A
40/// caller can also build an endpoint from its parts, with options of its own.
41///
42/// The [`Debug`] output of [`Endpoint::Http`] is the output of
43/// [`FetcherOptions`](ostrya_fetch::FetcherOptions), which shows no
44/// credential, no header value, and no userinfo.
45///
46/// # HTTP addresses
47///
48/// The forms are `http://HOST[:PORT][/PATH]` and `https://HOST[:PORT][/PATH]`.
49/// [`parse`](Endpoint::parse) refuses an `@` at any position, so it refuses
50/// userinfo. It also refuses a query, a fragment, an empty host, and a port
51/// that is not a number from 0 to 65535.
52#[derive(Debug, Clone)]
53pub enum Endpoint {
54 /// An ssh address and the options of the ssh client.
55 Ssh {
56 /// The ssh address.
57 address: SshAddress,
58 /// The options of the ssh client.
59 options: SshOptions,
60 },
61 /// The options of the HTTP client.
62 ///
63 /// [`mirrors`](ostrya_fetch::FetcherOptions::mirrors) holds the address:
64 /// exactly one mirror for a push, one or more for a pull.
65 Http(ostrya_fetch::FetcherOptions),
66}
67
68impl Endpoint {
69 /// Parses `address` into an endpoint with the default options.
70 ///
71 /// An address that starts with `http://` or `https://` gives
72 /// [`Endpoint::Http`] with
73 /// [`FetcherOptions::new`](ostrya_fetch::FetcherOptions::new) of the
74 /// address. Each other address gives [`Endpoint::Ssh`] with the default
75 /// [`SshOptions`].
76 ///
77 /// # Errors
78 ///
79 /// - [`Error::InvalidInput`] if `address` is not one of the
80 /// [ssh forms](SshAddress#forms) or the
81 /// [HTTP forms](Endpoint#http-addresses), or if the parse refuses a
82 /// part of it. No refusal shows the userinfo of the address.
83 ///
84 /// # Examples
85 ///
86 /// ```
87 /// use ostrya_remote::transport::Endpoint;
88 /// # fn main() -> ostrya_remote::Result<()> {
89 /// let endpoint = Endpoint::parse("builder@repo.example.com:/srv/repo")?;
90 /// let Endpoint::Ssh { address, options } = endpoint else {
91 /// panic!("an scp-form address gives an ssh endpoint");
92 /// };
93 /// assert_eq!(address.to_string(), "ssh://builder@repo.example.com/srv/repo");
94 /// assert_eq!(options.remote_command, None);
95 ///
96 /// let Endpoint::Http(http) = Endpoint::parse("https://repo.example.com/")? else {
97 /// panic!("an https address gives an HTTP endpoint");
98 /// };
99 /// assert_eq!(http.mirrors, ["https://repo.example.com/"]);
100 /// # Ok(()) }
101 /// ```
102 pub fn parse(address: &str) -> Result<Endpoint> {
103 parse_endpoint(address, cfg!(windows))
104 }
105}
106
107/// Parses `address` as [`Endpoint::parse`] does, with the Windows rules of an
108/// ssh address if `windows` is `true`.
109fn parse_endpoint(address: &str, windows: bool) -> Result<Endpoint> {
110 if address.starts_with("http://") || address.starts_with("https://") {
111 // The message of the fetcher holds no userinfo.
112 ostrya_fetch::check_base_url(address)
113 .map_err(|e| Error::InvalidInput(format!("address: {e}")))?;
114 Ok(Endpoint::Http(ostrya_fetch::FetcherOptions::new(address)))
115 } else {
116 Ok(Endpoint::Ssh {
117 address: SshAddress::parse_with(address, windows)?,
118 options: SshOptions::default(),
119 })
120 }
121}
122
123/// The open of a session over ssh or HTTP.
124impl PushSession {
125 /// Opens a push session to `endpoint` over ssh or HTTP.
126 ///
127 /// The call starts the transport, sends `Hello` with `refs`, and reads
128 /// `HelloReply`. It is [`prepare`](PushSession::prepare) and then
129 /// [`PreparedSession::open`].
130 ///
131 /// # Errors
132 ///
133 /// - Each error of [`prepare`](PushSession::prepare).
134 /// - Each error of [`PreparedSession::open`].
135 ///
136 /// # tokio runtime
137 ///
138 /// Under the tokio backend, the call must run within a runtime that has
139 /// the IO driver and the time driver enabled. The runtime builder enables
140 /// them with `enable_io` and `enable_time`, or with `enable_all`.
141 ///
142 /// The child process, its pipes, and the connections of an HTTP session
143 /// need the IO driver. The time limits need the time driver. The session
144 /// runs on the runtime that opened it.
145 ///
146 /// # ssh time limits
147 ///
148 /// After a failed write, the session reads the message that the server can
149 /// have sent before it closed. The read takes at most five seconds. A
150 /// server that closed its input and keeps its output open with no message
151 /// cannot hold the session. When the time ends, the call returns the error
152 /// of the write, or [`Error::CommitOutcomeUnknown`] after `Commit`.
153 ///
154 /// [`commit`](PushSession::commit) and [`abort`](PushSession::abort) close
155 /// the standard input of the ssh client. They then wait at most five
156 /// seconds for the ssh client to exit. They also wait if the stream is
157 /// broken and if `commit` refuses its updates. An open that fails waits in
158 /// the same way.
159 ///
160 /// If the session failed with an I/O error and the ssh client exited with a
161 /// failure status, the call returns [`Error::Transport`] with the status.
162 /// The status is also added to the message of
163 /// [`Error::CommitOutcomeUnknown`]. A session that committed returns its
164 /// outcome, whatever the exit status.
165 ///
166 /// The session drops the child with no wait in three cases:
167 ///
168 /// - the caller drops the session without `commit` or `abort`
169 /// - the caller drops the future of `commit` or `abort` before it completes
170 /// - the ssh client does not exit within the limit
171 ///
172 /// In each case, the standard input of the child closes, so the child
173 /// reads end of file on it.
174 ///
175 /// # HTTP
176 ///
177 /// Each step of a session is one request to the receive endpoint of the
178 /// server. The client adds `_ostrya/receive/v1/session` to the path of the
179 /// address, and then `/ID` and the step. The response to `Hello` gives
180 /// the `ID` in its `ostrya-session` header, as 64 lowercase hex digits.
181 ///
182 /// `ostrya serve` serves the endpoint at the root of the server. An
183 /// address with a path works only behind a proxy that removes that path,
184 /// or with a host that mounts the `ReceiveEndpoint` of `ostrya-server`
185 /// under that path.
186 ///
187 /// `Hello`, `Have`, and `Commit` go as whole request bodies. Each object
188 /// stream is the streamed body of one `objects` request. Each response
189 /// body holds one frame: the reply of the step, or an `Error` message.
190 ///
191 /// After the client sent the request body, it waits for the response. The
192 /// wait is at most 6 minutes for `Hello` and at most 1 hour for `Commit`.
193 /// For each other request, the limit is the
194 /// [`progress_timeout`](ostrya_fetch::FetcherOptions::progress_timeout) of
195 /// the options of [`Endpoint::Http`]. The client sends a request again only
196 /// if the attempt failed before it sent any byte of the request.
197 ///
198 /// The options of [`Endpoint::Http`] must name exactly one mirror, the
199 /// push address. The client sets
200 /// [`max_outstanding`](ostrya_fetch::FetcherOptions::max_outstanding) to 32
201 /// and [`max_redirects`](ostrya_fetch::FetcherOptions::max_redirects) to 0,
202 /// whatever values the options hold. The 32 requests are one for each of
203 /// the at most 31 object streams of [`PushSession::send`], and one `Have`
204 /// or `Commit` request. The client follows no redirect, and a 3xx answer
205 /// is [`Error::Transport`].
206 ///
207 /// The fetcher carries the credential, the TLS settings, the proxy, and
208 /// the headers of the options to each request. The client takes each trust
209 /// setting of the options, also a bypass variant of
210 /// [`TrustRoots`](ostrya_fetch::TrustRoots) that verifies no certificate
211 /// chain. The caller owns the trust policy.
212 ///
213 /// # Examples
214 ///
215 /// The example deletes a ref on the server if the ref exists.
216 ///
217 /// ```no_run
218 /// use ostrya_fetch::BearerToken;
219 /// use ostrya_remote::proto::{Expected, RefUpdate};
220 /// use ostrya_remote::session::{PushSession, SessionOptions};
221 /// use ostrya_remote::transport::Endpoint;
222 /// # async fn run(token: String) -> ostrya_remote::Result<()> {
223 /// let mut endpoint = Endpoint::parse("https://repo.example.com/")?;
224 /// if let Endpoint::Http(http) = &mut endpoint {
225 /// http.bearer_token = Some(BearerToken { token });
226 /// }
227 /// let refs = vec!["exampleos/testing".to_owned()];
228 /// let session = PushSession::connect(endpoint, &refs, SessionOptions::default()).await?;
229 /// let Some(tip) = session.server().tip(&refs[0]) else {
230 /// return session.abort().await;
231 /// };
232 /// let update = RefUpdate { name: refs[0].clone(), expected: Expected::Commit(tip), new: None };
233 /// let outcome = session.commit(&[update], false).await?;
234 /// assert_eq!(outcome.refs[0].new, None);
235 /// # Ok(()) }
236 /// ```
237 pub async fn connect(
238 endpoint: Endpoint,
239 refs: &[String],
240 opts: SessionOptions,
241 ) -> Result<PushSession> {
242 PushSession::prepare(endpoint).await?.open(refs, opts).await
243 }
244
245 /// Checks `endpoint` and makes the transport ready to open.
246 ///
247 /// For an ssh endpoint, the call reads the `OSTRYA_SSH_COMMAND`
248 /// environment variable and builds the command line of the ssh client by
249 /// the rules of the [ssh command line](SshOptions#ssh-command-line).
250 ///
251 /// For an HTTP endpoint, the call builds the HTTP client from the options,
252 /// as [`connect`](PushSession::connect) states. With
253 /// [`TrustRoots::System`](ostrya_fetch::TrustRoots::System), an `https://`
254 /// endpoint reads the trust store of the host, by the rule of
255 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new).
256 ///
257 /// The call starts no ssh client and sends no request. It refuses each
258 /// value that [`connect`](PushSession::connect) refuses before it starts
259 /// the transport. A caller can make these checks before its own local
260 /// work, and open the session with [`PreparedSession::open`] after that
261 /// work.
262 ///
263 /// Under the tokio backend, the call must run within a runtime that has
264 /// the IO driver enabled, as [`connect`](PushSession::connect) states.
265 ///
266 /// # Errors
267 ///
268 /// - [`Error::InvalidInput`] if the ssh command or the receive command is
269 /// empty or holds only white space, or if the value of
270 /// `OSTRYA_SSH_COMMAND` is not UTF-8. [`SshOptions`] states the full
271 /// rule under [Empty values](SshOptions#empty-values).
272 /// - [`Error::InvalidInput`] if the options of an HTTP endpoint do not name
273 /// exactly one mirror, or if
274 /// [`check_base_url`](ostrya_fetch::check_base_url) refuses the mirror.
275 /// The message holds no userinfo.
276 /// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new)
277 /// refuses the options. Examples:
278 /// - a credential to an `http://` address, with
279 /// [`allow_cleartext_credentials`](ostrya_fetch::FetcherOptions::allow_cleartext_credentials)
280 /// set to `false`
281 /// - a bearer token and an `Authorization` header together
282 /// - a client key that needs a passphrase that the options do not hold
283 pub async fn prepare(endpoint: Endpoint) -> Result<PreparedSession> {
284 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
285 let inner = prepare_with(endpoint, env.as_deref()).await?;
286 Ok(PreparedSession { inner })
287 }
288}
289
290/// A push session whose transport is checked and ready to open.
291///
292/// [`PushSession::prepare`] returns it. For ssh, it holds the command line of
293/// the ssh client. For HTTP, it holds the HTTP client and the credential of the
294/// session. No process runs and no request is sent before
295/// [`open`](PreparedSession::open).
296///
297/// The value is `Send + Sync`. Its `Debug` output shows the transport and the
298/// HTTP address alone, with no credential and no command line.
299pub struct PreparedSession {
300 inner: Prepared,
301}
302
303impl PreparedSession {
304 /// Opens the session, sends `Hello` with `refs` and the collection of
305 /// `opts`, and reads `HelloReply`.
306 ///
307 /// The call starts the ssh client, or sends the first HTTP request, as
308 /// [`PushSession::connect`] does. An ssh session has the ssh time limits of
309 /// [`PushSession::connect`].
310 ///
311 /// # Errors
312 ///
313 /// - An `Error` message from the server, as the [`Error`] variant of its
314 /// code.
315 /// - [`Error::Fetch`] if an HTTP request fails.
316 /// - [`Error::Transport`] if the ssh client cannot be started. The message
317 /// names the program.
318 /// - [`Error::Transport`] if an HTTP answer has a status that the endpoint
319 /// does not give, or a body that is not one frame. The message names the
320 /// URL and the status.
321 /// - [`Error::Transport`] if the HTTP answer to `Hello` has no session id.
322 /// - [`Error::Transport`] if the session fails with [`Error::Io`] and the
323 /// ssh client exits with a failure status. The message holds the status.
324 /// - [`Error::Protocol`] if the reply is not `HelloReply`, if its version
325 /// is not [`PROTOCOL_VERSION`](crate::proto::PROTOCOL_VERSION), if its
326 /// refs are not the refs of `Hello` in order, or if its `collection`
327 /// does not match [`SessionOptions::collection`].
328 /// - [`Error::LimitExceeded`] if the `Hello` frame is more than
329 /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT) bytes.
330 /// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses
331 /// a frame of the server over ssh, by the rules of
332 /// [`proto`](crate::proto#frames).
333 /// - [`Error::Io`] if a read or a write of the session fails.
334 pub async fn open(self, refs: &[String], opts: SessionOptions) -> Result<PushSession> {
335 self.inner.open(refs, opts).await
336 }
337}
338
339impl fmt::Debug for PreparedSession {
340 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341 let mut out = f.debug_struct("PreparedSession");
342 match &self.inner {
343 Prepared::Ssh(_) => out.field("transport", &"ssh"),
344 Prepared::Http(endpoint) => out.field("transport", &"http").field("url", &endpoint.url),
345 };
346 out.finish_non_exhaustive()
347 }
348}
349
350/// The transport of a session, checked and ready to open.
351pub(crate) enum Prepared {
352 /// The command line of the ssh client.
353 Ssh(Vec<String>),
354 /// The receive endpoint of an HTTP server.
355 Http(HttpEndpoint),
356}
357
358/// Checks `endpoint` and makes the transport ready to open, with `env` as the
359/// value of the `OSTRYA_SSH_COMMAND` environment variable. For ssh, it builds
360/// the command line. For HTTP, it builds the HTTP client. It starts nothing and
361/// sends nothing.
362async fn prepare_with(endpoint: Endpoint, env: Option<&OsStr>) -> Result<Prepared> {
363 match endpoint {
364 Endpoint::Ssh { address, options } => {
365 let program = options.program(env)?;
366 let receive = ssh::receive_command(options.remote_command.as_deref())?;
367 Ok(Prepared::Ssh(address.command_line(program, receive)))
368 }
369 // The HTTP preparation builds the fetcher. Its future is boxed, so
370 // that the future of an ssh connect does not hold it.
371 Endpoint::Http(http) => Ok(Prepared::Http(Box::pin(http::prepare(http)).await?)),
372 }
373}
374
375impl Prepared {
376 /// Opens a session over the transport, with the time limits of
377 /// [`PushSession::connect`].
378 async fn open(self, refs: &[String], opts: SessionOptions) -> Result<PushSession> {
379 self.open_with(refs, opts, PENDING_READ_LIMIT).await
380 }
381
382 /// Opens a session as [`open`](Prepared::open) does, with `limit` as the
383 /// time limit of an ssh session.
384 async fn open_with(
385 self,
386 refs: &[String],
387 opts: SessionOptions,
388 limit: Duration,
389 ) -> Result<PushSession> {
390 match self {
391 Prepared::Ssh(argv) => spawn_and_open(&argv, refs, opts, limit).await,
392 // The future is boxed, as the future of the HTTP preparation is.
393 Prepared::Http(endpoint) => {
394 Box::pin(PushSession::open_http(endpoint, refs, opts)).await
395 }
396 }
397 }
398}
399
400/// The open of a session over ssh.
401impl StreamSession {
402 /// Opens a stream session to the ssh address `address`.
403 ///
404 /// The call starts the ssh client, sends `PullHello`, and reads
405 /// `PullHelloReply`. The command line of the ssh client comes from
406 /// `options` by the rules of the
407 /// [ssh command line](SshOptions#ssh-command-line) of a pull. `session`
408 /// gives the agent in `PullHello` and the request limit of the session.
409 ///
410 /// The session has the ssh time limits of [`PushSession::connect`].
411 /// [`finish`](StreamSession::finish) waits for the ssh client as `commit`
412 /// and `abort` of a push do. The session puts no time limit on a read of
413 /// a reply.
414 ///
415 /// Under the tokio backend, the call must run within a runtime that has
416 /// the IO driver and the time driver enabled, as [`PushSession::connect`]
417 /// states. The session runs on the runtime that opened it.
418 ///
419 /// # Errors
420 ///
421 /// - An `Error` message from the server, as the [`Error`] variant of its
422 /// code.
423 /// - [`Error::InvalidInput`] if the ssh command or the send command is
424 /// empty or holds only white space, or if the value of
425 /// `OSTRYA_SSH_COMMAND` is not UTF-8.
426 /// - [`Error::Transport`] if the ssh client cannot be started. The message
427 /// names the program.
428 /// - [`Error::Transport`] if the session fails with [`Error::Io`] and the
429 /// ssh client exits with a failure status. The message holds the status.
430 /// - [`Error::VersionUnsupported`] if the reply has a pull version outside
431 /// 1 to [`PULL_PROTOCOL_VERSION`](crate::proto::PULL_PROTOCOL_VERSION).
432 /// The session then closes its output and sends no `Get`.
433 /// - [`Error::Protocol`] if the reply is not `PullHelloReply`.
434 /// - [`Error::Protocol`] if the [`agent`](StreamSessionOptions::agent) of
435 /// `session` holds a NUL byte.
436 /// - [`Error::LimitExceeded`] if the `PullHello` frame is more than
437 /// [`MIN_FRAME_LIMIT`](crate::proto::MIN_FRAME_LIMIT) bytes.
438 /// - [`Error::Protocol`] or [`Error::LimitExceeded`] if the codec refuses
439 /// a frame of the server, by the rules of
440 /// [`proto`](crate::proto#frames).
441 /// - [`Error::Io`] if a read or a write of the session fails, or if the
442 /// session ends before the reply.
443 ///
444 /// # Examples
445 ///
446 /// ```no_run
447 /// use futures_lite::AsyncReadExt;
448 /// use ostrya_remote::session::{StreamSession, StreamSessionOptions};
449 /// use ostrya_remote::transport::{SshAddress, SshOptions};
450 /// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
451 /// let address = SshAddress::parse("builder@repo.example.com:/srv/repo")?;
452 /// let options = SshOptions::default();
453 /// let session = StreamSession::connect(&address, &options, StreamSessionOptions::default()).await?;
454 /// if let Some(mut body) = session.get("config", 1 << 20).await? {
455 /// let mut config = Vec::new();
456 /// body.read_to_end(&mut config).await?;
457 /// }
458 /// session.finish().await?;
459 /// # Ok(()) }
460 /// ```
461 pub async fn connect(
462 address: &SshAddress,
463 options: &SshOptions,
464 session: StreamSessionOptions,
465 ) -> Result<StreamSession> {
466 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
467 let argv = pull_command_line(address, options, env.as_deref())?;
468 spawn_and_open_pull(&argv, session, PENDING_READ_LIMIT).await
469 }
470
471 /// Checks the command line of the ssh client that
472 /// [`connect`](StreamSession::connect) builds for `address` and
473 /// `options`.
474 ///
475 /// The call reads the `OSTRYA_SSH_COMMAND` environment variable, and
476 /// applies the [Empty values](SshOptions#empty-values) rules of a pull. It
477 /// starts no ssh client. A caller that opens sessions to more than one
478 /// remote can make this check for each remote before its first request.
479 ///
480 /// # Errors
481 ///
482 /// - [`Error::InvalidInput`] if the ssh command or the send command is
483 /// empty or holds only white space, or if the value of
484 /// `OSTRYA_SSH_COMMAND` is not UTF-8.
485 pub fn check_command_line(address: &SshAddress, options: &SshOptions) -> Result<()> {
486 let env = std::env::var_os("OSTRYA_SSH_COMMAND");
487 pull_command_line(address, options, env.as_deref()).map(drop)
488 }
489}
490
491/// The open of the session of a pull over ssh or HTTP.
492impl PullSession {
493 /// Opens the session of a pull to `endpoint`.
494 ///
495 /// For an [`Endpoint::Ssh`], the call is [`StreamSession::connect`] with
496 /// the address, the ssh options, and `opts`. The result is
497 /// [`PullSession::Stream`].
498 ///
499 /// For an [`Endpoint::Http`], the call builds the fetcher with
500 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new), and the result is
501 /// [`PullSession::Http`]. The call sends no HTTP request.
502 ///
503 /// Under the tokio backend, the call must run within a runtime that has
504 /// the IO driver and the time driver enabled, as [`PushSession::connect`]
505 /// states.
506 ///
507 /// # HTTP options
508 ///
509 /// The call gives the options of the endpoint to the fetcher with no
510 /// change:
511 ///
512 /// - The options can name one or more mirrors.
513 /// - The fetcher follows redirects up to
514 /// [`max_redirects`](ostrya_fetch::FetcherOptions::max_redirects).
515 /// - [`max_outstanding`](ostrya_fetch::FetcherOptions::max_outstanding) is
516 /// the request limit of the pull.
517 /// - A `User-Agent` entry of
518 /// [`headers`](ostrya_fetch::FetcherOptions::headers) sets the agent.
519 /// - The call does not apply [`check_base_url`](ostrya_fetch::check_base_url)
520 /// to the mirrors.
521 ///
522 /// The options give the agent and the request limit, so `opts` must set no
523 /// field.
524 ///
525 /// With [`TrustRoots::System`](ostrya_fetch::TrustRoots::System), the call
526 /// reads the trust store of the host by the rule of
527 /// [`Fetcher::new`](ostrya_fetch::Fetcher::new). An `https://` mirror
528 /// causes the read. The options that [`Endpoint::parse`] gives an
529 /// `http://` address also cause it, because their `max_redirects` is 10.
530 ///
531 /// # Errors
532 ///
533 /// - The errors of [`StreamSession::connect`] for an ssh endpoint.
534 /// - [`Error::InvalidInput`] if `opts` sets
535 /// [`agent`](StreamSessionOptions::agent) or
536 /// [`max_outstanding`](StreamSessionOptions::max_outstanding) for an HTTP
537 /// endpoint.
538 /// - [`Error::InvalidInput`] if the options of an HTTP endpoint name no
539 /// mirror.
540 /// - [`Error::Fetch`] if [`Fetcher::new`](ostrya_fetch::Fetcher::new)
541 /// refuses the options of an HTTP endpoint.
542 pub async fn connect(endpoint: Endpoint, opts: StreamSessionOptions) -> Result<PullSession> {
543 match endpoint {
544 Endpoint::Ssh { address, options } => StreamSession::connect(&address, &options, opts)
545 .await
546 .map(PullSession::Stream),
547 // The future of the fetcher construction is boxed, so that the
548 // future of an ssh connect does not hold it.
549 Endpoint::Http(http) => Ok(PullSession::Http(
550 Box::pin(http::prepare_pull(http, opts)).await?,
551 )),
552 }
553 }
554}
555
556/// Builds the command line of the ssh client of a pull to `address`, with
557/// `env` as the value of the `OSTRYA_SSH_COMMAND` environment variable.
558fn pull_command_line(
559 address: &SshAddress,
560 options: &SshOptions,
561 env: Option<&OsStr>,
562) -> Result<Vec<String>> {
563 let program = options.program(env)?;
564 let send = ssh::send_command(options.remote_command.as_deref())?;
565 Ok(address.command_line(program, send))
566}
567
568/// Starts `argv` and opens a stream session over its standard input and
569/// standard output, with `limit` as the time limit of the session.
570async fn spawn_and_open_pull(
571 argv: &[String],
572 opts: StreamSessionOptions,
573 limit: Duration,
574) -> Result<StreamSession> {
575 let (input, output, transport) = Transport::spawn(argv, limit)?;
576 match StreamSession::open(input, output, opts, Some(limit)).await {
577 Ok(session) => Ok(session.with_transport(transport)),
578 Err(e) => transport.finish(Err(e)).await,
579 }
580}
581
582/// Opens a stream session as [`StreamSession::connect`] does, with the value of
583/// the environment variable and the time limit as parameters.
584#[cfg(test)]
585async fn connect_pull_with(
586 address: &SshAddress,
587 options: &SshOptions,
588 env: Option<&OsStr>,
589 opts: StreamSessionOptions,
590 limit: Duration,
591) -> Result<StreamSession> {
592 let argv = pull_command_line(address, options, env)?;
593 spawn_and_open_pull(&argv, opts, limit).await
594}
595
596/// Opens a push session as [`PushSession::connect`] does, with the value of
597/// the environment variable and the time limit as parameters.
598#[cfg(test)]
599async fn connect_with(
600 endpoint: Endpoint,
601 env: Option<&OsStr>,
602 refs: &[String],
603 opts: SessionOptions,
604 limit: Duration,
605) -> Result<PushSession> {
606 prepare_with(endpoint, env)
607 .await?
608 .open_with(refs, opts, limit)
609 .await
610}
611
612/// Starts `argv` and opens a push session over its standard input and
613/// standard output, with `limit` as the time limit of the session.
614async fn spawn_and_open(
615 argv: &[String],
616 refs: &[String],
617 opts: SessionOptions,
618 limit: Duration,
619) -> Result<PushSession> {
620 let (input, output, transport) = Transport::spawn(argv, limit)?;
621 match PushSession::open(input, output, refs, opts, Some(limit)).await {
622 Ok(session) => Ok(session.with_transport(transport)),
623 Err(e) => transport.finish(Err(e)).await,
624 }
625}
626
627#[cfg(test)]
628mod tests;