lance-io 4.0.1

I/O utilities for Lance
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
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors

//! Wrappers around object_store that apply tracing

use std::ops::Range;
use std::sync::Arc;

use bytes::Bytes;
use futures::StreamExt;
use futures::stream::BoxStream;
use lance_core::utils::tracing::StreamTracingExt;
use object_store::path::Path;
use object_store::{
    GetOptions, GetResult, ListResult, MultipartUpload, ObjectMeta, PutMultipartOptions,
    PutOptions, PutPayload, PutResult, Result as OSResult, UploadPart,
};
use tracing::{Instrument, Span, instrument};

#[derive(Debug)]
pub struct TracedMultipartUpload {
    write_span: Span,
    target: Box<dyn MultipartUpload>,
    write_size: usize,
}

#[async_trait::async_trait]
impl MultipartUpload for TracedMultipartUpload {
    fn put_part(&mut self, data: PutPayload) -> UploadPart {
        let write_span = self.write_span.clone();
        self.write_size += data.content_length();
        let fut = self.target.put_part(data);
        Box::pin(fut.instrument(write_span))
    }

    #[instrument(level = "debug", skip_all)]
    async fn complete(&mut self) -> OSResult<PutResult> {
        let res = self.target.complete().await?;
        self.write_span.record("size", self.write_size);
        Ok(res)
    }

    #[instrument(level = "debug", skip_all)]
    async fn abort(&mut self) -> OSResult<()> {
        self.target.abort().await
    }
}

#[derive(Debug)]
pub struct TracedObjectStore {
    target: Arc<dyn object_store::ObjectStore>,
}

impl std::fmt::Display for TracedObjectStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_fmt(format_args!("TracedObjectStore({})", self.target))
    }
}

#[async_trait::async_trait]
#[deny(clippy::missing_trait_methods)]
impl object_store::ObjectStore for TracedObjectStore {
    #[instrument(level = "debug", skip(self, bytes, location), fields(path = location.as_ref(), size = bytes.content_length()))]
    async fn put(&self, location: &Path, bytes: PutPayload) -> OSResult<PutResult> {
        self.target.put(location, bytes).await
    }

    #[instrument(level = "debug", skip(self, bytes, location), fields(path = location.as_ref(), size = bytes.content_length()))]
    async fn put_opts(
        &self,
        location: &Path,
        bytes: PutPayload,
        opts: PutOptions,
    ) -> OSResult<PutResult> {
        self.target.put_opts(location, bytes, opts).await
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref(), size = tracing::field::Empty))]
    async fn put_multipart(
        &self,
        location: &Path,
    ) -> OSResult<Box<dyn object_store::MultipartUpload>> {
        let upload = self.target.put_multipart(location).await?;
        Ok(Box::new(TracedMultipartUpload {
            target: upload,
            write_span: tracing::Span::current(),
            write_size: 0,
        }))
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref(), size = tracing::field::Empty))]
    async fn put_multipart_opts(
        &self,
        location: &Path,
        opts: PutMultipartOptions,
    ) -> OSResult<Box<dyn object_store::MultipartUpload>> {
        let upload = self.target.put_multipart_opts(location, opts).await?;
        Ok(Box::new(TracedMultipartUpload {
            target: upload,
            write_span: tracing::Span::current(),
            write_size: 0,
        }))
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref(), size = tracing::field::Empty))]
    async fn get(&self, location: &Path) -> OSResult<GetResult> {
        let res = self.target.get(location).await?;

        let span = tracing::Span::current();
        span.record("size", res.meta.size);

        Ok(res)
    }

    #[instrument(level = "debug", skip(self, options, location), fields(path = location.as_ref(), size = tracing::field::Empty))]
    async fn get_opts(&self, location: &Path, options: GetOptions) -> OSResult<GetResult> {
        let res = self.target.get_opts(location, options).await?;

        let span = tracing::Span::current();
        span.record("size", res.range.end - res.range.start);

        Ok(res)
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref(), size = range.end - range.start))]
    async fn get_range(&self, location: &Path, range: Range<u64>) -> OSResult<Bytes> {
        self.target.get_range(location, range).await
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref(), size = ranges.iter().map(|r| r.end - r.start).sum::<u64>()))]
    async fn get_ranges(&self, location: &Path, ranges: &[Range<u64>]) -> OSResult<Vec<Bytes>> {
        self.target.get_ranges(location, ranges).await
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref()))]
    async fn head(&self, location: &Path) -> OSResult<ObjectMeta> {
        self.target.head(location).await
    }

    #[instrument(level = "debug", skip(self, location), fields(path = location.as_ref()))]
    async fn delete(&self, location: &Path) -> OSResult<()> {
        self.target.delete(location).await
    }

    #[instrument(level = "debug", skip_all)]
    fn delete_stream<'a>(
        &'a self,
        locations: BoxStream<'a, OSResult<Path>>,
    ) -> BoxStream<'a, OSResult<Path>> {
        self.target
            .delete_stream(locations)
            .stream_in_current_span()
            .boxed()
    }

    #[instrument(level = "debug", skip(self, prefix), fields(prefix = prefix.map(|p| p.as_ref())))]
    fn list(&self, prefix: Option<&Path>) -> BoxStream<'static, OSResult<ObjectMeta>> {
        self.target.list(prefix).stream_in_current_span().boxed()
    }

    #[instrument(level = "debug", skip(self, prefix, offset), fields(prefix = prefix.map(|p| p.as_ref()), offset = offset.as_ref()))]
    fn list_with_offset(
        &self,
        prefix: Option<&Path>,
        offset: &Path,
    ) -> BoxStream<'static, OSResult<ObjectMeta>> {
        self.target
            .list_with_offset(prefix, offset)
            .stream_in_current_span()
            .boxed()
    }

    #[instrument(level = "debug", skip(self, prefix), fields(prefix = prefix.map(|p| p.as_ref())))]
    async fn list_with_delimiter(&self, prefix: Option<&Path>) -> OSResult<ListResult> {
        self.target.list_with_delimiter(prefix).await
    }

    #[instrument(level = "debug", skip(self, from, to), fields(from = from.as_ref(), to = to.as_ref()))]
    async fn copy(&self, from: &Path, to: &Path) -> OSResult<()> {
        self.target.copy(from, to).await
    }

    #[instrument(level = "debug", skip(self, from, to), fields(from = from.as_ref(), to = to.as_ref()))]
    async fn rename(&self, from: &Path, to: &Path) -> OSResult<()> {
        self.target.rename(from, to).await
    }

    #[instrument(level = "debug", skip(self, from, to), fields(from = from.as_ref(), to = to.as_ref()))]
    async fn rename_if_not_exists(&self, from: &Path, to: &Path) -> OSResult<()> {
        self.target.rename_if_not_exists(from, to).await
    }

    #[instrument(level = "debug", skip(self, from, to), fields(from = from.as_ref(), to = to.as_ref()))]
    async fn copy_if_not_exists(&self, from: &Path, to: &Path) -> OSResult<()> {
        self.target.copy_if_not_exists(from, to).await
    }
}

pub trait ObjectStoreTracingExt {
    fn traced(self) -> Arc<dyn object_store::ObjectStore>;
}

impl ObjectStoreTracingExt for Arc<dyn object_store::ObjectStore> {
    fn traced(self) -> Arc<dyn object_store::ObjectStore> {
        Arc::new(TracedObjectStore { target: self })
    }
}

impl<T: object_store::ObjectStore> ObjectStoreTracingExt for Arc<T> {
    fn traced(self) -> Arc<dyn object_store::ObjectStore> {
        Arc::new(TracedObjectStore { target: self })
    }
}

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

    use bytes::Bytes;
    use object_store::PutPayload;
    use object_store::memory::InMemory;
    use object_store::path::Path;
    use tracing_mock::{expect, subscriber};

    fn payload(data: &[u8]) -> PutPayload {
        PutPayload::from_bytes(Bytes::copy_from_slice(data))
    }

    fn make_store() -> Arc<dyn object_store::ObjectStore> {
        Arc::new(InMemory::new()).traced()
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_put_records_path_and_size() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let span = expect::span().named("put");
        let (sub, handle) = subscriber::mock()
            .new_span(
                span.clone().with_fields(
                    expect::field("path")
                        .with_value(&"a/b.bin")
                        .and(expect::field("size").with_value(&data.len()))
                        .only(),
                ),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        make_store().put(&path, payload(data)).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_get_records_path_and_size() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";
        let size = data.len() as u64; // meta.size is u64

        // Seed without an active mock subscriber.
        let store = make_store();
        store.put(&path, payload(data)).await.unwrap();

        let span = expect::span().named("get");
        let (sub, handle) = subscriber::mock()
            .new_span(
                // size = Empty at span creation, so only path is visited.
                span.clone()
                    .with_fields(expect::field("path").with_value(&"a/b.bin").only()),
            )
            .enter(span.clone())
            .record(span.clone(), expect::field("size").with_value(&size))
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.get(&path).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_get_range_records_path_and_size() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let store = make_store();
        store.put(&path, payload(data)).await.unwrap();

        let range = 2u64..7u64;
        let size = range.end - range.start;

        let span = expect::span().named("get_range");
        let (sub, handle) = subscriber::mock()
            .new_span(
                // `range` is also captured automatically as a debug field since it
                // is not in the skip list, so we don't use `.only()` here.
                span.clone().with_fields(
                    expect::field("path")
                        .with_value(&"a/b.bin")
                        .and(expect::field("size").with_value(&size)),
                ),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.get_range(&path, range).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_get_ranges_records_path_and_total_size() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let store = make_store();
        store.put(&path, payload(data)).await.unwrap();

        let ranges = [2u64..5u64, 6u64..9u64];
        let size: u64 = ranges.iter().map(|r| r.end - r.start).sum();

        let span = expect::span().named("get_ranges");
        let (sub, handle) = subscriber::mock()
            .new_span(
                // `ranges` is also captured automatically as a debug field since
                // it is not in the skip list, so we don't use `.only()` here.
                span.clone().with_fields(
                    expect::field("path")
                        .with_value(&"a/b.bin")
                        .and(expect::field("size").with_value(&size)),
                ),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.get_ranges(&path, &ranges).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_head_records_path() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let store = make_store();
        store.put(&path, payload(data)).await.unwrap();

        let span = expect::span().named("head");
        let (sub, handle) = subscriber::mock()
            .new_span(
                span.clone()
                    .with_fields(expect::field("path").with_value(&"a/b.bin").only()),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.head(&path).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_delete_records_path() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let store = make_store();
        store.put(&path, payload(data)).await.unwrap();

        let span = expect::span().named("delete");
        let (sub, handle) = subscriber::mock()
            .new_span(
                span.clone()
                    .with_fields(expect::field("path").with_value(&"a/b.bin").only()),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.delete(&path).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_copy_records_from_and_to() {
        let from = Path::from("a/src.bin");
        let to = Path::from("a/dst.bin");
        let data = b"hello world";

        let store = make_store();
        store.put(&from, payload(data)).await.unwrap();

        let span = expect::span().named("copy");
        let (sub, handle) = subscriber::mock()
            .new_span(
                span.clone().with_fields(
                    expect::field("from")
                        .with_value(&"a/src.bin")
                        .and(expect::field("to").with_value(&"a/dst.bin"))
                        .only(),
                ),
            )
            .enter(span.clone())
            .exit(span.clone())
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        store.copy(&from, &to).await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }

    #[tokio::test(flavor = "current_thread")]
    async fn test_put_multipart_records_path() {
        let path = Path::from("a/b.bin");
        let data = b"hello world";

        let put_mp_span = expect::span().named("put_multipart");
        // Expect only the span creation; any subsequent enter/exit/record
        // events are not in the queue so they are silently ignored.
        let (sub, handle) = subscriber::mock()
            .new_span(
                // size = Empty at span creation, so only path is visited.
                put_mp_span.with_fields(expect::field("path").with_value(&"a/b.bin").only()),
            )
            .run_with_handle();

        let _guard = tracing::subscriber::set_default(sub);
        let store = make_store();
        let mut upload = store.put_multipart(&path).await.unwrap();
        upload.put_part(payload(data)).await.unwrap();
        upload.complete().await.unwrap();
        drop(_guard);

        handle.assert_finished();
    }
}