Skip to main content

PushSession

Struct PushSession 

Source
pub struct PushSession { /* private fields */ }
Expand description

A client session of a push, over a stream transport or over HTTP.

connect opens a session over ssh or HTTP, and prepare checks the transport before the open. over_stream opens a session over a pair of byte streams.

If the caller drops a session without commit, server_commit, or abort, the session sends nothing more. A stream transport then closes its output, so the server reads the end of the stream. Over HTTP, the server ends the session when its idle timeout ends.

After the server ends a session over HTTP, it answers each later request of that session with 404. The session reports a 404 on missing or send as Error::Transport, and a 404 on commit or server_commit as Error::CommitOutcomeUnknown.

§Verification

The session does not verify the objects that it sends. It computes no checksum and checks no size. The server verifies each object when it arrives. If a source fails while the session sends an object, the session abandons the object with the abandon marker and ends the session with Abort.

§Concurrent calls

The session is Send + Sync. On a stream transport, the session runs one call at a time. A call to missing or send while another call runs fails at once with Error::InvalidInput.

Over HTTP, several send calls can run at the same time, and a missing call can run beside them. A second missing call while one runs fails at once with Error::InvalidInput.

On both transports, a call that fails, or whose future the caller drops before it completes, leaves the session broken. Each later call then fails with Error::InvalidInput. If missing or send refuses an argument, the call sends nothing and the session stays usable.

Implementations§

Source§

impl PushSession

The open of a session over a pair of byte streams, and its calls.

Source

pub async fn over_stream<R, W>( input: R, output: W, refs: &[String], opts: SessionOptions, ) -> Result<PushSession>
where R: AsyncRead + Unpin + Send + 'static, W: AsyncWrite + Unpin + Send + 'static,

Opens a session over a pair of byte streams.

input comes from the server, and output goes to the server. The session sends Hello with refs, the refs that it intends to update, and reads HelloReply.

The caller owns the liveness of the two streams. The session puts no time limit on a read. A peer that stays silent keeps a call waiting until the caller drops its future or closes the streams.

A session over a stream uses the futures-io traits for its I/O, and needs no async runtime, except for send under the tokio backend.

§Errors
  • An Error message from the server, as the Error variant of its code, for example Error::VersionUnsupported.
  • Error::Protocol if the version of HelloReply is not the version of the session, or if its refs are not the refs of Hello in order.
  • Error::Protocol for a malformed frame, or for a reply that is not HelloReply.
  • Error::LimitExceeded for a frame over the frame limit.
  • Error::Io for a failure of a stream. An end of input before the reply has the kind UnexpectedEof.
Examples found in repository?
examples/send_pass.rs (lines 150-155)
138fn run(dir: &Path, count: u64, size: u64, compression: Compression) -> io::Result<()> {
139    fs::create_dir_all(dir)?;
140    write_files(dir, count, size)?;
141    ostrya_rt::block_on(async {
142        let model = TreeModel::scan(dir, ScanOptions::default())
143            .await
144            .map_err(io::Error::other)?;
145        let names: Vec<_> = model
146            .object_names()
147            .into_iter()
148            .filter(|name| name.ty == ObjectType::File)
149            .collect();
150        let session = PushSession::over_stream(
151            Cursor::new(scripted_replies().await?),
152            sink(),
153            &["main".to_string()],
154            SessionOptions::default(),
155        )
156        .await
157        .map_err(io::Error::other)?;
158        eprintln!("send pass: start");
159        let start = Instant::now();
160        session
161            .send(&model, &names, &[], compression)
162            .await
163            .map_err(io::Error::other)?;
164        let elapsed = start.elapsed();
165        let files = names.len().max(1) as f64;
166        println!(
167            "{} files of {size} bytes: {:.1} us per file, {:.3} s in all",
168            names.len(),
169            elapsed.as_secs_f64() * 1e6 / files,
170            elapsed.as_secs_f64()
171        );
172        if let Some(peak) = peak_rss() {
173            println!("VmHWM: {peak}");
174        }
175        Ok(())
176    })
177}
Source

pub fn server(&self) -> &ServerInfo

Returns the facts of the server.

Source

pub async fn missing(&self, names: &[ObjectName]) -> Result<Vec<ObjectName>>

Returns the objects of names that the server does not hold.

The order of the result is the order of names. The session sends Have messages of at most max-have names each. A Have also holds no more names than its frame can hold within max-frame.

Over HTTP, each Have is one request. The session sends the next Have after the response to the one before it.

§Errors
  • Error::InvalidInput if the type of a name is not a file, a dirtree, a dirmeta, or a commit. The call sends nothing, and the session stays usable.
  • Error::InvalidInput if another call runs, as the rules of concurrent calls state, or if the session is broken.
  • An Error message from the server, as the Error variant of its code.
  • Error::Protocol for a malformed reply, for a reply that is not HaveReply, or for a HaveReply whose length does not match its Have.
  • Error::LimitExceeded on a stream transport, for a frame over the frame limit.
  • Error::Io for a failure of the stream, or for a failed read of a response body over HTTP.
  • Error::Fetch over HTTP, for a failure of the HTTP client.
  • Error::Transport over HTTP, for a status other than 200, 401, 403, 409, 422, 500, and 503, or for a body that is not one frame. A 404 for a session that the server ended is such a status.
Source

pub async fn send( &self, source: &dyn ObjectSource, names: &[ObjectName], commits: &[Checksum], compression: Compression, ) -> Result<()>

Sends the objects names from source, then the detached metadata of commits.

On a stream transport, the objects go in one object stream. The call sends the detached metadata of each commit in commits that has detached metadata, if the session did not send it before. commits holds the commits of names and the new value of each ref update, also if names does not hold that commit. A call with nothing to send writes nothing.

If the session has a PushProgress and names holds at least one file object, the call first asks ObjectSource::content_size. The answer is the number of content bytes that the call sends.

§HTTP

Over HTTP, the call sends the objects in at most parallel-uploads object streams at the same time, and in no more streams than the objects that it sends. Each object stream is one request, and the objects of names can arrive in another order. The detached metadata goes in one of the streams, after its objects.

The object streams of all the calls of the session stay within parallel-uploads, at most 31. A stream waits for a permit. After the first failure, no stream starts a new object, and each stream reads its response.

§Errors
  • Error::InvalidInput if the level of compression is not 1 through 9, or if the type of a name is not a file, a dirtree, a dirmeta, or a commit. The call sends nothing, and the session stays usable.
  • Error::InvalidInput if another call runs, as the rules of concurrent calls state, or if the session is broken.
  • Error::Source if the source fails. The session ends with Abort.
  • Error::InvalidInput if the source gives data that the session cannot send, for example a symlink with a payload, or detached metadata that DetachedMetadata refuses. The session ends with Abort.
  • An Error message from the server, as the Error variant of its code.
  • Error::Protocol for a malformed reply, or for a reply that is not ObjectsReply.
  • Error::LimitExceeded on a stream transport, for a frame over the frame limit.
  • Error::Io for a failure of the stream, or for a failed read of a response body over HTTP.
  • Error::Fetch over HTTP, for a failure of the HTTP client.
  • Error::Transport over HTTP, for a status other than 200, 401, 403, 409, 422, 500, and 503, or for a body that is not one frame. A 404 for a session that the server ended is such a status.

If more than one object stream fails over HTTP, the call returns one error, in this order:

  1. Error::Source or Error::InvalidInput, a failure of the client
  2. an error with a wire code, for example an error that the server gave for its own cause
  3. any other error, also the Error::Protocol of a stream that ends because the server aborted the session for the failure of another stream
§Panics

Under the tokio backend, the call panics outside a tokio runtime context if the source gives a DetachedMetadata::Dict for a commit of commits. A session over ssh or HTTP also needs this context, as connect states.

Examples found in repository?
examples/send_pass.rs (line 161)
138fn run(dir: &Path, count: u64, size: u64, compression: Compression) -> io::Result<()> {
139    fs::create_dir_all(dir)?;
140    write_files(dir, count, size)?;
141    ostrya_rt::block_on(async {
142        let model = TreeModel::scan(dir, ScanOptions::default())
143            .await
144            .map_err(io::Error::other)?;
145        let names: Vec<_> = model
146            .object_names()
147            .into_iter()
148            .filter(|name| name.ty == ObjectType::File)
149            .collect();
150        let session = PushSession::over_stream(
151            Cursor::new(scripted_replies().await?),
152            sink(),
153            &["main".to_string()],
154            SessionOptions::default(),
155        )
156        .await
157        .map_err(io::Error::other)?;
158        eprintln!("send pass: start");
159        let start = Instant::now();
160        session
161            .send(&model, &names, &[], compression)
162            .await
163            .map_err(io::Error::other)?;
164        let elapsed = start.elapsed();
165        let files = names.len().max(1) as f64;
166        println!(
167            "{} files of {size} bytes: {:.1} us per file, {:.3} s in all",
168            names.len(),
169            elapsed.as_secs_f64() * 1e6 / files,
170            elapsed.as_secs_f64()
171        );
172        if let Some(peak) = peak_rss() {
173            println!("VmHWM: {peak}");
174        }
175        Ok(())
176    })
177}
Source

pub async fn commit( self, updates: &[RefUpdate], force: bool, ) -> Result<PushOutcome>

Sends Commit with updates, and returns the outcome from the reply.

The call consumes the session. The call sends no Commit if it refuses updates, if the session is broken, or if the Commit frame is over the frame limit. On a stream transport it then sends nothing, so the server reads the end of the stream. Over HTTP, it sends DELETE.

Over ssh, the call then waits for the ssh client to exit, also after a refusal. The ssh time limits of connect give the rules of the wait.

§HTTP

The client sends the Commit request once, and never sends it again. If the client did not hand the request over to a connection, the server changed no ref. After the hand-over, these failures are Error::CommitOutcomeUnknown:

  • a failure of the request
  • a response head that the client refuses, for example for a declared coding or for a declared length over the cap
  • a failed read of the response
  • a status other than 200, 401, 403, 409, 422, 500, and 503, for example the 404 of a session that the server ended
  • a body that is not one frame
§Errors
  • Error::InvalidInput if updates is empty, names a ref that Hello did not name, or names a ref twice.
  • Error::InvalidInput if the session is broken.
  • Error::LimitExceeded if the Commit frame is over the frame limit.
  • An Error message from the server, as the Error variant of its code. An ostrya server sends it before it changes a ref, with two exceptions. A failed write of the refs can leave some refs written, and a failure of a hook after the update keeps all the refs.
  • Error::Fetch over HTTP, if the client did not hand the request over to a connection.
  • Error::CommitOutcomeUnknown for each other end of the session after the session wrote Commit. The server can have written the refs. A CommitReply whose refs are not the refs of updates in order is one of these cases.

If the write of Commit fails with an I/O error, the session reads one message. An Error message gives the Error variant of its code, and a CommitReply gives the outcome. Any other result is Error::CommitOutcomeUnknown.

Source

pub fn check_server_commit(&self, sc: &ServerCommit) -> Result<()>

Checks the server commit sc against the session, and sends nothing.

The check is the check of server_commit before it sends Commit. A caller runs it after the session opens and before it offers or sends an object, so that a refused server commit sends no object.

§Errors
  • Error::InvalidInput if Hello did not name the branch or a tag of sc, if a name is not a ref, or if sc names a ref twice among its branch and its tags. ServerInfo::canonical maps each name first, so NAME and @OWN:NAME name one ref, where OWN is the collection id of the server.
  • Error::InvalidInput if the branch or a tag of sc is a local ref of the server whose name is 64 lowercase hex characters after that map: NAME or @OWN:NAME. A revision reads such a name as a commit checksum.
  • Error::InvalidInput if the branch and the tags of sc are not in one namespace of the server after that map: the local refs, or the refs of one collection.
  • Error::Protocol if the bytes of a metadata entry of sc are not a v in normal form.
  • Error::InvalidInput if a commit cannot hold a metadata value of sc. A commit holds 128 levels of containers, counted from its metadata dict, so the value can hold two levels fewer than a v.
  • Error::LimitExceeded if the CommitReply to sc can need a frame over the max-frame of the server. The longest reply holds the branch with an old and a new commit, and each tag with a new commit.
  • Error::LimitExceeded if the Commit frame that holds sc is over the max-frame of the server.
Source

pub async fn server_commit(self, sc: ServerCommit) -> Result<PushOutcome>

Sends Commit with the server commit sc, and returns the outcome from the reply.

The server makes a commit over the root dirtree and the root dirmeta of sc. It moves the branch of sc to the commit and creates each tag at it, in one transaction. PushOutcome::commit gives the new commit, and PushOutcome::refs gives the outcome of the branch, then of each tag.

The call consumes the session. It sends no detached metadata. It runs the checks of check_server_commit before it writes Commit. The encode of the Commit frame checks the length of the frame, so the call encodes the frame one time. If a check fails, or if the session is broken, the call sends no Commit and ends the session as commit does. The rules of the HTTP request and of the wait for the ssh client are those of commit.

§Errors
  • Each error of check_server_commit.
  • Error::InvalidInput if the session is broken.
  • An Error message from the server, as the Error variant of its code. An ostrya server sends it before it changes a ref. Examples are Error::RefDenied for a client with no c on the branch, or for a server whose hooks take no server commit, and Error::RefMismatch for a tag that exists.
  • Error::Fetch over HTTP, if the client did not hand the request over to a connection.
  • Error::CommitOutcomeUnknown for each other end of the session after the session wrote Commit. The server can have written the refs. A CommitReply that does not hold the branch and then each tag, each at one new commit, with no old commit for a tag, is one of these cases.
Source

pub async fn abort(self) -> Result<()>

Ends the session, so that the server aborts its transaction.

On a stream transport, if the stream is usable, the session writes Abort and closes its output. A broken session has no stream, so the call writes nothing. Over ssh, the call then waits for the ssh client to exit, as the ssh time limits of connect state.

Over HTTP, the call sends DELETE, also on a broken session. A 204 is success, and so is a 404, which the server gives for a session that it ended already.

§Errors
  • Error::InvalidInput if the session is broken. Over HTTP, the call sends DELETE first.
  • Error::Io if the write of Abort fails.
  • Error::Transport over ssh, if the write of Abort fails with an I/O error and the ssh client exits with a failure status. The error names the status.
  • An Error message from the server over HTTP, as the Error variant of its code.
  • Error::Fetch over HTTP, for a failure of the HTTP client.
  • Error::Transport over HTTP, for a status that the endpoint does not give, or for a body that is not one frame.
  • Error::Io over HTTP, for a failed read of the response body.
Source§

impl PushSession

The open of a session over ssh or HTTP.

Source

pub async fn connect( endpoint: Endpoint, refs: &[String], opts: SessionOptions, ) -> Result<PushSession>

Opens a push session to endpoint over ssh or HTTP.

The call starts the transport, sends Hello with refs, and reads HelloReply. It is prepare and then PreparedSession::open.

§Errors
§tokio runtime

Under the tokio backend, the call must run within a runtime that has the IO driver and the time driver enabled. The runtime builder enables them with enable_io and enable_time, or with enable_all.

The child process, its pipes, and the connections of an HTTP session need the IO driver. The time limits need the time driver. The session runs on the runtime that opened it.

§ssh time limits

After a failed write, the session reads the message that the server can have sent before it closed. The read takes at most five seconds. A server that closed its input and keeps its output open with no message cannot hold the session. When the time ends, the call returns the error of the write, or Error::CommitOutcomeUnknown after Commit.

commit and abort close the standard input of the ssh client. They then wait at most five seconds for the ssh client to exit. They also wait if the stream is broken and if commit refuses its updates. An open that fails waits in the same way.

If the session failed with an I/O error and the ssh client exited with a failure status, the call returns Error::Transport with the status. The status is also added to the message of Error::CommitOutcomeUnknown. A session that committed returns its outcome, whatever the exit status.

The session drops the child with no wait in three cases:

  • the caller drops the session without commit or abort
  • the caller drops the future of commit or abort before it completes
  • the ssh client does not exit within the limit

In each case, the standard input of the child closes, so the child reads end of file on it.

§HTTP

Each step of a session is one request to the receive endpoint of the server. The client adds _ostrya/receive/v1/session to the path of the address, and then /ID and the step. The response to Hello gives the ID in its ostrya-session header, as 64 lowercase hex digits.

ostrya serve serves the endpoint at the root of the server. An address with a path works only behind a proxy that removes that path, or with a host that mounts the ReceiveEndpoint of ostrya-server under that path.

Hello, Have, and Commit go as whole request bodies. Each object stream is the streamed body of one objects request. Each response body holds one frame: the reply of the step, or an Error message.

After the client sent the request body, it waits for the response. The wait is at most 6 minutes for Hello and at most 1 hour for Commit. For each other request, the limit is the progress_timeout of the options of Endpoint::Http. The client sends a request again only if the attempt failed before it sent any byte of the request.

The options of Endpoint::Http must name exactly one mirror, the push address. The client sets max_outstanding to 32 and max_redirects to 0, whatever values the options hold. The 32 requests are one for each of the at most 31 object streams of PushSession::send, and one Have or Commit request. The client follows no redirect, and a 3xx answer is Error::Transport.

The fetcher carries the credential, the TLS settings, the proxy, and the headers of the options to each request. The client takes each trust setting of the options, also a bypass variant of TrustRoots that verifies no certificate chain. The caller owns the trust policy.

§Examples

The example deletes a ref on the server if the ref exists.

use ostrya_fetch::BearerToken;
use ostrya_remote::proto::{Expected, RefUpdate};
use ostrya_remote::session::{PushSession, SessionOptions};
use ostrya_remote::transport::Endpoint;
let mut endpoint = Endpoint::parse("https://repo.example.com/")?;
if let Endpoint::Http(http) = &mut endpoint {
    http.bearer_token = Some(BearerToken { token });
}
let refs = vec!["exampleos/testing".to_owned()];
let session = PushSession::connect(endpoint, &refs, SessionOptions::default()).await?;
let Some(tip) = session.server().tip(&refs[0]) else {
    return session.abort().await;
};
let update = RefUpdate { name: refs[0].clone(), expected: Expected::Commit(tip), new: None };
let outcome = session.commit(&[update], false).await?;
assert_eq!(outcome.refs[0].new, None);
Source

pub async fn prepare(endpoint: Endpoint) -> Result<PreparedSession>

Checks endpoint and makes the transport ready to open.

For an ssh endpoint, the call reads the OSTRYA_SSH_COMMAND environment variable and builds the command line of the ssh client by the rules of the ssh command line. check makes the same checks alone.

For an HTTP endpoint, the call builds the HTTP client from the options, as connect states. With TrustRoots::System, an https:// endpoint reads the trust store of the host, by the rule of Fetcher::new. check makes the checks of the options that read no file alone.

The call starts no ssh client and sends no request. It refuses each value that connect refuses before it starts the transport. A caller can make these checks before its own local work, and open the session with PreparedSession::open after that work.

Under the tokio backend, the call must run within a runtime that has the IO driver enabled, as connect states.

§Errors
Source

pub fn check(endpoint: &Endpoint) -> Result<()>

Makes each refusal of prepare that reads no file, in the order of prepare, with the same errors.

For an ssh endpoint, the call reads the OSTRYA_SSH_COMMAND environment variable and applies the rules of the ssh command line. For an HTTP endpoint, it checks the push address and makes the checks of check_options, so it reads the proxy variables of the environment for Proxy::Environment. It reads no file and no trust store, starts no ssh client, and builds no HTTP client. A caller can make these checks before it resolves the files of an endpoint, for example its token file and its PEM files.

For an HTTP endpoint, prepare also makes the refusals of the TLS setup. So a success of this call does not show that prepare succeeds.

§Errors

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more