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.
impl PushSession
The open of a session over a pair of byte streams, and its calls.
Sourcepub async fn over_stream<R, W>(
input: R,
output: W,
refs: &[String],
opts: SessionOptions,
) -> Result<PushSession>
pub async fn over_stream<R, W>( input: R, output: W, refs: &[String], opts: SessionOptions, ) -> Result<PushSession>
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
Errormessage from the server, as theErrorvariant of its code, for exampleError::VersionUnsupported. Error::Protocolif the version ofHelloReplyis not the version of the session, or if its refs are not the refs ofHelloin order.Error::Protocolfor a malformed frame, or for a reply that is notHelloReply.Error::LimitExceededfor a frame over the frame limit.Error::Iofor a failure of a stream. An end ofinputbefore the reply has the kindUnexpectedEof.
Examples found in repository?
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}Sourcepub fn server(&self) -> &ServerInfo
pub fn server(&self) -> &ServerInfo
Returns the facts of the server.
Sourcepub async fn missing(&self, names: &[ObjectName]) -> Result<Vec<ObjectName>>
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::InvalidInputif 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::InvalidInputif another call runs, as the rules of concurrent calls state, or if the session is broken.- An
Errormessage from the server, as theErrorvariant of its code. Error::Protocolfor a malformed reply, for a reply that is notHaveReply, or for aHaveReplywhose length does not match itsHave.Error::LimitExceededon a stream transport, for a frame over the frame limit.Error::Iofor a failure of the stream, or for a failed read of a response body over HTTP.Error::Fetchover HTTP, for a failure of the HTTP client.Error::Transportover 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.
Sourcepub async fn send(
&self,
source: &dyn ObjectSource,
names: &[ObjectName],
commits: &[Checksum],
compression: Compression,
) -> Result<()>
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::InvalidInputif the level ofcompressionis 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::InvalidInputif another call runs, as the rules of concurrent calls state, or if the session is broken.Error::Sourceif the source fails. The session ends withAbort.Error::InvalidInputif the source gives data that the session cannot send, for example a symlink with a payload, or detached metadata thatDetachedMetadatarefuses. The session ends withAbort.- An
Errormessage from the server, as theErrorvariant of its code. Error::Protocolfor a malformed reply, or for a reply that is notObjectsReply.Error::LimitExceededon a stream transport, for a frame over the frame limit.Error::Iofor a failure of the stream, or for a failed read of a response body over HTTP.Error::Fetchover HTTP, for a failure of the HTTP client.Error::Transportover 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:
Error::SourceorError::InvalidInput, a failure of the client- an error with a wire code, for example an error that the server gave for its own cause
- any other error, also the
Error::Protocolof 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?
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}Sourcepub async fn commit(
self,
updates: &[RefUpdate],
force: bool,
) -> Result<PushOutcome>
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::InvalidInputifupdatesis empty, names a ref thatHellodid not name, or names a ref twice.Error::InvalidInputif the session is broken.Error::LimitExceededif theCommitframe is over the frame limit.- An
Errormessage from the server, as theErrorvariant 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::Fetchover HTTP, if the client did not hand the request over to a connection.Error::CommitOutcomeUnknownfor each other end of the session after the session wroteCommit. The server can have written the refs. ACommitReplywhose refs are not the refs ofupdatesin 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.
Sourcepub fn check_server_commit(&self, sc: &ServerCommit) -> Result<()>
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::InvalidInputifHellodid not name the branch or a tag ofsc, if a name is not a ref, or ifscnames a ref twice among its branch and its tags.ServerInfo::canonicalmaps each name first, soNAMEand@OWN:NAMEname one ref, whereOWNis the collection id of the server.Error::InvalidInputif the branch or a tag ofscis a local ref of the server whose name is 64 lowercase hex characters after that map:NAMEor@OWN:NAME. A revision reads such a name as a commit checksum.Error::InvalidInputif the branch and the tags ofscare not in one namespace of the server after that map: the local refs, or the refs of one collection.Error::Protocolif the bytes of a metadata entry ofscare not avin normal form.Error::Protocolif an attachment ofschas an empty name.Error::InvalidInputif a commit cannot hold a metadata value ofsc. A commit holds 128 levels of containers, counted from its metadata dict, so the value can hold two levels fewer than av.Error::LimitExceededif theCommitReplytosccan need a frame over themax-frameof the server. The longest reply holds the branch with an old and a new commit, and each tag with a new commit.Error::LimitExceededif theCommitframe that holdsscis over themax-frameof the server.
Sourcepub async fn server_commit(self, sc: ServerCommit) -> Result<PushOutcome>
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::InvalidInputif the session is broken.- An
Errormessage from the server, as theErrorvariant of its code. An ostrya server sends it before it changes a ref. Examples areError::RefDeniedfor a client with nocon the branch, or for a server whose hooks take no server commit, andError::RefMismatchfor a tag that exists. Error::Fetchover HTTP, if the client did not hand the request over to a connection.Error::CommitOutcomeUnknownfor each other end of the session after the session wroteCommit. The server can have written the refs. ACommitReplythat 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.
Sourcepub async fn abort(self) -> Result<()>
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::InvalidInputif the session is broken. Over HTTP, the call sendsDELETEfirst.Error::Ioif the write ofAbortfails.Error::Transportover ssh, if the write ofAbortfails with an I/O error and the ssh client exits with a failure status. The error names the status.- An
Errormessage from the server over HTTP, as theErrorvariant of its code. Error::Fetchover HTTP, for a failure of the HTTP client.Error::Transportover HTTP, for a status that the endpoint does not give, or for a body that is not one frame.Error::Ioover HTTP, for a failed read of the response body.
Source§impl PushSession
The open of a session over ssh or HTTP.
impl PushSession
The open of a session over ssh or HTTP.
Sourcepub async fn connect(
endpoint: Endpoint,
refs: &[String],
opts: SessionOptions,
) -> Result<PushSession>
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
- Each error of
prepare. - Each error of
PreparedSession::open.
§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
commitorabort - the caller drops the future of
commitorabortbefore 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);Sourcepub async fn prepare(endpoint: Endpoint) -> Result<PreparedSession>
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
Error::InvalidInputif the ssh command or the receive command is empty or holds only white space, or if the value ofOSTRYA_SSH_COMMANDis not UTF-8.SshOptionsstates the full rule under Empty values.Error::InvalidInputif the options of an HTTP endpoint do not name exactly one mirror, or ifcheck_base_urlrefuses the mirror. The message holds no userinfo.Error::InvalidInputfor anEndpoint::S3.Error::FetchifFetcher::newrefuses the options. Examples:- a credential to an
http://address, withallow_cleartext_credentialsset tofalse - a bearer token and an
Authorizationheader together - a client key that needs a passphrase that the options do not hold
- a credential to an
Sourcepub fn check(endpoint: &Endpoint) -> Result<()>
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
Error::InvalidInputif the ssh command or the receive command is empty or holds only white space, or if the value ofOSTRYA_SSH_COMMANDis not UTF-8.SshOptionsstates the full rule under Empty values.Error::InvalidInputif the options of an HTTP endpoint do not name exactly one mirror, or ifcheck_base_urlrefuses the mirror. The message holds no userinfo.Error::InvalidInputfor anEndpoint::S3.Error::Fetchifcheck_optionsrefuses the options of an HTTP endpoint, for example a bad header, a low-speed rule with a zero, or a bad proxy URL.