storelib_rs 0.1.10

Rust port of StoreLib - Microsoft Store API client
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
//! C-compatible FFI layer for `storelib_rs`.
//!
//! Enabled with `--features ffi` and excluded on `wasm32` targets.
//!
//! # Memory contract
//!
//! - Strings **returned** by the library (`char *`) are heap-allocated by
//!   Rust and **must** be released by the caller with [`storelib_free_string`].
//! - Strings **passed in** by the caller are borrowed for the duration of the
//!   call only; the caller retains ownership.
//! - The last-error string returned by [`storelib_last_error`] is owned by the
//!   handle and is valid until the next call on that handle or until the handle
//!   is freed — do **not** pass it to [`storelib_free_string`].

#![allow(clippy::missing_safety_doc)]

use std::ffi::{CStr, CString};
use std::os::raw::c_char;

use std::ffi::c_void;

use crate::cancellation::CancellationToken;
use crate::models::enums::{DeviceFamily, IdentifierType};
use crate::services::display_catalog::{DisplayCatalogHandler, ProgressEvent};

// ---------------------------------------------------------------------------
// Error codes (mirrored in the C header)
// ---------------------------------------------------------------------------

pub const STORELIB_OK: i32 = 0;
pub const STORELIB_ERR_NULL: i32 = -1;
pub const STORELIB_ERR_HTTP: i32 = -2;
pub const STORELIB_ERR_JSON: i32 = -3;
pub const STORELIB_ERR_XML: i32 = -4;
pub const STORELIB_ERR_NOT_FOUND: i32 = -5;
pub const STORELIB_ERR_TIMEOUT: i32 = -6;
pub const STORELIB_ERR_OTHER: i32 = -7;
pub const STORELIB_ERR_CANCELLED: i32 = -8;

fn err_code(e: &crate::error::StoreError) -> i32 {
    use crate::error::StoreError::*;
    match e {
        Http(_) => STORELIB_ERR_HTTP,
        Json(_) => STORELIB_ERR_JSON,
        Xml(_) => STORELIB_ERR_XML,
        NotFound => STORELIB_ERR_NOT_FOUND,
        TimedOut => STORELIB_ERR_TIMEOUT,
        Cancelled => STORELIB_ERR_CANCELLED,
        Other(_) => STORELIB_ERR_OTHER,
    }
}

// ---------------------------------------------------------------------------
// Opaque handle
// ---------------------------------------------------------------------------

pub struct StorelibHandle {
    handler: DisplayCatalogHandler,
    rt: tokio::runtime::Runtime,
    last_error: Option<CString>,
}

impl StorelibHandle {
    fn set_error(&mut self, msg: &str) {
        self.last_error = CString::new(msg).ok();
    }
    fn clear_error(&mut self) {
        self.last_error = None;
    }
}

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

/// Create a new handle configured for the production endpoint (US/en locale).
///
/// Returns `NULL` if the tokio runtime cannot be initialised.
/// Free with [`storelib_free`].
#[no_mangle]
pub extern "C" fn storelib_new() -> *mut StorelibHandle {
    let rt = match tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
    {
        Ok(r) => r,
        Err(_) => return std::ptr::null_mut(),
    };
    let handle = Box::new(StorelibHandle {
        handler: DisplayCatalogHandler::production(),
        rt,
        last_error: None,
    });
    Box::into_raw(handle)
}

/// Free a handle created with [`storelib_new`].
///
/// # Safety
/// `handle` must be a valid pointer returned by [`storelib_new`] that has not
/// already been freed.
#[no_mangle]
pub unsafe extern "C" fn storelib_free(handle: *mut StorelibHandle) {
    if !handle.is_null() {
        drop(Box::from_raw(handle));
    }
}

// ---------------------------------------------------------------------------
// Error retrieval
// ---------------------------------------------------------------------------

/// Return the last error message for `handle`, or `NULL` if there was none.
///
/// The returned pointer is valid until the next call on this handle or until
/// the handle is freed. **Do not** pass it to [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_last_error(handle: *const StorelibHandle) -> *const c_char {
    if handle.is_null() {
        return std::ptr::null();
    }
    match &(*handle).last_error {
        Some(s) => s.as_ptr(),
        None => std::ptr::null(),
    }
}

// ---------------------------------------------------------------------------
// Query
// ---------------------------------------------------------------------------

/// Query the DisplayCatalog for a product.
///
/// `id_type` is one of the `STORELIB_ID_*` constants.
/// `auth_token` may be `NULL` for unauthenticated queries.
///
/// Returns [`STORELIB_OK`] on success or a negative error code on failure.
/// Call [`storelib_is_found`] afterwards to check whether the product exists.
///
/// # Safety
/// `handle` and `id` must be valid non-null pointers; `auth_token` may be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_query(
    handle: *mut StorelibHandle,
    id: *const c_char,
    id_type: u32,
    auth_token: *const c_char,
) -> i32 {
    storelib_query_with_cancel(handle, id, id_type, auth_token, std::ptr::null())
}

/// Returns `1` if the last [`storelib_query`] found the product, `0` otherwise.
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_is_found(handle: *const StorelibHandle) -> i32 {
    if handle.is_null() {
        return 0;
    }
    if (*handle).handler.is_found {
        1
    } else {
        0
    }
}

// ---------------------------------------------------------------------------
// Product info
// ---------------------------------------------------------------------------

/// Return the product listing as a JSON string, or `NULL` if no product has
/// been queried yet.
///
/// The caller **must** free the returned string with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_product_json(handle: *const StorelibHandle) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    let listing = match &(*handle).handler.product_listing {
        Some(l) => l,
        None => return std::ptr::null_mut(),
    };
    match serde_json::to_string(listing) {
        Ok(json) => cstring_into_raw(json),
        Err(_) => std::ptr::null_mut(),
    }
}

// ---------------------------------------------------------------------------
// Typed accessors
// ---------------------------------------------------------------------------

/// Return the first product's title (UTF-8, NUL-terminated) or `NULL` if
/// the listing has no localized properties / no title.
///
/// The caller **must** free the returned string with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_product_title(handle: *const StorelibHandle) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match (*handle).handler.title() {
        Some(s) => cstring_into_raw(s.to_owned()),
        None => std::ptr::null_mut(),
    }
}

/// Return the first product's publisher name, or `NULL`.
/// Caller frees with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_product_publisher(handle: *const StorelibHandle) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match (*handle).handler.publisher_name() {
        Some(s) => cstring_into_raw(s.to_owned()),
        None => std::ptr::null_mut(),
    }
}

/// Return the first price as a JSON string
/// (`{currencyCode, isPIRequired, listPrice, msrp, ...}`), or `NULL` if
/// none is listed.
/// Caller frees with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_price_json(handle: *const StorelibHandle) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match (*handle).handler.price() {
        Some(price) => match serde_json::to_string(price) {
            Ok(json) => cstring_into_raw(json),
            Err(_) => std::ptr::null_mut(),
        },
        None => std::ptr::null_mut(),
    }
}

/// Return all `Package` entries from the first SKU as a JSON array, or
/// `NULL` if none are listed. Caller frees with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_packages_listed_json(
    handle: *const StorelibHandle,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match serde_json::to_string((*handle).handler.packages()) {
        Ok(json) => cstring_into_raw(json),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Return all `Availability` entries flattened across SKUs as a JSON array.
/// Returns `"[]"` (a valid empty JSON array) when none exist.
/// Caller frees with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_availabilities_json(
    handle: *const StorelibHandle,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match serde_json::to_string(&(*handle).handler.availabilities()) {
        Ok(json) => cstring_into_raw(json),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Return the `WuCategoryId` (used to drive FE3) from the first SKU's
/// fulfillment data, or `NULL`. Caller frees with [`storelib_free_string`].
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_wu_category_id(handle: *const StorelibHandle) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    match (*handle).handler.wu_category_id() {
        Some(s) => cstring_into_raw(s.to_owned()),
        None => std::ptr::null_mut(),
    }
}

// ---------------------------------------------------------------------------
// Batch query
// ---------------------------------------------------------------------------

/// Query the DisplayCatalog for many products in a single round-trip via
/// the `bigIds` parameter.
///
/// `ids` is an array of `id_count` NUL-terminated UTF-8 strings; each must
/// be a Microsoft Store Product ID (alternate identifiers are not supported
/// by the batch endpoint). Returns the response as a JSON array of products
/// (the same shape `storelib_product_json()` yields, but at the array level).
///
/// Returns `NULL` on error; inspect [`storelib_last_error`] for details.
/// Caller frees the returned string with [`storelib_free_string`].
///
/// # Safety
/// `handle` and `ids` must be valid non-null pointers; each `ids[i]` must
/// be a valid NUL-terminated UTF-8 string. `auth_token` may be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_query_batch_json(
    handle: *mut StorelibHandle,
    ids: *const *const c_char,
    id_count: usize,
    auth_token: *const c_char,
) -> *mut c_char {
    storelib_query_batch_json_with_cancel(handle, ids, id_count, auth_token, std::ptr::null())
}

/// Cancellable variant of [`storelib_query_batch_json`].
///
/// # Safety
/// Same as [`storelib_query_batch_json`]; `cancel` may be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_query_batch_json_with_cancel(
    handle: *mut StorelibHandle,
    ids: *const *const c_char,
    id_count: usize,
    auth_token: *const c_char,
    cancel: *const StorelibCancellation,
) -> *mut c_char {
    if handle.is_null() || ids.is_null() || id_count == 0 {
        return std::ptr::null_mut();
    }
    let h = &mut *handle;
    h.clear_error();

    // Collect owned Strings so the &str refs we hand to the inner call have
    // a stable backing store for the whole call.
    let mut owned: Vec<String> = Vec::with_capacity(id_count);
    for i in 0..id_count {
        let ptr = *ids.add(i);
        if ptr.is_null() {
            h.set_error("ids[i] is null");
            return std::ptr::null_mut();
        }
        match CStr::from_ptr(ptr).to_str() {
            Ok(s) => owned.push(s.to_owned()),
            Err(_) => {
                h.set_error("ids[i] is not valid UTF-8");
                return std::ptr::null_mut();
            }
        }
    }
    let id_refs: Vec<&str> = owned.iter().map(String::as_str).collect();

    let token = match cstr_opt_to_str(auth_token, h, "auth_token") {
        Ok(t) => t,
        Err(()) => return std::ptr::null_mut(),
    };
    let cancel_ref = cancel_token_ref(cancel);

    match h.rt.block_on(
        h.handler
            .query_dcat_batch_with_cancel(&id_refs, token, cancel_ref),
    ) {
        Ok(()) => match serde_json::to_string(h.handler.products()) {
            Ok(json) => cstring_into_raw(json),
            Err(e) => {
                h.set_error(&e.to_string());
                std::ptr::null_mut()
            }
        },
        Err(e) => {
            h.set_error(&e.to_string());
            std::ptr::null_mut()
        }
    }
}

// ---------------------------------------------------------------------------
// Packages
// ---------------------------------------------------------------------------

/// Resolve and return the package list as a JSON array.
///
/// `msa_token` may be `NULL`.  The caller **must** free the returned string
/// with [`storelib_free_string`].
///
/// Returns `NULL` on error; inspect [`storelib_last_error`] for details.
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_packages_json(
    handle: *mut StorelibHandle,
    msa_token: *const c_char,
) -> *mut c_char {
    storelib_packages_json_with_cancel(handle, msa_token, std::ptr::null())
}

// ---------------------------------------------------------------------------
// Search
// ---------------------------------------------------------------------------

/// Search the catalog and return the results as a JSON string.
///
/// `family` is one of the `STORELIB_FAMILY_*` constants.
/// The caller **must** free the returned string with [`storelib_free_string`].
///
/// Returns `NULL` on error; inspect [`storelib_last_error`] for details.
///
/// # Safety
/// `handle` and `query` must be valid non-null pointers.
#[no_mangle]
pub unsafe extern "C" fn storelib_search_json(
    handle: *mut StorelibHandle,
    query: *const c_char,
    family: u32,
) -> *mut c_char {
    storelib_search_json_with_cancel(handle, query, family, std::ptr::null())
}

// ---------------------------------------------------------------------------
// Progress callback
// ---------------------------------------------------------------------------

/// C-compatible progress callback signature.
///
/// Fired during `storelib_query`, `storelib_packages_json`, and
/// `storelib_search_json` at each phase boundary. `stage` and `message` are
/// NUL-terminated UTF-8, valid only for the duration of the call. `has_current`
/// and `has_total` are `1` when `current`/`total` carry a meaningful counter
/// (e.g. "5 of 12 packages") and `0` otherwise. `user_data` is the opaque
/// pointer passed to [`storelib_set_progress_callback`].
pub type StorelibProgressCallback = extern "C" fn(
    stage: *const c_char,
    message: *const c_char,
    has_current: i32,
    current: u32,
    has_total: i32,
    total: u32,
    user_data: *mut c_void,
);

/// Install a progress callback. Pass `NULL` as `callback` to detach.
///
/// `user_data` is opaque and is passed back to the callback on every event;
/// it may be `NULL`. The callback is invoked from the Tokio runtime worker
/// thread that drives the active async call, so it must be thread-safe.
///
/// # Safety
/// `handle` must be a valid non-null pointer; `callback` must outlive any
/// pending in-flight `storelib_*` call on this handle.
#[no_mangle]
pub unsafe extern "C" fn storelib_set_progress_callback(
    handle: *mut StorelibHandle,
    callback: Option<StorelibProgressCallback>,
    user_data: *mut c_void,
) -> i32 {
    if handle.is_null() {
        return STORELIB_ERR_NULL;
    }
    let h = &mut *handle;
    match callback {
        Some(cb) => {
            // Carry user_data across the Send boundary as an integer; the
            // closure casts it back to *mut c_void on entry. Function pointers
            // are already Send + Sync.
            let user_data_addr = user_data as usize;
            h.handler.progress.set(Box::new(move |e: ProgressEvent| {
                let stage = CString::new(e.stage).unwrap_or_default();
                let message = CString::new(e.message).unwrap_or_default();
                let (has_c, cur) = match e.current {
                    Some(v) => (1, v),
                    None => (0, 0),
                };
                let (has_t, tot) = match e.total {
                    Some(v) => (1, v),
                    None => (0, 0),
                };
                (cb)(
                    stage.as_ptr(),
                    message.as_ptr(),
                    has_c,
                    cur,
                    has_t,
                    tot,
                    user_data_addr as *mut c_void,
                );
            }));
        }
        None => h.handler.progress.clear(),
    }
    STORELIB_OK
}

/// Detach the progress callback (equivalent to passing `NULL` to
/// [`storelib_set_progress_callback`]).
///
/// # Safety
/// `handle` must be a valid non-null pointer.
#[no_mangle]
pub unsafe extern "C" fn storelib_clear_progress_callback(handle: *mut StorelibHandle) -> i32 {
    if handle.is_null() {
        return STORELIB_ERR_NULL;
    }
    (*handle).handler.progress.clear();
    STORELIB_OK
}

// ---------------------------------------------------------------------------
// Cancellation
// ---------------------------------------------------------------------------

/// Opaque cancellation handle. Create with [`storelib_cancellation_new`], pass
/// to any `storelib_*_with_cancel` function, and signal cancellation from any
/// thread with [`storelib_cancellation_cancel`]. Free with
/// [`storelib_cancellation_free`].
pub struct StorelibCancellation {
    token: CancellationToken,
}

/// Allocate a fresh, uncancelled cancellation token. Returns `NULL` only on
/// allocation failure (extremely unlikely). Free with
/// [`storelib_cancellation_free`].
#[no_mangle]
pub extern "C" fn storelib_cancellation_new() -> *mut StorelibCancellation {
    Box::into_raw(Box::new(StorelibCancellation {
        token: CancellationToken::new(),
    }))
}

/// Signal cancellation. Safe to call from any thread (including a thread
/// other than the one running an in-flight `storelib_*_with_cancel` call).
/// Idempotent — subsequent calls are no-ops.
///
/// # Safety
/// `token` must be a valid pointer returned by [`storelib_cancellation_new`]
/// that has not been freed. Passing `NULL` is a safe no-op.
#[no_mangle]
pub unsafe extern "C" fn storelib_cancellation_cancel(token: *const StorelibCancellation) {
    if !token.is_null() {
        (*token).token.cancel();
    }
}

/// Returns `1` if the token has been cancelled, `0` otherwise (or if `token`
/// is `NULL`).
///
/// # Safety
/// `token` must be a valid pointer or `NULL`.
#[no_mangle]
pub unsafe extern "C" fn storelib_cancellation_is_cancelled(
    token: *const StorelibCancellation,
) -> i32 {
    if token.is_null() {
        return 0;
    }
    if (*token).token.is_cancelled() {
        1
    } else {
        0
    }
}

/// Free a cancellation token. After this call the pointer is invalid.
///
/// # Safety
/// `token` must be a pointer returned by [`storelib_cancellation_new`] that
/// has not already been freed. Passing `NULL` is a safe no-op.
#[no_mangle]
pub unsafe extern "C" fn storelib_cancellation_free(token: *mut StorelibCancellation) {
    if !token.is_null() {
        drop(Box::from_raw(token));
    }
}

/// Like [`storelib_query`] but races against a cancellation token. Pass `NULL`
/// for `cancel` to disable cancellation (equivalent to `storelib_query`).
/// On cancellation the call returns [`STORELIB_ERR_CANCELLED`] and the
/// underlying HTTP request is dropped.
///
/// # Safety
/// `handle` and `id` must be valid non-null pointers; `auth_token` and
/// `cancel` may be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_query_with_cancel(
    handle: *mut StorelibHandle,
    id: *const c_char,
    id_type: u32,
    auth_token: *const c_char,
    cancel: *const StorelibCancellation,
) -> i32 {
    if handle.is_null() || id.is_null() {
        return STORELIB_ERR_NULL;
    }
    let h = &mut *handle;
    h.clear_error();

    let id_str = match cstr_required_to_str(id, h, "id") {
        Ok(s) => s,
        Err(()) => return STORELIB_ERR_NULL,
    };
    let token = match cstr_opt_to_str(auth_token, h, "auth_token") {
        Ok(t) => t,
        Err(()) => return STORELIB_ERR_NULL,
    };
    let id_enum = id_type_from_u32(id_type);
    let cancel_ref = cancel_token_ref(cancel);

    match h.rt.block_on(
        h.handler
            .query_dcat_with_cancel(id_str, id_enum, token, cancel_ref),
    ) {
        Ok(_) => STORELIB_OK,
        Err(e) => {
            let code = err_code(&e);
            h.set_error(&e.to_string());
            code
        }
    }
}

/// Like [`storelib_packages_json`] but races against a cancellation token.
/// Pass `NULL` for `cancel` to disable cancellation. Returns `NULL` on error
/// or cancellation; inspect [`storelib_last_error`] for details.
///
/// # Safety
/// `handle` must be a valid non-null pointer; `msa_token` and `cancel` may
/// be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_packages_json_with_cancel(
    handle: *mut StorelibHandle,
    msa_token: *const c_char,
    cancel: *const StorelibCancellation,
) -> *mut c_char {
    if handle.is_null() {
        return std::ptr::null_mut();
    }
    let h = &mut *handle;
    h.clear_error();

    let token = match cstr_opt_to_str(msa_token, h, "msa_token") {
        Ok(t) => t,
        Err(()) => return std::ptr::null_mut(),
    };
    let cancel_ref = cancel_token_ref(cancel);

    match h.rt.block_on(
        h.handler
            .get_packages_for_product_with_cancel(token, cancel_ref),
    ) {
        Ok(pkgs) => json_result_to_cstr(&pkgs, h),
        Err(e) => {
            h.set_error(&e.to_string());
            std::ptr::null_mut()
        }
    }
}

/// Like [`storelib_search_json`] but races against a cancellation token.
/// Pass `NULL` for `cancel` to disable cancellation. Returns `NULL` on error
/// or cancellation; inspect [`storelib_last_error`] for details.
///
/// # Safety
/// `handle` and `query` must be valid non-null pointers; `cancel` may be null.
#[no_mangle]
pub unsafe extern "C" fn storelib_search_json_with_cancel(
    handle: *mut StorelibHandle,
    query: *const c_char,
    family: u32,
    cancel: *const StorelibCancellation,
) -> *mut c_char {
    if handle.is_null() || query.is_null() {
        return std::ptr::null_mut();
    }
    let h = &mut *handle;
    h.clear_error();

    let query_str = match cstr_required_to_str(query, h, "query") {
        Ok(s) => s,
        Err(()) => return std::ptr::null_mut(),
    };
    let fam = family_from_u32(family);
    let cancel_ref = cancel_token_ref(cancel);

    match h.rt.block_on(
        h.handler
            .search_dcat_with_cancel(query_str, fam, cancel_ref),
    ) {
        Ok(results) => json_result_to_cstr(&results, h),
        Err(e) => {
            h.set_error(&e.to_string());
            std::ptr::null_mut()
        }
    }
}

// ---------------------------------------------------------------------------
// String management
// ---------------------------------------------------------------------------

/// Free a string that was returned by this library.
///
/// Passing a string **not** allocated by this library is undefined behaviour.
/// Passing `NULL` is safe (no-op).
///
/// # Safety
/// `s` must be a pointer previously returned by a `storelib_*` function, or
/// `NULL`.
#[no_mangle]
pub unsafe extern "C" fn storelib_free_string(s: *mut c_char) {
    if !s.is_null() {
        drop(CString::from_raw(s));
    }
}

// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------

fn cstring_into_raw(s: String) -> *mut c_char {
    match CString::new(s) {
        Ok(cs) => cs.into_raw(),
        Err(_) => std::ptr::null_mut(),
    }
}

/// Convert a possibly-null `*const c_char` into `Option<&str>`. On invalid
/// UTF-8 records an error on `h` and returns `Err(())`; the caller should
/// short-circuit to a `null_mut()` or `STORELIB_ERR_*` return.
unsafe fn cstr_opt_to_str<'a>(
    ptr: *const c_char,
    h: &mut StorelibHandle,
    name: &str,
) -> Result<Option<&'a str>, ()> {
    if ptr.is_null() {
        return Ok(None);
    }
    match CStr::from_ptr(ptr).to_str() {
        Ok(s) => Ok(Some(s)),
        Err(_) => {
            h.set_error(&format!("{name} is not valid UTF-8"));
            Err(())
        }
    }
}

/// Like [`cstr_opt_to_str`] but the input is required; null is treated as
/// invalid UTF-8 (callers should null-check before calling).
unsafe fn cstr_required_to_str<'a>(
    ptr: *const c_char,
    h: &mut StorelibHandle,
    name: &str,
) -> Result<&'a str, ()> {
    match CStr::from_ptr(ptr).to_str() {
        Ok(s) => Ok(s),
        Err(_) => {
            h.set_error(&format!("{name} is not valid UTF-8"));
            Err(())
        }
    }
}

/// Translate a `*const StorelibCancellation` into the borrowed token form
/// the Rust-side `_with_cancel` methods expect.
unsafe fn cancel_token_ref<'a>(
    cancel: *const StorelibCancellation,
) -> Option<&'a CancellationToken> {
    if cancel.is_null() {
        None
    } else {
        Some(&(*cancel).token)
    }
}

/// Serialize `value` to JSON and convert it to a heap-allocated C string.
/// On serialization failure records the error on `h` and returns null.
fn json_result_to_cstr<T: serde::Serialize + ?Sized>(
    value: &T,
    h: &mut StorelibHandle,
) -> *mut c_char {
    match serde_json::to_string(value) {
        Ok(json) => cstring_into_raw(json),
        Err(e) => {
            h.set_error(&e.to_string());
            std::ptr::null_mut()
        }
    }
}

fn id_type_from_u32(v: u32) -> IdentifierType {
    match v {
        1 => IdentifierType::XboxTitleId,
        2 => IdentifierType::PackageFamilyName,
        3 => IdentifierType::ContentId,
        4 => IdentifierType::LegacyWindowsPhoneProductId,
        5 => IdentifierType::LegacyWindowsStoreProductId,
        6 => IdentifierType::LegacyXboxProductId,
        _ => IdentifierType::ProductId,
    }
}

fn family_from_u32(v: u32) -> DeviceFamily {
    match v {
        1 => DeviceFamily::Mobile,
        2 => DeviceFamily::Xbox,
        3 => DeviceFamily::ServerCore,
        4 => DeviceFamily::IotCore,
        5 => DeviceFamily::HoloLens,
        6 => DeviceFamily::Andromeda,
        7 => DeviceFamily::Universal,
        8 => DeviceFamily::Wcos,
        _ => DeviceFamily::Desktop,
    }
}