1use 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
73struct 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
132pub 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#[derive(Debug, Clone, Copy)]
172pub struct AsyncProducts;
173
174impl AsyncProducts {
175 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
199pub 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#[derive(Debug, Clone, Copy)]
242pub struct AsyncPurchase;
243
244impl AsyncPurchase {
245 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
285pub 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
311pub 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#[derive(Debug, Clone, Copy, Default)]
369pub struct AsyncAppStore;
370
371impl AsyncAppStore {
372 #[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 #[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
422pub 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#[derive(Debug, Clone, Copy)]
466pub struct AsyncAppTransaction;
467
468impl AsyncAppTransaction {
469 #[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#[derive(serde::Deserialize)]
490struct StorefrontCurrentPayload {
491 storefront: Option<StorefrontPayload>,
492}
493
494pub 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#[derive(Debug, Clone, Copy)]
524pub struct AsyncStorefront;
525
526impl AsyncStorefront {
527 #[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}