arxivis 1.0.0

Official Rust SDK for the Arxivis document store
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::time::Duration;

use reqwest::{
    multipart::{Form, Part},
    Client, Response, StatusCode,
};
use url::Url;

use crate::{
    error::ArxivisError,
    types::{
        ApiKey, CreateKeyRequest, CreateKeyResult, FileRecord, KeysEnvelope, ListOptions,
        ListResult, SearchOptions, SearchResult, Stats, UploadOptions, ZipRequest,
    },
};

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

/// Async HTTP client for the Arxivis document store API.
///
/// All methods are `async` and return `Result<_, ArxivisError>`.
/// `ArxivisClient` is `Clone + Send + Sync`.
///
/// # Example
///
/// ```rust,no_run
/// use arxivis::{ArxivisClient, UploadOptions};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let client = ArxivisClient::new("http://localhost:8080", "axv_xxxx_yyyy")?;
///
///     let data = std::fs::read("invoice.pdf")?;
///     let record = client
///         .upload(data, "invoice.pdf", UploadOptions::new().path("/invoices/2024/"))
///         .await?;
///     println!("stored: {}", record.id);
///     Ok(())
/// }
/// ```
#[derive(Clone)]
pub struct ArxivisClient {
    base: String,
    api_key: String,
    http: Client,
}

impl ArxivisClient {
    /// Create a new client.
    ///
    /// * `base_url` — base URL of the Arxivis instance, e.g. `"http://localhost:8080"`
    /// * `api_key`  — API key in the format `axv_<prefix>_<secret>`
    pub fn new(
        base_url: impl Into<String>,
        api_key: impl Into<String>,
    ) -> Result<Self, ArxivisError> {
        let http = Client::builder()
            .timeout(DEFAULT_TIMEOUT)
            .build()
            .map_err(ArxivisError::Http)?;

        Ok(Self {
            base: base_url.into().trim_end_matches('/').to_owned() + "/api/v1",
            api_key: api_key.into(),
            http,
        })
    }

    /// Return a copy of the client that uses a custom request timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Result<Self, ArxivisError> {
        self.http = Client::builder()
            .timeout(timeout)
            .build()
            .map_err(ArxivisError::Http)?;
        Ok(self)
    }

    // ── internal helpers ──────────────────────────────────────────────────────

    fn api_url(&self, path: &str) -> String {
        format!("{}{}", self.base, path)
    }

    async fn check(resp: Response) -> Result<Response, ArxivisError> {
        if resp.status().is_success() {
            return Ok(resp);
        }
        let status = resp.status().as_u16();
        let message = resp
            .json::<serde_json::Value>()
            .await
            .ok()
            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
            .unwrap_or_else(|| format!("HTTP {status}"));
        Err(ArxivisError::Api { status, message })
    }

    async fn fetch<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
    ) -> Result<T, ArxivisError> {
        let resp = self
            .http
            .get(self.api_url(path))
            .header("X-API-Key", &self.api_key)
            .header("Accept", "application/json")
            .send()
            .await?;
        Ok(Self::check(resp).await?.json::<T>().await?)
    }

    async fn fetch_params<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        params: &[(&str, String)],
    ) -> Result<T, ArxivisError> {
        let mut url = Url::parse(&self.api_url(path))
            .map_err(|e| ArxivisError::Api { status: 0, message: e.to_string() })?;
        for (k, v) in params {
            url.query_pairs_mut().append_pair(k, v);
        }
        let resp = self
            .http
            .get(url)
            .header("X-API-Key", &self.api_key)
            .header("Accept", "application/json")
            .send()
            .await?;
        Ok(Self::check(resp).await?.json::<T>().await?)
    }

    async fn fetch_bytes(&self, path: &str) -> Result<bytes::Bytes, ArxivisError> {
        let resp = self
            .http
            .get(self.api_url(path))
            .header("X-API-Key", &self.api_key)
            .send()
            .await?;
        Ok(Self::check(resp).await?.bytes().await?)
    }

    async fn post_json<B, T>(&self, path: &str, body: &B) -> Result<T, ArxivisError>
    where
        B: serde::Serialize,
        T: serde::de::DeserializeOwned,
    {
        let resp = self
            .http
            .post(self.api_url(path))
            .header("X-API-Key", &self.api_key)
            .header("Accept", "application/json")
            .json(body)
            .send()
            .await?;
        Ok(Self::check(resp).await?.json::<T>().await?)
    }

    async fn post_json_bytes<B>(&self, path: &str, body: &B) -> Result<bytes::Bytes, ArxivisError>
    where
        B: serde::Serialize,
    {
        let http = Client::builder()
            .timeout(Duration::from_secs(600))
            .build()
            .map_err(ArxivisError::Http)?;
        let resp = http
            .post(self.api_url(path))
            .header("X-API-Key", &self.api_key)
            .json(body)
            .send()
            .await?;
        Ok(Self::check(resp).await?.bytes().await?)
    }

    async fn do_delete(&self, path: &str) -> Result<(), ArxivisError> {
        let resp = self
            .http
            .delete(self.api_url(path))
            .header("X-API-Key", &self.api_key)
            .send()
            .await?;
        if resp.status() == StatusCode::NO_CONTENT || resp.status().is_success() {
            return Ok(());
        }
        let status = resp.status().as_u16();
        let message = resp
            .json::<serde_json::Value>()
            .await
            .ok()
            .and_then(|v| v.get("error").and_then(|e| e.as_str()).map(String::from))
            .unwrap_or_else(|| format!("HTTP {status}"));
        Err(ArxivisError::Api { status, message })
    }

    // ── Stats ─────────────────────────────────────────────────────────────────

    /// Return aggregate storage statistics.
    pub async fn get_stats(&self) -> Result<Stats, ArxivisError> {
        self.fetch("/stats").await
    }

    // ── Files ─────────────────────────────────────────────────────────────────

    /// Upload raw bytes as a file.
    ///
    /// * `data`     — raw file content
    /// * `filename` — the original filename stored on the server
    /// * `opts`     — upload options (path, tags, compression, encryption)
    pub async fn upload(
        &self,
        data: impl Into<Vec<u8>>,
        filename: impl Into<String>,
        opts: UploadOptions,
    ) -> Result<FileRecord, ArxivisError> {
        let filename = filename.into();
        let mime = mime_guess::from_path(&filename)
            .first_or_octet_stream()
            .to_string();

        let file_part = Part::bytes(data.into())
            .file_name(filename.clone())
            .mime_str(&mime)
            .map_err(|e| ArxivisError::Http(e.into()))?;

        let mut form = Form::new().part("file", file_part);

        if !opts.tags.is_empty() {
            form = form.text("tags", opts.tags.join(","));
        }
        if let Some(path) = opts.path {
            form = form.text("path", path);
        }
        if let Some(c) = opts.compress {
            form = form.text("compress", if c { "true" } else { "false" });
        }
        if let Some(e) = opts.encrypt {
            form = form.text("encrypt", if e { "true" } else { "false" });
        }

        let resp = self
            .http
            .post(self.api_url("/files"))
            .header("X-API-Key", &self.api_key)
            .header("Accept", "application/json")
            .multipart(form)
            .send()
            .await?;

        Ok(Self::check(resp).await?.json::<FileRecord>().await?)
    }

    /// List files under `path` (default `"/"`).
    pub async fn list(
        &self,
        path: impl Into<String>,
        opts: ListOptions,
    ) -> Result<ListResult, ArxivisError> {
        let limit = if opts.limit == 0 { 50 } else { opts.limit };
        self.fetch_params(
            "/files",
            &[
                ("path", path.into()),
                ("limit", limit.to_string()),
                ("offset", opts.offset.to_string()),
            ],
        )
        .await
    }

    /// Fetch a single file record by ID.
    pub async fn get(&self, id: &str) -> Result<FileRecord, ArxivisError> {
        self.fetch(&format!("/files/{id}")).await
    }

    /// Resolve a virtual path to a file record.
    ///
    /// `virtual_path` is the full path, e.g. `"/albaranes/albaran_1620.pdf"`.
    /// Returns `Err` with HTTP 404 if no file exists at that path.
    pub async fn get_by_virtual_path(&self, virtual_path: &str) -> Result<FileRecord, ArxivisError> {
        let encoded = urlencoding::encode(virtual_path);
        self.fetch(&format!("/files/resolve?path={encoded}")).await
    }

    /// Download the raw bytes of a file by ID.
    pub async fn download(&self, id: &str) -> Result<bytes::Bytes, ArxivisError> {
        self.fetch_bytes(&format!("/files/{id}/download")).await
    }

    /// Soft-delete a file by ID.
    pub async fn delete_file(&self, id: &str) -> Result<(), ArxivisError> {
        self.do_delete(&format!("/files/{id}")).await
    }

    /// Export multiple files as a ZIP archive.
    ///
    /// `ids` — slice of file ID strings (maximum 500)
    pub async fn download_zip(&self, ids: &[&str]) -> Result<bytes::Bytes, ArxivisError> {
        self.post_json_bytes("/files/zip", &ZipRequest { ids }).await
    }

    // ── Folders ───────────────────────────────────────────────────────────────

    /// Create a virtual folder.
    ///
    /// Returns the normalised path as confirmed by the server.
    pub async fn create_folder(&self, path: &str) -> Result<String, ArxivisError> {
        let resp: serde_json::Value =
            self.post_json("/folders", &serde_json::json!({ "path": path })).await?;
        Ok(resp
            .get("path")
            .and_then(|v| v.as_str())
            .unwrap_or(path)
            .to_owned())
    }

    // ── Search ────────────────────────────────────────────────────────────────

    /// Full-text search using SQLite FTS5.
    pub async fn search(
        &self,
        query: &str,
        opts: SearchOptions,
    ) -> Result<ListResult, ArxivisError> {
        let limit = if opts.limit == 0 { 50 } else { opts.limit };
        self.fetch_params(
            "/search",
            &[
                ("q", query.to_owned()),
                ("limit", limit.to_string()),
                ("offset", opts.offset.to_string()),
            ],
        )
        .await
    }

    /// Vector / semantic search using the configured embedding model.
    pub async fn semantic_search(
        &self,
        query: &str,
        opts: SearchOptions,
    ) -> Result<SearchResult, ArxivisError> {
        let limit = if opts.limit == 0 { 20 } else { opts.limit };
        self.fetch_params(
            "/search/semantic",
            &[("q", query.to_owned()), ("limit", limit.to_string())],
        )
        .await
    }

    /// Hybrid search combining FTS5 and semantic results via Reciprocal Rank Fusion.
    pub async fn hybrid_search(
        &self,
        query: &str,
        opts: SearchOptions,
    ) -> Result<SearchResult, ArxivisError> {
        let limit = if opts.limit == 0 { 30 } else { opts.limit };
        self.fetch_params(
            "/search/hybrid",
            &[("q", query.to_owned()), ("limit", limit.to_string())],
        )
        .await
    }

    // ── API Keys ──────────────────────────────────────────────────────────────

    /// Create a new API key.
    ///
    /// **The `key` field in the result is shown only once — store it immediately.**
    pub async fn create_key(&self, name: &str) -> Result<CreateKeyResult, ArxivisError> {
        self.post_json("/keys", &CreateKeyRequest { name }).await
    }

    /// List all API keys (secrets are never included).
    pub async fn list_keys(&self) -> Result<Vec<ApiKey>, ArxivisError> {
        let envelope: KeysEnvelope = self.fetch("/keys").await?;
        Ok(envelope.keys)
    }

    /// Permanently revoke an API key by its ID.
    pub async fn revoke_key(&self, id: &str) -> Result<(), ArxivisError> {
        self.do_delete(&format!("/keys/{id}")).await
    }

    // ── URL helpers ───────────────────────────────────────────────────────────

    /// Build a direct download URL with the API key embedded.
    pub fn download_url(&self, id: &str) -> String {
        let base = self.base.trim_end_matches("/api/v1");
        format!(
            "{}/api/v1/files/{}/download?api_key={}",
            base,
            id,
            urlencoding::encode(&self.api_key)
        )
    }

    /// Build an inline preview URL with the API key embedded.
    pub fn preview_url(&self, id: &str) -> String {
        let base = self.base.trim_end_matches("/api/v1");
        format!(
            "{}/api/v1/files/{}/preview?api_key={}",
            base,
            id,
            urlencoding::encode(&self.api_key)
        )
    }

    /// Build a virtual-path URL for a file, e.g. `"/invoices/2024/factura.pdf"`.
    pub fn path_url(&self, file_path: &str) -> String {
        let base = self.base.trim_end_matches("/api/v1");
        let clean = file_path.trim_start_matches('/');
        format!(
            "{}/f/{}?api_key={}",
            base,
            clean,
            urlencoding::encode(&self.api_key)
        )
    }
}