From 5488caab6c905b51ec237d8b0b1e0722fac5bbb1 Mon Sep 17 00:00:00 2001 From: CommaBot Date: Sat, 28 Nov 2026 19:06:42 +0000 Subject: [PATCH] fix(server): fix payment test flakes, predeploy steps, and large root doc refs (#15962) - Avoid TIMESTAMPTZ(3) future rounding on `next_attempt_at` and release `PaymentConnection` locks before returning. - Align `self-host-predeploy.js` with `package.json` predeploy steps (`admit-legacy-context-blobs` and `validate-cutover`). - Share bounded workspace root avatar extraction across `blob_access` and `doc_blob_refs`. Co-authored-by: DarkSky --- .../backend_runtime/blob_access/cache.rs | 93 ++-- .../backend_runtime/payment/app_store.rs | 104 ++-- .../payment/command/account.rs | 33 +- .../payment/command/app_store.rs | 436 ++++++++-------- .../payment/command/catalog.rs | 105 ++-- .../payment/command/checkout.rs | 456 ++++++++-------- .../payment/command/executor.rs | 39 +- .../payment/command/helpers.rs | 84 +-- .../payment/command/license/legacy.rs | 122 +++-- .../payment/command/license/mod.rs | 290 ++++++----- .../backend_runtime/payment/command/mod.rs | 6 +- .../payment/command/mutation.rs | 201 ++++---- .../payment/command/recovery.rs | 63 ++- .../payment/command/revenuecat.rs | 193 +++---- .../payment/command/schedule.rs | 458 ++++++++-------- .../payment/command/stripe_checkout.rs | 189 +++---- .../backend_runtime/payment/connection.rs | 45 +- .../payment/financial_reconcile.rs | 8 +- .../backend_runtime/payment/ops/mod.rs | 488 +++++++++--------- .../backend_runtime/payment/reconcile.rs | 14 +- .../backend_runtime/payment/runtime.rs | 20 +- .../runtime/backend_runtime/payment/tests.rs | 20 +- packages/backend/native/src/runtime/mod.rs | 40 +- .../runtime/storage_runtime/blob_cleanup.rs | 65 +++ .../runtime/storage_runtime/doc_blob_refs.rs | 17 +- .../server/scripts/self-host-predeploy.js | 46 +- .../__tests__/self-host-predeploy.spec.ts | 51 ++ 27 files changed, 1998 insertions(+), 1688 deletions(-) create mode 100644 packages/backend/server/src/data/__tests__/self-host-predeploy.spec.ts diff --git a/packages/backend/native/src/runtime/backend_runtime/blob_access/cache.rs b/packages/backend/native/src/runtime/backend_runtime/blob_access/cache.rs index 3b6d931f31..f32202e519 100644 --- a/packages/backend/native/src/runtime/backend_runtime/blob_access/cache.rs +++ b/packages/backend/native/src/runtime/backend_runtime/blob_access/cache.rs @@ -5,45 +5,18 @@ use std::{ time::{Duration, Instant}, }; -use affine_doc_loader::blob_refs::{BlobRefProjectionError, MAX_SOURCE_BINARY_BYTES, live_blob_keys}; +use affine_doc_loader::blob_refs::{MAX_SOURCE_BINARY_BYTES, live_blob_keys}; use tokio::sync::{Mutex, OwnedSemaphorePermit, Semaphore}; use super::{SourceIdentity, blocking, types::LoadedSource}; use crate::runtime::{ RuntimeError, RuntimeResult, backend_runtime::permission::PermissionTelemetry, blob_ref_projection_error_code, + extract_workspace_avatar_keys, }; const DEFAULT_MAX_BYTES: usize = 64 * 1024 * 1024; const HARD_TTL: Duration = Duration::from_secs(5 * 60); -fn workspace_avatar_keys(blob: Vec) -> Result>, BlobRefProjectionError> { - use y_octo::{Any, Doc, ReadDoc, ReadError, ReadValue, Value}; - - let blob = Arc::<[u8]>::from(blob); - let avatar = match ReadDoc::from_full_update_v1(Arc::clone(&blob)) { - Ok(doc) => match doc.map("meta").and_then(|meta| meta.get("avatar")) { - Some(ReadValue::Any(value)) => value.as_str().map(str::to_owned), - Some(ReadValue::Text(text)) => Some(text.to_string()), - _ => None, - }, - Err(ReadError::IncompleteSnapshot(_)) => { - let doc = Doc::try_from_binary_v1(&blob).map_err(|_| BlobRefProjectionError::InvalidBinary)?; - match doc.get_map("meta").ok().and_then(|meta| meta.get("avatar")) { - Some(Value::Any(Any::String(key))) => Some(key), - Some(Value::Text(text)) => Some(text.to_string()), - _ => None, - } - } - Err(ReadError::ResourceLimit(_)) => return Err(BlobRefProjectionError::Unsupported), - Err(ReadError::InvalidUpdate(_)) => return Err(BlobRefProjectionError::InvalidBinary), - }; - match avatar { - Some(key) if key.len() > 1024 => Err(BlobRefProjectionError::KeyTooLarge), - Some(key) if !key.is_empty() => Ok(vec![key.into_boxed_str()]), - _ => Ok(Vec::new()), - } -} - #[derive(Clone)] struct Entry { stamp: Box, @@ -173,7 +146,7 @@ impl BlobRefCache { let workspace_root = identity.is_workspace_root(); let parsed = blocking::spawn(permit, move || { if workspace_root { - workspace_avatar_keys(blob) + extract_workspace_avatar_keys(blob) } else { live_blob_keys(blob, false) } @@ -612,4 +585,64 @@ mod tests { first_task.await.unwrap().unwrap(); assert_eq!(cache.flights().await, 0); } + + #[tokio::test] + async fn large_workspace_root_doc_extracts_avatar_keys() { + let root = Doc::with_client(1); + let mut meta = root.get_or_create_map("meta").unwrap(); + meta + .insert("avatar".to_string(), Any::String("synthetic-avatar-key".to_string())) + .unwrap(); + let mut pages = root.create_array().unwrap(); + let title_padding = "t".repeat(900); + for index in 0..1_200 { + let mut page = root.create_map().unwrap(); + page + .insert("id".to_string(), Any::String(format!("synthetic-page-{index:04}"))) + .unwrap(); + page + .insert( + "title".to_string(), + Any::String(format!("Synthetic Page {index:04} {title_padding}")), + ) + .unwrap(); + pages.push(page).unwrap(); + } + meta.insert("pages".to_string(), pages).unwrap(); + let complete_blob = root.encode_update_v1().unwrap(); + assert!(complete_blob.len() > 1024 * 1024); + + let peer = Doc::with_client(42); + let mut peer_meta = peer.get_or_create_map("meta").unwrap(); + peer_meta + .insert("name".to_string(), Any::String("missing-prefix".to_string())) + .unwrap(); + let state = peer.get_state_vector(); + peer_meta + .insert("avatar".to_string(), Any::String("pending-avatar".to_string())) + .unwrap(); + let delta = peer.encode_state_as_update_v1(&state).unwrap(); + let incomplete_blob = y_octo::merge_updates_v1([complete_blob.as_slice(), delta.as_slice()]) + .unwrap() + .encode_v1() + .unwrap(); + assert!(incomplete_blob.len() > 1024 * 1024); + + let cache = BlobRefCache::with_limits(4096, 1, 2); + for (stamp, blob) in [("complete", complete_blob), ("incomplete", incomplete_blob)] { + let source = LoadedSource { + identity: SourceIdentity::CurrentDoc { + workspace_id: "synthetic-workspace".to_string(), + doc_id: "synthetic-workspace".to_string(), + }, + stamp: stamp.to_string(), + blob, + }; + let refs = cache.refs(source, || async { Ok(()) }).await.unwrap(); + assert_eq!( + refs.iter().map(AsRef::as_ref).collect::>(), + ["synthetic-avatar-key"] + ); + } + } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/app_store.rs b/packages/backend/native/src/runtime/backend_runtime/payment/app_store.rs index 7508b97f8b..139960e7d8 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/app_store.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/app_store.rs @@ -146,62 +146,62 @@ impl PaymentRuntime { PaymentScope::source(transaction.namespace, &matched.id)?, PaymentScope::customer(transaction.namespace, transaction.user_id)?, ]; - let Some(mut connection) = PaymentConnection::try_acquire(&self.pool, resources).await? else { + let Some(connection) = PaymentConnection::try_acquire(&self.pool, resources).await? else { return Ok("processing"); }; - for expansions in 0..=4 { - let [matched] = matches.as_slice() else { - return Ok(if matches.is_empty() { "processing" } else { "failed" }); - }; - let source_scope = PaymentScope::source(transaction.namespace, &matched.id)?; - let mut expansion = required_scope_expansion(connection.scopes(), [source_scope]); - if expansion.is_empty() { - let subscriptions = client - .customer_subscriptions(transaction.user_id) - .await - .map_err(|error| RuntimeError::invalid_state(error.code))?; - let Some(owned) = subscriptions.into_iter().find(|source| { - source.id == matched.id - && source.customer_id.as_deref() == Some(transaction.user_id) - && source.store == "app_store" - && source.environment == client.namespace().environment.as_str() - }) else { - return Ok("processing"); - }; - let snapshot = revenuecat_customer_snapshot( - &self.pool, - client, - config, - transaction.user_id, - vec![owned], - SnapshotCoverage::Single, - Vec::new(), - ) - .await?; - let Some(source) = transaction.source(&snapshot, &matched.id).cloned() else { - return Ok("failed"); - }; - match apply_payment_snapshot(&mut connection, snapshot, self.deployment, &self.mail_hash_key).await { - Ok(applied) => { - changes.extend(applied); - return transaction - .confirm_and_finish(connection.connection(), &source, attempt_id) - .await; + connection + .with_release(async |connection| { + for expansions in 0..=4 { + let [matched] = matches.as_slice() else { + return Ok(if matches.is_empty() { "processing" } else { "failed" }); + }; + let source_scope = PaymentScope::source(transaction.namespace, &matched.id)?; + let mut expansion = required_scope_expansion(connection.scopes(), [source_scope]); + if expansion.is_empty() { + let subscriptions = client + .customer_subscriptions(transaction.user_id) + .await + .map_err(|error| RuntimeError::invalid_state(error.code))?; + let Some(owned) = subscriptions.into_iter().find(|source| { + source.id == matched.id + && source.customer_id.as_deref() == Some(transaction.user_id) + && source.store == "app_store" + && source.environment == client.namespace().environment.as_str() + }) else { + return Ok("processing"); + }; + let snapshot = revenuecat_customer_snapshot( + &self.pool, + client, + config, + transaction.user_id, + vec![owned], + SnapshotCoverage::Single, + Vec::new(), + ) + .await?; + let Some(source) = transaction.source(&snapshot, &matched.id).cloned() else { + return Ok("failed"); + }; + match apply_payment_snapshot(connection, snapshot, self.deployment, &self.mail_hash_key).await { + Ok(applied) => { + changes.extend(applied); + return transaction + .confirm_and_finish(connection.connection(), &source, attempt_id) + .await; + } + Err(PaymentApplyError::Runtime(error)) => return Err(error), + Err(PaymentApplyError::LockSetExpanded(required)) => expansion = required, + } } - Err(PaymentApplyError::Runtime(error)) => return Err(error), - Err(PaymentApplyError::LockSetExpanded(required)) => expansion = required, + if expansions == 4 || !connection.reacquire_with(&self.pool, expansion).await? { + return Ok("processing"); + } + matches = locate_app_store_transaction(client, transaction.transaction_id).await?; } - } - if expansions == 4 { - break; - } - let Some(reacquired) = connection.reacquire_with(&self.pool, expansion).await? else { - return Ok("processing"); - }; - connection = reacquired; - matches = locate_app_store_transaction(client, transaction.transaction_id).await?; - } - Ok("processing") + Ok("processing") + }) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/account.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/account.rs index 685dd73b9c..50f1b14ba3 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/account.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/account.rs @@ -53,22 +53,27 @@ impl PaymentRuntime { }); } if prepared != 0 { - let Some(mut connection) = PaymentConnection::try_acquire(&self.pool, resources.clone()).await? else { + let Some(connection) = PaymentConnection::try_acquire(&self.pool, resources.clone()).await? else { return Err(RuntimeError::invalid_state("payment_busy")); }; - freeze_operation( - &mut connection, - &OperationIntent { - namespace: namespace.clone(), - operation_type: "account_delete_cancel".to_string(), - intent_id: format!("account-delete:{user_id}"), - resources, - target_type: Some("user".to_string()), - target_id: Some(user_id.to_string()), - steps, - }, - ) - .await?; + connection + .with_release(async |connection| { + freeze_operation( + connection, + &OperationIntent { + namespace: namespace.clone(), + operation_type: "account_delete_cancel".to_string(), + intent_id: format!("account-delete:{user_id}"), + resources, + target_type: Some("user".to_string()), + target_id: Some(user_id.to_string()), + steps, + }, + ) + .await?; + Ok(()) + }) + .await?; } Ok(json!({ "prepared": prepared })) } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/app_store.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/app_store.rs index 1a124d0701..3c7d448796 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/app_store.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/app_store.rs @@ -53,232 +53,234 @@ impl PaymentRuntime { if matches!(input.purchase_action, AppStoreAction::Cancel) { scopes.push(PaymentScope::customer(&namespace, user_id)?); } - let mut connection = PaymentConnection::try_acquire(&self.pool, scopes) + let connection = PaymentConnection::try_acquire(&self.pool, scopes) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let now = purchase_time(&mut connection).await?; - let open = open_purchase(&mut connection, &scope, now).await?; + connection + .with_release(async |connection| { + let now = purchase_time(connection).await?; + let open = open_purchase(connection, &scope, now).await?; - if matches!(input.purchase_action, AppStoreAction::Prepare) { - let intent_id = input - .intent_id - .as_deref() - .ok_or_else(|| RuntimeError::invalid_input("missing purchase intent"))?; - validate_intent(intent_id)?; - if let Some(attempt) = open - .as_ref() - .filter(|attempt| attempt.namespace == namespace && attempt.intent_id == intent_id) - { - if attempt.result.as_ref().and_then(|result| result["productId"].as_str()) != Some(&input.product_id) { - return Err(RuntimeError::invalid_state("payment intent payload changed")); - } - if attempt.status == "pending" { - return Ok(json!({ "status": "prepared", "attemptId": attempt.id })); - } - } - let facts = load_user_purchase_facts(&mut connection, user_id, family).await?; - return match facts.admission(family, Provider::RevenueCat, recurring, now, open.is_some()) { - PurchaseAdmission::Allowed => { - let attempt_id = uuid::Uuid::new_v4().to_string(); - let inserted = sqlx::query( - "INSERT INTO payment_operations( - id,provider,provider_namespace,operation_type,intent_id,primary_resource_key,resource_keys, - target_type,target_id,status,result,replay_deadline) - VALUES($1,'revenuecat',$2,'app_store_purchase',$3,$4,ARRAY[$4],'user',$5,'pending',$6,$7) - ON CONFLICT(provider_namespace,intent_id) DO NOTHING", - ) - .bind(&attempt_id) - .bind(&namespace) - .bind(intent_id) - .bind(scope.as_str()) - .bind(user_id) - .bind(json!({ "productId": input.product_id })) - .bind(now + Duration::minutes(5)) - .execute(connection.connection()) - .await - .map_err(|error| RuntimeError::database("prepare App Store purchase", error))?; - if inserted.rows_affected() == 0 { - return Ok(json!({ "status": "processing" })); + if matches!(input.purchase_action, AppStoreAction::Prepare) { + let intent_id = input + .intent_id + .as_deref() + .ok_or_else(|| RuntimeError::invalid_input("missing purchase intent"))?; + validate_intent(intent_id)?; + if let Some(attempt) = open + .as_ref() + .filter(|attempt| attempt.namespace == namespace && attempt.intent_id == intent_id) + { + if attempt.result.as_ref().and_then(|result| result["productId"].as_str()) != Some(&input.product_id) { + return Err(RuntimeError::invalid_state("payment intent payload changed")); + } + if attempt.status == "pending" { + return Ok(json!({ "status": "prepared", "attemptId": attempt.id })); + } } - Ok(json!({ "status": "prepared", "attemptId": attempt_id })) - } - PurchaseAdmission::Existing(provider) => Ok(json!({ "status": "existing", "provider": provider })), - PurchaseAdmission::InProgress => { - let stripe_checkout = - open.filter(|attempt| attempt.operation_type == "purchase_checkout" && attempt.status == "waiting"); - Ok(match stripe_checkout { - Some(attempt) => json!({ "status": "processing", "provider": "stripe", "attemptId": attempt.id }), - None => json!({ "status": "processing" }), - }) - } - PurchaseAdmission::NeedsVerification => Ok(json!({ "status": "conflict" })), - }; - } - - let restore = matches!(input.purchase_action, AppStoreAction::Restore); - let attempt = open.filter(|attempt| { - attempt.namespace == namespace - && attempt.operation_type == "app_store_purchase" - && attempt.result.as_ref().and_then(|result| result["productId"].as_str()) == Some(&input.product_id) - && (restore || input.attempt_id.as_deref() == Some(&attempt.id)) - }); - match input.purchase_action { - AppStoreAction::Prepare => unreachable!(), - AppStoreAction::Claim => { - let Some(attempt) = attempt.filter(|attempt| attempt.status == "pending") else { - return Ok(json!({ "status": "processing" })); - }; - let facts = load_user_purchase_facts(&mut connection, user_id, family).await?; - match facts.admission(family, Provider::RevenueCat, recurring, now, false) { - PurchaseAdmission::Allowed => {} - PurchaseAdmission::Existing(provider) => return Ok(json!({ "status": "existing", "provider": provider })), - _ => return Ok(json!({ "status": "conflict" })), - } - sqlx::query( - "UPDATE payment_operations SET status='waiting',first_sent_at=$2,replay_deadline=NULL,updated_at=$2 - WHERE id=$1 AND status='pending'", - ) - .bind(&attempt.id) - .bind(now) - .execute(connection.connection()) - .await - .map_err(|error| RuntimeError::database("claim App Store purchase", error))?; - Ok(json!({ "status": "start", "attemptId": attempt.id })) - } - AppStoreAction::Cancel => { - let Some(attempt) = attempt.filter(|attempt| attempt.status == "waiting") else { - let canceled: bool = sqlx::query_scalar( - "SELECT EXISTS(SELECT 1 FROM payment_operations WHERE id=$1 AND provider_namespace=$2 - AND target_type='user' AND target_id=$3 AND operation_type='app_store_purchase' - AND status='completed' AND result->>'productId'=$4 AND last_error_code='sdk_cancelled')", - ) - .bind(input.attempt_id.as_deref()) - .bind(&namespace) - .bind(user_id) - .bind(&input.product_id) - .fetch_one(connection.connection()) - .await - .map_err(|error| RuntimeError::database("load App Store cancellation result", error))?; - return Ok(json!({ "status": if canceled { "canceled" } else { "processing" } })); - }; - if attempt - .result - .as_ref() - .and_then(|result| result["transactionId"].as_str()) - .is_some() - { - return Ok(json!({ "status": "processing" })); - } - let mut now = now; - for expansions in 0..=4 { - let snapshot = self.observe_revenuecat_customer(user_id).await?; - let occupies = snapshot.subscriptions.iter().any(|subscription| { - UserPlanFamily::from_plan(subscription.plan) == Some(family) - && BillingRelationship { - provider: Provider::RevenueCat, - lifecycle: subscription.lifecycle, - period_end: subscription.period_end, - canceled_at: subscription.canceled_at, - } - .occupies_purchase(subscription.plan, FinancialRestriction::None, now) - }); - match apply_payment_snapshot(&mut connection, snapshot, self.deployment, &self.mail_hash_key).await { - Ok(applied) => changes.extend(applied), - Err(PaymentApplyError::Runtime(error)) => return Err(error), - Err(PaymentApplyError::LockSetExpanded(expansion)) => { - if expansions == 4 { - break; - } - let Some(reacquired) = connection.reacquire_with(&self.pool, expansion).await? else { + let facts = load_user_purchase_facts(connection, user_id, family).await?; + return match facts.admission(family, Provider::RevenueCat, recurring, now, open.is_some()) { + PurchaseAdmission::Allowed => { + let attempt_id = uuid::Uuid::new_v4().to_string(); + let inserted = sqlx::query( + "INSERT INTO payment_operations( + id,provider,provider_namespace,operation_type,intent_id,primary_resource_key,resource_keys, + target_type,target_id,status,result,replay_deadline) + VALUES($1,'revenuecat',$2,'app_store_purchase',$3,$4,ARRAY[$4],'user',$5,'pending',$6,$7) + ON CONFLICT(provider_namespace,intent_id) DO NOTHING", + ) + .bind(&attempt_id) + .bind(&namespace) + .bind(intent_id) + .bind(scope.as_str()) + .bind(user_id) + .bind(json!({ "productId": input.product_id })) + .bind(now + Duration::minutes(5)) + .execute(connection.connection()) + .await + .map_err(|error| RuntimeError::database("prepare App Store purchase", error))?; + if inserted.rows_affected() == 0 { return Ok(json!({ "status": "processing" })); - }; - connection = reacquired; - now = purchase_time(&mut connection).await?; - continue; + } + Ok(json!({ "status": "prepared", "attemptId": attempt_id })) } - } - let cancelable: bool = sqlx::query_scalar( - "SELECT EXISTS(SELECT 1 FROM payment_operations - WHERE id=$1 AND status='waiting' AND result->>'transactionId' IS NULL)", - ) - .bind(&attempt.id) - .fetch_one(connection.connection()) - .await - .map_err(|error| RuntimeError::database("check App Store cancellation after observation", error))?; - if occupies || !cancelable { - return Ok(json!({ "status": "processing" })); - } - finish_purchase(&mut connection, &attempt.id, "sdk_cancelled").await?; - return Ok(json!({ "status": "canceled" })); - } - Ok(json!({ "status": "processing" })) - } - AppStoreAction::Submit | AppStoreAction::Restore => { - let transaction_id = input - .transaction_id - .as_deref() - .ok_or_else(|| RuntimeError::invalid_input("missing App Store transaction"))?; - validate_identity(transaction_id, "App Store transaction")?; - let attempt = attempt.filter(|attempt| attempt.status == "waiting"); - if !restore && attempt.is_none() { - let prior: Option = sqlx::query_scalar( - "SELECT result FROM payment_operations WHERE id=$1 AND provider_namespace=$2 AND target_id=$3 - AND target_type='user' AND operation_type='app_store_purchase' AND status='completed' - AND result->>'productId'=$4 AND result->>'transactionId'=$5", - ) - .bind(input.attempt_id.as_deref()) - .bind(&namespace) - .bind(user_id) - .bind(&input.product_id) - .bind(transaction_id) - .fetch_optional(connection.connection()) - .await - .map_err(|error| RuntimeError::database("load App Store purchase result", error))?; - return Ok(match prior { - Some(mut prior) => { - prior["attemptId"] = json!(input.attempt_id); - prior + PurchaseAdmission::Existing(provider) => Ok(json!({ "status": "existing", "provider": provider })), + PurchaseAdmission::InProgress => { + let stripe_checkout = + open.filter(|attempt| attempt.operation_type == "purchase_checkout" && attempt.status == "waiting"); + Ok(match stripe_checkout { + Some(attempt) => json!({ "status": "processing", "provider": "stripe", "attemptId": attempt.id }), + None => json!({ "status": "processing" }), + }) } - None => json!({ "status": "processing" }), - }); + PurchaseAdmission::NeedsVerification => Ok(json!({ "status": "conflict" })), + }; } - if let Some(attempt) = attempt.as_ref().filter(|_| !restore) { - let recorded = sqlx::query( - "UPDATE payment_operations SET result=result || jsonb_build_object('transactionId',$2::text), - next_attempt_at=clock_timestamp()+INTERVAL '1 minute' WHERE id=$1 AND status='waiting' - AND (result->>'transactionId' IS NULL OR result->>'transactionId'=$2)", - ) - .bind(&attempt.id) - .bind(transaction_id) - .execute(connection.connection()) - .await - .map_err(|error| RuntimeError::database("record App Store transaction", error))?; - if recorded.rows_affected() == 0 { - return Ok(json!({ "status": "processing" })); + + let restore = matches!(input.purchase_action, AppStoreAction::Restore); + let attempt = open.filter(|attempt| { + attempt.namespace == namespace + && attempt.operation_type == "app_store_purchase" + && attempt.result.as_ref().and_then(|result| result["productId"].as_str()) == Some(&input.product_id) + && (restore || input.attempt_id.as_deref() == Some(&attempt.id)) + }); + match input.purchase_action { + AppStoreAction::Prepare => unreachable!(), + AppStoreAction::Claim => { + let Some(attempt) = attempt.filter(|attempt| attempt.status == "pending") else { + return Ok(json!({ "status": "processing" })); + }; + let facts = load_user_purchase_facts(connection, user_id, family).await?; + match facts.admission(family, Provider::RevenueCat, recurring, now, false) { + PurchaseAdmission::Allowed => {} + PurchaseAdmission::Existing(provider) => { + return Ok(json!({ "status": "existing", "provider": provider })); + } + _ => return Ok(json!({ "status": "conflict" })), + } + sqlx::query( + "UPDATE payment_operations SET status='waiting',first_sent_at=$2,replay_deadline=NULL,updated_at=$2 + WHERE id=$1 AND status='pending'", + ) + .bind(&attempt.id) + .bind(now) + .execute(connection.connection()) + .await + .map_err(|error| RuntimeError::database("claim App Store purchase", error))?; + Ok(json!({ "status": "start", "attemptId": attempt.id })) + } + AppStoreAction::Cancel => { + let Some(attempt) = attempt.filter(|attempt| attempt.status == "waiting") else { + let canceled: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM payment_operations WHERE id=$1 AND provider_namespace=$2 + AND target_type='user' AND target_id=$3 AND operation_type='app_store_purchase' + AND status='completed' AND result->>'productId'=$4 AND last_error_code='sdk_cancelled')", + ) + .bind(input.attempt_id.as_deref()) + .bind(&namespace) + .bind(user_id) + .bind(&input.product_id) + .fetch_one(connection.connection()) + .await + .map_err(|error| RuntimeError::database("load App Store cancellation result", error))?; + return Ok(json!({ "status": if canceled { "canceled" } else { "processing" } })); + }; + if attempt + .result + .as_ref() + .and_then(|result| result["transactionId"].as_str()) + .is_some() + { + return Ok(json!({ "status": "processing" })); + } + let mut now = now; + for expansions in 0..=4 { + let snapshot = self.observe_revenuecat_customer(user_id).await?; + let occupies = snapshot.subscriptions.iter().any(|subscription| { + UserPlanFamily::from_plan(subscription.plan) == Some(family) + && BillingRelationship { + provider: Provider::RevenueCat, + lifecycle: subscription.lifecycle, + period_end: subscription.period_end, + canceled_at: subscription.canceled_at, + } + .occupies_purchase(subscription.plan, FinancialRestriction::None, now) + }); + match apply_payment_snapshot(connection, snapshot, self.deployment, &self.mail_hash_key).await { + Ok(applied) => changes.extend(applied), + Err(PaymentApplyError::Runtime(error)) => return Err(error), + Err(PaymentApplyError::LockSetExpanded(expansion)) => { + if expansions == 4 || !connection.reacquire_with(&self.pool, expansion).await? { + return Ok(json!({ "status": "processing" })); + } + now = purchase_time(connection).await?; + continue; + } + } + let cancelable: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM payment_operations + WHERE id=$1 AND status='waiting' AND result->>'transactionId' IS NULL)", + ) + .bind(&attempt.id) + .fetch_one(connection.connection()) + .await + .map_err(|error| RuntimeError::database("check App Store cancellation after observation", error))?; + if occupies || !cancelable { + return Ok(json!({ "status": "processing" })); + } + finish_purchase(connection, &attempt.id, "sdk_cancelled").await?; + return Ok(json!({ "status": "canceled" })); + } + Ok(json!({ "status": "processing" })) + } + AppStoreAction::Submit | AppStoreAction::Restore => { + let transaction_id = input + .transaction_id + .as_deref() + .ok_or_else(|| RuntimeError::invalid_input("missing App Store transaction"))?; + validate_identity(transaction_id, "App Store transaction")?; + let attempt = attempt.filter(|attempt| attempt.status == "waiting"); + if !restore && attempt.is_none() { + let prior: Option = sqlx::query_scalar( + "SELECT result FROM payment_operations WHERE id=$1 AND provider_namespace=$2 AND target_id=$3 + AND target_type='user' AND operation_type='app_store_purchase' AND status='completed' + AND result->>'productId'=$4 AND result->>'transactionId'=$5", + ) + .bind(input.attempt_id.as_deref()) + .bind(&namespace) + .bind(user_id) + .bind(&input.product_id) + .bind(transaction_id) + .fetch_optional(connection.connection()) + .await + .map_err(|error| RuntimeError::database("load App Store purchase result", error))?; + return Ok(match prior { + Some(mut prior) => { + prior["attemptId"] = json!(input.attempt_id); + prior + } + None => json!({ "status": "processing" }), + }); + } + if let Some(attempt) = attempt.as_ref().filter(|_| !restore) { + let recorded = sqlx::query( + "UPDATE payment_operations SET result=result || jsonb_build_object('transactionId',$2::text), + next_attempt_at=clock_timestamp()+INTERVAL '1 minute' WHERE id=$1 AND status='waiting' + AND (result->>'transactionId' IS NULL OR result->>'transactionId'=$2)", + ) + .bind(&attempt.id) + .bind(transaction_id) + .execute(connection.connection()) + .await + .map_err(|error| RuntimeError::database("record App Store transaction", error))?; + if recorded.rows_affected() == 0 { + return Ok(json!({ "status": "processing" })); + } + } + connection.release_locks().await?; + let transaction = AppStoreTransaction { + namespace: &namespace, + user_id, + product_id: &input.product_id, + transaction_id, + family, + }; + let status = self + .verify_app_store_purchase( + changes, + &transaction, + &scope, + attempt.as_ref().map(|attempt| attempt.id.as_str()), + ) + .await?; + let mut result = json!({ "status": status }); + if !restore && let Some(attempt) = attempt { + result["attemptId"] = json!(attempt.id); + } + Ok(result) } } - drop(connection); - let transaction = AppStoreTransaction { - namespace: &namespace, - user_id, - product_id: &input.product_id, - transaction_id, - family, - }; - let status = self - .verify_app_store_purchase( - changes, - &transaction, - &scope, - attempt.as_ref().map(|attempt| attempt.id.as_str()), - ) - .await?; - let mut result = json!({ "status": status }); - if !restore && let Some(attempt) = attempt { - result["attemptId"] = json!(attempt.id); - } - Ok(result) - } - } + }) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs index af13d4701d..ed5c82e46b 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/catalog.rs @@ -124,28 +124,27 @@ impl PaymentRuntime { "v1/prices", fields, ); - match self.execute_stripe_operation(operation).await? { - OperationExecution::Completed(result) => results.push(result), - OperationExecution::Sent { - connection, - operation_id, - response, - } => { - let price: StripePrice = serde_json::from_value(response) - .map_err(|error| RuntimeError::json("invalid provisioned Stripe price", error))?; - validate_catalog_price(&price, specification)?; - let result = catalog_result(&price, true); - changes.extend( - self - .apply_with_connection( - connection, - empty_snapshot(namespace.clone(), None, operation_id, result.clone()), - ) - .await?, - ); - results.push(result); - } - } + let result = self + .with_stripe_operation(operation, async |connection, execution| match execution { + OperationExecution::Completed(result) => Ok(result), + OperationExecution::Sent { operation_id, response } => { + let price: StripePrice = serde_json::from_value(response) + .map_err(|error| RuntimeError::json("invalid provisioned Stripe price", error))?; + validate_catalog_price(&price, specification)?; + let result = catalog_result(&price, true); + changes.extend( + self + .apply_in_connection( + connection, + empty_snapshot(namespace.clone(), None, operation_id, result.clone()), + ) + .await?, + ); + Ok(result) + } + }) + .await?; + results.push(result); } Ok(json!({ "prices": results })) } @@ -179,39 +178,37 @@ impl PaymentRuntime { text_field("metadata[affineUserId]", user_id), ], ); - match self.execute_stripe_operation(intent).await? { - OperationExecution::Completed(result) => result - .get("customerId") - .and_then(Value::as_str) - .map(str::to_string) - .ok_or_else(|| RuntimeError::invalid_state("stored Stripe customer result is invalid")), - OperationExecution::Sent { - connection, - operation_id, - response, - } => { - let customer: StripeCustomer = serde_json::from_value(response) - .map_err(|error| RuntimeError::json("invalid Stripe customer response", error))?; - if !customer.matches_email(email) { - return Err(RuntimeError::invalid_state( - "Stripe customer response does not match request", - )); + self + .with_stripe_operation(intent, async |connection, execution| match execution { + OperationExecution::Completed(result) => result + .get("customerId") + .and_then(Value::as_str) + .map(str::to_string) + .ok_or_else(|| RuntimeError::invalid_state("stored Stripe customer result is invalid")), + OperationExecution::Sent { operation_id, response } => { + let customer: StripeCustomer = serde_json::from_value(response) + .map_err(|error| RuntimeError::json("invalid Stripe customer response", error))?; + if !customer.matches_email(email) { + return Err(RuntimeError::invalid_state( + "Stripe customer response does not match request", + )); + } + let result = json!({ "customerId": customer.id }); + let mut snapshot = empty_snapshot( + namespace.clone(), + Some(customer.id.clone()), + operation_id, + result.clone(), + ); + snapshot.customers.push(CustomerSnapshot { + user_id: user_id.to_string(), + external_customer_id: customer.id.clone(), + }); + changes.extend(self.apply_in_connection(connection, snapshot).await?); + Ok(customer.id) } - let result = json!({ "customerId": customer.id }); - let mut snapshot = empty_snapshot( - namespace.clone(), - Some(customer.id.clone()), - operation_id, - result.clone(), - ); - snapshot.customers.push(CustomerSnapshot { - user_id: user_id.to_string(), - external_customer_id: customer.id.clone(), - }); - changes.extend(self.apply_with_connection(connection, snapshot).await?); - Ok(customer.id) - } - } + }) + .await } pub(super) async fn find_price( diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/checkout.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/checkout.rs index 56afec337a..d26c6d272a 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/checkout.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/checkout.rs @@ -96,192 +96,196 @@ impl PaymentRuntime { if let Some(customer_id) = customer_id.as_deref().filter(|_| family.is_none()) { resources.push(PaymentScope::customer(&namespace_key, customer_id)?); } - let mut connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) + let connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let now = purchase_time(&mut connection).await?; - if let Some(family) = family { - let attempt = open_purchase(&mut connection, &target_scope, now).await?; - let facts = load_user_purchase_facts(&mut connection, &target_id, family).await?; - let admission = facts.admission(family, Provider::Stripe, recurring, now, attempt.is_some()); - match admission { - PurchaseAdmission::Allowed => {} - PurchaseAdmission::Existing(Provider::RevenueCat) => { - return Err(RuntimeError::invalid_state("managed_by_app_store")); - } - PurchaseAdmission::Existing(Provider::Stripe) => { - return Err(RuntimeError::invalid_state("subscription_already_exists")); - } - PurchaseAdmission::NeedsVerification => { - return Err(RuntimeError::invalid_state("purchase_needs_verification")); - } - PurchaseAdmission::InProgress => { - let attempt = attempt.expect("purchase admission found an open attempt"); - if attempt.operation_type != "purchase_checkout" - || attempt.namespace != namespace_key - || checkout_product(&attempt.steps) != Some(&lookup_key) - { - return Err(RuntimeError::invalid_state("purchase_in_progress")); - } - if attempt.status == "waiting" { - let result = attempt - .result - .ok_or_else(|| RuntimeError::invalid_state("missing checkout result"))?; - let session_id = result["sessionId"] - .as_str() - .ok_or_else(|| RuntimeError::invalid_state("missing checkout session"))?; - let session = self - .stripe()? - .checkout_session(session_id) - .await - .map_err(provider_runtime_error)?; - if session.status.as_deref() == Some("open") { - return Ok(result); + connection + .with_release(async |connection| { + let now = purchase_time(connection).await?; + if let Some(family) = family { + let attempt = open_purchase(connection, &target_scope, now).await?; + let facts = load_user_purchase_facts(connection, &target_id, family).await?; + let admission = facts.admission(family, Provider::Stripe, recurring, now, attempt.is_some()); + match admission { + PurchaseAdmission::Allowed => {} + PurchaseAdmission::Existing(Provider::RevenueCat) => { + return Err(RuntimeError::invalid_state("managed_by_app_store")); } - if session.status.as_deref() != Some("expired") { - return Err(RuntimeError::invalid_state("purchase_in_progress")); + PurchaseAdmission::Existing(Provider::Stripe) => { + return Err(RuntimeError::invalid_state("subscription_already_exists")); } - finish_purchase(&mut connection, &attempt.id, "expired").await?; - match facts.admission(family, Provider::Stripe, recurring, now, false) { - PurchaseAdmission::Allowed => {} - PurchaseAdmission::Existing(Provider::Stripe) => { - return Err(RuntimeError::invalid_state("subscription_already_exists")); + PurchaseAdmission::NeedsVerification => { + return Err(RuntimeError::invalid_state("purchase_needs_verification")); + } + PurchaseAdmission::InProgress => { + let attempt = attempt.expect("purchase admission found an open attempt"); + if attempt.operation_type != "purchase_checkout" + || attempt.namespace != namespace_key + || checkout_product(&attempt.steps) != Some(&lookup_key) + { + return Err(RuntimeError::invalid_state("purchase_in_progress")); } - PurchaseAdmission::Existing(Provider::RevenueCat) => { - return Err(RuntimeError::invalid_state("managed_by_app_store")); + if attempt.status == "waiting" { + let result = attempt + .result + .ok_or_else(|| RuntimeError::invalid_state("missing checkout result"))?; + let session_id = result["sessionId"] + .as_str() + .ok_or_else(|| RuntimeError::invalid_state("missing checkout session"))?; + let session = self + .stripe()? + .checkout_session(session_id) + .await + .map_err(provider_runtime_error)?; + if session.status.as_deref() == Some("open") { + return Ok(result); + } + if session.status.as_deref() != Some("expired") { + return Err(RuntimeError::invalid_state("purchase_in_progress")); + } + finish_purchase(connection, &attempt.id, "expired").await?; + match facts.admission(family, Provider::Stripe, recurring, now, false) { + PurchaseAdmission::Allowed => {} + PurchaseAdmission::Existing(Provider::Stripe) => { + return Err(RuntimeError::invalid_state("subscription_already_exists")); + } + PurchaseAdmission::Existing(Provider::RevenueCat) => { + return Err(RuntimeError::invalid_state("managed_by_app_store")); + } + _ => return Err(RuntimeError::invalid_state("purchase_needs_verification")), + } + } else { + return self + .send_checkout( + changes, + connection, + OperationIntent { + namespace, + operation_type: attempt.operation_type, + intent_id: attempt.intent_id, + resources, + target_type: Some(target_type.to_string()), + target_id: Some(target_id), + steps: attempt.steps, + }, + None, + ) + .await; } - _ => return Err(RuntimeError::invalid_state("purchase_needs_verification")), } - } else { - return self - .send_checkout( - changes, - connection, - OperationIntent { - namespace, - operation_type: attempt.operation_type, - intent_id: attempt.intent_id, - resources, - target_type: Some(target_type.to_string()), - target_id: Some(target_id), - steps: attempt.steps, - }, - None, - ) - .await; } - } - } - } else { - let rows = sqlx::query( - r#"SELECT plan,status,recurring,period_end,NULL::timestamptz AS grace_until, - NULL::timestamptz AS expires_at,true AS provider - FROM provider_subscriptions WHERE target_type=$1 AND target_id=$2 - UNION ALL - SELECT plan,status,metadata->>'recurring',NULL,grace_until,expires_at,false - FROM entitlements WHERE target_type=$1 AND target_id=$2 AND source='cloud_subscription'"#, - ) - .bind(target_type) - .bind(&target_id) - .fetch_all(connection.connection()) - .await - .map_err(|error| RuntimeError::database("load existing checkout subscriptions", error))?; - let facts = rows - .into_iter() - .map(|row| checkout_existing_fact(&row)) - .collect::>>()?; - if checkout_has_conflict(plan, recurring, now, &facts) { - return Err(RuntimeError::invalid_state("subscription_already_exists")); - } - } - let price = self.find_price(&lookup_key, recurring).await?; - let coupon_id = if let Some(coupon) = coupon.filter(|coupon| !coupon.is_empty()) { - self.resolve_coupon(coupon, customer_id.as_deref()).await? - } else { - None - }; - let trial_used = if plan == Plan::Ai { - sqlx::query_scalar::<_, bool>( - "SELECT EXISTS(SELECT 1 FROM subscription_trial_usages WHERE target_type='user' AND target_id=$1 AND \ - plan='ai')", - ) - .bind(&target_id) - .fetch_one(connection.connection()) - .await - .map_err(|error| RuntimeError::database("check payment trial history", error))? - } else { - false - }; - let trial = trial_eligible(plan, trial_used); - let mut fields = vec![ - text_field("line_items[0][price]", price.id), - text_field("line_items[0][quantity]", quantity.unwrap_or(1).to_string()), - text_field( - "success_url", - if target_type == "instance" { - append_checkout_session_placeholder(success_url)? } else { - success_url.to_string() - }, - ), - text_field( - "mode", + let rows = sqlx::query( + r#"SELECT plan,status,recurring,period_end,NULL::timestamptz AS grace_until, + NULL::timestamptz AS expires_at,true AS provider + FROM provider_subscriptions WHERE target_type=$1 AND target_id=$2 + UNION ALL + SELECT plan,status,metadata->>'recurring',NULL,grace_until,expires_at,false + FROM entitlements WHERE target_type=$1 AND target_id=$2 AND source='cloud_subscription'"#, + ) + .bind(target_type) + .bind(&target_id) + .fetch_all(connection.connection()) + .await + .map_err(|error| RuntimeError::database("load existing checkout subscriptions", error))?; + let facts = rows + .into_iter() + .map(|row| checkout_existing_fact(&row)) + .collect::>>()?; + if checkout_has_conflict(plan, recurring, now, &facts) { + return Err(RuntimeError::invalid_state("subscription_already_exists")); + } + } + let price = self.find_price(&lookup_key, recurring).await?; + let coupon_id = if let Some(coupon) = coupon.filter(|coupon| !coupon.is_empty()) { + self.resolve_coupon(coupon, customer_id.as_deref()).await? + } else { + None + }; + let trial_used = if plan == Plan::Ai { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS(SELECT 1 FROM subscription_trial_usages WHERE target_type='user' AND target_id=$1 AND \ + plan='ai')", + ) + .bind(&target_id) + .fetch_one(connection.connection()) + .await + .map_err(|error| RuntimeError::database("check payment trial history", error))? + } else { + false + }; + let trial = trial_eligible(plan, trial_used); + let mut fields = vec![ + text_field("line_items[0][price]", price.id), + text_field("line_items[0][quantity]", quantity.unwrap_or(1).to_string()), + text_field( + "success_url", + if target_type == "instance" { + append_checkout_session_placeholder(success_url)? + } else { + success_url.to_string() + }, + ), + text_field( + "mode", + if recurring == SubscriptionRecurring::Lifetime { + "payment" + } else { + "subscription" + }, + ), + ]; + if family.is_some() { + fields.push(text_field("metadata[affine_checkout_product]", lookup_key)); + } + if let Some(customer_id) = customer_id.as_deref() { + fields.push(text_field("customer", customer_id)); + } + if target_type == "workspace" { + fields.push(text_field("subscription_data[metadata][workspaceId]", &target_id)); + } else if target_type == "instance" { + fields.push(text_field("subscription_data[metadata][licenseKey]", &target_id)); + fields.push(text_field("line_items[0][adjustable_quantity][enabled]", "true")); + fields.push(text_field("line_items[0][adjustable_quantity][minimum]", "1")); + fields.push(text_field("tax_id_collection[enabled]", "true")); + } else if trial { + fields.push(text_field( + "subscription_data[trial_period_days]", + AI_TRIAL_DAYS.to_string(), + )); + } if recurring == SubscriptionRecurring::Lifetime { - "payment" + fields.push(text_field("invoice_creation[enabled]", "true")); + } + if let Some(coupon_id) = coupon_id { + fields.push(text_field("discounts[0][coupon]", coupon_id)); } else { - "subscription" - }, - ), - ]; - if family.is_some() { - fields.push(text_field("metadata[affine_checkout_product]", lookup_key)); - } - if let Some(customer_id) = customer_id.as_deref() { - fields.push(text_field("customer", customer_id)); - } - if target_type == "workspace" { - fields.push(text_field("subscription_data[metadata][workspaceId]", &target_id)); - } else if target_type == "instance" { - fields.push(text_field("subscription_data[metadata][licenseKey]", &target_id)); - fields.push(text_field("line_items[0][adjustable_quantity][enabled]", "true")); - fields.push(text_field("line_items[0][adjustable_quantity][minimum]", "1")); - fields.push(text_field("tax_id_collection[enabled]", "true")); - } else if trial { - fields.push(text_field( - "subscription_data[trial_period_days]", - AI_TRIAL_DAYS.to_string(), - )); - } - if recurring == SubscriptionRecurring::Lifetime { - fields.push(text_field("invoice_creation[enabled]", "true")); - } - if let Some(coupon_id) = coupon_id { - fields.push(text_field("discounts[0][coupon]", coupon_id)); - } else { - fields.push(text_field("allow_promotion_codes", "true")); - } - let operation_intent = stripe_operation( - namespace.clone(), - if family.is_some() { - "purchase_checkout" - } else { - "create_checkout" - }, - intent_id, - resources, - Some((target_type, &target_id)), - "v1/checkout/sessions", - fields, - ); - self - .send_checkout(changes, connection, operation_intent, workspace_actor) + fields.push(text_field("allow_promotion_codes", "true")); + } + let operation_intent = stripe_operation( + namespace.clone(), + if family.is_some() { + "purchase_checkout" + } else { + "create_checkout" + }, + intent_id, + resources, + Some((target_type, &target_id)), + "v1/checkout/sessions", + fields, + ); + self + .send_checkout(changes, connection, operation_intent, workspace_actor) + .await + }) .await } async fn send_checkout( &self, changes: &mut super::super::PaymentApplyResult, - connection: PaymentConnection, + connection: &mut PaymentConnection, intent: OperationIntent, workspace_actor: Option<&str>, ) -> RuntimeResult { @@ -298,11 +302,7 @@ impl PaymentRuntime { Err(RuntimeError::invalid_state("purchase_checkout_intent_used")) } OperationExecution::Completed(result) => Ok(result), - OperationExecution::Sent { - connection, - operation_id, - response, - } => { + OperationExecution::Sent { operation_id, response } => { let snapshot = recover_checkout( namespace, target_type, @@ -312,7 +312,7 @@ impl PaymentRuntime { reserves_trial, )?; let result = snapshot.operation.as_ref().expect("checkout completion").result.clone(); - changes.extend(self.apply_with_connection(connection, snapshot).await?); + changes.extend(self.apply_in_connection(connection, snapshot).await?); Ok(result) } } @@ -357,59 +357,63 @@ impl PaymentRuntime { PaymentScope::source(&namespace_key, &source.source_id)?, PaymentScope::billing_target(&namespace_key, "instance", &license_key)?, ]; - let mut connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) + let connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let step_key = format!("payment:{intent_id}:verify-session"); - let frozen = freeze_operation( - &mut connection, - &OperationIntent { - namespace: namespace.clone(), - operation_type: "reveal_license".to_string(), - intent_id: intent_id.to_string(), - resources, - target_type: Some("instance".to_string()), - target_id: Some(license_key.clone()), - steps: vec![PaymentStepState { - key: step_key.clone(), - request: PaymentStep::VerifySource { - source_id: session_id.to_string(), + connection + .with_release(async |connection| { + let step_key = format!("payment:{intent_id}:verify-session"); + let frozen = freeze_operation( + connection, + &OperationIntent { + namespace: namespace.clone(), + operation_type: "reveal_license".to_string(), + intent_id: intent_id.to_string(), + resources, + target_type: Some("instance".to_string()), + target_id: Some(license_key.clone()), + steps: vec![PaymentStepState { + key: step_key.clone(), + request: PaymentStep::VerifySource { + source_id: session_id.to_string(), + }, + first_sent_at: None, + result: None, + }], }, - first_sent_at: None, - result: None, - }], - }, - ) - .await?; - if frozen.status == "completed" { - return frozen - .result - .ok_or_else(|| RuntimeError::invalid_state("completed payment operation has no result")); - } - if frozen.status != "pending" { - return Err(RuntimeError::invalid_state("payment_operation_blocked")); - } - if frozen.steps[0].result.is_none() { - if mark_operation_step_sent(&mut connection, &frozen.id, &step_key, chrono::Duration::days(1)).await? - == PaymentSendDecision::Blocked - { - return Err(RuntimeError::invalid_state("payment_operation_blocked")); - } - record_operation_step_result( - &mut connection, - &frozen.id, - &step_key, - json!({ "sessionId": session.id, "subscriptionId": subscription_id }), - ) - .await?; - } - let result = Value::String(license_key.clone()); - snapshot.licenses[0].revealed_at = Some(chrono::Utc::now()); - snapshot.operation = Some(OperationCompletion { - operation_id: frozen.id, - result: result.clone(), - }); - changes.extend(self.apply_with_connection(connection, snapshot).await?); - Ok(result) + ) + .await?; + if frozen.status == "completed" { + return frozen + .result + .ok_or_else(|| RuntimeError::invalid_state("completed payment operation has no result")); + } + if frozen.status != "pending" { + return Err(RuntimeError::invalid_state("payment_operation_blocked")); + } + if frozen.steps[0].result.is_none() { + if mark_operation_step_sent(connection, &frozen.id, &step_key, chrono::Duration::days(1)).await? + == PaymentSendDecision::Blocked + { + return Err(RuntimeError::invalid_state("payment_operation_blocked")); + } + record_operation_step_result( + connection, + &frozen.id, + &step_key, + json!({ "sessionId": session.id, "subscriptionId": subscription_id }), + ) + .await?; + } + let result = Value::String(license_key.clone()); + snapshot.licenses[0].revealed_at = Some(chrono::Utc::now()); + snapshot.operation = Some(OperationCompletion { + operation_id: frozen.id, + result: result.clone(), + }); + changes.extend(self.apply_in_connection(connection, snapshot).await?); + Ok(result) + }) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/executor.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/executor.rs index 230e7d3bcb..a5abdf73a6 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/executor.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/executor.rs @@ -1,16 +1,25 @@ use super::*; impl PaymentRuntime { - pub(super) async fn execute_stripe_operation(&self, intent: OperationIntent) -> RuntimeResult { + pub(super) async fn with_stripe_operation( + &self, + intent: OperationIntent, + work: impl AsyncFnOnce(&mut PaymentConnection, OperationExecution) -> RuntimeResult, + ) -> RuntimeResult { let connection = PaymentConnection::try_acquire(&self.pool, intent.resources.clone()) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - self.execute_locked_stripe_operation(connection, intent, None).await + connection + .with_release(async |connection| { + let execution = self.execute_locked_stripe_operation(connection, intent, None).await?; + work(connection, execution).await + }) + .await } pub(super) async fn execute_locked_stripe_operation( &self, - mut connection: PaymentConnection, + connection: &mut PaymentConnection, intent: OperationIntent, workspace_actor: Option<&str>, ) -> RuntimeResult { @@ -19,16 +28,16 @@ impl PaymentRuntime { use super::super::super::permission::{PermissionAuthorizer, PermissionTelemetry}; let authorizer = PermissionAuthorizer::with_telemetry(self.pool.clone(), self.deployment, PermissionTelemetry::default()); - freeze_stripe_operation(&mut connection, &intent, Some((&authorizer, actor))).await? + freeze_stripe_operation(connection, &intent, Some((&authorizer, actor))).await? } else { - freeze_operation(&mut connection, &intent).await? + freeze_operation(connection, &intent).await? }; match frozen.status.as_str() { "completed" => { - return frozen + let result = frozen .result - .map(OperationExecution::Completed) - .ok_or_else(|| RuntimeError::invalid_state("completed payment operation has no result")); + .ok_or_else(|| RuntimeError::invalid_state("completed payment operation has no result"))?; + return Ok(OperationExecution::Completed(result)); } "pending" => {} "blocked" => return Err(RuntimeError::invalid_state("payment_operation_blocked")), @@ -40,7 +49,7 @@ impl PaymentRuntime { continue; } let step = &steps[index]; - if mark_operation_step_sent(&mut connection, &frozen.id, &step.key, Duration::minutes(10)).await? + if mark_operation_step_sent(connection, &frozen.id, &step.key, Duration::minutes(10)).await? == PaymentSendDecision::Blocked { return Err(RuntimeError::invalid_state("payment_operation_blocked")); @@ -79,18 +88,11 @@ impl PaymentRuntime { let response: Value = match response { Ok(response) => response, Err(error) => { - record_operation_error( - &mut connection, - &frozen.id, - error.code, - error.retryable, - error.uncertain, - ) - .await?; + record_operation_error(connection, &frozen.id, error.code, error.retryable, error.uncertain).await?; return Err(provider_runtime_error(error)); } }; - record_operation_step_result(&mut connection, &frozen.id, &step.key, response.clone()).await?; + record_operation_step_result(connection, &frozen.id, &step.key, response.clone()).await?; steps[index].result = Some(response); } let response = steps @@ -98,7 +100,6 @@ impl PaymentRuntime { .and_then(|step| step.result.clone()) .ok_or_else(|| RuntimeError::invalid_state("payment operation produced no result"))?; Ok(OperationExecution::Sent { - connection, operation_id: frozen.id, response, }) diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/helpers.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/helpers.rs index 277fbaffde..cb67b333bb 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/helpers.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/helpers.rs @@ -122,7 +122,6 @@ pub(super) fn required_column(row: &sqlx::postgres::PgRow, column: &str, error: } pub(super) struct LockedStripeSubscription { - pub connection: PaymentConnection, pub resources: Vec, pub subscription_id: String, pub recurring: Option, @@ -133,13 +132,14 @@ pub(super) struct LockedStripeSubscription { } impl PaymentRuntime { - pub(super) async fn lock_stripe_subscription( + pub(super) async fn with_locked_stripe_subscription( &self, namespace: &str, target_type: &str, target_id: &str, plan: Plan, - ) -> RuntimeResult { + work: impl AsyncFnOnce(&mut PaymentConnection, LockedStripeSubscription) -> RuntimeResult, + ) -> RuntimeResult { let discovery = sqlx::query( r#"SELECT source_identity,external_customer_id FROM provider_subscriptions @@ -168,45 +168,49 @@ impl PaymentRuntime { PaymentScope::customer(namespace, &customer_id)?, target_scope, ]; - let mut connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) + let connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let row = sqlx::query( - r#"SELECT source_identity,external_customer_id,external_subscription_id,recurring,canceled_at, - period_start,metadata,quantity - FROM provider_subscriptions - WHERE provider='stripe' AND provider_namespace=$1 AND target_type=$2 AND target_id=$3 - AND (plan=$4 OR ($4='selfhost_team' AND plan='selfhostedteam')) - AND status IN ('active','trialing','past_due') AND (period_end IS NULL OR period_end>clock_timestamp()) - ORDER BY updated_at DESC LIMIT 1"#, - ) - .bind(namespace) - .bind(target_type) - .bind(target_id) - .bind(plan.as_str()) - .fetch_optional(connection.connection()) - .await - .map_err(|error| RuntimeError::database("load locked Stripe subscription", error))? - .ok_or_else(|| RuntimeError::invalid_state("subscription_not_found"))?; - let locked_source_id = required_column(&row, "source_identity", "payment subscription identity missing")?; - let locked_customer_id = required_column(&row, "external_customer_id", "payment customer identity missing")?; - if locked_source_id != source_id || locked_customer_id != customer_id { - return Err(RuntimeError::invalid_state("payment_subscription_changed")); - } - Ok(LockedStripeSubscription { - connection, - resources, - subscription_id: required_column( - &row, - "external_subscription_id", - "payment subscription identity missing", - )?, - recurring: row.get("recurring"), - canceled_at: row.get("canceled_at"), - period_start: row.get("period_start"), - metadata: row.get("metadata"), - quantity: row.get("quantity"), - }) + connection + .with_release(async |connection| { + let row = sqlx::query( + r#"SELECT source_identity,external_customer_id,external_subscription_id,recurring,canceled_at, + period_start,metadata,quantity + FROM provider_subscriptions + WHERE provider='stripe' AND provider_namespace=$1 AND target_type=$2 AND target_id=$3 + AND (plan=$4 OR ($4='selfhost_team' AND plan='selfhostedteam')) + AND status IN ('active','trialing','past_due') AND (period_end IS NULL OR period_end>clock_timestamp()) + ORDER BY updated_at DESC LIMIT 1"#, + ) + .bind(namespace) + .bind(target_type) + .bind(target_id) + .bind(plan.as_str()) + .fetch_optional(connection.connection()) + .await + .map_err(|error| RuntimeError::database("load locked Stripe subscription", error))? + .ok_or_else(|| RuntimeError::invalid_state("subscription_not_found"))?; + let locked_source_id = required_column(&row, "source_identity", "payment subscription identity missing")?; + let locked_customer_id = required_column(&row, "external_customer_id", "payment customer identity missing")?; + if locked_source_id != source_id || locked_customer_id != customer_id { + return Err(RuntimeError::invalid_state("payment_subscription_changed")); + } + let locked = LockedStripeSubscription { + resources, + subscription_id: required_column( + &row, + "external_subscription_id", + "payment subscription identity missing", + )?, + recurring: row.get("recurring"), + canceled_at: row.get("canceled_at"), + period_start: row.get("period_start"), + metadata: row.get("metadata"), + quantity: row.get("quantity"), + }; + work(connection, locked).await + }) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/license/legacy.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/license/legacy.rs index f9c99d9636..b7d6781df8 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/license/legacy.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/license/legacy.rs @@ -13,27 +13,31 @@ impl PaymentRuntime { ) -> RuntimeResult { validate_identity(license_key, "license")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = license_connection(self, license_key, &namespace).await?; - let mut tx = connection.begin().await?; - let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; - let validate_key = uuid::Uuid::new_v4().to_string(); - let updated = sqlx::query( - "UPDATE licenses SET installed_at=clock_timestamp(),validate_key=$2 WHERE key=$1 AND workspace_id IS NULL AND \ - installed_at IS NULL AND validate_key IS NULL", - ) - .bind(license_key) - .bind(&validate_key) - .execute(&mut *tx) - .await - .map_err(|error| RuntimeError::database("activate legacy license", error))?; - if updated.rows_affected() != 1 { - return Err(RuntimeError::invalid_state("invalid_license")); - } - let response = legacy_response(subscription, validate_key)?; - tx.commit() + let connection = license_connection(self, license_key, &namespace).await?; + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; + let validate_key = uuid::Uuid::new_v4().to_string(); + let updated = sqlx::query( + "UPDATE licenses SET installed_at=clock_timestamp(),validate_key=$2 WHERE key=$1 AND workspace_id IS NULL \ + AND installed_at IS NULL AND validate_key IS NULL", + ) + .bind(license_key) + .bind(&validate_key) + .execute(&mut *tx) + .await + .map_err(|error| RuntimeError::database("activate legacy license", error))?; + if updated.rows_affected() != 1 { + return Err(RuntimeError::invalid_state("invalid_license")); + } + let response = legacy_response(subscription, validate_key)?; + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit legacy activation", error))?; + Ok(response) + }) .await - .map_err(|error| RuntimeError::database("commit legacy activation", error))?; - Ok(response) } pub(in crate::runtime::backend_runtime::payment::command) async fn check_legacy_license_health( @@ -44,28 +48,32 @@ impl PaymentRuntime { validate_identity(license_key, "license")?; validate_uuid(validate_key, "license validate key")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = license_connection(self, license_key, &namespace).await?; - let mut tx = connection.begin().await?; - let license = sqlx::query("SELECT workspace_id,installed_at,validate_key FROM licenses WHERE key=$1 FOR SHARE") - .bind(license_key) - .fetch_optional(&mut *tx) + let connection = license_connection(self, license_key, &namespace).await?; + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let license = sqlx::query("SELECT workspace_id,installed_at,validate_key FROM licenses WHERE key=$1 FOR SHARE") + .bind(license_key) + .fetch_optional(&mut *tx) + .await + .map_err(|error| RuntimeError::database("read legacy license binding", error))? + .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; + if license.get::, _>("workspace_id").is_some() { + return Err(RuntimeError::invalid_state("license_protocol_upgraded")); + } + if license.get::>, _>("installed_at").is_none() + || license.get::, _>("validate_key").as_deref() != Some(validate_key) + { + return Err(RuntimeError::invalid_state("invalid_validate_key")); + } + let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; + let response = legacy_response(subscription, validate_key.to_string())?; + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit legacy health check", error))?; + Ok(response) + }) .await - .map_err(|error| RuntimeError::database("read legacy license binding", error))? - .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; - if license.get::, _>("workspace_id").is_some() { - return Err(RuntimeError::invalid_state("license_protocol_upgraded")); - } - if license.get::>, _>("installed_at").is_none() - || license.get::, _>("validate_key").as_deref() != Some(validate_key) - { - return Err(RuntimeError::invalid_state("invalid_validate_key")); - } - let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; - let response = legacy_response(subscription, validate_key.to_string())?; - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit legacy health check", error))?; - Ok(response) } pub(in crate::runtime::backend_runtime::payment::command) async fn deactivate_legacy_license( @@ -74,26 +82,30 @@ impl PaymentRuntime { ) -> RuntimeResult { validate_identity(license_key, "license")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = PaymentConnection::try_acquire( + let connection = PaymentConnection::try_acquire( &self.pool, vec![PaymentScope::billing_target(&namespace, "instance", license_key)?], ) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let mut tx = connection.begin().await?; - let updated = - sqlx::query("UPDATE licenses SET installed_at=NULL,validate_key=NULL WHERE key=$1 AND workspace_id IS NULL") - .bind(license_key) - .execute(&mut *tx) - .await - .map_err(|error| RuntimeError::database("deactivate legacy license", error))?; - if updated.rows_affected() != 1 { - return Err(RuntimeError::invalid_state("license_protocol_upgraded")); - } - tx.commit() + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let updated = + sqlx::query("UPDATE licenses SET installed_at=NULL,validate_key=NULL WHERE key=$1 AND workspace_id IS NULL") + .bind(license_key) + .execute(&mut *tx) + .await + .map_err(|error| RuntimeError::database("deactivate legacy license", error))?; + if updated.rows_affected() != 1 { + return Err(RuntimeError::invalid_state("license_protocol_upgraded")); + } + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit legacy deactivation", error))?; + Ok(json!({ "success": true })) + }) .await - .map_err(|error| RuntimeError::database("commit legacy deactivation", error))?; - Ok(json!({ "success": true })) } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/license/mod.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/license/mod.rs index a5932b5759..f309aeefb1 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/license/mod.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/license/mod.rs @@ -25,93 +25,102 @@ impl PaymentRuntime { validate_identity(workspace_id, "license workspace")?; validate_uuid(operation_id, "license operation")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = license_connection(self, license_key, &namespace).await?; - let mut tx = connection.begin().await?; - let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; - let license = sqlx::query( - "SELECT workspace_id,installed_at,validate_key,clock_timestamp() AS now FROM licenses WHERE key=$1 FOR UPDATE", - ) - .bind(license_key) - .fetch_optional(&mut *tx) - .await - .map_err(|error| RuntimeError::database("lock payment license", error))? - .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; - let bound_workspace: Option = license.get("workspace_id"); - if bound_workspace.as_deref().is_some_and(|bound| bound != workspace_id) { - return Err(RuntimeError::invalid_state("invalid_license")); - } - if bound_workspace.is_none() && license.get::>, _>("installed_at").is_some() { - return Err(RuntimeError::invalid_state("license_upgrade_required")); - } - let now: DateTime = license.get("now"); - let validate_key = license - .get::, _>("validate_key") - .unwrap_or_else(|| operation_id.to_string()); - let envelope = issue_license( - self.license_issuer_private_key.as_ref().map(|key| key.as_str()), - license_key, - workspace_id, - subscription.quantity, - subscription.period_end, - now, - )?; - let updated = sqlx::query( - "UPDATE licenses SET workspace_id=$2,installed_at=$3,validate_key=$4 WHERE key=$1 AND (workspace_id IS NULL OR \ - workspace_id=$2)", - ) - .bind(license_key) - .bind(workspace_id) - .bind(now) - .bind(&validate_key) - .execute(&mut *tx) - .await - .map_err(|error| RuntimeError::database("bind payment license", error))?; - if updated.rows_affected() != 1 { - return Err(RuntimeError::invalid_state("invalid_license")); - } - tx.commit() + let connection = license_connection(self, license_key, &namespace).await?; + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; + let license = sqlx::query( + "SELECT workspace_id,installed_at,validate_key,clock_timestamp() AS now FROM licenses WHERE key=$1 FOR \ + UPDATE", + ) + .bind(license_key) + .fetch_optional(&mut *tx) + .await + .map_err(|error| RuntimeError::database("lock payment license", error))? + .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; + let bound_workspace: Option = license.get("workspace_id"); + if bound_workspace.as_deref().is_some_and(|bound| bound != workspace_id) { + return Err(RuntimeError::invalid_state("invalid_license")); + } + if bound_workspace.is_none() && license.get::>, _>("installed_at").is_some() { + return Err(RuntimeError::invalid_state("license_upgrade_required")); + } + let now: DateTime = license.get("now"); + let validate_key = license + .get::, _>("validate_key") + .unwrap_or_else(|| operation_id.to_string()); + let envelope = issue_license( + self.license_issuer_private_key.as_ref().map(|key| key.as_str()), + license_key, + workspace_id, + subscription.quantity, + subscription.period_end, + now, + )?; + let updated = sqlx::query( + "UPDATE licenses SET workspace_id=$2,installed_at=$3,validate_key=$4 WHERE key=$1 AND (workspace_id IS NULL \ + OR workspace_id=$2)", + ) + .bind(license_key) + .bind(workspace_id) + .bind(now) + .bind(&validate_key) + .execute(&mut *tx) + .await + .map_err(|error| RuntimeError::database("bind payment license", error))?; + if updated.rows_affected() != 1 { + return Err(RuntimeError::invalid_state("invalid_license")); + } + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit license activation", error))?; + Ok(license_response(envelope, validate_key, subscription.recurring)) + }) .await - .map_err(|error| RuntimeError::database("commit license activation", error))?; - Ok(license_response(envelope, validate_key, subscription.recurring)) } pub(super) async fn deactivate_license(&self, license_key: &str, validate_key: &str) -> RuntimeResult { validate_identity(license_key, "license")?; validate_uuid(validate_key, "license validate key")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = PaymentConnection::try_acquire( + let connection = PaymentConnection::try_acquire( &self.pool, vec![PaymentScope::billing_target(&namespace, "instance", license_key)?], ) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let mut tx = connection.begin().await?; - let license = sqlx::query("SELECT workspace_id,validate_key FROM licenses WHERE key=$1 FOR UPDATE") - .bind(license_key) - .fetch_optional(&mut *tx) + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let license = sqlx::query("SELECT workspace_id,validate_key FROM licenses WHERE key=$1 FOR UPDATE") + .bind(license_key) + .fetch_optional(&mut *tx) + .await + .map_err(|error| RuntimeError::database("lock payment license for deactivation", error))? + .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; + let bound_workspace: Option = license.get("workspace_id"); + let bound_validate_key: Option = license.get("validate_key"); + if bound_workspace.is_none() && bound_validate_key.is_none() { + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit already-unbound license deactivation", error))?; + return Ok(json!({ "status": "already_unbound" })); + } + if bound_validate_key.as_deref() != Some(validate_key) { + return Err(RuntimeError::invalid_state("invalid_validate_key")); + } + sqlx::query("UPDATE licenses SET workspace_id=NULL,installed_at=NULL,validate_key=NULL WHERE key=$1") + .bind(license_key) + .execute(&mut *tx) + .await + .map_err(|error| RuntimeError::database("deactivate payment license", error))?; + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit license deactivation", error))?; + Ok(json!({ "status": "deactivated" })) + }) .await - .map_err(|error| RuntimeError::database("lock payment license for deactivation", error))? - .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; - let bound_workspace: Option = license.get("workspace_id"); - let bound_validate_key: Option = license.get("validate_key"); - if bound_workspace.is_none() && bound_validate_key.is_none() { - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit already-unbound license deactivation", error))?; - return Ok(json!({ "status": "already_unbound" })); - } - if bound_validate_key.as_deref() != Some(validate_key) { - return Err(RuntimeError::invalid_state("invalid_validate_key")); - } - sqlx::query("UPDATE licenses SET workspace_id=NULL,installed_at=NULL,validate_key=NULL WHERE key=$1") - .bind(license_key) - .execute(&mut *tx) - .await - .map_err(|error| RuntimeError::database("deactivate payment license", error))?; - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit license deactivation", error))?; - Ok(json!({ "status": "deactivated" })) } pub(super) async fn check_license_health( @@ -124,51 +133,56 @@ impl PaymentRuntime { validate_identity(workspace_id, "license workspace")?; validate_uuid(validate_key, "license validate key")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = license_connection(self, license_key, &namespace).await?; - let mut tx = connection.begin().await?; - let license = sqlx::query( - "SELECT workspace_id,validate_key,installed_at,clock_timestamp() AS now FROM licenses WHERE key=$1 FOR UPDATE", - ) - .bind(license_key) - .fetch_optional(&mut *tx) - .await - .map_err(|error| RuntimeError::database("read payment license", error))? - .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; - if license.get::>, _>("installed_at").is_none() { - return Err(RuntimeError::invalid_state("license_unbound")); - } - if license.get::, _>("validate_key").as_deref() != Some(validate_key) { - return Err(RuntimeError::invalid_state("invalid_validate_key")); - } - let bound_workspace: Option = license.get("workspace_id"); - if bound_workspace.as_deref().is_some_and(|bound| bound != workspace_id) { - return Err(RuntimeError::invalid_state("license_workspace_mismatch")); - } - let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; - let envelope = issue_license( - self.license_issuer_private_key.as_ref().map(|key| key.as_str()), - license_key, - workspace_id, - subscription.quantity, - subscription.period_end, - license.get("now"), - )?; - if bound_workspace.is_none() { - sqlx::query("UPDATE licenses SET workspace_id=$2 WHERE key=$1") + let connection = license_connection(self, license_key, &namespace).await?; + connection + .with_release(async |connection| { + let mut tx = connection.begin().await?; + let license = sqlx::query( + "SELECT workspace_id,validate_key,installed_at,clock_timestamp() AS now FROM licenses WHERE key=$1 FOR \ + UPDATE", + ) .bind(license_key) - .bind(workspace_id) - .execute(&mut *tx) + .fetch_optional(&mut *tx) .await - .map_err(|error| RuntimeError::database("upgrade license binding", error))?; - } - tx.commit() + .map_err(|error| RuntimeError::database("read payment license", error))? + .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; + if license.get::>, _>("installed_at").is_none() { + return Err(RuntimeError::invalid_state("license_unbound")); + } + if license.get::, _>("validate_key").as_deref() != Some(validate_key) { + return Err(RuntimeError::invalid_state("invalid_validate_key")); + } + let bound_workspace: Option = license.get("workspace_id"); + if bound_workspace.as_deref().is_some_and(|bound| bound != workspace_id) { + return Err(RuntimeError::invalid_state("license_workspace_mismatch")); + } + let subscription = active_license_subscription(&mut tx, license_key, &namespace).await?; + let envelope = issue_license( + self.license_issuer_private_key.as_ref().map(|key| key.as_str()), + license_key, + workspace_id, + subscription.quantity, + subscription.period_end, + license.get("now"), + )?; + if bound_workspace.is_none() { + sqlx::query("UPDATE licenses SET workspace_id=$2 WHERE key=$1") + .bind(license_key) + .bind(workspace_id) + .execute(&mut *tx) + .await + .map_err(|error| RuntimeError::database("upgrade license binding", error))?; + } + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit license health check", error))?; + Ok(license_response( + envelope, + validate_key.to_string(), + subscription.recurring, + )) + }) .await - .map_err(|error| RuntimeError::database("commit license health check", error))?; - Ok(license_response( - envelope, - validate_key.to_string(), - subscription.recurring, - )) } pub(in crate::runtime::backend_runtime) async fn license_customer_portal_url( @@ -178,32 +192,36 @@ impl PaymentRuntime { ) -> RuntimeResult { validate_identity(license_key, "license")?; let namespace = canonical_namespace(self.stripe()?.namespace())?; - let mut connection = PaymentConnection::try_acquire( + let connection = PaymentConnection::try_acquire( &self.pool, vec![PaymentScope::billing_target(&namespace, "instance", license_key)?], ) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - assert_license_access(connection.connection(), license_key, validate_key).await?; - let customer: String = sqlx::query_scalar( - "SELECT external_customer_id FROM provider_subscriptions WHERE provider_namespace=$1 AND target_type='instance' \ - AND target_id=$2 AND plan IN ('selfhost_team','selfhostedteam') AND external_customer_id IS NOT NULL ORDER BY \ - updated_at DESC LIMIT 1", - ) - .bind(&namespace) - .bind(license_key) - .fetch_optional(connection.connection()) - .await - .map_err(|error| RuntimeError::database("load license portal customer", error))? - .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; - let mut form = StripeForm::default(); - form.push("customer", StripeFormValue::Text(customer)); - let portal: StripePortalSession = self - .stripe()? - .post("v1/billing_portal/sessions", &form, &uuid::Uuid::new_v4().to_string()) + connection + .with_release(async |connection| { + assert_license_access(connection.connection(), license_key, validate_key).await?; + let customer: String = sqlx::query_scalar( + "SELECT external_customer_id FROM provider_subscriptions WHERE provider_namespace=$1 AND \ + target_type='instance' AND target_id=$2 AND plan IN ('selfhost_team','selfhostedteam') AND \ + external_customer_id IS NOT NULL ORDER BY updated_at DESC LIMIT 1", + ) + .bind(&namespace) + .bind(license_key) + .fetch_optional(connection.connection()) + .await + .map_err(|error| RuntimeError::database("load license portal customer", error))? + .ok_or_else(|| RuntimeError::invalid_state("license_not_found"))?; + let mut form = StripeForm::default(); + form.push("customer", StripeFormValue::Text(customer)); + let portal: StripePortalSession = self + .stripe()? + .post("v1/billing_portal/sessions", &form, &uuid::Uuid::new_v4().to_string()) + .await + .map_err(provider_runtime_error)?; + Ok(portal.url) + }) .await - .map_err(provider_runtime_error)?; - Ok(portal.url) } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs index 792e7a86eb..6a2ad23766 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/mod.rs @@ -53,11 +53,7 @@ use crate::runtime::{RuntimeError, RuntimeResult}; enum OperationExecution { Completed(Value), - Sent { - connection: PaymentConnection, - operation_id: String, - response: Value, - }, + Sent { operation_id: String, response: Value }, } #[derive(serde::Deserialize)] diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/mutation.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/mutation.rs index 1efc832c5a..7247edfa01 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/mutation.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/mutation.rs @@ -36,105 +36,108 @@ impl PaymentRuntime { let stripe = self.stripe()?; let namespace = stripe.namespace().clone(); let namespace_key = canonical_namespace(&namespace)?; - let locked = self - .lock_stripe_subscription(&namespace_key, target_type, target_id, plan) - .await?; - let subscription_id = locked.subscription_id.clone(); - let canceled_at = locked.canceled_at; - let stored_recurring = locked - .recurring - .as_deref() - .and_then(SubscriptionRecurring::parse) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; - validate_subscription_mutation( - plan, - billing_target(target_type)?, - stored_recurring, - canceled_at.is_some(), - mutation, - ) - .map_err(subscription_mutation_error)?; - let direct_form = vec![text_field( - "cancel_at_period_end", - if mutation == SubscriptionMutation::Cancel { - "true" - } else { - "false" - }, - )]; - let schedule_id = locked - .metadata - .get("stripeScheduleId") - .and_then(Value::as_str) - .map(str::to_string); - let (path, form) = if let Some(schedule_id) = schedule_id.as_deref() { - let schedule = stripe - .subscription_schedule(schedule_id) - .await - .map_err(provider_runtime_error)?; - super::schedule::validate_subscription(&schedule, &subscription_id)?; - let anchor = locked - .period_start - .map(|value| value.timestamp()) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; - let form = if mutation == SubscriptionMutation::Cancel { - schedule::cancel_fields(&schedule, anchor)? - } else { - schedule::resume_fields(&schedule, anchor)? - }; - ( - format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), - form, + self + .with_locked_stripe_subscription( + &namespace_key, + target_type, + target_id, + plan, + async |connection, locked| { + let subscription_id = locked.subscription_id.clone(); + let canceled_at = locked.canceled_at; + let stored_recurring = locked + .recurring + .as_deref() + .and_then(SubscriptionRecurring::parse) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; + validate_subscription_mutation( + plan, + billing_target(target_type)?, + stored_recurring, + canceled_at.is_some(), + mutation, + ) + .map_err(subscription_mutation_error)?; + let direct_form = vec![text_field( + "cancel_at_period_end", + if mutation == SubscriptionMutation::Cancel { + "true" + } else { + "false" + }, + )]; + let schedule_id = locked + .metadata + .get("stripeScheduleId") + .and_then(Value::as_str) + .map(str::to_string); + let (path, form) = if let Some(schedule_id) = schedule_id.as_deref() { + let schedule = stripe + .subscription_schedule(schedule_id) + .await + .map_err(provider_runtime_error)?; + super::schedule::validate_subscription(&schedule, &subscription_id)?; + let anchor = locked + .period_start + .map(|value| value.timestamp()) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; + let form = if mutation == SubscriptionMutation::Cancel { + schedule::cancel_fields(&schedule, anchor)? + } else { + schedule::resume_fields(&schedule, anchor)? + }; + ( + format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), + form, + ) + } else { + ( + format!("v1/subscriptions/{}", encode_segment(&subscription_id)), + direct_form, + ) + }; + let intent = stripe_operation( + namespace.clone(), + mutation.as_str(), + intent_id, + locked.resources.clone(), + Some((target_type, target_id)), + &path, + form, + ); + match self + .execute_locked_stripe_operation(connection, intent, workspace_actor) + .await? + { + OperationExecution::Completed(result) => Ok(result), + OperationExecution::Sent { operation_id, response } => { + let subscription: StripeSubscription = if schedule_id.is_some() { + stripe + .subscription(&subscription_id) + .await + .map_err(provider_runtime_error)? + } else { + serde_json::from_value(response) + .map_err(|error| RuntimeError::json("invalid Stripe subscription response", error))? + }; + let result = subscription_result(&subscription, plan); + let snapshot = super::super::snapshot::stripe_subscription_snapshot( + &self.pool, + stripe, + subscription, + Vec::new(), + Some(OperationCompletion { + operation_id, + result: result.clone(), + }), + ) + .await?; + changes.extend(self.apply_in_connection(connection, snapshot).await?); + Ok(result) + } + } + }, ) - } else { - ( - format!("v1/subscriptions/{}", encode_segment(&subscription_id)), - direct_form, - ) - }; - let intent = stripe_operation( - namespace.clone(), - mutation.as_str(), - intent_id, - locked.resources.clone(), - Some((target_type, target_id)), - &path, - form, - ); - match self - .execute_locked_stripe_operation(locked.connection, intent, workspace_actor) - .await? - { - OperationExecution::Completed(result) => Ok(result), - OperationExecution::Sent { - connection, - operation_id, - response, - } => { - let subscription: StripeSubscription = if schedule_id.is_some() { - stripe - .subscription(&subscription_id) - .await - .map_err(provider_runtime_error)? - } else { - serde_json::from_value(response) - .map_err(|error| RuntimeError::json("invalid Stripe subscription response", error))? - }; - let result = subscription_result(&subscription, plan); - let snapshot = super::super::snapshot::stripe_subscription_snapshot( - &self.pool, - stripe, - subscription, - Vec::new(), - Some(OperationCompletion { - operation_id, - result: result.clone(), - }), - ) - .await?; - changes.extend(self.apply_with_connection(connection, snapshot).await?); - Ok(result) - } - } + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/recovery.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/recovery.rs index 19beab411f..4846faee7e 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/recovery.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/recovery.rs @@ -44,38 +44,37 @@ pub(in crate::runtime::backend_runtime::payment) async fn recover_one_stripe_ope .map_err(|error| RuntimeError::json("decode pending Stripe operation", error))?, }; let reserves_trial = checkout_reserves_trial(&intent.steps); - let OperationExecution::Sent { - connection, - operation_id, - response, - } = runtime.execute_stripe_operation(intent).await? - else { - return Ok(None); - }; - let snapshot = match operation_type.as_str() { - "create_customer" => recover_customer( - stripe.namespace().clone(), - target_type, - target_id, - operation_id, - response, - )?, - "create_checkout" | "purchase_checkout" => recover_checkout( - stripe.namespace().clone(), - target_type, - target_id, - operation_id, - response, - reserves_trial, - )?, - "cancel" | "resume" | "update_recurring" | "update_quantity" => { - recover_subscription(runtime, operation_id, target_type, target_id).await? - } - "account_delete_cancel" => recover_account_delete(stripe.namespace().clone(), operation_id, response)?, - "provision_price" => recover_price(stripe.namespace().clone(), operation_id, response)?, - _ => return Err(RuntimeError::invalid_state("unsupported pending Stripe operation")), - }; - runtime.apply_with_connection(connection, snapshot).await.map(Some) + runtime + .with_stripe_operation(intent, async |connection, execution| { + let OperationExecution::Sent { operation_id, response } = execution else { + return Ok(None); + }; + let snapshot = match operation_type.as_str() { + "create_customer" => recover_customer( + stripe.namespace().clone(), + target_type, + target_id, + operation_id, + response, + )?, + "create_checkout" | "purchase_checkout" => recover_checkout( + stripe.namespace().clone(), + target_type, + target_id, + operation_id, + response, + reserves_trial, + )?, + "cancel" | "resume" | "update_recurring" | "update_quantity" => { + recover_subscription(runtime, operation_id, target_type, target_id).await? + } + "account_delete_cancel" => recover_account_delete(stripe.namespace().clone(), operation_id, response)?, + "provision_price" => recover_price(stripe.namespace().clone(), operation_id, response)?, + _ => return Err(RuntimeError::invalid_state("unsupported pending Stripe operation")), + }; + runtime.apply_in_connection(connection, snapshot).await.map(Some) + }) + .await } fn recover_price( diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs index 838eab0c45..3ffd5b699e 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/revenuecat.rs @@ -141,86 +141,83 @@ impl PaymentRuntime { let mut resources = super::super::apply::snapshot_scopes(&provisional, &namespace)?; resources.push(PaymentScope::customer(&namespace, source_customer_id)?); let step_key = format!("payment:{intent_id}:revenuecat-identify"); - let mut connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) + let connection = PaymentConnection::try_acquire(&self.pool, resources.clone()) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let frozen = freeze_operation( - &mut connection, - &OperationIntent { - namespace: client.namespace().clone(), - operation_type: "revenuecat_identify".to_string(), - intent_id: intent_id.to_string(), - resources, - target_type: Some("user".to_string()), - target_id: Some(user_id.to_string()), - steps: vec![PaymentStepState { - key: step_key.clone(), - request: PaymentStep::IdentifyRevenueCat { - source_customer_id: source_customer_id.to_string(), - customer_id: user_id.to_string(), - source_ids: source_ids.clone(), - store_subscription_identifier: transaction_id.to_string(), + connection + .with_release(async |connection| { + let frozen = freeze_operation( + connection, + &OperationIntent { + namespace: client.namespace().clone(), + operation_type: "revenuecat_identify".to_string(), + intent_id: intent_id.to_string(), + resources, + target_type: Some("user".to_string()), + target_id: Some(user_id.to_string()), + steps: vec![PaymentStepState { + key: step_key.clone(), + request: PaymentStep::IdentifyRevenueCat { + source_customer_id: source_customer_id.to_string(), + customer_id: user_id.to_string(), + source_ids: source_ids.clone(), + store_subscription_identifier: transaction_id.to_string(), + }, + first_sent_at: None, + result: None, + }], }, - first_sent_at: None, - result: None, - }], - }, - ) - .await?; - if frozen.status == "completed" { - return Ok(IdentifyOutcome::Confirmed(super::super::PaymentApplyResult::default())); - } - if frozen.status != "pending" { - return Err(RuntimeError::invalid_state("payment_operation_blocked")); - } - if let Some(snapshot) = self - .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) - .await? - { - return self - .apply_with_connection(connection, snapshot) - .await - .map(IdentifyOutcome::Confirmed); - } - if frozen.steps[0].first_sent_at.is_some() { - return Ok(IdentifyOutcome::Pending); - } - if mark_operation_step_sent(&mut connection, &frozen.id, &step_key, Duration::minutes(10)).await? - == PaymentSendDecision::Blocked - { - return Err(RuntimeError::invalid_state("payment_operation_blocked")); - } - let response = match client.identify(source_customer_id, user_id).await { - Ok(response) => response, - Err(error) => { - record_operation_error( - &mut connection, - &frozen.id, - error.code, - error.retryable, - error.uncertain, ) .await?; - return Err(provider_runtime_error(error)); - } - }; - record_operation_step_result( - &mut connection, - &frozen.id, - &step_key, - json!({ "wasCreated": response.was_created }), - ) - .await?; - let Some(snapshot) = self - .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) - .await? - else { - return Ok(IdentifyOutcome::Pending); - }; - self - .apply_with_connection(connection, snapshot) + if frozen.status == "completed" { + return Ok(IdentifyOutcome::Confirmed(super::super::PaymentApplyResult::default())); + } + if frozen.status != "pending" { + return Err(RuntimeError::invalid_state("payment_operation_blocked")); + } + if let Some(snapshot) = self + .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) + .await? + { + return self + .apply_in_connection(connection, snapshot) + .await + .map(IdentifyOutcome::Confirmed); + } + if frozen.steps[0].first_sent_at.is_some() { + return Ok(IdentifyOutcome::Pending); + } + if mark_operation_step_sent(connection, &frozen.id, &step_key, Duration::minutes(10)).await? + == PaymentSendDecision::Blocked + { + return Err(RuntimeError::invalid_state("payment_operation_blocked")); + } + let response = match client.identify(source_customer_id, user_id).await { + Ok(response) => response, + Err(error) => { + record_operation_error(connection, &frozen.id, error.code, error.retryable, error.uncertain).await?; + return Err(provider_runtime_error(error)); + } + }; + record_operation_step_result( + connection, + &frozen.id, + &step_key, + json!({ "wasCreated": response.was_created }), + ) + .await?; + let Some(snapshot) = self + .confirmed_revenuecat_identify(user_id, &source_ids, &frozen.id) + .await? + else { + return Ok(IdentifyOutcome::Pending); + }; + self + .apply_in_connection(connection, snapshot) + .await + .map(IdentifyOutcome::Confirmed) + }) .await - .map(IdentifyOutcome::Confirmed) } async fn confirmed_revenuecat_identify( @@ -328,26 +325,30 @@ pub(in crate::runtime::backend_runtime::payment) async fn recover_one_revenuecat let Some(connection) = PaymentConnection::try_acquire(&runtime.pool, scopes).await? else { return Ok(None); }; - if let Some(snapshot) = runtime - .confirmed_revenuecat_identify(customer_id, source_ids, &operation_id) - .await? - { - return runtime.apply_with_connection(connection, snapshot).await.map(Some); - } - let deadline: Option> = row.get("replay_deadline"); - let now: chrono::DateTime = row.get("now"); - let blocked = deadline.is_some_and(|deadline| deadline <= now); - sqlx::query( - "UPDATE payment_operations SET status=CASE WHEN $2 THEN 'blocked' ELSE status END,next_attempt_at=CASE WHEN $2 \ - THEN NULL ELSE $3 \ - END,last_error_code='revenuecat_identify_unconfirmed',last_error='revenuecat_identify_unconfirmed',updated_at=$3 \ - WHERE id=$1 AND status='pending'", - ) - .bind(&operation_id) - .bind(blocked) - .bind(now + Duration::seconds(5)) - .execute(&runtime.pool) - .await - .map_err(|error| RuntimeError::database("defer RevenueCat identify confirmation", error))?; - Ok(None) + connection + .with_release(async |connection| { + if let Some(snapshot) = runtime + .confirmed_revenuecat_identify(customer_id, source_ids, &operation_id) + .await? + { + return runtime.apply_in_connection(connection, snapshot).await.map(Some); + } + let deadline: Option> = row.get("replay_deadline"); + let now: chrono::DateTime = row.get("now"); + let blocked = deadline.is_some_and(|deadline| deadline <= now); + sqlx::query( + "UPDATE payment_operations SET status=CASE WHEN $2 THEN 'blocked' ELSE status END,next_attempt_at=CASE WHEN \ + $2 THEN NULL ELSE $3 \ + END,last_error_code='revenuecat_identify_unconfirmed',last_error='revenuecat_identify_unconfirmed',\ + updated_at=$3 WHERE id=$1 AND status='pending'", + ) + .bind(&operation_id) + .bind(blocked) + .bind(now + Duration::seconds(5)) + .execute(&runtime.pool) + .await + .map_err(|error| RuntimeError::database("defer RevenueCat identify confirmation", error))?; + Ok(None) + }) + .await } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/schedule.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/schedule.rs index 114fcbb7fb..8307d3bfa6 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/schedule.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/schedule.rs @@ -48,114 +48,117 @@ impl PaymentRuntime { .map_err(subscription_mutation_error)?; let namespace = self.stripe()?.namespace().clone(); let namespace_key = canonical_namespace(&namespace)?; - let mut locked = self - .lock_stripe_subscription(&namespace_key, target_type, target_id, plan) - .await?; - if target_type == "instance" { - assert_license_access(locked.connection.connection(), target_id, validate_key).await?; - } - let stored_recurring = locked - .recurring - .as_deref() - .and_then(SubscriptionRecurring::parse) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; - validate_subscription_mutation( - plan, - billing_target(target_type)?, - stored_recurring, - locked.canceled_at.is_some(), - SubscriptionMutation::ChangeRecurring(recurring), - ) - .map_err(subscription_mutation_error)?; - let subscription_id = locked.subscription_id.clone(); - let phase_anchor = locked - .period_start - .map(|value| value.timestamp()) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; - let lookup_key = stripe_lookup_key(plan, recurring, None)?; - let price = self.find_price(&lookup_key, recurring).await?; - let steps = if let Some(schedule_id) = locked.metadata.get("stripeScheduleId").and_then(Value::as_str) { - let schedule = self - .stripe()? - .subscription_schedule(schedule_id) - .await - .map_err(provider_runtime_error)?; - validate_subscription(&schedule, &subscription_id)?; - vec![PaymentStepState { - key: format!("payment:{intent_id}:schedule-update"), - request: PaymentStep::StripePost { - path: format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), - api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), - form: recurring_fields(&schedule, phase_anchor, &price.id)?, + self + .with_locked_stripe_subscription( + &namespace_key, + target_type, + target_id, + plan, + async |connection, locked| { + if target_type == "instance" { + assert_license_access(connection.connection(), target_id, validate_key).await?; + } + let stored_recurring = locked + .recurring + .as_deref() + .and_then(SubscriptionRecurring::parse) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; + validate_subscription_mutation( + plan, + billing_target(target_type)?, + stored_recurring, + locked.canceled_at.is_some(), + SubscriptionMutation::ChangeRecurring(recurring), + ) + .map_err(subscription_mutation_error)?; + let subscription_id = locked.subscription_id.clone(); + let phase_anchor = locked + .period_start + .map(|value| value.timestamp()) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; + let lookup_key = stripe_lookup_key(plan, recurring, None)?; + let price = self.find_price(&lookup_key, recurring).await?; + let steps = if let Some(schedule_id) = locked.metadata.get("stripeScheduleId").and_then(Value::as_str) { + let schedule = self + .stripe()? + .subscription_schedule(schedule_id) + .await + .map_err(provider_runtime_error)?; + validate_subscription(&schedule, &subscription_id)?; + vec![PaymentStepState { + key: format!("payment:{intent_id}:schedule-update"), + request: PaymentStep::StripePost { + path: format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), + api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), + form: recurring_fields(&schedule, phase_anchor, &price.id)?, + }, + first_sent_at: None, + result: None, + }] + } else { + let create_key = format!("payment:{intent_id}:schedule-create"); + vec![ + PaymentStepState { + key: create_key.clone(), + request: PaymentStep::StripePost { + path: "v1/subscription_schedules".to_string(), + api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), + form: vec![text_field("from_subscription", &subscription_id)], + }, + first_sent_at: None, + result: None, + }, + PaymentStepState { + key: format!("payment:{intent_id}:schedule-update"), + request: PaymentStep::StripeUpdateScheduleRecurring { + schedule_step_key: create_key, + price_id: price.id, + phase_anchor, + }, + first_sent_at: None, + result: None, + }, + ] + }; + let intent = OperationIntent { + namespace: namespace.clone(), + operation_type: "update_recurring".to_string(), + intent_id: intent_id.to_string(), + resources: locked.resources.clone(), + target_type: Some(target_type.to_string()), + target_id: Some(target_id.to_string()), + steps, + }; + match self + .execute_locked_stripe_operation(connection, intent, workspace_actor) + .await? + { + OperationExecution::Completed(result) => Ok(result), + OperationExecution::Sent { operation_id, .. } => { + let subscription = self + .stripe()? + .subscription(&subscription_id) + .await + .map_err(provider_runtime_error)?; + let result = subscription_result(&subscription, plan); + let snapshot = super::super::snapshot::stripe_subscription_snapshot( + &self.pool, + self.stripe()?, + subscription, + Vec::new(), + Some(OperationCompletion { + operation_id, + result: result.clone(), + }), + ) + .await?; + changes.extend(self.apply_in_connection(connection, snapshot).await?); + Ok(result) + } + } }, - first_sent_at: None, - result: None, - }] - } else { - let create_key = format!("payment:{intent_id}:schedule-create"); - vec![ - PaymentStepState { - key: create_key.clone(), - request: PaymentStep::StripePost { - path: "v1/subscription_schedules".to_string(), - api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), - form: vec![text_field("from_subscription", &subscription_id)], - }, - first_sent_at: None, - result: None, - }, - PaymentStepState { - key: format!("payment:{intent_id}:schedule-update"), - request: PaymentStep::StripeUpdateScheduleRecurring { - schedule_step_key: create_key, - price_id: price.id, - phase_anchor, - }, - first_sent_at: None, - result: None, - }, - ] - }; - let intent = OperationIntent { - namespace: namespace.clone(), - operation_type: "update_recurring".to_string(), - intent_id: intent_id.to_string(), - resources: locked.resources.clone(), - target_type: Some(target_type.to_string()), - target_id: Some(target_id.to_string()), - steps, - }; - match self - .execute_locked_stripe_operation(locked.connection, intent, workspace_actor) - .await? - { - OperationExecution::Completed(result) => Ok(result), - OperationExecution::Sent { - connection, - operation_id, - .. - } => { - let subscription = self - .stripe()? - .subscription(&subscription_id) - .await - .map_err(provider_runtime_error)?; - let result = subscription_result(&subscription, plan); - let snapshot = super::super::snapshot::stripe_subscription_snapshot( - &self.pool, - self.stripe()?, - subscription, - Vec::new(), - Some(OperationCompletion { - operation_id, - result: result.clone(), - }), - ) - .await?; - changes.extend(self.apply_with_connection(connection, snapshot).await?); - Ok(result) - } - } + ) + .await } pub(super) async fn update_quantity( @@ -195,127 +198,130 @@ impl PaymentRuntime { .map_err(subscription_mutation_error)?; let namespace = self.stripe()?.namespace().clone(); let namespace_key = canonical_namespace(&namespace)?; - let mut locked = self - .lock_stripe_subscription(&namespace_key, target_type, target_id, plan) - .await?; - if target_type == "instance" { - assert_license_access(locked.connection.connection(), target_id, validate_key).await?; - } - let stored_recurring = locked - .recurring - .as_deref() - .and_then(SubscriptionRecurring::parse) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; - validate_subscription_mutation( - plan, - billing_target(target_type)?, - stored_recurring, - locked.canceled_at.is_some(), - SubscriptionMutation::ChangeQuantity(quantity), - ) - .map_err(subscription_mutation_error)?; - if locked.quantity == i32::try_from(quantity).ok() { - return Ok(json!({ "status": "unchanged", "quantity": quantity })); - } - let subscription_id = locked.subscription_id.clone(); - let remote_subscription = self - .stripe()? - .subscription(&subscription_id) - .await - .map_err(provider_runtime_error)?; - let item_id = match remote_subscription.items.data.as_slice() { - [item] => item.id.clone(), - _ => { - return Err(RuntimeError::invalid_state( - "payment subscription items are not canonical", - )); - } - }; - let recurring = stored_recurring; - let phase_anchor = locked - .period_start - .map(|value| value.timestamp()) - .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; - let mut steps = vec![PaymentStepState { - key: format!("payment:{intent_id}:subscription-quantity"), - request: PaymentStep::StripePost { - path: format!("v1/subscriptions/{}", encode_segment(&subscription_id)), - api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), - form: vec![ - text_field("items[0][id]", &item_id), - text_field("items[0][quantity]", quantity.to_string()), - text_field("payment_behavior", "pending_if_incomplete"), - text_field( - "proration_behavior", - if recurring == SubscriptionRecurring::Yearly { - "always_invoice" - } else { - "none" + self + .with_locked_stripe_subscription( + &namespace_key, + target_type, + target_id, + plan, + async |connection, locked| { + if target_type == "instance" { + assert_license_access(connection.connection(), target_id, validate_key).await?; + } + let stored_recurring = locked + .recurring + .as_deref() + .and_then(SubscriptionRecurring::parse) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription recurring is invalid"))?; + validate_subscription_mutation( + plan, + billing_target(target_type)?, + stored_recurring, + locked.canceled_at.is_some(), + SubscriptionMutation::ChangeQuantity(quantity), + ) + .map_err(subscription_mutation_error)?; + if locked.quantity == i32::try_from(quantity).ok() { + return Ok(json!({ "status": "unchanged", "quantity": quantity })); + } + let subscription_id = locked.subscription_id.clone(); + let remote_subscription = self + .stripe()? + .subscription(&subscription_id) + .await + .map_err(provider_runtime_error)?; + let item_id = match remote_subscription.items.data.as_slice() { + [item] => item.id.clone(), + _ => { + return Err(RuntimeError::invalid_state( + "payment subscription items are not canonical", + )); + } + }; + let recurring = stored_recurring; + let phase_anchor = locked + .period_start + .map(|value| value.timestamp()) + .ok_or_else(|| RuntimeError::invalid_state("payment subscription period is missing"))?; + let mut steps = vec![PaymentStepState { + key: format!("payment:{intent_id}:subscription-quantity"), + request: PaymentStep::StripePost { + path: format!("v1/subscriptions/{}", encode_segment(&subscription_id)), + api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), + form: vec![ + text_field("items[0][id]", &item_id), + text_field("items[0][quantity]", quantity.to_string()), + text_field("payment_behavior", "pending_if_incomplete"), + text_field( + "proration_behavior", + if recurring == SubscriptionRecurring::Yearly { + "always_invoice" + } else { + "none" + }, + ), + ], }, - ), - ], - }, - first_sent_at: None, - result: None, - }]; - if let Some(schedule_id) = locked.metadata.get("stripeScheduleId").and_then(Value::as_str) { - let schedule = self - .stripe()? - .subscription_schedule(schedule_id) - .await - .map_err(provider_runtime_error)?; - validate_subscription(&schedule, &subscription_id)?; - steps.push(PaymentStepState { - key: format!("payment:{intent_id}:schedule-quantity"), - request: PaymentStep::StripePost { - path: format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), - api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), - form: quantity_fields(&schedule, phase_anchor, quantity)?, + first_sent_at: None, + result: None, + }]; + if let Some(schedule_id) = locked.metadata.get("stripeScheduleId").and_then(Value::as_str) { + let schedule = self + .stripe()? + .subscription_schedule(schedule_id) + .await + .map_err(provider_runtime_error)?; + validate_subscription(&schedule, &subscription_id)?; + steps.push(PaymentStepState { + key: format!("payment:{intent_id}:schedule-quantity"), + request: PaymentStep::StripePost { + path: format!("v1/subscription_schedules/{}", encode_segment(schedule_id)), + api_version: super::super::stripe_client::STRIPE_API_VERSION.to_string(), + form: quantity_fields(&schedule, phase_anchor, quantity)?, + }, + first_sent_at: None, + result: None, + }); + } + let intent = OperationIntent { + namespace: namespace.clone(), + operation_type: "update_quantity".to_string(), + intent_id: intent_id.to_string(), + resources: locked.resources.clone(), + target_type: Some(target_type.to_string()), + target_id: Some(target_id.to_string()), + steps, + }; + match self + .execute_locked_stripe_operation(connection, intent, workspace_actor) + .await? + { + OperationExecution::Completed(result) => Ok(result), + OperationExecution::Sent { operation_id, .. } => { + let subscription = self + .stripe()? + .subscription(&subscription_id) + .await + .map_err(provider_runtime_error)?; + let result = subscription_result(&subscription, plan); + let snapshot = super::super::snapshot::stripe_subscription_snapshot( + &self.pool, + self.stripe()?, + subscription, + Vec::new(), + Some(OperationCompletion { + operation_id, + result: result.clone(), + }), + ) + .await?; + changes.extend(self.apply_in_connection(connection, snapshot).await?); + Ok(result) + } + } }, - first_sent_at: None, - result: None, - }); - } - let intent = OperationIntent { - namespace: namespace.clone(), - operation_type: "update_quantity".to_string(), - intent_id: intent_id.to_string(), - resources: locked.resources.clone(), - target_type: Some(target_type.to_string()), - target_id: Some(target_id.to_string()), - steps, - }; - match self - .execute_locked_stripe_operation(locked.connection, intent, workspace_actor) - .await? - { - OperationExecution::Completed(result) => Ok(result), - OperationExecution::Sent { - connection, - operation_id, - .. - } => { - let subscription = self - .stripe()? - .subscription(&subscription_id) - .await - .map_err(provider_runtime_error)?; - let result = subscription_result(&subscription, plan); - let snapshot = super::super::snapshot::stripe_subscription_snapshot( - &self.pool, - self.stripe()?, - subscription, - Vec::new(), - Some(OperationCompletion { - operation_id, - result: result.clone(), - }), - ) - .await?; - changes.extend(self.apply_with_connection(connection, snapshot).await?); - Ok(result) - } - } + ) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/command/stripe_checkout.rs b/packages/backend/native/src/runtime/backend_runtime/payment/command/stripe_checkout.rs index 09e85d7376..bd862ec28e 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/command/stripe_checkout.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/command/stripe_checkout.rs @@ -67,55 +67,59 @@ impl PaymentRuntime { let stripe = self.stripe()?; let namespace = canonical_namespace(stripe.namespace())?; let scope = PaymentScope::cloud_target("user", user_id, plan)?; - let mut connection = PaymentConnection::try_acquire(&self.pool, vec![scope.clone()]) + let connection = PaymentConnection::try_acquire(&self.pool, vec![scope.clone()]) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let now = purchase_time(&mut connection).await?; - let Some(attempt) = open_purchase(&mut connection, &scope, now).await? else { - return Ok(Value::Bool(true)); - }; - if attempt.id != attempt_id - || attempt.operation_type != "purchase_checkout" - || attempt.namespace != namespace - || attempt.status != "waiting" - { - return Ok(Value::Bool(false)); - } - let session_id = attempt - .result - .as_ref() - .and_then(|value| value["sessionId"].as_str()) - .ok_or_else(|| RuntimeError::invalid_state("missing checkout session"))?; - let session = stripe - .checkout_session(session_id) - .await - .map_err(provider_runtime_error)?; - let expired = match session.status.as_deref() { - Some("expired") => true, - Some("open") => { - let path = format!("v1/checkout/sessions/{}/expire", encode_segment(session_id)); - match stripe - .post::(&path, &StripeForm::default(), &format!("payment:{}:expire", attempt.id)) - .await + connection + .with_release(async |connection| { + let now = purchase_time(connection).await?; + let Some(attempt) = open_purchase(connection, &scope, now).await? else { + return Ok(Value::Bool(true)); + }; + if attempt.id != attempt_id + || attempt.operation_type != "purchase_checkout" + || attempt.namespace != namespace + || attempt.status != "waiting" { - Ok(session) => session.status.as_deref() == Some("expired"), - Err(_) => { - stripe - .checkout_session(session_id) - .await - .map_err(provider_runtime_error)? - .status - .as_deref() - == Some("expired") - } + return Ok(Value::Bool(false)); } - } - _ => false, - }; - if expired { - finish_purchase(&mut connection, &attempt.id, "expired").await?; - } - Ok(Value::Bool(expired)) + let session_id = attempt + .result + .as_ref() + .and_then(|value| value["sessionId"].as_str()) + .ok_or_else(|| RuntimeError::invalid_state("missing checkout session"))?; + let session = stripe + .checkout_session(session_id) + .await + .map_err(provider_runtime_error)?; + let expired = match session.status.as_deref() { + Some("expired") => true, + Some("open") => { + let path = format!("v1/checkout/sessions/{}/expire", encode_segment(session_id)); + match stripe + .post::(&path, &StripeForm::default(), &format!("payment:{}:expire", attempt.id)) + .await + { + Ok(session) => session.status.as_deref() == Some("expired"), + Err(_) => { + stripe + .checkout_session(session_id) + .await + .map_err(provider_runtime_error)? + .status + .as_deref() + == Some("expired") + } + } + } + _ => false, + }; + if expired { + finish_purchase(connection, &attempt.id, "expired").await?; + } + Ok(Value::Bool(expired)) + }) + .await } } @@ -129,7 +133,7 @@ pub(in crate::runtime::backend_runtime::payment) async fn stripe_checkout_receip .and_then(Value::as_str) .ok_or_else(|| RuntimeError::invalid_input("Stripe checkout receipt has no identity"))?; sqlx::query( - "UPDATE payment_operations SET next_attempt_at=clock_timestamp() + "UPDATE payment_operations SET next_attempt_at=date_trunc('milliseconds', clock_timestamp()) WHERE provider_namespace=$1 AND operation_type='purchase_checkout' AND status='waiting' AND result->>'sessionId'=$2", ) @@ -191,56 +195,61 @@ pub(in crate::runtime::backend_runtime::payment) async fn recover_waiting_checko if let Some(customer) = session.customer.as_ref() { scopes.push(PaymentScope::customer(&namespace, customer.id())?); } - let Some(mut connection) = PaymentConnection::try_acquire(&runtime.pool, scopes).await? else { + let Some(connection) = PaymentConnection::try_acquire(&runtime.pool, scopes).await? else { return Ok(None); }; - for _ in 0..=4 { - let observed_at = chrono::Utc::now(); - let mut snapshot = if let Some(invoice) = session.invoice.as_ref() { - let invoice = stripe.invoice(invoice.id()).await.map_err(provider_runtime_error)?; - stripe_invoice_snapshot(&runtime.pool, stripe, invoice, Vec::new(), observed_at).await? - } else if let Some(subscription) = session.subscription.as_ref() { - let subscription = stripe - .subscription(subscription.id()) - .await - .map_err(provider_runtime_error)?; - stripe_subscription_snapshot(&runtime.pool, stripe, subscription, Vec::new(), None).await? - } else { - return Ok(None); - }; - if !snapshot - .subscriptions - .iter() - .any(|source| source.target_type == "user" && source.target_id == target_id && source.source_id == source_id) - { - return Err(RuntimeError::invalid_state( - "Stripe checkout source target does not match", - )); - } - snapshot.operation = Some(OperationCompletion { - operation_id: operation_id.clone(), - result: result.clone(), - }); - match apply_payment_snapshot(&mut connection, snapshot, runtime.deployment, &runtime.mail_hash_key).await { - Ok(changes) => return Ok(Some(changes)), - Err(PaymentApplyError::Runtime(error)) => return Err(error), - Err(PaymentApplyError::LockSetExpanded(expansion)) => { - let Some(reacquired) = connection.reacquire_with(&runtime.pool, expansion).await? else { + return connection + .with_release(async |connection| { + for _ in 0..=4 { + let observed_at = chrono::Utc::now(); + let mut snapshot = if let Some(invoice) = session.invoice.as_ref() { + let invoice = stripe.invoice(invoice.id()).await.map_err(provider_runtime_error)?; + stripe_invoice_snapshot(&runtime.pool, stripe, invoice, Vec::new(), observed_at).await? + } else if let Some(subscription) = session.subscription.as_ref() { + let subscription = stripe + .subscription(subscription.id()) + .await + .map_err(provider_runtime_error)?; + stripe_subscription_snapshot(&runtime.pool, stripe, subscription, Vec::new(), None).await? + } else { return Ok(None); }; - connection = reacquired; + if !snapshot.subscriptions.iter().any(|source| { + source.target_type == "user" && source.target_id == target_id && source.source_id == source_id + }) { + return Err(RuntimeError::invalid_state( + "Stripe checkout source target does not match", + )); + } + snapshot.operation = Some(OperationCompletion { + operation_id: operation_id.clone(), + result: result.clone(), + }); + match apply_payment_snapshot(connection, snapshot, runtime.deployment, &runtime.mail_hash_key).await { + Ok(changes) => return Ok(Some(changes)), + Err(PaymentApplyError::Runtime(error)) => return Err(error), + Err(PaymentApplyError::LockSetExpanded(expansion)) => { + if !connection.reacquire_with(&runtime.pool, expansion).await? { + return Ok(None); + } + } + } } - } - } - return Err(RuntimeError::invalid_state("payment_busy")); + Err(RuntimeError::invalid_state("payment_busy")) + }) + .await; } - let Some(mut connection) = PaymentConnection::try_acquire(&runtime.pool, vec![scope]).await? else { + let Some(connection) = PaymentConnection::try_acquire(&runtime.pool, vec![scope]).await? else { return Ok(None); }; - if let Some((reason, _)) = - stripe_checkout_termination(connection.connection(), stripe, &namespace, &session, None).await? - { - finish_purchase(&mut connection, &operation_id, reason).await?; - } - Ok(None) + connection + .with_release(async |connection| { + if let Some((reason, _)) = + stripe_checkout_termination(connection.connection(), stripe, &namespace, &session, None).await? + { + finish_purchase(connection, &operation_id, reason).await?; + } + Ok(None) + }) + .await } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/connection.rs b/packages/backend/native/src/runtime/backend_runtime/payment/connection.rs index adf2de40c8..1e02e43c8a 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/connection.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/connection.rs @@ -89,7 +89,7 @@ pub(super) fn required_scope_expansion( } pub(super) struct PaymentConnection { - connection: PoolConnection, + connection: Option>, scopes: Vec, } @@ -126,36 +126,61 @@ impl PaymentConnection { } acquired_any = true; } - Ok(Some(Self { connection, scopes })) + Ok(Some(Self { + connection: Some(connection), + scopes, + })) } pub(super) fn scopes(&self) -> &[PaymentScope] { &self.scopes } - pub(super) async fn release(mut self) -> RuntimeResult<()> { + pub(super) async fn with_release( + mut self, + work: impl AsyncFnOnce(&mut PaymentConnection) -> RuntimeResult, + ) -> RuntimeResult { + let result = work(&mut self).await; + let _ = self.release().await; + result + } + + pub(super) async fn release_locks(&mut self) -> RuntimeResult<()> { + let Some(mut connection) = self.connection.take() else { + return Ok(()); + }; let unlock_res = sqlx::query("SELECT pg_advisory_unlock_all()") - .execute(&mut *self.connection) + .execute(&mut *connection) .await; - let _ = self.connection.close().await; + let _ = connection.close().await; unlock_res .map(|_| ()) .map_err(|error| RuntimeError::database("release payment session locks", error)) } - pub(super) async fn reacquire_with(self, pool: &PgPool, required: Vec) -> RuntimeResult> { + pub(super) async fn release(mut self) -> RuntimeResult<()> { + self.release_locks().await + } + + pub(super) async fn reacquire_with(&mut self, pool: &PgPool, required: Vec) -> RuntimeResult { let scopes = self.scopes.iter().cloned().chain(required).collect::>(); - self.release().await?; - Self::try_acquire(pool, scopes).await + self.release_locks().await?; + if let Some(reacquired) = Self::try_acquire(pool, scopes).await? { + self.connection = reacquired.connection; + self.scopes = reacquired.scopes; + Ok(true) + } else { + Ok(false) + } } pub(super) fn connection(&mut self) -> &mut sqlx::PgConnection { - &mut self.connection + self.connection.as_deref_mut().expect("payment connection is active") } pub(super) async fn begin(&mut self) -> RuntimeResult> { self - .connection + .connection() .begin() .await .map_err(|error| RuntimeError::database("begin payment transaction", error)) diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/financial_reconcile.rs b/packages/backend/native/src/runtime/backend_runtime/payment/financial_reconcile.rs index b864a786df..3769dc859d 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/financial_reconcile.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/financial_reconcile.rs @@ -59,8 +59,12 @@ async fn reconcile_financial( let connection = PaymentConnection::try_acquire(&runtime.pool, resources) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let snapshot = recover_financial(runtime, candidate).await?; - runtime.apply_with_connection(connection, snapshot).await + connection + .with_release(async |connection| { + let snapshot = recover_financial(runtime, candidate).await?; + runtime.apply_in_connection(connection, snapshot).await + }) + .await } async fn recover_financial(runtime: &PaymentRuntime, candidate: &FinancialCandidate) -> RuntimeResult { diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/ops/mod.rs b/packages/backend/native/src/runtime/backend_runtime/payment/ops/mod.rs index 02eaa1db79..8de8bb0a79 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/ops/mod.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/ops/mod.rs @@ -89,259 +89,261 @@ impl PaymentRuntime { let family_scope = PaymentScope::cloud_target("user", &request.user_id, plan)?; let request_scope = PaymentScope::billing_target("payment:v1:cloud", "reconciliation", &request.request_id)?; - let mut connection = PaymentConnection::try_acquire(&self.pool, vec![family_scope, request_scope]) + let connection = PaymentConnection::try_acquire(&self.pool, vec![family_scope, request_scope]) .await? .ok_or_else(payment_busy)?; - for _ in 0..=4 { - if let Some(value) = request.replay(connection.connection()).await? { - return Ok(value); - } - let before = request.load_case(connection.connection()).await?; - let attempt = request.attempt(&before)?; - if let (Some(attempt), Some(transaction)) = (attempt, request.transaction_id.as_deref()) { - if attempt.provider != "revenuecat" { - return Err(RuntimeError::invalid_input( - "Stripe reconciliation uses the recorded checkout session", - )); - } - if attempt - .transaction_id - .as_deref() - .is_some_and(|recorded| recorded != transaction) - { - return Err(RuntimeError::invalid_input( - "App Store reconciliation transaction changed", - )); - } - } - if attempt.is_none() && !before.conflicted { - return Err(RuntimeError::invalid_input( - "no payment reconciliation case for this family", - )); - } - let stripe_namespace = namespace(self.stripe.as_deref().map(StripeClient::namespace))?; - let revenuecat_namespace = namespace(self.revenuecat.as_ref().map(|client| client.namespace()))?; - let stripe_customer = if let Some(namespace) = stripe_namespace.as_deref() { - load_stripe_customer(&self.pool, &request.user_id, namespace).await? - } else { - None - }; - - let mut required = Vec::new(); - for source in &before.sources { - if let (Some(namespace), Some(source_id)) = (&source.provider_namespace, &source.source_identity) { - required.push(PaymentScope::source(namespace, source_id)?); - for fact in &source.financial_facts { - required.push(PaymentScope::financial(namespace, &fact.kind, &fact.id)?); + connection + .with_release(async |connection| { + for _ in 0..=4 { + if let Some(value) = request.replay(connection.connection()).await? { + return Ok(value); } - if let Some(customer) = &source.external_customer_id { + let before = request.load_case(connection.connection()).await?; + let attempt = request.attempt(&before)?; + if let (Some(attempt), Some(transaction)) = (attempt, request.transaction_id.as_deref()) { + if attempt.provider != "revenuecat" { + return Err(RuntimeError::invalid_input( + "Stripe reconciliation uses the recorded checkout session", + )); + } + if attempt + .transaction_id + .as_deref() + .is_some_and(|recorded| recorded != transaction) + { + return Err(RuntimeError::invalid_input( + "App Store reconciliation transaction changed", + )); + } + } + if attempt.is_none() && !before.conflicted { + return Err(RuntimeError::invalid_input( + "no payment reconciliation case for this family", + )); + } + let stripe_namespace = namespace(self.stripe.as_deref().map(StripeClient::namespace))?; + let revenuecat_namespace = namespace(self.revenuecat.as_ref().map(|client| client.namespace()))?; + let stripe_customer = if let Some(namespace) = stripe_namespace.as_deref() { + load_stripe_customer(&self.pool, &request.user_id, namespace).await? + } else { + None + }; + + let mut required = Vec::new(); + for source in &before.sources { + if let (Some(namespace), Some(source_id)) = (&source.provider_namespace, &source.source_identity) { + required.push(PaymentScope::source(namespace, source_id)?); + for fact in &source.financial_facts { + required.push(PaymentScope::financial(namespace, &fact.kind, &fact.id)?); + } + if let Some(customer) = &source.external_customer_id { + required.push(PaymentScope::customer(namespace, customer)?); + } + } + } + if let (Some(namespace), Some(customer)) = (&stripe_namespace, &stripe_customer) { required.push(PaymentScope::customer(namespace, customer)?); } - } - } - if let (Some(namespace), Some(customer)) = (&stripe_namespace, &stripe_customer) { - required.push(PaymentScope::customer(namespace, customer)?); - } - if let Some(namespace) = &revenuecat_namespace { - required.push(PaymentScope::customer(namespace, &request.user_id)?); - } - let expansion = required_scope_expansion(connection.scopes(), required); - if !expansion.is_empty() { - connection = connection - .reacquire_with(&self.pool, expansion) - .await? - .ok_or_else(payment_busy)?; - continue; - } - - let all_providers_verified = !(before.conflicted - && (stripe_namespace.is_none() || revenuecat_namespace.is_none())) - && before.sources.iter().all(|source| { - source.source_identity.is_some() - && match Provider::parse(&source.provider) { - Some(Provider::Stripe) => stripe_customer.is_some() && source.provider_namespace == stripe_namespace, - Some(Provider::RevenueCat) => { - self.revenuecat.is_some() && source.provider_namespace == revenuecat_namespace - } - None => false, - } - }); - let mut snapshots = Vec::new(); - let mut stripe_completion = None; - let mut app_store_completion = None; - let mut attempt_observation = Value::Null; - if all_providers_verified { - let stripe_invoices = if let (Some(client), Some(namespace), Some(customer)) = ( - self.stripe.as_ref(), - stripe_namespace.as_deref(), - stripe_customer.as_deref(), - ) { - let (stripe_snapshots, invoices) = observe_stripe(self, client, namespace, customer, &before, family).await?; - snapshots.extend(stripe_snapshots); - invoices - } else { - Default::default() - }; - if let Some(attempt) = attempt.filter(|attempt| attempt.status == "waiting") { - if attempt.provider == "stripe" && stripe_namespace.as_deref() == Some(&attempt.provider_namespace) { - let client = self.stripe.as_ref().expect("configured Stripe namespace"); - let (result, observation) = observe_checkout( - &mut connection, - client, - attempt, - stripe_customer.as_deref(), - &snapshots, - &stripe_invoices, - ) - .await?; - stripe_completion = result.map(|reason| (attempt.id.as_str(), reason)); - attempt_observation = observation; - } else if attempt.provider == "revenuecat" - && revenuecat_namespace.as_deref() == Some(&attempt.provider_namespace) - && let (Some(product_id), Some(transaction_id)) = ( - attempt.product_id.as_deref(), - request.transaction_id.as_deref().or(attempt.transaction_id.as_deref()), - ) - { - let transaction = AppStoreTransaction { - namespace: &attempt.provider_namespace, - user_id: &request.user_id, - product_id, - transaction_id, - family, - }; - let client = self.revenuecat.as_ref().expect("configured RevenueCat namespace"); - let (source_id, observation) = observe_app_store_attempt(client, &transaction).await?; - app_store_completion = source_id.map(|source_id| (attempt.id.as_str(), transaction, source_id)); - attempt_observation = observation; + if let Some(namespace) = &revenuecat_namespace { + required.push(PaymentScope::customer(namespace, &request.user_id)?); } - } - if self.revenuecat.is_some() { - snapshots.push(self.observe_revenuecat_customer(&request.user_id).await?); - } - } - - let mut required = Vec::new(); - let mut prepared = Vec::with_capacity(snapshots.len()); - for snapshot in snapshots { - let (namespace, expansion) = check_snapshot_scopes(&mut connection, &snapshot).await?; - required.extend(expansion); - for fact in &snapshot.financial_facts { - required.push(PaymentScope::financial( - &namespace, - fact.fact.kind.as_str(), - &fact.external_id, - )?); - } - prepared.push((snapshot, namespace)); - } - let expansion = required_scope_expansion(connection.scopes(), required); - if !expansion.is_empty() { - connection = connection - .reacquire_with(&self.pool, expansion) - .await? - .ok_or_else(payment_busy)?; - continue; - } - - let scopes = connection.scopes().to_vec(); - let mut tx = connection.begin().await?; - let settlement = all_providers_verified.then_some(BindingSettlement { - user_id: &request.user_id, - family: family.as_str(), - }); - let applied = if all_providers_verified { - match apply_locked_snapshots( - &mut tx, - &prepared, - &scopes, - self.deployment, - &self.mail_hash_key, - settlement.as_ref(), - ) - .await - { - Ok(applied) => applied, - Err(PaymentApplyError::Runtime(error)) => return Err(error), - Err(PaymentApplyError::LockSetExpanded(expansion)) => { - tx.rollback() - .await - .map_err(|error| RuntimeError::database("rollback payment reconciliation", error))?; - connection = connection - .reacquire_with(&self.pool, expansion) - .await? - .ok_or_else(payment_busy)?; + let expansion = required_scope_expansion(connection.scopes(), required); + if !expansion.is_empty() { + if !connection.reacquire_with(&self.pool, expansion).await? { + return Err(payment_busy()); + } continue; } + + let all_providers_verified = !(before.conflicted + && (stripe_namespace.is_none() || revenuecat_namespace.is_none())) + && before.sources.iter().all(|source| { + source.source_identity.is_some() + && match Provider::parse(&source.provider) { + Some(Provider::Stripe) => stripe_customer.is_some() && source.provider_namespace == stripe_namespace, + Some(Provider::RevenueCat) => { + self.revenuecat.is_some() && source.provider_namespace == revenuecat_namespace + } + None => false, + } + }); + let mut snapshots = Vec::new(); + let mut stripe_completion = None; + let mut app_store_completion = None; + let mut attempt_observation = Value::Null; + if all_providers_verified { + let stripe_invoices = if let (Some(client), Some(namespace), Some(customer)) = ( + self.stripe.as_ref(), + stripe_namespace.as_deref(), + stripe_customer.as_deref(), + ) { + let (stripe_snapshots, invoices) = + observe_stripe(self, client, namespace, customer, &before, family).await?; + snapshots.extend(stripe_snapshots); + invoices + } else { + Default::default() + }; + if let Some(attempt) = attempt.filter(|attempt| attempt.status == "waiting") { + if attempt.provider == "stripe" && stripe_namespace.as_deref() == Some(&attempt.provider_namespace) { + let client = self.stripe.as_ref().expect("configured Stripe namespace"); + let (result, observation) = observe_checkout( + connection, + client, + attempt, + stripe_customer.as_deref(), + &snapshots, + &stripe_invoices, + ) + .await?; + stripe_completion = result.map(|reason| (attempt.id.as_str(), reason)); + attempt_observation = observation; + } else if attempt.provider == "revenuecat" + && revenuecat_namespace.as_deref() == Some(&attempt.provider_namespace) + && let (Some(product_id), Some(transaction_id)) = ( + attempt.product_id.as_deref(), + request.transaction_id.as_deref().or(attempt.transaction_id.as_deref()), + ) + { + let transaction = AppStoreTransaction { + namespace: &attempt.provider_namespace, + user_id: &request.user_id, + product_id, + transaction_id, + family, + }; + let client = self.revenuecat.as_ref().expect("configured RevenueCat namespace"); + let (source_id, observation) = observe_app_store_attempt(client, &transaction).await?; + app_store_completion = source_id.map(|source_id| (attempt.id.as_str(), transaction, source_id)); + attempt_observation = observation; + } + } + if self.revenuecat.is_some() { + snapshots.push(self.observe_revenuecat_customer(&request.user_id).await?); + } + } + + let mut required = Vec::new(); + let mut prepared = Vec::with_capacity(snapshots.len()); + for snapshot in snapshots { + let (namespace, expansion) = check_snapshot_scopes(connection, &snapshot).await?; + required.extend(expansion); + for fact in &snapshot.financial_facts { + required.push(PaymentScope::financial( + &namespace, + fact.fact.kind.as_str(), + &fact.external_id, + )?); + } + prepared.push((snapshot, namespace)); + } + let expansion = required_scope_expansion(connection.scopes(), required); + if !expansion.is_empty() { + if !connection.reacquire_with(&self.pool, expansion).await? { + return Err(payment_busy()); + } + continue; + } + + let scopes = connection.scopes().to_vec(); + let mut tx = connection.begin().await?; + let settlement = all_providers_verified.then_some(BindingSettlement { + user_id: &request.user_id, + family: family.as_str(), + }); + let applied = if all_providers_verified { + match apply_locked_snapshots( + &mut tx, + &prepared, + &scopes, + self.deployment, + &self.mail_hash_key, + settlement.as_ref(), + ) + .await + { + Ok(applied) => applied, + Err(PaymentApplyError::Runtime(error)) => return Err(error), + Err(PaymentApplyError::LockSetExpanded(expansion)) => { + tx.rollback() + .await + .map_err(|error| RuntimeError::database("rollback payment reconciliation", error))?; + if !connection.reacquire_with(&self.pool, expansion).await? { + return Err(payment_busy()); + } + continue; + } + } + } else { + PaymentApplyResult::default() + }; + if let Some((attempt_id, reason)) = stripe_completion { + finish_stripe_attempt(&mut tx, attempt_id, reason).await?; + } + if let Some((attempt_id, transaction, source_id)) = app_store_completion + && let Some(source) = prepared + .iter() + .filter(|(_, namespace)| namespace == transaction.namespace) + .find_map(|(snapshot, _)| transaction.source(snapshot, &source_id)) + { + transaction + .confirm_and_finish(&mut tx, source, Some(attempt_id)) + .await?; + } + let after = request.load_case(&mut tx).await?; + let attempt_status = request.attempt(&after)?.map(|attempt| attempt.status.as_str()); + let reason = if !all_providers_verified { + Some("provider_unverified") + } else if after.conflicted { + Some("multiple_sources") + } else if attempt_status.is_some_and(|status| status != "completed") { + Some("attempt_unverified") + } else { + None + }; + let value = json!({ + "requestId": request.request_id, "userId": request.user_id, "planFamily": request.plan_family, + "status": if reason.is_some() { "pending" } else { "resolved" }, "reason": reason, + "conflicted": after.conflicted, "boundProviderNamespace": after.bound_provider_namespace, + "boundSourceIdentity": after.bound_source_identity, "attemptId": request.attempt_id, "attemptStatus": attempt_status + }); + let observations = prepared.iter().map(|(snapshot, namespace)| { + json!({ + "providerNamespace": namespace, "customerId": snapshot.customer_id, + "verifiedMissingSources": match &snapshot.coverage { + SnapshotCoverage::Complete { verified_missing_revenuecat_sources } => Some(verified_missing_revenuecat_sources), + _ => None + }, + "sources": snapshot.subscriptions.iter().map(|source| json!({ + "sourceIdentity": source.source_id, "externalRef": source.external_ref, "plan": source.plan.as_str(), + "status": source.lifecycle.as_str(), "givesAccess": source.gives_access, "willRenew": source.will_renew, + "periodEnd": source.period_end + })).collect::>(), + "financialFacts": snapshot.financial_facts.iter().map(|fact| json!({ + "kind": fact.fact.kind.as_str(), "id": fact.external_id, "invoiceId": fact.external_invoice_id, + "status": fact.fact.status.as_str(), "observedAt": fact.observed_at + })).collect::>() + }) + }).collect::>(); + request + .record( + &mut tx, + json!({ + "response": value, "before": before, "after": after, + "providerObservations": observations, "attemptObservation": attempt_observation + }), + ) + .await?; + tx.commit() + .await + .map_err(|error| RuntimeError::database("commit payment reconciliation", error))?; + changes.extend(applied); + return Ok(value); } - } else { - PaymentApplyResult::default() - }; - if let Some((attempt_id, reason)) = stripe_completion { - finish_stripe_attempt(&mut tx, attempt_id, reason).await?; - } - if let Some((attempt_id, transaction, source_id)) = app_store_completion - && let Some(source) = prepared - .iter() - .filter(|(_, namespace)| namespace == transaction.namespace) - .find_map(|(snapshot, _)| transaction.source(snapshot, &source_id)) - { - transaction - .confirm_and_finish(&mut tx, source, Some(attempt_id)) - .await?; - } - let after = request.load_case(&mut tx).await?; - let attempt_status = request.attempt(&after)?.map(|attempt| attempt.status.as_str()); - let reason = if !all_providers_verified { - Some("provider_unverified") - } else if after.conflicted { - Some("multiple_sources") - } else if attempt_status.is_some_and(|status| status != "completed") { - Some("attempt_unverified") - } else { - None - }; - let value = json!({ - "requestId": request.request_id, "userId": request.user_id, "planFamily": request.plan_family, - "status": if reason.is_some() { "pending" } else { "resolved" }, "reason": reason, - "conflicted": after.conflicted, "boundProviderNamespace": after.bound_provider_namespace, - "boundSourceIdentity": after.bound_source_identity, "attemptId": request.attempt_id, "attemptStatus": attempt_status - }); - let observations = prepared.iter().map(|(snapshot, namespace)| { - json!({ - "providerNamespace": namespace, "customerId": snapshot.customer_id, - "verifiedMissingSources": match &snapshot.coverage { - SnapshotCoverage::Complete { verified_missing_revenuecat_sources } => Some(verified_missing_revenuecat_sources), - _ => None - }, - "sources": snapshot.subscriptions.iter().map(|source| json!({ - "sourceIdentity": source.source_id, "externalRef": source.external_ref, "plan": source.plan.as_str(), - "status": source.lifecycle.as_str(), "givesAccess": source.gives_access, "willRenew": source.will_renew, - "periodEnd": source.period_end - })).collect::>(), - "financialFacts": snapshot.financial_facts.iter().map(|fact| json!({ - "kind": fact.fact.kind.as_str(), "id": fact.external_id, "invoiceId": fact.external_invoice_id, - "status": fact.fact.status.as_str(), "observedAt": fact.observed_at - })).collect::>() - }) - }).collect::>(); - request - .record( - &mut tx, - json!({ - "response": value, "before": before, "after": after, - "providerObservations": observations, "attemptObservation": attempt_observation - }), - ) - .await?; - tx.commit() - .await - .map_err(|error| RuntimeError::database("commit payment reconciliation", error))?; - changes.extend(applied); - return Ok(value); - } - Err(payment_busy()) + Err(payment_busy()) + }) + .await } } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/reconcile.rs b/packages/backend/native/src/runtime/backend_runtime/payment/reconcile.rs index e42c511071..9e3cd04230 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/reconcile.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/reconcile.rs @@ -206,11 +206,15 @@ async fn reconcile_source( let connection = PaymentConnection::try_acquire(&runtime.pool, resources) .await? .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; - let snapshot = match candidate.provider { - Provider::Stripe => reconcile_stripe(runtime, candidate).await?, - Provider::RevenueCat => reconcile_revenuecat(runtime, candidate).await?, - }; - runtime.apply_with_connection(connection, snapshot).await.map(Some) + connection + .with_release(async |connection| { + let snapshot = match candidate.provider { + Provider::Stripe => reconcile_stripe(runtime, candidate).await?, + Provider::RevenueCat => reconcile_revenuecat(runtime, candidate).await?, + }; + runtime.apply_in_connection(connection, snapshot).await.map(Some) + }) + .await } async fn reconcile_stripe(runtime: &PaymentRuntime, candidate: &SourceCandidate) -> RuntimeResult { diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/runtime.rs b/packages/backend/native/src/runtime/backend_runtime/payment/runtime.rs index 8807f7aada..7f59eb5224 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/runtime.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/runtime.rs @@ -140,22 +140,28 @@ impl PaymentRuntime { pub(super) async fn apply_with_connection( &self, - mut connection: PaymentConnection, + connection: PaymentConnection, + snapshot: PaymentSnapshot, + ) -> RuntimeResult { + connection + .with_release(async |connection| self.apply_in_connection(connection, snapshot).await) + .await + } + + pub(super) async fn apply_in_connection( + &self, + connection: &mut PaymentConnection, mut snapshot: PaymentSnapshot, ) -> RuntimeResult { const MAX_LOCK_EXPANSIONS: usize = 4; for attempt in 0..=MAX_LOCK_EXPANSIONS { - match apply_payment_snapshot(&mut connection, snapshot.clone(), self.deployment, &self.mail_hash_key).await { + match apply_payment_snapshot(connection, snapshot.clone(), self.deployment, &self.mail_hash_key).await { Ok(result) => return Ok(result), Err(PaymentApplyError::Runtime(error)) => return Err(error), Err(PaymentApplyError::LockSetExpanded(expansion)) => { - if attempt == MAX_LOCK_EXPANSIONS { + if attempt == MAX_LOCK_EXPANSIONS || !connection.reacquire_with(&self.pool, expansion).await? { return Err(RuntimeError::invalid_state("payment_busy")); } - connection = connection - .reacquire_with(&self.pool, expansion) - .await? - .ok_or_else(|| RuntimeError::invalid_state("payment_busy"))?; if matches!(snapshot.coverage, super::SnapshotCoverage::Complete { .. }) { snapshot = self.refresh_complete_snapshot(&snapshot).await?; } diff --git a/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs b/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs index d15426e428..a74b8d2e77 100644 --- a/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs +++ b/packages/backend/native/src/runtime/backend_runtime/payment/tests.rs @@ -387,13 +387,13 @@ async fn payment_session_locks_are_sorted_nonblocking_and_connection_bound() { for step in 0..32 { let extra = PaymentScope::source(namespace(), &format!("sub-lock-reacquire-{step}")).unwrap(); - replacement = replacement - .reacquire_with(&pool, vec![extra.clone()]) - .await - .unwrap() - .expect("reacquire_with must not collide with its own released session locks"); + assert!( + replacement.reacquire_with(&pool, vec![extra.clone()]).await.unwrap(), + "reacquire_with must not collide with its own released session locks" + ); assert!(replacement.scopes().contains(&extra)); } + replacement.release().await.unwrap(); } #[tokio::test] @@ -1578,8 +1578,8 @@ async fn snapshot_commit_is_atomic_and_transfer_moves_the_entitlement() { assert!((retry.1 - delay).abs() < 1.0); assert!(super::worker::claim_receipt(&webhook_runtime).await.unwrap().is_none()); sqlx::query( - "UPDATE payment_events SET next_attempt_at=clock_timestamp() WHERE provider_namespace=$1 AND \ - external_event_id=$2", + "UPDATE payment_events SET next_attempt_at=clock_timestamp()-INTERVAL '1 second' WHERE provider_namespace=$1 \ + AND external_event_id=$2", ) .bind(&namespace) .bind(&healthy_event) @@ -4620,7 +4620,7 @@ async fn purchase_attempts_survive_checkout_and_storekit_handoff() { .to_string() .contains("purchase_in_progress") ); - sqlx::query("UPDATE payment_operations SET next_attempt_at=clock_timestamp() WHERE id=$1") + sqlx::query("UPDATE payment_operations SET next_attempt_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1") .bind(attempt_id) .execute(&pool) .await @@ -4833,7 +4833,7 @@ async fn purchase_attempts_survive_checkout_and_storekit_handoff() { sqlx::query( "UPDATE payment_operations SET first_sent_at=clock_timestamp()-INTERVAL '1 minute', - next_attempt_at=clock_timestamp() WHERE id=$1", + next_attempt_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1", ) .bind(attempt_id) .execute(&pool) @@ -4868,7 +4868,7 @@ async fn purchase_attempts_survive_checkout_and_storekit_handoff() { .any(|target| target.target_id == user_id) ); assert_eq!(load_attempt(waiting_id).await.unwrap().0, "waiting"); - sqlx::query("UPDATE payment_operations SET next_attempt_at=clock_timestamp() WHERE id=$1") + sqlx::query("UPDATE payment_operations SET next_attempt_at=clock_timestamp()-INTERVAL '1 second' WHERE id=$1") .bind(waiting_id) .execute(&pool) .await diff --git a/packages/backend/native/src/runtime/mod.rs b/packages/backend/native/src/runtime/mod.rs index 7561c084b0..3121d6b764 100644 --- a/packages/backend/native/src/runtime/mod.rs +++ b/packages/backend/native/src/runtime/mod.rs @@ -19,7 +19,45 @@ use storage_lifecycle::{ }; pub(crate) mod types; -pub(super) use affine_doc_loader::blob_refs::{BlobRefProjectionError, extract_blob_refs}; +pub(super) use affine_doc_loader::blob_refs::{BlobRefProjectionError, MAX_SOURCE_BINARY_BYTES, extract_blob_refs}; + +pub(in crate::runtime) fn extract_workspace_avatar_keys( + blob: Vec, +) -> Result>, BlobRefProjectionError> { + use std::sync::Arc; + + use y_octo::{Any, Doc, ReadDoc, ReadError, ReadValue, Value}; + + if blob.len() > MAX_SOURCE_BINARY_BYTES { + return Err(BlobRefProjectionError::SourceTooLarge); + } + let blob = Arc::<[u8]>::from(blob); + let avatar = match ReadDoc::from_full_update_v1_with_limits( + Arc::clone(&blob), + crate::doc::WORKSPACE_LIFECYCLE_MIGRATION_READ_LIMITS, + ) { + Ok(doc) => match doc.map("meta").and_then(|meta| meta.get("avatar")) { + Some(ReadValue::Any(value)) => value.as_str().map(str::to_owned), + Some(ReadValue::Text(text)) => Some(text.to_string()), + _ => None, + }, + Err(ReadError::IncompleteSnapshot(_)) => { + let doc = Doc::try_from_binary_v1(&blob).map_err(|_| BlobRefProjectionError::InvalidBinary)?; + match doc.get_map("meta").ok().and_then(|meta| meta.get("avatar")) { + Some(Value::Any(Any::String(key))) => Some(key), + Some(Value::Text(text)) => Some(text.to_string()), + _ => None, + } + } + Err(ReadError::ResourceLimit(_)) => return Err(BlobRefProjectionError::Unsupported), + Err(ReadError::InvalidUpdate(_)) => return Err(BlobRefProjectionError::InvalidBinary), + }; + match avatar { + Some(key) if key.len() > 1024 => Err(BlobRefProjectionError::KeyTooLarge), + Some(key) if !key.is_empty() => Ok(vec![key.into_boxed_str()]), + _ => Ok(Vec::new()), + } +} #[cfg(test)] pub(crate) use config::AuthRuntimeConfig; pub use config::{AppConfigDescriptor, app_config_descriptors, validate_app_config_value}; diff --git a/packages/backend/native/src/runtime/storage_runtime/blob_cleanup.rs b/packages/backend/native/src/runtime/storage_runtime/blob_cleanup.rs index 65f116f8b7..fea5837fbb 100644 --- a/packages/backend/native/src/runtime/storage_runtime/blob_cleanup.rs +++ b/packages/backend/native/src/runtime/storage_runtime/blob_cleanup.rs @@ -1230,4 +1230,69 @@ mod tests { } Ok(()) } + + #[tokio::test] + #[ignore = "requires DATABASE_URL and a migrated PostgreSQL database"] + async fn blob_cleanup_projection_handles_large_incomplete_workspace_root_doc() -> AnyResult<()> { + let _guard = EMBEDDING_TEST_LOCK.lock().await; + let fixture = blob_cleanup_fixture(true).await?; + let _object_root = &fixture.object_root; + + let root = y_octo::Doc::with_client(1); + let mut meta = root.get_or_create_map("meta")?; + meta.insert("avatar".to_string(), y_octo::Any::String(fixture.blob_key.clone()))?; + let mut pages = root.create_array()?; + let title_padding = "t".repeat(900); + for index in 0..1_200 { + let mut page = root.create_map()?; + page.insert( + "id".to_string(), + y_octo::Any::String(format!("synthetic-page-{index:04}")), + )?; + page.insert( + "title".to_string(), + y_octo::Any::String(format!("Synthetic Page {index:04} {title_padding}")), + )?; + pages.push(page)?; + } + meta.insert("pages".to_string(), pages)?; + let complete_blob = root.encode_update_v1()?; + + let peer = y_octo::Doc::with_client(42); + let mut peer_meta = peer.get_or_create_map("meta")?; + peer_meta.insert("name".to_string(), y_octo::Any::String("missing-prefix".to_string()))?; + let state = peer.get_state_vector(); + peer_meta.insert("avatar".to_string(), y_octo::Any::String("pending-avatar".to_string()))?; + let delta = peer.encode_state_as_update_v1(&state)?; + let large_incomplete_root = y_octo::merge_updates_v1([complete_blob.as_slice(), delta.as_slice()])?.encode_v1()?; + assert!(large_incomplete_root.len() > 1024 * 1024); + + sqlx::query( + "INSERT INTO snapshots(workspace_id,guid,blob,updated_at) VALUES($1,$1,$2,CURRENT_TIMESTAMP) + ON CONFLICT (workspace_id,guid) DO UPDATE SET blob=EXCLUDED.blob,updated_at=EXCLUDED.updated_at", + ) + .bind(&fixture.workspace_id) + .bind(&large_incomplete_root) + .execute(&fixture.pool) + .await?; + + let rebuilt = fixture + .runtime + .rebuild_workspace_doc_blob_refs(fixture.workspace_id.clone(), 100) + .await + .map_err(|err| anyhow::anyhow!(err.to_string()))?; + assert_eq!(rebuilt.failed_docs, 0); + assert!(rebuilt.parsed_docs >= 1); + + let avatar_ref: Option = sqlx::query_scalar( + "SELECT blob_key FROM doc_blob_refs WHERE workspace_id=$1 AND doc_id=$1 AND flavour='workspace:avatar'", + ) + .bind(&fixture.workspace_id) + .fetch_optional(&fixture.pool) + .await?; + assert_eq!(avatar_ref.as_deref(), Some(fixture.blob_key.as_str())); + + cleanup_blob_fixture(&fixture).await?; + Ok(()) + } } diff --git a/packages/backend/native/src/runtime/storage_runtime/doc_blob_refs.rs b/packages/backend/native/src/runtime/storage_runtime/doc_blob_refs.rs index d2e144a5a0..517764d07d 100644 --- a/packages/backend/native/src/runtime/storage_runtime/doc_blob_refs.rs +++ b/packages/backend/native/src/runtime/storage_runtime/doc_blob_refs.rs @@ -340,8 +340,23 @@ async fn rebuild_doc_blob_refs_inner( return Ok(stats); } let mut refs = Vec::new(); + let is_workspace_root = doc_id == workspace_id; for blob in current.into_iter().map(|doc| doc.blob).chain(histories) { - match super::extract_blob_refs(blob) { + let extracted = if is_workspace_root { + crate::runtime::extract_workspace_avatar_keys(blob).map(|keys| { + keys + .into_iter() + .map(|key| ExtractedRef { + blob_key: key.into_string(), + block_id: "meta".to_string(), + flavour: "workspace:avatar".to_string(), + }) + .collect() + }) + } else { + super::extract_blob_refs(blob) + }; + match extracted { Ok(extracted) => refs.extend(extracted), Err(error) => { let code = super::blob_ref_projection_error_code(error); diff --git a/packages/backend/server/scripts/self-host-predeploy.js b/packages/backend/server/scripts/self-host-predeploy.js index a08a3829a3..62ab795509 100644 --- a/packages/backend/server/scripts/self-host-predeploy.js +++ b/packages/backend/server/scripts/self-host-predeploy.js @@ -3,6 +3,7 @@ import { generateKeyPairSync } from 'node:crypto'; import fs from 'node:fs'; import { homedir } from 'node:os'; import path from 'node:path'; +import { pathToFileURL } from 'node:url'; import { upgradeConfig } from './upgrade-config.js'; @@ -42,32 +43,23 @@ function prepare() { } } -function runPrismaMigrations() { - console.log('running prisma migrations.'); - execSync('yarn prisma migrate deploy', { +function runStep(command, label, exec) { + console.log(label); + exec(command, { encoding: 'utf-8', env: process.env, stdio: 'inherit', }); } -function runDataMigrations() { - console.log('running data migrations.'); - execSync('yarn cli run', { - encoding: 'utf-8', - env: process.env, - stdio: 'inherit', - }); -} - -function fixFailedMigrations() { +function fixFailedMigrations(exec) { console.log('fixing failed migrations.'); const maybeFailedMigrations = [ '20250521083048_fix_workspace_embedding_chunk_primary_key', ]; for (const migration of maybeFailedMigrations) { try { - execSync(`yarn prisma migrate resolve --rolled-back ${migration}`, { + exec(`yarn prisma migrate resolve --rolled-back ${migration}`, { encoding: 'utf-8', env: process.env, stdio: 'pipe', @@ -96,7 +88,25 @@ function fixFailedMigrations() { } } -prepare(); -fixFailedMigrations(); -runPrismaMigrations(); -runDataMigrations(); +export function runSelfHostPredeploy({ + prepareConfig = prepare, + exec = execSync, +} = {}) { + prepareConfig(); + fixFailedMigrations(exec); + runStep( + 'yarn cli admit-legacy-context-blobs', + 'admitting legacy context blobs.', + exec + ); + runStep('yarn prisma migrate deploy', 'running prisma migrations.', exec); + runStep('yarn cli run', 'running data migrations.', exec); + runStep('yarn cli validate-cutover', 'validating canonical cutover.', exec); +} + +if ( + process.argv[1] && + import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href +) { + runSelfHostPredeploy(); +} diff --git a/packages/backend/server/src/data/__tests__/self-host-predeploy.spec.ts b/packages/backend/server/src/data/__tests__/self-host-predeploy.spec.ts new file mode 100644 index 0000000000..0b25983b8d --- /dev/null +++ b/packages/backend/server/src/data/__tests__/self-host-predeploy.spec.ts @@ -0,0 +1,51 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +import test from 'ava'; + +const serverRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../..' +); + +type RunSelfHostPredeploy = (options?: { + prepareConfig?: () => void; + exec?: (command: string, options?: unknown) => string; +}) => void; + +test('self-host-predeploy runs all package.json predeploy steps in order', async t => { + const pkg = JSON.parse( + fs.readFileSync(path.join(serverRoot, 'package.json'), 'utf-8') + ) as { scripts: { predeploy: string } }; + const expectedPredeploySteps = pkg.scripts.predeploy + .split('&&') + .map(step => step.trim()); + + const scriptUrl = pathToFileURL( + path.join(serverRoot, 'scripts/self-host-predeploy.js') + ).href; + const { runSelfHostPredeploy } = (await import(scriptUrl)) as { + runSelfHostPredeploy: RunSelfHostPredeploy; + }; + + const executed: string[] = []; + let prepared = false; + + runSelfHostPredeploy({ + prepareConfig: () => { + prepared = true; + }, + exec: command => { + executed.push(command); + return ''; + }, + }); + + t.true(prepared); + t.is( + executed[0], + 'yarn prisma migrate resolve --rolled-back 20250521083048_fix_workspace_embedding_chunk_primary_key' + ); + t.deepEqual(executed.slice(1), expectedPredeploySteps); +});