Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions .github/workflows/rust-file-paths.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Rust file path validation

on:
pull_request:
branches: [main, "release/**"]
paths:
- "sdk/rust/**"
- ".github/workflows/rust-file-paths.yml"
push:
branches: [main, "release/**"]
paths:
- "sdk/rust/**"
- ".github/workflows/rust-file-paths.yml"
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}

permissions:
contents: read

jobs:
native-paths:
name: Native paths (${{ matrix.os }}, Rust ${{ matrix.rust }}, CPython 3.14)
runs-on: ${{ matrix.os }}
timeout-minutes: 10
strategy:
fail-fast: false
matrix:
os: [ubuntu-24.04, windows-2025]
rust: ["1.85.1", stable]
env:
RUSTUP_TOOLCHAIN: ${{ matrix.rust }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.14"
- name: Install the Rust toolchain
shell: bash
run: rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --no-self-update
- name: Compare native paths with CPython and run all resolver tests
# The harness enables SeCreateSymbolicLinkPrivilege on Windows. Missing
# privileges, junction support or long-path support fail this job.
shell: bash
run: python sdk/rust/tests/native_paths/check.py --toolchain "$RUSTUP_TOOLCHAIN"
3 changes: 2 additions & 1 deletion sdk/rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ required-features = ["blocking"]

[dependencies]
base64 = "0.22"
bytes = "1"
reqwest = { version = "0.12.28", default-features = false, features = [
"json",
"rustls-tls",
Expand All @@ -36,12 +37,12 @@ unicode-general-category = "0.6"
tempfile = "3"
filetime = "0.2"
hostname = "0.4"
sha2 = "0.10"

[target.'cfg(unix)'.dependencies]
libc = { version = "0.2" }

[dev-dependencies]
sha2 = "0.10"
tokio = { version = "1", features = [
"macros",
"rt-multi-thread",
Expand Down
85 changes: 85 additions & 0 deletions sdk/rust/examples/ingest_file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use clickhouse_loom::{Client, FileIngestOptions, IngestWaitOptions};
use std::{
env,
error::Error,
fs::OpenOptions,
io::{self, Write},
path::Path,
time::Duration,
};

fn save_id(path: &Path, id: &str) -> io::Result<()> {
let mut saved = OpenOptions::new().write(true).create_new(true).open(path)?;
writeln!(saved, "{id}")
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let path = env::args().nth(1).ok_or("usage: ingest_file <path>")?;
let client = Client::builder(
env::var("LOOM_ORG")?,
env::var("LOOM_NAMESPACE")?,
"file-example",
)
.base_url(env::var("LOOM_BASE_URL").unwrap_or_else(|_| "http://localhost:7777".into()))
.api_key(env::var("LOOM_TOKEN").unwrap_or_default())
.build()?;
let job = client
.knowledge_start_file_ingest_with_options(
&path,
FileIngestOptions::default().tags(["example"]),
)
.await?
.data;
save_id(Path::new("ingestion-id.txt"), &job.ingestion_id).map_err(|error| {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 — With an existing ingestion-id.txt, the example uploads the file and queues another job before failing to save the new ID. The first ID remains on disk. Reserve the destination before sending either request, or resume the saved job.

format!(
"job {} started; cannot save its ID: {error}",
job.ingestion_id
)
})?;
let status = client
.knowledge_wait_for_ingest_with_options(
&job.ingestion_id,
IngestWaitOptions::default().timeout(Duration::from_secs(120)),
)
.await?
.data;
if !status.found
|| !matches!(status.state.as_str(), "ready" | "partial")
|| status.retrieval != "ready"
{
return Err(format!(
"ingestion {}: {} ({})",
job.ingestion_id, status.state, status.error_message
)
.into());
}
let bytes = client.knowledge_download(&job.source_uri).await?;
println!(
"{}: {} bytes, revision {:?}",
job.source_uri,
bytes.len(),
status.revision
);
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn saving_a_job_id_never_overwrites_the_input_or_an_earlier_id() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("ingestion-id.txt");
std::fs::write(&path, b"original file").unwrap();
assert_eq!(
save_id(&path, "job").unwrap_err().kind(),
io::ErrorKind::AlreadyExists
);
assert_eq!(std::fs::read(&path).unwrap(), b"original file");
let new_path = dir.path().join("new-id.txt");
save_id(&new_path, "job").unwrap();
assert_eq!(std::fs::read(new_path).unwrap(), b"job\n");
}
}
139 changes: 129 additions & 10 deletions sdk/rust/src/blocking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,123 @@ macro_rules! typed_call {
}

impl Client {
/// See [`crate::Client::knowledge_upload`].
pub fn knowledge_upload(
&self,
data: Vec<u8>,
filename: impl Into<String>,
) -> Result<crate::KnowledgeUploadOutput, Error> {
self.knowledge_upload_with_options(data, filename, crate::KnowledgeUploadOptions::default())
.map(|result| result.data)
.map_err(|failure| failure.error)
}

pub fn knowledge_upload_with_options(
&self,
data: Vec<u8>,
filename: impl Into<String>,
options: crate::KnowledgeUploadOptions,
) -> Result<CallResult<crate::KnowledgeUploadOutput>, CallFailure> {
let filename = filename.into();
self.submit(move |client| async move {
client
.knowledge_upload_with_options(data, filename, options)
.await
})
}

/// See [`crate::Client::knowledge_download`].
pub fn knowledge_download(&self, source_uri: &str) -> Result<Vec<u8>, Error> {
self.knowledge_download_with_options(source_uri, CallOptions::default())
.map(|result| result.data)
.map_err(|failure| failure.error)
}

pub fn knowledge_download_with_options(
&self,
source_uri: &str,
options: CallOptions,
) -> Result<CallResult<Vec<u8>>, CallFailure> {
let source_uri = source_uri.to_owned();
self.submit(move |client| async move {
client
.knowledge_download_with_options(&source_uri, options)
.await
})
}

/// See [`crate::Client::knowledge_ingest_file`].
pub fn knowledge_ingest_file(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<crate::KnowledgeIngestStatusOutput, Error> {
self.knowledge_ingest_file_with_options(path, crate::FileIngestOptions::default())
.map(|result| result.data)
.map_err(|failure| failure.error)
}

pub fn knowledge_ingest_file_with_options(
&self,
path: impl AsRef<std::path::Path>,
options: crate::FileIngestOptions,
) -> Result<CallResult<crate::KnowledgeIngestStatusOutput>, CallFailure> {
let path = path.as_ref().to_owned();
self.submit(move |client| async move {
client
.knowledge_ingest_file_with_options(path, options)
.await
})
}

/// See [`crate::Client::knowledge_start_file_ingest`].
pub fn knowledge_start_file_ingest(
&self,
path: impl AsRef<std::path::Path>,
) -> Result<crate::KnowledgeIngestOutput, Error> {
self.knowledge_start_file_ingest_with_options(path, crate::FileIngestOptions::default())
.map(|result| result.data)
.map_err(|failure| failure.error)
}

pub fn knowledge_start_file_ingest_with_options(
&self,
path: impl AsRef<std::path::Path>,
options: crate::FileIngestOptions,
) -> Result<CallResult<crate::KnowledgeIngestOutput>, CallFailure> {
let path = path.as_ref().to_owned();
self.submit(move |client| async move {
client
.knowledge_start_file_ingest_with_options(path, options)
.await
})
}

/// See [`crate::Client::knowledge_wait_for_ingest`].
pub fn knowledge_wait_for_ingest(
&self,
ingestion_id: &str,
) -> Result<crate::KnowledgeIngestStatusOutput, Error> {
self.knowledge_wait_for_ingest_with_options(
ingestion_id,
crate::IngestWaitOptions::default(),
)
.map(|result| result.data)
.map_err(|failure| failure.error)
}

pub fn knowledge_wait_for_ingest_with_options(
&self,
ingestion_id: &str,
options: crate::IngestWaitOptions,
) -> Result<CallResult<crate::KnowledgeIngestStatusOutput>, CallFailure> {
let ingestion_id = ingestion_id.to_owned();
self.submit(move |client| async move {
client
.knowledge_wait_for_ingest_with_options(&ingestion_id, options)
.await
})
}

pub fn builder(
org: impl Into<String>,
namespace: impl Into<String>,
Expand Down Expand Up @@ -271,9 +388,18 @@ impl Client {
{
outside_runtime()?;
let (sender, receiver) = std::sync::mpsc::sync_channel(1);
let retry = self.retry.clone();
let job: Job = Box::new(move |client| {
Box::pin(async move {
let _ = sender.send(job(client).await);
let result = async move {
let client = match retry {
Some(retry) => client.with_retry(retry)?,
None => client,
};
job(client).await
}
.await;
let _ = sender.send(result);
})
});
self.worker
Expand All @@ -290,15 +416,8 @@ impl Client {
F: FnOnce(crate::Client) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, Error>> + Send + 'static,
{
let retry = self.retry.clone();
self.submit(move |client| async move {
let client = match retry {
Some(retry) => client.with_retry(retry)?,
None => client,
};
Ok(job(client).await?)
})
.map_err(|failure| failure.error)
self.submit(move |client| async move { Ok(job(client).await?) })
.map_err(|failure| failure.error)
}
}

Expand Down
11 changes: 11 additions & 0 deletions sdk/rust/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,17 @@ pub struct ClientBuilder {
}

impl Client {
pub(crate) fn file_scope(&self) -> Result<(String, String), Error> {
let scope = |key: &str| {
self.identity
.get(key)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_owned)
.ok_or_else(|| Error::Input(format!("file operations require an explicit {key}")))
};
Ok((scope("org")?, scope("namespace")?))
}
typed_call!(
health,
health_with_options,
Expand Down
Loading
Loading