alien-bindings 3.3.77

Alien direct in-process resource bindings
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::providers::utils::{prefixed_path, relativize_path};
use crate::{
    error::{Error, ErrorData},
    presigned::{LocalOperation, PresignedOperation, PresignedRequest, PresignedRequestBackend},
    traits::{Binding, Storage},
};
use alien_error::{AlienError, Context, IntoAlienError};
use async_trait::async_trait;
use bytes::Bytes;
use chrono::Utc;
use futures::stream::BoxStream;
use futures::TryStreamExt as _;
use object_store::{
    local::LocalFileSystem, // Use LocalFileSystem directly
    parse_url,              // Also needed for the URL case
    path::Path,
    GetOptions,
    GetResult,
    ListResult,
    ObjectMeta,
    ObjectStore,
    PutMultipartOptions,
    PutOptions,
    PutPayload,
    PutResult,
    Result as ObjectStoreResult,
};
use std::path::PathBuf as StdPathBuf;
use std::time::Duration;
use url::Url;

/// Local storage implementation.
///
/// Can be backed by either a generic store parsed from a URL (typically `file://`)
/// or a `LocalFileSystem` instance pointing to a specific directory.
#[derive(Debug)]
pub struct LocalStorage {
    // Store the URL for reference, even if using LocalFileSystem directly
    url: Url,
    base_dir: Path,
    inner: Box<dyn ObjectStore>,
}

impl LocalStorage {
    /// Creates a new `LocalStorage` instance from a storage path.
    ///
    /// The path can be either:
    /// - A file:// URL (e.g., "file:///path/to/storage")
    /// - An absolute filesystem path (e.g., "/path/to/storage")
    pub fn new(storage_path: String) -> Result<Self, Error> {
        // Check if it's a file:// URL or an absolute path
        if storage_path.starts_with("file://") {
            Self::new_from_url(&storage_path)
        } else {
            // Treat as an absolute filesystem path
            Self::new_from_path(&storage_path)
        }
    }

    /// Creates a new `LocalStorage` instance from a URL string.
    /// Uses `parse_url` to handle the URL (likely `file://`).
    pub fn new_from_url(url_str: &str) -> Result<Self, Error> {
        let url =
            Url::parse(url_str)
                .into_alien_error()
                .context(ErrorData::InvalidConfigurationUrl {
                    url: url_str.to_string(),
                    reason: "Invalid storage URL for local storage".to_string(),
                })?;

        let (store, base_dir) =
            parse_url(&url)
                .into_alien_error()
                .context(ErrorData::BindingSetupFailed {
                    binding_type: "local storage".to_string(),
                    reason: format!("Failed to initialize storage from URL '{}'", url_str),
                })?;

        Ok(Self {
            url,
            base_dir,
            inner: store,
        })
    }

    /// Creates a new `LocalStorage` instance from an absolute filesystem path.
    pub fn new_from_path(path: &str) -> Result<Self, Error> {
        let path_buf = StdPathBuf::from(path);

        // Create the directory if it doesn't exist
        std::fs::create_dir_all(&path_buf)
            .into_alien_error()
            .context(ErrorData::LocalFilesystemError {
                path: path_buf.to_string_lossy().to_string(),
                operation: "create_dir_all".to_string(),
            })?;

        // Build the LocalFileSystem store
        let store = LocalFileSystem::new_with_prefix(&path_buf)
            .into_alien_error()
            .context(ErrorData::BindingSetupFailed {
                binding_type: "local storage".to_string(),
                reason: format!("Failed to initialize LocalFileSystem at: {:?}", path_buf),
            })?;

        // Construct a file:// URL for reference
        let url_string = if cfg!(windows) {
            format!("file:///{}?path={}", path_buf.display(), path_buf.display()).replace('\\', "/")
        } else {
            format!("file://{}", path_buf.display())
        };

        let url = Url::parse(&url_string).into_alien_error().context(
            ErrorData::InvalidConfigurationUrl {
                url: url_string.clone(),
                reason: format!("Failed to construct file URL for path: {:?}", path_buf),
            },
        )?;

        Ok(Self {
            url,
            base_dir: Path::default(),
            inner: Box::new(store),
        })
    }
}

impl Binding for LocalStorage {}

#[async_trait]
impl Storage for LocalStorage {
    fn get_base_dir(&self) -> Path {
        // Note: When using LocalFileSystem::new_with_prefix, the prefix
        // is handled internally by the store. So the base_dir passed
        // to the ObjectStore methods should be relative to that prefix.
        // If created via parse_url, base_dir will have the path part.
        self.base_dir.clone()
    }

    fn get_url(&self) -> Url {
        self.url.clone()
    }

    async fn presigned_put(
        &self,
        path: &Path,
        expires_in: Duration,
    ) -> crate::error::Result<PresignedRequest> {
        let dst = prefixed_path(&self.base_dir, path);

        // For local storage, we need to convert the logical path to a filesystem path
        // This is a bit tricky since we need to map from the object store path to the actual file path
        let file_path = if let Some(url_path) = self.url.to_file_path().ok() {
            // URL-based local storage (file://)
            url_path.join(dst.to_string()).to_string_lossy().to_string()
        } else {
            // Direct LocalFileSystem usage - we need to infer the base directory
            // This is a simplification - in practice you might want to store the actual base path
            format!("{}/{}", self.url.path().trim_start_matches('/'), dst)
        };

        Ok(PresignedRequest {
            backend: PresignedRequestBackend::Local {
                file_path,
                operation: LocalOperation::Put,
            },
            expiration: Utc::now()
                + chrono::Duration::from_std(expires_in)
                    .into_alien_error()
                    .context(ErrorData::Other {
                        message: "Invalid duration".to_string(),
                    })?,
            operation: PresignedOperation::Put,
            path: path.to_string(),
        })
    }

    async fn presigned_get(
        &self,
        path: &Path,
        expires_in: Duration,
    ) -> crate::error::Result<PresignedRequest> {
        let dst = prefixed_path(&self.base_dir, path);

        let file_path = if let Some(url_path) = self.url.to_file_path().ok() {
            url_path.join(dst.to_string()).to_string_lossy().to_string()
        } else {
            format!("{}/{}", self.url.path().trim_start_matches('/'), dst)
        };

        Ok(PresignedRequest {
            backend: PresignedRequestBackend::Local {
                file_path,
                operation: LocalOperation::Get,
            },
            expiration: Utc::now()
                + chrono::Duration::from_std(expires_in)
                    .into_alien_error()
                    .context(ErrorData::Other {
                        message: "Invalid duration".to_string(),
                    })?,
            operation: PresignedOperation::Get,
            path: path.to_string(),
        })
    }

    async fn presigned_delete(
        &self,
        path: &Path,
        expires_in: Duration,
    ) -> crate::error::Result<PresignedRequest> {
        let dst = prefixed_path(&self.base_dir, path);

        let file_path = if let Some(url_path) = self.url.to_file_path().ok() {
            url_path.join(dst.to_string()).to_string_lossy().to_string()
        } else {
            format!("{}/{}", self.url.path().trim_start_matches('/'), dst)
        };

        Ok(PresignedRequest {
            backend: PresignedRequestBackend::Local {
                file_path,
                operation: LocalOperation::Delete,
            },
            expiration: Utc::now()
                + chrono::Duration::from_std(expires_in)
                    .into_alien_error()
                    .context(ErrorData::Other {
                        message: "Invalid duration".to_string(),
                    })?,
            operation: PresignedOperation::Delete,
            path: path.to_string(),
        })
    }
}

// Delegate ObjectStore trait implementation to the inner store.
// When using LocalFileSystem::new_with_prefix, paths passed here are
// relative to the prefix directory.
// When using parse_url("file:///prefix/..."), the base_dir adjustment handles the prefix.
#[async_trait]
impl ObjectStore for LocalStorage {
    async fn put(&self, location: &Path, payload: PutPayload) -> ObjectStoreResult<PutResult> {
        let dst = prefixed_path(&self.base_dir, location);
        self.inner.put(&dst, payload).await
    }

    async fn put_opts(
        &self,
        location: &Path,
        payload: PutPayload,
        opts: PutOptions,
    ) -> ObjectStoreResult<PutResult> {
        let dst = prefixed_path(&self.base_dir, location);
        if !opts.attributes.is_empty() {
            return Err(object_store::Error::NotSupported {
                source: Box::new(AlienError::new(ErrorData::OperationNotSupported {
                    operation: "storage.put object attributes".to_string(),
                    reason: "the local filesystem backend cannot persist object attributes"
                        .to_string(),
                })),
            });
        }
        // LocalFileSystem doesn't support tags. Preserve the existing behavior
        // for Rust callers that use PutOptions only for conditional writes.
        let opts = PutOptions {
            mode: opts.mode,
            tags: Default::default(),
            attributes: Default::default(),
            extensions: opts.extensions,
        };
        self.inner.put_opts(&dst, payload, opts).await
    }

    async fn put_multipart(
        &self,
        location: &Path,
    ) -> ObjectStoreResult<Box<dyn object_store::MultipartUpload>> {
        let dst = prefixed_path(&self.base_dir, location);
        self.inner.put_multipart(&dst).await
    }

    async fn put_multipart_opts(
        &self,
        location: &Path,
        opts: PutMultipartOptions,
    ) -> ObjectStoreResult<Box<dyn object_store::MultipartUpload>> {
        let dst = prefixed_path(&self.base_dir, location);
        self.inner.put_multipart_opts(&dst, opts).await
    }

    async fn get(&self, location: &Path) -> ObjectStoreResult<GetResult> {
        let src = prefixed_path(&self.base_dir, location);
        self.inner.get(&src).await
    }

    async fn get_opts(&self, location: &Path, options: GetOptions) -> ObjectStoreResult<GetResult> {
        let src = prefixed_path(&self.base_dir, location);
        self.inner.get_opts(&src, options).await
    }

    async fn get_range(
        &self,
        location: &Path,
        range: std::ops::Range<u64>,
    ) -> ObjectStoreResult<Bytes> {
        let src = prefixed_path(&self.base_dir, location);
        self.inner.get_range(&src, range).await
    }

    async fn head(&self, location: &Path) -> ObjectStoreResult<ObjectMeta> {
        let src = prefixed_path(&self.base_dir, location);
        let mut meta = self.inner.head(&src).await?;
        meta.location = relativize_path(&self.base_dir, meta.location, "LocalStorage")?;
        Ok(meta)
    }

    async fn delete(&self, location: &Path) -> ObjectStoreResult<()> {
        let src = prefixed_path(&self.base_dir, location);
        self.inner.delete(&src).await
    }

    fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, ObjectStoreResult<ObjectMeta>> {
        let list_prefix_for_inner = prefix
            .map(|p| prefixed_path(&self.base_dir, p))
            .unwrap_or_else(|| self.base_dir.clone());

        let base_dir_for_stream = self.base_dir.clone();

        Box::pin(
            self.inner
                .list(Some(&list_prefix_for_inner))
                .and_then(move |mut meta| {
                    let captured_base_dir = base_dir_for_stream.clone();
                    async move {
                        meta.location =
                            relativize_path(&captured_base_dir, meta.location, "LocalStorage")?;
                        Ok(meta)
                    }
                }),
        )
    }

    fn list_with_offset(
        &self,
        prefix: Option<&Path>,
        offset: &Path,
    ) -> BoxStream<'static, ObjectStoreResult<ObjectMeta>> {
        let list_prefix_for_inner = prefix
            .map(|p| prefixed_path(&self.base_dir, p))
            .unwrap_or_else(|| self.base_dir.clone());
        let offset_for_inner = prefixed_path(&self.base_dir, offset);

        let base_dir_for_stream = self.base_dir.clone();

        // Forward to the inner store so it can send a native start-after request
        // instead of listing the whole prefix and filtering on the client.
        Box::pin(
            self.inner
                .list_with_offset(Some(&list_prefix_for_inner), &offset_for_inner)
                .and_then(move |mut meta| {
                    let captured_base_dir = base_dir_for_stream.clone();
                    async move {
                        meta.location =
                            relativize_path(&captured_base_dir, meta.location, "LocalStorage")?;
                        Ok(meta)
                    }
                }),
        )
    }

    async fn list_with_delimiter(&self, prefix: Option<&Path>) -> ObjectStoreResult<ListResult> {
        let list_prefix_for_inner = prefix
            .map(|p| prefixed_path(&self.base_dir, p))
            .unwrap_or_else(|| self.base_dir.clone());

        let mut result = self
            .inner
            .list_with_delimiter(Some(&list_prefix_for_inner))
            .await?;

        for meta in &mut result.objects {
            let original_location = std::mem::take(&mut meta.location);
            meta.location = relativize_path(&self.base_dir, original_location, "LocalStorage")?;
        }

        let mut new_common_prefixes = Vec::with_capacity(result.common_prefixes.len());
        for cp in result.common_prefixes {
            new_common_prefixes.push(relativize_path(&self.base_dir, cp, "LocalStorage")?);
        }
        result.common_prefixes = new_common_prefixes;

        Ok(result)
    }

    async fn copy(&self, from: &Path, to: &Path) -> ObjectStoreResult<()> {
        let src = prefixed_path(&self.base_dir, from);
        let dst = prefixed_path(&self.base_dir, to);
        self.inner.copy(&src, &dst).await
    }

    async fn copy_if_not_exists(&self, from: &Path, to: &Path) -> ObjectStoreResult<()> {
        let src = prefixed_path(&self.base_dir, from);
        let dst = prefixed_path(&self.base_dir, to);
        self.inner.copy_if_not_exists(&src, &dst).await
    }
}

impl std::fmt::Display for LocalStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "LocalStorage(url={})", self.url)
    }
}

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

    #[tokio::test]
    async fn list_with_offset_returns_only_keys_after_offset_relative_to_base_dir() {
        let directory = tempfile::tempdir().unwrap();
        let store =
            LocalStorage::new_from_url(&format!("file://{}/base/", directory.path().display()))
                .unwrap();
        for key in ["items/a", "items/b", "items/c", "items/d", "other/z"] {
            store
                .put(&Path::from(key), Bytes::from_static(b"x").into())
                .await
                .unwrap();
        }

        let listed: Vec<String> = store
            .list_with_offset(Some(&Path::from("items")), &Path::from("items/b"))
            .map_ok(|meta| meta.location.to_string())
            .try_collect()
            .await
            .unwrap();

        let mut listed = listed;
        listed.sort();
        assert_eq!(listed, vec!["items/c", "items/d"]);
    }
}