hazine 0.2.9

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
//! Uploads to the lake's bucket, for files too big for DuckDB (a BLOB holds
//! at most 4 GB): multipart and streamed, with the credentials `hazine
//! setup` wrote.

use std::io::Read;
use std::path::Path;

use object_store::aws::{AmazonS3, AmazonS3Builder};
use object_store::path::Path as Key;
use object_store::{ObjectStoreExt, WriteMultipart};

use crate::Error;
use crate::setup::render;

/// Bytes per uploaded part: S3 allows 10,000 parts, so up to ~640 GB.
const PART_SIZE: usize = 64 * 1024 * 1024;

/// Parts uploading at once.
const CONCURRENCY: usize = 4;

/// The lake's bucket.
pub(crate) struct Bucket {
    store: AmazonS3,
    name: String,
    runtime: tokio::runtime::Handle,
}

fn s3_error(error: impl std::fmt::Display) -> Error {
    Error::Import(format!("object storage: {error}"))
}

impl Bucket {
    /// The bucket of `HAZINE_DATA_PATH`, with the env file's S3 settings;
    /// `use_ssl` as in `init.sql`. Must run inside a Tokio runtime (in
    /// `spawn_blocking` is fine).
    pub(crate) fn from_env(
        env: impl Fn(&str) -> Option<String>,
        use_ssl: bool,
    ) -> Result<Self, Error> {
        let get = |name: &'static str| {
            env(name).ok_or_else(|| Error::InvalidSetting {
                name: "hazine.env",
                reason: format!("has no {name}; rerun hazine setup"),
            })
        };
        let data_path = render::data_path(&get("HAZINE_DATA_PATH")?)?;
        let name = render::scope(&data_path)["s3://".len()..].to_string();
        let endpoint = get("HAZINE_S3_ENDPOINT")?;
        let vhost = get("HAZINE_S3_URL_STYLE")? != render::UrlStyle::Path.as_str();
        crate::tls::init();
        let mut builder = AmazonS3Builder::new()
            .with_bucket_name(&name)
            .with_region(get("HAZINE_S3_REGION")?)
            .with_access_key_id(get("HAZINE_S3_KEY_ID")?)
            .with_secret_access_key(get("HAZINE_S3_SECRET")?)
            .with_virtual_hosted_style_request(vhost);
        if endpoint != render::AWS {
            let scheme = if use_ssl { "https" } else { "http" };
            // A virtual-hosted endpoint names the bucket already.
            let host = if vhost {
                format!("{name}.{endpoint}")
            } else {
                endpoint
            };
            builder = builder
                .with_allow_http(!use_ssl)
                .with_endpoint(format!("{scheme}://{host}"));
        }
        Ok(Bucket {
            store: builder.build().map_err(s3_error)?,
            name,
            runtime: tokio::runtime::Handle::try_current().map_err(s3_error)?,
        })
    }

    /// `s3://bucket/key`.
    pub(crate) fn url(&self, key: &str) -> String {
        format!("s3://{}/{key}", self.name)
    }

    /// The size of the object at `key`; none if there is none.
    pub(crate) fn size(&self, key: &str) -> Result<Option<u64>, Error> {
        match self.runtime.block_on(self.store.head(&Key::from(key))) {
            Ok(meta) => Ok(Some(meta.size)),
            Err(object_store::Error::NotFound { .. }) => Ok(None),
            Err(error) => Err(s3_error(error)),
        }
    }

    /// Upload the file at `path` to `key` unchanged, in parts; returns its
    /// size. A failed upload is aborted, leaving no object behind.
    pub(crate) fn upload(&self, path: &Path, key: &str) -> Result<u64, Error> {
        let mut file = std::fs::File::open(path)?;
        self.runtime.block_on(async {
            let upload = self
                .store
                .put_multipart(&Key::from(key))
                .await
                .map_err(s3_error)?;
            let mut writer = WriteMultipart::new_with_chunk_size(upload, PART_SIZE);
            let mut buffer = vec![0; 8 * 1024 * 1024];
            let mut total = 0u64;
            let result: Result<(), Error> = async {
                loop {
                    let read = file.read(&mut buffer)?;
                    if read == 0 {
                        return Ok(());
                    }
                    writer
                        .wait_for_capacity(CONCURRENCY)
                        .await
                        .map_err(s3_error)?;
                    writer.write(&buffer[..read]);
                    total += read as u64;
                }
            }
            .await;
            match result {
                Ok(()) => {
                    writer.finish().await.map_err(s3_error)?;
                    Ok(total)
                }
                Err(error) => {
                    // The error that matters is the first; an abort that
                    // fails too leaves the uploaded parts in the bucket.
                    let _ = writer.abort().await;
                    Err(error)
                }
            }
        })
    }
}