use std::io;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::task::{Context, Poll, ready};
use futures_io::AsyncRead;
use ostrya_core::RefSelector;
use crate::error::{Error, Result};
use crate::fetch::{Fetcher, Priority};
#[cfg(feature = "s3")]
use crate::remote::s3::Bucket;
use crate::remote::{self, PullBody, PullSession, StreamSession};
use crate::summary::{SUMMARY_FILE, SUMMARY_SIG_FILE};
use super::http::{CONFIG_FILE, MAX_ROOT_FILE, fetch_optional, read_whole, ref_request_path};
pub(crate) struct Connection {
pub(crate) session: PullSession,
#[cfg(feature = "s3")]
pub(crate) bucket: Option<Bucket>,
}
impl From<PullSession> for Connection {
fn from(session: PullSession) -> Connection {
Connection {
session,
#[cfg(feature = "s3")]
bucket: None,
}
}
}
pub(crate) struct RemoteSource {
session: PullSession,
transferred: Vec<Arc<AtomicU64>>,
#[cfg(feature = "s3")]
bucket: Option<Bucket>,
}
pub(crate) enum Transfer<'a> {
Http(&'a Fetcher),
Stream(StreamSource<'a>),
}
pub(crate) struct StreamSource<'a> {
session: &'a StreamSession,
transferred: &'a [Arc<AtomicU64>],
}
#[derive(Default)]
pub(crate) struct RootFiles {
pub(crate) summary: Option<Vec<u8>>,
pub(crate) signature: Option<Vec<u8>>,
config: Option<Option<Vec<u8>>>,
}
impl RootFiles {
pub(crate) async fn config(&mut self, source: &RemoteSource) -> Result<Option<Vec<u8>>> {
match self.config.take() {
Some(config) => Ok(config),
None => source.read_root(CONFIG_FILE).await,
}
}
}
impl RemoteSource {
pub(crate) fn new(connection: Connection, transferred: Vec<Arc<AtomicU64>>) -> RemoteSource {
let session = match connection.session {
PullSession::Http(fetcher) => PullSession::Http(fetcher.counted(transferred.clone())),
stream => stream,
};
RemoteSource {
session,
#[cfg(feature = "s3")]
bucket: connection
.bucket
.map(|bucket| bucket.counted(transferred.clone())),
transferred,
}
}
pub(crate) fn transfer(&self) -> Transfer<'_> {
match &self.session {
PullSession::Http(fetcher) => Transfer::Http(fetcher),
PullSession::Stream(session) => Transfer::Stream(StreamSource {
session,
transferred: &self.transferred,
}),
}
}
pub(crate) fn max_outstanding(&self) -> usize {
self.session.max_outstanding()
}
pub(crate) async fn read_optional(
&self,
path: &str,
priority: Priority,
cap: u64,
) -> Result<Option<Vec<u8>>> {
match self.transfer() {
Transfer::Http(fetcher) => fetch_optional(fetcher, path, priority, cap).await,
Transfer::Stream(stream) => stream.read_optional(path, cap).await,
}
}
pub(crate) async fn read_root(&self, path: &str) -> Result<Option<Vec<u8>>> {
#[cfg(feature = "s3")]
if let Some(bucket) = &self.bucket {
let object = bucket.get(path, MAX_ROOT_FILE).await.map_err(http_error)?;
return Ok(object.map(|object| object.bytes));
}
self.read_optional(path, Priority::High, MAX_ROOT_FILE)
.await
}
async fn http_summary_files(&self) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
#[cfg(feature = "s3")]
if self.bucket.is_some() {
let summary = async { Ok::<_, Error>(self.read_root(SUMMARY_FILE).await) };
let (signature, summary) =
futures_lite::future::try_zip(self.read_root(SUMMARY_SIG_FILE), summary).await?;
return Ok((summary?, signature));
}
self.session.fetch_summary().await.map_err(http_error)
}
pub(crate) async fn root_files(&self) -> Result<RootFiles> {
match self.transfer() {
Transfer::Http(_) => {
let (summary, signature) = self.http_summary_files().await?;
Ok(RootFiles {
summary,
signature,
config: None,
})
}
Transfer::Stream(stream) => {
let ((signature, summary), config) = futures_lite::future::zip(
futures_lite::future::zip(
stream.read_optional(SUMMARY_SIG_FILE, MAX_ROOT_FILE),
stream.read_optional(SUMMARY_FILE, MAX_ROOT_FILE),
),
stream.read_optional(CONFIG_FILE, MAX_ROOT_FILE),
)
.await;
Ok(RootFiles {
signature: signature?,
summary: summary?,
config: Some(config?),
})
}
}
}
pub(crate) async fn summary_files(&self) -> Result<(Option<Vec<u8>>, Option<Vec<u8>>)> {
match self.transfer() {
Transfer::Http(_) => self.http_summary_files().await,
Transfer::Stream(stream) => {
let (signature, summary) = futures_lite::future::zip(
stream.read_optional(SUMMARY_SIG_FILE, MAX_ROOT_FILE),
stream.read_optional(SUMMARY_FILE, MAX_ROOT_FILE),
)
.await;
Ok((summary?, signature?))
}
}
}
pub(crate) async fn ref_listing(
&self,
refs: &RefSelector,
collections: Option<&RefSelector>,
) -> Result<Option<Vec<u8>>> {
self.session
.fetch_refs(refs, collections)
.await
.map_err(http_error)
}
pub(crate) fn ref_path(&self, dir: &str, name: &str) -> String {
match self.transfer() {
Transfer::Http(_) => ref_request_path(dir, name),
Transfer::Stream(_) => format!("{dir}/{name}"),
}
}
pub(crate) fn has_bucket(&self) -> bool {
#[cfg(feature = "s3")]
return self.bucket.is_some();
#[cfg(not(feature = "s3"))]
false
}
pub(crate) fn into_connection(self) -> Connection {
Connection {
session: self.session,
#[cfg(feature = "s3")]
bucket: self.bucket,
}
}
pub(crate) async fn finish<T>(self, result: Result<T>) -> Result<T> {
match self.session {
PullSession::Http(_) => result,
PullSession::Stream(session) => {
let ended = session.finish().await;
match (result, ended) {
(Ok(value), ended) => ended.map(|()| value).map_err(Error::Remote),
(Err(Error::Remote(_)), Err(ended)) => Err(Error::Remote(ended)),
(Err(e), _) => Err(e),
}
}
}
}
}
impl<'a> StreamSource<'a> {
pub(crate) async fn get(&self, path: &str, cap: u64) -> Result<Option<Counted<'a>>> {
Ok(self.session.get(path, cap).await?.map(|body| Counted {
body,
sinks: self.transferred,
}))
}
async fn read_optional(&self, path: &str, cap: u64) -> Result<Option<Vec<u8>>> {
let Some(body) = self.get(path, cap).await? else {
return Ok(None);
};
let declared = body.len();
let out = read_whole(body, declared, cap)
.await
.map_err(|e| session_error(Error::Io(e)))?;
Ok(Some(out))
}
}
pub(crate) struct Counted<'a> {
body: PullBody,
sinks: &'a [Arc<AtomicU64>],
}
impl Counted<'_> {
pub(crate) fn len(&self) -> Option<u64> {
self.body.len()
}
}
impl AsyncRead for Counted<'_> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
let me = self.get_mut();
let n = ready!(Pin::new(&mut me.body).poll_read(cx, buf))?;
for sink in me.sinks {
sink.fetch_add(n as u64, Ordering::Relaxed);
}
Poll::Ready(Ok(n))
}
}
pub(crate) fn http_error(error: remote::Error) -> Error {
match error {
remote::Error::Fetch(e) => Error::from(e),
remote::Error::Io(e) => Error::Io(e),
remote::Error::InvalidInput(message) => Error::InvalidInput(message),
other => Error::Remote(other),
}
}
pub(crate) fn session_error(error: Error) -> Error {
match error {
Error::Io(io) => match io.downcast::<remote::Error>() {
Ok(e) => Error::Remote(e),
Err(io) => Error::Io(io),
},
other => other,
}
}
#[cfg(test)]
mod tests {
use futures_lite::io::Cursor;
use super::*;
use crate::remote::proto::{
FrameWriter, GetReply, Message, PULL_PROTOCOL_VERSION, PullHelloReply,
};
fn served(body: &[u8]) -> Vec<u8> {
ostrya_rt::block_on(async {
let mut writer = FrameWriter::new(Cursor::new(Vec::new()));
writer
.write_message(&Message::PullHelloReply(PullHelloReply {
version: PULL_PROTOCOL_VERSION,
}))
.await
.unwrap();
writer
.write_message(&Message::GetReply(GetReply {
found: true,
len: Some(body.len() as u64),
}))
.await
.unwrap();
writer.write_object_data(body).await.unwrap();
writer.end_object().await.unwrap();
writer.into_inner().into_inner()
})
}
#[test]
fn a_body_of_its_stated_length_is_not_grown() {
let body: Vec<u8> = (0..100_000u32).map(|i| i as u8).collect();
let input = served(&body);
let out = ostrya_rt::block_on(async {
let session = StreamSession::over_stream(
Cursor::new(input),
futures_lite::io::sink(),
Default::default(),
)
.await
.unwrap();
let source = RemoteSource::new(PullSession::Stream(session).into(), Vec::new());
source
.read_optional("summary", Priority::High, 1 << 20)
.await
.unwrap()
})
.unwrap();
assert_eq!(out, body);
assert_eq!(out.capacity(), body.len());
}
}