Skip to main content

storekit/
async_api.rs

1//! Async API for `StoreKit` — Tier 1 Future wrappers.
2//!
3//! This module requires the **`async`** Cargo feature:
4//! ```toml
5//! storekit-rs = { version = "0.5", features = ["async"] }
6//! ```
7//!
8//! Every public type is an executor-agnostic [`Future`] backed by a
9//! `doom_fish_utils` completion handler.  The futures work with any async
10//! runtime (`tokio`, `async-std`, `smol`, `pollster`, …).
11//!
12//! ## Available types
13//!
14//! | Type | Description |
15//! |------|-------------|
16//! | [`AsyncProducts`] | Fetch products by identifier |
17//! | [`AsyncPurchase`] | Purchase a product |
18//! | [`AsyncAppStore`] | Request review / manage subscriptions |
19//! | [`AsyncAppTransaction`] | Fetch the app transaction |
20//! | [`AsyncStorefront`] | Fetch the current storefront |
21//!
22//! ## `AsyncSequence` APIs — deferred to Tier 2
23//!
24//! The following `StoreKit` APIs expose `AsyncSequence` (multi-fire streams).
25//! They are intentionally **not** included here; they will be wrapped as
26//! `Stream` types in the Tier 2 rollout:
27//!
28//! - `Transaction.updates` — use [`crate::transaction::TransactionStream`] in the meantime
29//! - `Transaction.currentEntitlements` — use [`crate::transaction::TransactionStream`]
30//! - `Transaction.unfinished` — use [`crate::transaction::TransactionStream`]
31//!
32//! ## Examples
33//!
34//! ```rust,no_run
35//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
36//! # pollster::block_on(async {
37//! use storekit::async_api::{AsyncProducts, AsyncAppTransaction};
38//!
39//! let products = AsyncProducts::fetch(["com.example.pro"])?.await?;
40//! println!("{} product(s) found", products.len());
41//!
42//! let app_tx = AsyncAppTransaction::shared().await?;
43//! println!("bundle: {}", app_tx.payload_value()?.bundle_id);
44//! # Ok::<(), Box<dyn std::error::Error>>(())
45//! # })?;
46//! # Ok(())
47//! # }
48//! ```
49
50use std::ffi::{c_char, c_void, CStr};
51use std::future::Future;
52use std::pin::Pin;
53use std::task::{Context, Poll};
54
55use doom_fish_utils::completion::{AsyncCompletion, AsyncCompletionFuture};
56use doom_fish_utils::panic_safe::catch_user_panic;
57
58use crate::advanced_commerce::{
59    AppStoreMerchandisingKind, AppStoreMerchandisingPresentationResult,
60    AppStoreMerchandisingPresentationResultPayload,
61};
62use crate::app_transaction::{AppTransaction, AppTransactionPayload};
63use crate::error::{from_status_message, StoreKitError};
64use crate::ffi;
65use crate::private::{cstring_from_str, json_cstring, parse_json_str};
66use crate::product::{Product, ProductPayload};
67use crate::purchase_option::{PurchaseOption, PurchaseResult, PurchaseResultPayload};
68use crate::storefront::{Storefront, StorefrontPayload};
69use crate::transaction::TransactionHandle;
70use crate::verification_result::{VerificationResult, VerificationResultPayload};
71use crate::window::NSWindowHandle;
72
73// ============================================================================
74// Internal helpers
75// ============================================================================
76
77struct BridgeReply {
78    status: i32,
79    json: Option<String>,
80    transaction: Option<TransactionHandle>,
81    error: Option<String>,
82}
83
84unsafe fn copy_c_str(ptr: *const c_char) -> Option<String> {
85    if ptr.is_null() {
86        None
87    } else {
88        Some(
89            unsafe { CStr::from_ptr(ptr) }
90                .to_string_lossy()
91                .into_owned(),
92        )
93    }
94}
95
96unsafe extern "C" fn bridge_callback(
97    ctx: *mut c_void,
98    status: i32,
99    json: *const c_char,
100    transaction: *mut c_void,
101    error: *const c_char,
102) {
103    let transaction = unsafe { TransactionHandle::from_raw(transaction) };
104    catch_user_panic("storekit async callback", || {
105        let reply = BridgeReply {
106            status,
107            json: unsafe { copy_c_str(json) },
108            transaction,
109            error: unsafe { copy_c_str(error) },
110        };
111        unsafe { AsyncCompletion::complete_ok(ctx, reply) };
112    });
113}
114
115type BridgeSuccess = (Option<String>, Option<TransactionHandle>);
116
117fn reply_result(reply: Result<BridgeReply, String>) -> Result<BridgeSuccess, StoreKitError> {
118    let reply = reply.map_err(StoreKitError::Unknown)?;
119    if reply.status == ffi::status::OK {
120        Ok((reply.json, reply.transaction))
121    } else {
122        Err(from_status_message(reply.status, reply.error))
123    }
124}
125
126fn reply_json(json: Option<String>, context: &str) -> Result<String, StoreKitError> {
127    json.ok_or_else(|| {
128        StoreKitError::InvalidArgument(format!("missing JSON payload for {context}"))
129    })
130}
131
132// ============================================================================
133// AsyncProducts — Product.products(for:) async throws -> [Product]
134// ============================================================================
135
136/// Future for [`AsyncProducts::fetch`].
137pub struct ProductsFuture {
138    inner: AsyncCompletionFuture<BridgeReply>,
139}
140
141impl std::fmt::Debug for ProductsFuture {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.debug_struct("ProductsFuture").finish_non_exhaustive()
144    }
145}
146
147impl Future for ProductsFuture {
148    type Output = Result<Vec<Product>, StoreKitError>;
149
150    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
151        Pin::new(&mut self.inner).poll(cx).map(|reply| {
152            let (json, _) = reply_result(reply)?;
153            let payloads: Vec<ProductPayload> =
154                parse_json_str(&reply_json(json, "products")?, "products")?;
155            payloads
156                .into_iter()
157                .map(ProductPayload::into_product)
158                .collect()
159        })
160    }
161}
162
163/// Async wrapper for `Product.products(for:)`.
164///
165/// Fetches products from the App Store for a set of product identifiers.
166///
167/// # Notes
168///
169/// On macOS Sandbox / Xcode previews you must configure a `StoreKit
170/// Configuration File` in your scheme for products to be returned.
171#[derive(Debug, Clone, Copy)]
172pub struct AsyncProducts;
173
174impl AsyncProducts {
175    /// Asynchronously fetch products for the given identifiers.
176    ///
177    /// Equivalent to `Product.products(for: identifiers)` in Swift.
178    ///
179    /// # Errors
180    ///
181    /// Returns an error if the App Store request fails or the product
182    /// identifiers cannot be encoded.
183    pub fn fetch<I, S>(identifiers: I) -> Result<ProductsFuture, StoreKitError>
184    where
185        I: IntoIterator<Item = S>,
186        S: AsRef<str>,
187    {
188        let ids: Vec<String> = identifiers
189            .into_iter()
190            .map(|s| s.as_ref().to_owned())
191            .collect();
192        let ids_json = json_cstring(&ids, "product identifiers")?;
193        let (future, ctx) = AsyncCompletion::create();
194        unsafe { ffi::sk_products_async(ids_json.as_ptr(), bridge_callback, ctx) }
195        Ok(ProductsFuture { inner: future })
196    }
197}
198
199// ============================================================================
200// AsyncPurchase — Product.purchase(options:) async throws -> Product.PurchaseResult
201// ============================================================================
202
203/// Future for [`AsyncPurchase::buy`].
204pub struct PurchaseFuture {
205    inner: AsyncCompletionFuture<BridgeReply>,
206}
207
208impl std::fmt::Debug for PurchaseFuture {
209    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210        f.debug_struct("PurchaseFuture").finish_non_exhaustive()
211    }
212}
213
214impl Future for PurchaseFuture {
215    type Output = Result<PurchaseResult, StoreKitError>;
216
217    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
218        Pin::new(&mut self.inner).poll(cx).map(|reply| {
219            let (json, transaction) = reply_result(reply)?;
220            parse_json_str::<PurchaseResultPayload>(
221                &reply_json(json, "purchase result")?,
222                "purchase result",
223            )?
224            .into_purchase_result(transaction)
225        })
226    }
227}
228
229/// Async wrapper for `Product.purchase(options:)`.
230///
231/// Initiates an in-app purchase and resolves to the `PurchaseResult`.
232/// The purchase sheet is shown on the **main actor** (equivalent to Swift's
233/// `@MainActor`).
234///
235/// # Notes
236///
237/// - The future must be awaited until completion; cancellation is not
238///   supported by the `StoreKit` 2 purchase API.
239/// - `Transaction.currentEntitlements` and `Transaction.updates`
240///   (multi-fire streams) are deferred to Tier 2.
241#[derive(Debug, Clone, Copy)]
242pub struct AsyncPurchase;
243
244impl AsyncPurchase {
245    /// Asynchronously purchase a product.
246    ///
247    /// Equivalent to `product.purchase(options:)` in Swift.
248    ///
249    /// # Errors
250    ///
251    /// Returns an error if the product cannot be found, the purchase fails,
252    /// or the options cannot be encoded.
253    pub fn buy(
254        product_id: &str,
255        options: &[PurchaseOption],
256    ) -> Result<PurchaseFuture, StoreKitError> {
257        let id = cstring_from_str(product_id, "product id")?;
258        let opts = json_cstring(options, "purchase options")?;
259        let (future, ctx) = AsyncCompletion::create();
260        unsafe { ffi::sk_product_purchase_async(id.as_ptr(), opts.as_ptr(), bridge_callback, ctx) }
261        Ok(PurchaseFuture { inner: future })
262    }
263
264    pub fn buy_in_window(
265        product_id: &str,
266        window: &NSWindowHandle,
267        options: &[PurchaseOption],
268    ) -> Result<PurchaseFuture, StoreKitError> {
269        let id = cstring_from_str(product_id, "product id")?;
270        let opts = json_cstring(options, "purchase options")?;
271        let (future, ctx) = AsyncCompletion::create();
272        unsafe {
273            ffi::sk_product_purchase_in_window_async(
274                id.as_ptr(),
275                window.as_raw(),
276                opts.as_ptr(),
277                bridge_callback,
278                ctx,
279            );
280        }
281        Ok(PurchaseFuture { inner: future })
282    }
283}
284
285// ============================================================================
286// AsyncAppStore — AppStore.requestReview() / showManageSubscriptions()
287// ============================================================================
288
289/// Future for [`AsyncAppStore::request_review`].
290pub struct RequestReviewFuture {
291    inner: AsyncCompletionFuture<BridgeReply>,
292}
293
294impl std::fmt::Debug for RequestReviewFuture {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        f.debug_struct("RequestReviewFuture")
297            .finish_non_exhaustive()
298    }
299}
300
301impl Future for RequestReviewFuture {
302    type Output = Result<(), StoreKitError>;
303
304    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
305        Pin::new(&mut self.inner)
306            .poll(cx)
307            .map(|reply| reply_result(reply).map(|_| ()))
308    }
309}
310
311/// Future for [`AsyncAppStore::show_manage_subscriptions`].
312pub struct ShowManageSubscriptionsFuture {
313    inner: AsyncCompletionFuture<BridgeReply>,
314}
315
316impl std::fmt::Debug for ShowManageSubscriptionsFuture {
317    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318        f.debug_struct("ShowManageSubscriptionsFuture")
319            .finish_non_exhaustive()
320    }
321}
322
323impl Future for ShowManageSubscriptionsFuture {
324    type Output = Result<(), StoreKitError>;
325
326    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
327        Pin::new(&mut self.inner)
328            .poll(cx)
329            .map(|reply| reply_result(reply).map(|_| ()))
330    }
331}
332
333pub struct PresentMerchandisingFuture {
334    inner: AsyncCompletionFuture<BridgeReply>,
335}
336
337impl std::fmt::Debug for PresentMerchandisingFuture {
338    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339        f.debug_struct("PresentMerchandisingFuture")
340            .finish_non_exhaustive()
341    }
342}
343
344impl Future for PresentMerchandisingFuture {
345    type Output = Result<AppStoreMerchandisingPresentationResult, StoreKitError>;
346
347    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
348        Pin::new(&mut self.inner).poll(cx).map(|reply| {
349            let (json, transaction) = reply_result(reply)?;
350            parse_json_str::<AppStoreMerchandisingPresentationResultPayload>(
351                &reply_json(json, "App Store merchandising presentation result")?,
352                "App Store merchandising presentation result",
353            )?
354            .into_result(transaction)
355        })
356    }
357}
358
359/// Async wrapper for `AppStore` UI APIs.
360///
361/// # Notes
362///
363/// - [`AsyncAppStore::request_review`] requires macOS 13.0+ and an
364///   `NSViewController`-backed window.
365/// - [`AsyncAppStore::show_manage_subscriptions`] is scene-based (`SwiftUI`)
366///   and always returns a `NotSupported` error on macOS.  Consider opening
367///   the `itms-apps://` URL directly for `AppKit` apps.
368#[derive(Debug, Clone, Copy, Default)]
369pub struct AsyncAppStore;
370
371impl AsyncAppStore {
372    /// Asynchronously prompt the user for an App Store review.
373    ///
374    /// Equivalent to `AppStore.requestReview(in:)` in Swift.
375    ///
376    /// # Errors
377    ///
378    /// Returns a `NotSupported` error when:
379    /// - Running on macOS < 13.0.
380    /// - No `NSViewController`-backed key window is available.
381    #[must_use = "futures do nothing unless polled"]
382    pub fn request_review() -> RequestReviewFuture {
383        let (future, ctx) = AsyncCompletion::create();
384        unsafe { ffi::sk_app_store_request_review_async(bridge_callback, ctx) }
385        RequestReviewFuture { inner: future }
386    }
387
388    /// Asynchronously show the "Manage Subscriptions" sheet.
389    ///
390    /// Equivalent to `AppStore.showManageSubscriptions(in:)` in Swift.
391    ///
392    /// # Errors
393    ///
394    /// Always returns a `NotSupported` error on macOS because
395    /// `showManageSubscriptions(in:)` is scene-based and unavailable in
396    /// the macOS `StoreKit` SDK.
397    #[must_use = "futures do nothing unless polled"]
398    pub fn show_manage_subscriptions() -> ShowManageSubscriptionsFuture {
399        let (future, ctx) = AsyncCompletion::create();
400        unsafe { ffi::sk_app_store_show_manage_subscriptions_async(bridge_callback, ctx) }
401        ShowManageSubscriptionsFuture { inner: future }
402    }
403
404    pub fn present_merchandising(
405        kind: &AppStoreMerchandisingKind,
406        window: &NSWindowHandle,
407    ) -> Result<PresentMerchandisingFuture, StoreKitError> {
408        let kind_json = json_cstring(kind, "App Store merchandising kind")?;
409        let (future, ctx) = AsyncCompletion::create();
410        unsafe {
411            ffi::sk_app_store_present_merchandising_async(
412                kind_json.as_ptr(),
413                window.as_raw(),
414                bridge_callback,
415                ctx,
416            );
417        }
418        Ok(PresentMerchandisingFuture { inner: future })
419    }
420}
421
422// ============================================================================
423// AsyncAppTransaction — AppTransaction.shared async throws
424// ============================================================================
425
426/// Future for [`AsyncAppTransaction::shared`].
427pub struct AppTransactionFuture {
428    inner: AsyncCompletionFuture<BridgeReply>,
429}
430
431impl std::fmt::Debug for AppTransactionFuture {
432    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
433        f.debug_struct("AppTransactionFuture")
434            .finish_non_exhaustive()
435    }
436}
437
438impl Future for AppTransactionFuture {
439    type Output = Result<VerificationResult<AppTransaction>, StoreKitError>;
440
441    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
442        Pin::new(&mut self.inner).poll(cx).map(|reply| {
443            let (json, _) = reply_result(reply)?;
444            parse_json_str::<VerificationResultPayload<AppTransactionPayload>>(
445                &reply_json(json, "app transaction")?,
446                "app transaction",
447            )?
448            .into_result(AppTransactionPayload::into_app_transaction)
449        })
450    }
451}
452
453/// Async wrapper for `AppTransaction.shared`.
454///
455/// Returns a `VerificationResult<AppTransaction>`; use
456/// [`VerificationResult::payload_value`] to read the app transaction only
457/// after `StoreKit` has verified it.
458///
459/// Requires macOS 13.0+.
460///
461/// # Notes
462///
463/// `AppTransaction.shared` may prompt the user to authenticate with the
464/// App Store, so it should be awaited before presenting any gated content.
465#[derive(Debug, Clone, Copy)]
466pub struct AsyncAppTransaction;
467
468impl AsyncAppTransaction {
469    /// Asynchronously fetch `AppTransaction.shared`.
470    ///
471    /// Equivalent to `AppTransaction.shared` in Swift.
472    ///
473    /// # Errors
474    ///
475    /// Returns a `NotSupported` error on macOS < 13.0.
476    #[must_use = "futures do nothing unless polled"]
477    pub fn shared() -> AppTransactionFuture {
478        let (future, ctx) = AsyncCompletion::create();
479        unsafe { ffi::sk_app_transaction_shared_async(bridge_callback, ctx) }
480        AppTransactionFuture { inner: future }
481    }
482}
483
484// ============================================================================
485// AsyncStorefront — Storefront.current async
486// ============================================================================
487
488/// JSON envelope emitted by `sk_storefront_current_async`.
489#[derive(serde::Deserialize)]
490struct StorefrontCurrentPayload {
491    storefront: Option<StorefrontPayload>,
492}
493
494/// Future for [`AsyncStorefront::current`].
495pub struct StorefrontCurrentFuture {
496    inner: AsyncCompletionFuture<BridgeReply>,
497}
498
499impl std::fmt::Debug for StorefrontCurrentFuture {
500    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
501        f.debug_struct("StorefrontCurrentFuture")
502            .finish_non_exhaustive()
503    }
504}
505
506impl Future for StorefrontCurrentFuture {
507    type Output = Result<Option<Storefront>, StoreKitError>;
508
509    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
510        Pin::new(&mut self.inner).poll(cx).map(|reply| {
511            let (json, _) = reply_result(reply)?;
512            let wrapper: StorefrontCurrentPayload =
513                parse_json_str(&reply_json(json, "storefront")?, "storefront")?;
514            Ok(wrapper.storefront.map(StorefrontPayload::into_storefront))
515        })
516    }
517}
518
519/// Async wrapper for `Storefront.current`.
520///
521/// Returns the current App Store storefront, or `None` if no storefront is
522/// available (e.g. the device is not connected to the App Store).
523#[derive(Debug, Clone, Copy)]
524pub struct AsyncStorefront;
525
526impl AsyncStorefront {
527    /// Asynchronously fetch `Storefront.current`.
528    ///
529    /// Equivalent to `Storefront.current` in Swift.
530    #[must_use = "futures do nothing unless polled"]
531    pub fn current() -> StorefrontCurrentFuture {
532        let (future, ctx) = AsyncCompletion::create();
533        unsafe { ffi::sk_storefront_current_async(bridge_callback, ctx) }
534        StorefrontCurrentFuture { inner: future }
535    }
536}
537
538#[cfg(test)]
539mod tests {
540    use std::ffi::CString;
541    use std::ptr;
542
543    use super::{
544        bridge_callback, AsyncCompletion, PurchaseFuture, RequestReviewFuture,
545        StorefrontCurrentFuture,
546    };
547    use crate::error::{ProductPurchaseErrorCode, StoreKitError, VerificationErrorCode};
548    use crate::ffi::status;
549
550    fn fire(ctx: *mut std::ffi::c_void, status: i32, json: Option<&str>, error: Option<&str>) {
551        let json = json.map(|value| CString::new(value).expect("json without NUL"));
552        let error = error.map(|value| CString::new(value).expect("error without NUL"));
553        unsafe {
554            bridge_callback(
555                ctx,
556                status,
557                json.as_ref().map_or(ptr::null(), |value| value.as_ptr()),
558                ptr::null_mut(),
559                error.as_ref().map_or(ptr::null(), |value| value.as_ptr()),
560            );
561        }
562    }
563
564    #[test]
565    fn framework_errors_keep_their_typed_details() {
566        let (inner, ctx) = AsyncCompletion::create();
567        fire(
568            ctx,
569            status::FRAMEWORK_ERROR,
570            None,
571            Some(
572                r#"{"kind":"purchaseError","code":"invalidQuantity","errorDescription":"bad quantity","failureReason":null,"recoverySuggestion":null}"#,
573            ),
574        );
575        let error = pollster::block_on(PurchaseFuture { inner }).expect_err("framework error");
576        assert!(matches!(error, StoreKitError::Framework(_)));
577        assert_eq!(
578            error.product_purchase_error().map(|typed| typed.code),
579            Some(ProductPurchaseErrorCode::InvalidQuantity)
580        );
581    }
582
583    #[test]
584    fn bridge_statuses_map_to_their_error_variants() {
585        let (inner, ctx) = AsyncCompletion::create();
586        fire(ctx, status::NOT_SUPPORTED, None, Some("needs macOS 13.0+"));
587        match pollster::block_on(RequestReviewFuture { inner }) {
588            Err(StoreKitError::NotSupported(message)) => assert_eq!(message, "needs macOS 13.0+"),
589            other => panic!("expected NotSupported, got {other:?}"),
590        }
591
592        let (inner, ctx) = AsyncCompletion::create();
593        fire(
594            ctx,
595            status::VERIFICATION_ERROR,
596            None,
597            Some(
598                r#"{"kind":"verification","code":"invalidSignature","localizedDescription":"bad signature"}"#,
599            ),
600        );
601        match pollster::block_on(PurchaseFuture { inner }) {
602            Err(StoreKitError::Verification(failure)) => {
603                assert_eq!(failure.code, VerificationErrorCode::InvalidSignature);
604            }
605            other => panic!("expected a verification error, got {other:?}"),
606        }
607
608        let (inner, ctx) = AsyncCompletion::create();
609        fire(ctx, status::TIMED_OUT, None, None);
610        assert!(matches!(
611            pollster::block_on(RequestReviewFuture { inner }),
612            Err(StoreKitError::TimedOut(_))
613        ));
614    }
615
616    #[test]
617    fn successful_replies_decode_their_payload() {
618        let (inner, ctx) = AsyncCompletion::create();
619        fire(
620            ctx,
621            status::OK,
622            Some(r#"{"storefront":{"countryCode":"USA","id":"143441","currencyCode":"USD"}}"#),
623            None,
624        );
625        let storefront = pollster::block_on(StorefrontCurrentFuture { inner })
626            .expect("storefront reply")
627            .expect("storefront present");
628        assert_eq!(storefront.country_code, "USA");
629        assert_eq!(storefront.currency_code.as_deref(), Some("USD"));
630
631        let (inner, ctx) = AsyncCompletion::create();
632        fire(ctx, status::OK, None, None);
633        assert!(matches!(
634            pollster::block_on(StorefrontCurrentFuture { inner }),
635            Err(StoreKitError::InvalidArgument(_))
636        ));
637    }
638}