marina 0.2.3

A dataset manager for robotics to organize, share, and discover datasets and metadata across storage backends.
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
use std::cell::RefCell;
use std::ffi::{CStr, CString, c_char, c_void};

use crate::{Marina, ProgressEvent, ProgressReporter, ProgressSink, ResolveResult, WriterProgress};

pub const MARINA_RESOLVE_ERROR: i32 = -1;
pub const MARINA_RESOLVE_LOCAL: i32 = 0;
pub const MARINA_RESOLVE_CACHED: i32 = 1;
pub const MARINA_RESOLVE_REMOTE_AVAILABLE: i32 = 2;
pub const MARINA_RESOLVE_AMBIGUOUS: i32 = 3;
pub const MARINA_PROGRESS_MODE_SILENT: i32 = 0;
pub const MARINA_PROGRESS_MODE_STDOUT: i32 = 1;

pub type MarinaProgressCallback =
    Option<extern "C" fn(phase: *const c_char, message: *const c_char, user_data: *mut c_void)>;

#[repr(C)]
pub struct MarinaResolveDetailed {
    pub kind: i32,
    pub path: *mut c_char,
    pub bag: *mut c_char,
    pub registry: *mut c_char,
    pub message: *mut c_char,
}

unsafe fn parse_optional_cstr(
    ptr: *const c_char,
    arg_name: &str,
) -> Result<Option<String>, String> {
    if ptr.is_null() {
        return Ok(None);
    }
    let value = read_cstr(ptr, arg_name)?;
    if value.is_empty() {
        Ok(None)
    } else {
        Ok(Some(value))
    }
}

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = const { RefCell::new(None) };
}

fn set_last_error(msg: impl Into<String>) {
    let fallback = CString::new("unknown error").expect("CString literal");
    let cmsg = CString::new(msg.into()).unwrap_or(fallback);
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = Some(cmsg);
    });
}

fn clear_last_error() {
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = None;
    });
}

fn read_cstr(ptr: *const c_char, arg_name: &str) -> Result<String, String> {
    if ptr.is_null() {
        return Err(format!("{} was null", arg_name));
    }
    // SAFETY: caller guarantees a valid null-terminated C string pointer.
    let s = unsafe { CStr::from_ptr(ptr) };
    s.to_str()
        .map(|v| v.to_string())
        .map_err(|_| format!("{} was not valid UTF-8", arg_name))
}

fn cstring_from_string(s: String) -> *mut c_char {
    match CString::new(s) {
        Ok(v) => v.into_raw(),
        Err(_) => {
            set_last_error("result string contained interior NUL byte");
            std::ptr::null_mut()
        }
    }
}

fn cstring_from_opt(s: Option<String>) -> *mut c_char {
    match s {
        Some(v) => cstring_from_string(v),
        None => std::ptr::null_mut(),
    }
}

fn parse_registry(registry: *const c_char) -> Result<Option<String>, String> {
    if registry.is_null() {
        Ok(None)
    } else {
        read_cstr(registry, "registry").map(Some)
    }
}

fn parse_bag_ref(bag_ref: *const c_char) -> Result<crate::BagRef, String> {
    let bag_ref = read_cstr(bag_ref, "bag_ref")?;
    bag_ref
        .parse()
        .map_err(|e| format!("invalid bag reference: {e}"))
}

struct CCallbackProgress {
    callback: extern "C" fn(*const c_char, *const c_char, *mut c_void),
    user_data: *mut c_void,
}

impl ProgressSink for CCallbackProgress {
    fn emit(&mut self, event: ProgressEvent) {
        let phase = match CString::new(event.phase) {
            Ok(v) => v,
            Err(_) => return,
        };
        let message = match CString::new(event.message) {
            Ok(v) => v,
            Err(_) => return,
        };
        (self.callback)(phase.as_ptr(), message.as_ptr(), self.user_data);
    }
}

fn do_pull_with_progress(
    bag: crate::BagRef,
    registry: Option<String>,
    progress_mode: i32,
    callback: MarinaProgressCallback,
    user_data: *mut c_void,
) -> *mut c_char {
    let mut marina = match Marina::load() {
        Ok(v) => v,
        Err(e) => {
            set_last_error(format!("failed to load marina: {e}"));
            return std::ptr::null_mut();
        }
    };

    let rt = match tokio::runtime::Runtime::new() {
        Ok(v) => v,
        Err(e) => {
            set_last_error(format!("failed to create tokio runtime: {e}"));
            return std::ptr::null_mut();
        }
    };

    let path = if let Some(cb) = callback {
        let mut sink = CCallbackProgress {
            callback: cb,
            user_data,
        };
        let mut progress = ProgressReporter::new(&mut sink);
        rt.block_on(marina.pull_exact_with_progress(&bag, registry.as_deref(), &mut progress))
    } else if progress_mode == MARINA_PROGRESS_MODE_STDOUT {
        let mut stdout = std::io::stdout();
        let mut sink = WriterProgress::new(&mut stdout);
        let mut progress = ProgressReporter::new(&mut sink);
        rt.block_on(marina.pull_exact_with_progress(&bag, registry.as_deref(), &mut progress))
    } else {
        rt.block_on(marina.pull_exact(&bag, registry.as_deref()))
    };

    match path {
        Ok(v) => cstring_from_string(v.display().to_string()),
        Err(e) => {
            set_last_error(format!("pull failed: {e}"));
            std::ptr::null_mut()
        }
    }
}

fn detailed_error(msg: String) -> MarinaResolveDetailed {
    set_last_error(msg.clone());
    MarinaResolveDetailed {
        kind: MARINA_RESOLVE_ERROR,
        path: std::ptr::null_mut(),
        bag: std::ptr::null_mut(),
        registry: std::ptr::null_mut(),
        message: cstring_from_string(msg),
    }
}

/// # Safety
/// `target` must be a valid, non-null, null-terminated C string.
/// `registry` must be a valid null-terminated C string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn marina_resolve_detailed(
    target: *const c_char,
    registry: *const c_char,
) -> MarinaResolveDetailed {
    clear_last_error();

    let target = match read_cstr(target, "target") {
        Ok(v) => v,
        Err(e) => return detailed_error(e),
    };

    let registry = match unsafe { parse_optional_cstr(registry, "registry") } {
        Ok(v) => v,
        Err(e) => return detailed_error(e),
    };

    let marina = match Marina::load() {
        Ok(v) => v,
        Err(e) => return detailed_error(format!("failed to load marina: {e}")),
    };

    let rt = match tokio::runtime::Runtime::new() {
        Ok(v) => v,
        Err(e) => return detailed_error(format!("failed to create tokio runtime: {e}")),
    };

    match rt.block_on(marina.resolve_target(&target, registry.as_deref())) {
        Ok(ResolveResult::LocalPath(p)) => MarinaResolveDetailed {
            kind: MARINA_RESOLVE_LOCAL,
            path: cstring_from_string(p.display().to_string()),
            bag: std::ptr::null_mut(),
            registry: std::ptr::null_mut(),
            message: cstring_from_string("local path resolved".to_string()),
        },
        Ok(ResolveResult::Cached(p)) => MarinaResolveDetailed {
            kind: MARINA_RESOLVE_CACHED,
            path: cstring_from_string(p.display().to_string()),
            bag: std::ptr::null_mut(),
            registry: std::ptr::null_mut(),
            message: cstring_from_string("cached path resolved".to_string()),
        },
        Ok(ResolveResult::RemoteAvailable { bag, registry, .. }) => MarinaResolveDetailed {
            kind: MARINA_RESOLVE_REMOTE_AVAILABLE,
            path: std::ptr::null_mut(),
            bag: cstring_from_string(bag.to_string()),
            registry: cstring_from_string(registry),
            message: cstring_from_string(
                "remote bag available; call marina_pull(...) to fetch".to_string(),
            ),
        },
        Ok(ResolveResult::Ambiguous { mut candidates }) => {
            candidates.sort_by(|a, b| a.0.cmp(&b.0));
            let (registry, bag) = candidates.remove(0);
            MarinaResolveDetailed {
                kind: MARINA_RESOLVE_AMBIGUOUS,
                path: std::ptr::null_mut(),
                bag: cstring_from_string(bag.to_string()),
                registry: cstring_from_string(registry),
                message: cstring_from_string(
                    "bag found in multiple registries; first registry selected".to_string(),
                ),
            }
        }
        Err(e) => detailed_error(format!("resolve failed: {e}")),
    }
}

/// # Safety
/// `result` must be a pointer obtained from `marina_resolve_detailed`, or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn marina_free_resolve_detailed(result: *mut MarinaResolveDetailed) {
    if result.is_null() {
        return;
    }
    // SAFETY: caller passes pointer to a struct obtained from marina_resolve_detailed.
    unsafe {
        marina_free_string((*result).path);
        marina_free_string((*result).bag);
        marina_free_string((*result).registry);
        marina_free_string((*result).message);
        (*result).path = std::ptr::null_mut();
        (*result).bag = std::ptr::null_mut();
        (*result).registry = std::ptr::null_mut();
        (*result).message = std::ptr::null_mut();
    }
}

/// # Safety
/// `target` must be a valid, non-null, null-terminated C string.
/// `registry` must be a valid null-terminated C string or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn marina_resolve(
    target: *const c_char,
    registry: *const c_char,
) -> *mut c_char {
    let mut detailed = unsafe { marina_resolve_detailed(target, registry) };
    let out = if detailed.kind == MARINA_RESOLVE_LOCAL || detailed.kind == MARINA_RESOLVE_CACHED {
        cstring_from_opt(Some(
            // SAFETY: pointer generated by this library.
            unsafe { CStr::from_ptr(detailed.path) }
                .to_string_lossy()
                .to_string(),
        ))
    } else if detailed.kind == MARINA_RESOLVE_REMOTE_AVAILABLE {
        let bag = if detailed.bag.is_null() {
            "<unknown>".to_string()
        } else {
            // SAFETY: pointer generated by this library.
            unsafe { CStr::from_ptr(detailed.bag) }
                .to_string_lossy()
                .to_string()
        };
        let registry = if detailed.registry.is_null() {
            "<unknown>".to_string()
        } else {
            // SAFETY: pointer generated by this library.
            unsafe { CStr::from_ptr(detailed.registry) }
                .to_string_lossy()
                .to_string()
        };
        cstring_from_string(format!("REMOTE:{}@{}", bag, registry))
    } else {
        std::ptr::null_mut()
    };
    // SAFETY: detailed was allocated by marina_resolve_detailed above.
    unsafe { marina_free_resolve_detailed(&mut detailed) };
    out
}

#[unsafe(no_mangle)]
pub extern "C" fn marina_pull(bag_ref: *const c_char, registry: *const c_char) -> *mut c_char {
    clear_last_error();

    let bag = match parse_bag_ref(bag_ref) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    let registry = match parse_registry(registry) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    do_pull_with_progress(
        bag,
        registry,
        MARINA_PROGRESS_MODE_SILENT,
        None,
        std::ptr::null_mut(),
    )
}

#[unsafe(no_mangle)]
pub extern "C" fn marina_pull_with_progress(
    bag_ref: *const c_char,
    registry: *const c_char,
    progress_mode: i32,
) -> *mut c_char {
    clear_last_error();

    let bag = match parse_bag_ref(bag_ref) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    let registry = match parse_registry(registry) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    do_pull_with_progress(bag, registry, progress_mode, None, std::ptr::null_mut())
}

#[unsafe(no_mangle)]
pub extern "C" fn marina_pull_with_callback(
    bag_ref: *const c_char,
    registry: *const c_char,
    callback: MarinaProgressCallback,
    user_data: *mut c_void,
) -> *mut c_char {
    clear_last_error();

    let bag = match parse_bag_ref(bag_ref) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    let registry = match parse_registry(registry) {
        Ok(v) => v,
        Err(e) => {
            set_last_error(e);
            return std::ptr::null_mut();
        }
    };

    do_pull_with_progress(
        bag,
        registry,
        MARINA_PROGRESS_MODE_SILENT,
        callback,
        user_data,
    )
}

#[unsafe(no_mangle)]
pub extern "C" fn marina_last_error_message() -> *mut c_char {
    LAST_ERROR.with(|slot| match &*slot.borrow() {
        Some(err) => match CString::new(err.to_bytes()) {
            Ok(copy) => copy.into_raw(),
            Err(_) => std::ptr::null_mut(),
        },
        None => std::ptr::null_mut(),
    })
}

/// # Safety
/// `ptr` must be a pointer obtained from a marina string-returning function, or null.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn marina_free_string(ptr: *mut c_char) {
    if ptr.is_null() {
        return;
    }
    // SAFETY: pointer must have been allocated by CString::into_raw in this library.
    unsafe {
        let _ = CString::from_raw(ptr);
    }
}