syrup-rail-postgres 0.2.2

Canonical provider-neutral PostgreSQL schema contract and SQLx orchestration for Syrup Rail
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
use std::{fmt, time::Duration};

use chrono::{DateTime, Utc};
use sqlx::{PgConnection, PgPool, Row};
use syrup_rail::{
    BillingEvent, BillingScopeId, GatewayDiagnostic, GatewayNotSubmittedError, GatewayOrderId,
    GatewayProviderKey, PaymentAttempt, PaymentAttemptIdentity, PaymentAttemptKind,
    PaymentAttemptRequest, PaymentAttemptStatus, PaymentMethodId, PaymentResolutionCode, PlanKey,
    ProcessorChargeProgression, ProcessorEvidence, SubscriberId, Subscription,
    SubscriptionEnrollmentPaymentResult, SubscriptionEnrollmentReservation, SubscriptionId,
    SubscriptionPaymentMethodReplacement, SubscriptionRecoveryReservation,
    SubscriptionRenewalReservation,
};
use thiserror::Error;
use uuid::Uuid;

use crate::{
    BillingTransaction, BillingTransactionError,
    attempts::{
        AttemptApproval, AttemptResolutionStatus, AttemptTransition, PaymentAttemptStoreError,
        find_payment_attempt_by_id_on_connection, lock_payment_attempt_by_id_on_connection,
        persist_attempt_transition,
    },
    processor_charges::{
        LockFreeApprovedEvidenceOutcome, LockFreeApprovedEvidenceTerms, observe_processor_charge,
    },
    renewal_failure::RenewalFailureStoreError,
    subscription_persistence::{
        SubscriptionPersistenceCodecError, subscription_from_row as decode_subscription_row,
    },
};

mod initial;
mod payment_method_replacement;
mod recovery;
mod renewal;

pub(crate) use initial::resolve_non_approved_outcome;
pub use initial::{
    AdmittedSubscriptionEnrollment, SubscriptionEnrollmentAdmissionOutcome,
    SubscriptionEnrollmentProviderResult, admit_subscription_enrollment_submission,
    apply_reconciled_subscription_enrollment_gateway_outcome,
    apply_subscription_enrollment_gateway_outcome, submit_admitted_subscription_enrollment,
};
pub(crate) use payment_method_replacement::resolve_payment_method_replacement_non_approved_outcome;
pub use payment_method_replacement::{
    AdmittedSubscriptionPaymentMethodReplacement,
    SubscriptionPaymentMethodReplacementAdmissionOutcome,
    SubscriptionPaymentMethodReplacementProviderResult,
    admit_subscription_payment_method_replacement,
    apply_reconciled_subscription_payment_method_replacement_gateway_outcome,
    apply_subscription_payment_method_replacement_gateway_outcome,
    submit_admitted_subscription_payment_method_replacement,
};
pub(crate) use recovery::resolve_recovery_non_approved_outcome;
pub use recovery::{
    AdmittedSubscriptionRecovery, SubscriptionRecoveryAdmissionOutcome,
    SubscriptionRecoveryProviderResult, admit_subscription_recovery_submission,
    apply_reconciled_subscription_recovery_gateway_outcome,
    apply_subscription_recovery_gateway_outcome, submit_admitted_subscription_recovery,
};
pub(crate) use renewal::resolve_renewal_non_approved_outcome;
pub use renewal::{
    AdmittedSubscriptionRenewal, SubscriptionRenewalAdmissionOutcome,
    SubscriptionRenewalProviderResult, admit_subscription_renewal_submission,
    apply_reconciled_subscription_renewal_gateway_outcome,
    apply_subscription_renewal_gateway_outcome, submit_admitted_subscription_renewal,
};

const BILLING_LOCK_TIMEOUT: Duration = Duration::from_millis(250);
const BILLING_ROW_LOCK_TIMEOUT: &str = "250ms";
const BILLING_OPERATION_TIMEOUT: &str = "5s";
const APPROVED_EVIDENCE_WRITE_ATTEMPTS: usize = 3;
const APPROVED_EVIDENCE_RETRY_DELAY: Duration = Duration::from_millis(50);
const APPROVED_APPLICATION_ATTEMPTS: usize = 3;
const PROVIDER_RATE_LIMIT_RETRY_AFTER_SECONDS: i64 = 60;
const INVALID_APPLICATION_STATE: &str = "canonical initial-enrollment application state is invalid";
const CURRENT_SUBSCRIPTION_CONFLICT_TEXT: &str =
    "Approved subscription enrollment conflicts with a current subscription.";
const CURRENT_GRANT_CONFLICT_TEXT: &str =
    "Approved subscription enrollment conflicts with an active subscription grant.";
const INCOMPLETE_APPROVAL_TEXT: &str =
    "Approved subscription enrollment is missing required processor identity.";
const APPROVED_STORAGE_FAILURE_TEXT: &str =
    "Approved subscription enrollment could not be applied; manual review is required.";
const TERMINAL_APPROVAL_RACE_TEXT: &str =
    "Approved processor evidence arrived after the enrollment attempt became terminal.";
const RECOVERY_INCOMPLETE_APPROVAL_TEXT: &str =
    "Approved subscription recovery is missing required processor identity.";
const RECOVERY_APPROVED_STORAGE_FAILURE_TEXT: &str =
    "Approved subscription recovery could not be applied; manual review is required.";
const RECOVERY_STALE_STATE_TEXT: &str = "Approved subscription recovery could not update billing state because the subscription changed.";
const RENEWAL_INCOMPLETE_APPROVAL_TEXT: &str =
    "Approved subscription renewal is missing required processor identity.";
const RENEWAL_APPROVED_STORAGE_FAILURE_TEXT: &str =
    "Approved subscription renewal could not be applied; manual review is required.";
const RENEWAL_STALE_STATE_TEXT: &str = "Approved subscription renewal could not update billing state because the subscription changed.";
const PAYMENT_METHOD_REPLACEMENT_INCOMPLETE_APPROVAL_TEXT: &str =
    "Approved payment method replacement is missing required processor identity.";
const PAYMENT_METHOD_REPLACEMENT_STORAGE_FAILURE_TEXT: &str =
    "Approved payment method replacement could not be applied; manual review is required.";
const PAYMENT_METHOD_REPLACEMENT_STALE_STATE_TEXT: &str =
    "Approved payment method replacement could not attach because the subscription changed.";

#[derive(Error)]
pub enum SubscriptionEnrollmentApplicationError {
    #[error("subscription enrollment application storage failed")]
    Sql(#[from] sqlx::Error),
    #[error("subscription enrollment attempt storage failed")]
    Attempt(#[from] PaymentAttemptStoreError),
    #[error("host billing transaction failed")]
    Transaction(#[from] BillingTransactionError),
    #[error("host billing event append failed")]
    Event(#[from] crate::BillingEventWriteError),
    #[error("approved subscription enrollment could not be durably applied or parked")]
    ApprovedEvidenceNotDurable,
    #[error("admitted subscription enrollment does not match the submission command or gateway")]
    SubmissionIdentityMismatch,
    #[error("{0}")]
    InvalidState(&'static str),
}

impl From<crate::processor_charges::ProcessorChargeStoreError>
    for SubscriptionEnrollmentApplicationError
{
    fn from(error: crate::processor_charges::ProcessorChargeStoreError) -> Self {
        match error {
            crate::processor_charges::ProcessorChargeStoreError::Sql(error) => Self::Sql(error),
            crate::processor_charges::ProcessorChargeStoreError::Attempt(error) => {
                Self::Attempt(error)
            }
            crate::processor_charges::ProcessorChargeStoreError::InvalidState(message) => {
                Self::InvalidState(message)
            }
        }
    }
}

impl From<RenewalFailureStoreError> for SubscriptionEnrollmentApplicationError {
    fn from(error: RenewalFailureStoreError) -> Self {
        match error {
            RenewalFailureStoreError::Sql(error) => Self::Sql(error),
            RenewalFailureStoreError::Attempt(error) => Self::Attempt(error),
            RenewalFailureStoreError::InvalidState(message) => Self::InvalidState(message),
        }
    }
}

fn map_subscription_persistence_error(
    error: SubscriptionPersistenceCodecError,
) -> SubscriptionEnrollmentApplicationError {
    match error {
        SubscriptionPersistenceCodecError::RowRead(error) => {
            SubscriptionEnrollmentApplicationError::Sql(error)
        }
        SubscriptionPersistenceCodecError::InvalidState => {
            SubscriptionEnrollmentApplicationError::InvalidState(INVALID_APPLICATION_STATE)
        }
    }
}

pub(crate) fn map_attempt_transition_error(
    error: PaymentAttemptStoreError,
) -> SubscriptionEnrollmentApplicationError {
    match error {
        PaymentAttemptStoreError::Sql(error) => SubscriptionEnrollmentApplicationError::Sql(error),
        PaymentAttemptStoreError::InvalidState(_) => {
            SubscriptionEnrollmentApplicationError::InvalidState(INVALID_APPLICATION_STATE)
        }
    }
}

impl fmt::Debug for SubscriptionEnrollmentApplicationError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Sql(_) => formatter.write_str("SubscriptionEnrollmentApplicationError::Sql"),
            Self::Attempt(_) => {
                formatter.write_str("SubscriptionEnrollmentApplicationError::Attempt")
            }
            Self::Transaction(_) => {
                formatter.write_str("SubscriptionEnrollmentApplicationError::Transaction")
            }
            Self::Event(_) => formatter.write_str("SubscriptionEnrollmentApplicationError::Event"),
            Self::ApprovedEvidenceNotDurable => formatter
                .write_str("SubscriptionEnrollmentApplicationError::ApprovedEvidenceNotDurable"),
            Self::SubmissionIdentityMismatch => formatter
                .write_str("SubscriptionEnrollmentApplicationError::SubmissionIdentityMismatch"),
            Self::InvalidState(detail) => formatter
                .debug_tuple("SubscriptionEnrollmentApplicationError::InvalidState")
                .field(detail)
                .finish(),
        }
    }
}

async fn finalize_approved_application(
    mut transaction: Box<dyn BillingTransaction>,
    application: Result<
        (SubscriptionEnrollmentPaymentResult, Option<BillingEvent>),
        SubscriptionEnrollmentApplicationError,
    >,
) -> Result<SubscriptionEnrollmentPaymentResult, SubscriptionEnrollmentApplicationError> {
    let (result, event) = match application {
        Ok(application) => application,
        Err(error) => {
            let _ = transaction.rollback().await;
            return Err(error);
        }
    };
    if let Some(event) = event.as_ref()
        && let Err(error) = transaction.append_event(event).await
    {
        let _ = transaction.rollback().await;
        return Err(error.into());
    }
    transaction.commit().await?;
    Ok(result)
}

async fn lock_expected_reservation_attempt(
    connection: &mut PgConnection,
    reservation: OutcomeReservation<'_>,
) -> Result<PaymentAttempt, SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let attempt = lock_payment_attempt_by_id_on_connection(
        connection,
        identity.billing_scope_id(),
        identity.attempt_id(),
    )
    .await?
    .ok_or(SubscriptionEnrollmentApplicationError::InvalidState(
        INVALID_APPLICATION_STATE,
    ))?;
    if !reservation.matches_attempt(&attempt) {
        return Err(SubscriptionEnrollmentApplicationError::InvalidState(
            INVALID_APPLICATION_STATE,
        ));
    }
    Ok(attempt)
}

async fn recovery_subscription_matches(
    connection: &mut PgConnection,
    reservation: &SubscriptionRecoveryReservation,
) -> Result<bool, SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let expected = reservation.expected_state();
    let row = sqlx::query(
        r#"
        SELECT status, payment_method_id, initial_transaction_id, next_renewal_at
        FROM billing_subscriptions
        WHERE id = $1 AND billing_scope_id = $2 AND subscriber_id = $3
            AND gateway_account_id = $4 AND plan_key = $5
        FOR UPDATE
        "#,
    )
    .bind(reservation.subscription_id().as_uuid())
    .bind(identity.billing_scope_id().as_uuid())
    .bind(identity.subscriber_id().as_uuid())
    .bind(identity.gateway_account_id().as_uuid())
    .bind(reservation.plan_key().as_str())
    .fetch_optional(&mut *connection)
    .await?;
    let Some(row) = row else {
        return Ok(false);
    };
    let status = row.try_get::<String, _>("status")?;
    let payment_method_id: Uuid = row.try_get("payment_method_id")?;
    let initial_transaction_id: String = row.try_get("initial_transaction_id")?;
    let next_renewal_at: DateTime<Utc> = row.try_get("next_renewal_at")?;
    Ok(status == expected.status().as_str()
        && matches!(status.as_str(), "active" | "past_due")
        && payment_method_id == expected.payment_method_id().into_uuid()
        && syrup_rail::canonical_gateway_transaction_ids_equal(
            &initial_transaction_id,
            expected.initial_transaction_id().expose(),
        )
        && next_renewal_at == *reservation.period().start_at())
}

async fn renewal_subscription_matches(
    connection: &mut PgConnection,
    reservation: &SubscriptionRenewalReservation,
) -> Result<bool, SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let expected = reservation.expected_state();
    let row = sqlx::query(
        r#"
        SELECT status, payment_method_id, initial_transaction_id,
            amount_cents, currency, next_renewal_at
        FROM billing_subscriptions
        WHERE id = $1 AND billing_scope_id = $2 AND subscriber_id = $3
            AND gateway_account_id = $4 AND plan_key = $5
        FOR UPDATE
        "#,
    )
    .bind(reservation.subscription_id().as_uuid())
    .bind(identity.billing_scope_id().as_uuid())
    .bind(identity.subscriber_id().as_uuid())
    .bind(identity.gateway_account_id().as_uuid())
    .bind(reservation.plan_key().as_str())
    .fetch_optional(&mut *connection)
    .await?;
    let Some(row) = row else {
        return Ok(false);
    };
    let status = row.try_get::<String, _>("status")?;
    let initial_transaction_id: String = row.try_get("initial_transaction_id")?;
    Ok(status == expected.status().as_str()
        && matches!(status.as_str(), "active" | "past_due")
        && row.try_get::<Uuid, _>("payment_method_id")? == expected.payment_method_id().into_uuid()
        && syrup_rail::canonical_gateway_transaction_ids_equal(
            &initial_transaction_id,
            expected.initial_transaction_id().expose(),
        )
        && row.try_get::<i32, _>("amount_cents")? == reservation.request().amount().cents()
        && row.try_get::<String, _>("currency")?
            == reservation.request().amount().currency().as_str()
        && row.try_get::<DateTime<Utc>, _>("next_renewal_at")? == *reservation.period().start_at())
}

async fn disable_payment_method_if_unreferenced(
    connection: &mut PgConnection,
    payment_method_id: PaymentMethodId,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        r#"
        UPDATE billing_payment_methods AS methods
        SET status = 'disabled', updated_at = clock_timestamp()
        WHERE methods.id = $1 AND methods.status = 'active'
            AND NOT EXISTS (
                SELECT 1 FROM billing_subscriptions AS subscriptions
                WHERE subscriptions.payment_method_id = methods.id
                    AND subscriptions.status IN ('active', 'past_due')
            )
        "#,
    )
    .bind(payment_method_id.as_uuid())
    .execute(connection)
    .await?;
    Ok(())
}

async fn advance_subscription_discount_after_successful_charge(
    connection: &mut PgConnection,
    subscription_id: SubscriptionId,
    plan_key: &PlanKey,
) -> Result<(), SubscriptionEnrollmentApplicationError> {
    let row = sqlx::query(
        r#"
        SELECT duration, status, periods_total, periods_applied, base_amount_cents
        FROM billing_subscription_discounts
        WHERE subscription_id = $1 AND plan_key = $2
        FOR UPDATE
        "#,
    )
    .bind(subscription_id.as_uuid())
    .bind(plan_key.as_str())
    .fetch_optional(&mut *connection)
    .await?;
    let Some(row) = row else {
        return Ok(());
    };
    let duration: String = row.try_get("duration")?;
    let status: String = row.try_get("status")?;
    if status == "completed" {
        return Ok(());
    }
    let periods_applied: i32 = row.try_get("periods_applied")?;
    if duration == "indefinite" {
        match periods_applied {
            0 => {
                sqlx::query(
                    r#"
                    UPDATE billing_subscription_discounts
                    SET periods_applied = 1
                    WHERE subscription_id = $1 AND plan_key = $2
                        AND status = 'active' AND periods_applied = 0
                    "#,
                )
                .bind(subscription_id.as_uuid())
                .bind(plan_key.as_str())
                .execute(&mut *connection)
                .await?;
                return Ok(());
            }
            1 => return Ok(()),
            _ => {
                return Err(SubscriptionEnrollmentApplicationError::InvalidState(
                    INVALID_APPLICATION_STATE,
                ));
            }
        }
    }
    if duration != "limited_months" {
        return Err(SubscriptionEnrollmentApplicationError::InvalidState(
            INVALID_APPLICATION_STATE,
        ));
    }
    let periods_total: i32 = row.try_get("periods_total")?;
    if periods_applied >= periods_total {
        return Err(SubscriptionEnrollmentApplicationError::InvalidState(
            INVALID_APPLICATION_STATE,
        ));
    }
    let next_periods_applied = periods_applied + 1;
    let completed = next_periods_applied == periods_total;
    sqlx::query(
        r#"
        UPDATE billing_subscription_discounts
        SET periods_applied = $3,
            status = CASE WHEN $4 THEN 'completed' ELSE 'active' END,
            completed_at = CASE WHEN $4 THEN clock_timestamp() ELSE NULL END
        WHERE subscription_id = $1 AND plan_key = $2
        "#,
    )
    .bind(subscription_id.as_uuid())
    .bind(plan_key.as_str())
    .bind(next_periods_applied)
    .bind(completed)
    .execute(&mut *connection)
    .await?;
    if completed {
        let base_amount_cents: i32 = row.try_get("base_amount_cents")?;
        sqlx::query(
            "UPDATE billing_subscriptions SET amount_cents = $2, updated_at = clock_timestamp() WHERE id = $1",
        )
        .bind(subscription_id.as_uuid())
        .bind(base_amount_cents)
        .execute(&mut *connection)
        .await?;
    }
    Ok(())
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum OutcomeResolutionBoundary {
    Prepared,
    AdmittedNotSubmitted,
    Submitted,
}

#[derive(Clone, Copy)]
pub(crate) enum RateLimitCooldown {
    Account,
    Provider,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ReservationOperation {
    Initial,
    Recovery,
    Renewal,
    PaymentMethodReplacement,
}

impl ReservationOperation {
    const fn expected_kind(self) -> PaymentAttemptKind {
        match self {
            Self::Initial => PaymentAttemptKind::SubscriptionInitial,
            Self::Recovery => PaymentAttemptKind::SubscriptionRecovery,
            Self::Renewal => PaymentAttemptKind::SubscriptionRenewal,
            Self::PaymentMethodReplacement => PaymentAttemptKind::SubscriptionPaymentMethodUpdate,
        }
    }

    const fn preserves_review_required_for_unknown(self) -> bool {
        matches!(self, Self::PaymentMethodReplacement)
    }
}

/// A closed, secret-free view of the durable terms used while applying a
/// provider outcome. It keeps each operation's matching rule explicit while
/// sharing only the common locking and cooldown mechanics.
#[derive(Clone, Copy)]
enum OutcomeReservation<'a> {
    Initial(&'a SubscriptionEnrollmentReservation),
    Recovery(&'a SubscriptionRecoveryReservation),
    Renewal(&'a SubscriptionRenewalReservation),
    PaymentMethodReplacement(&'a SubscriptionPaymentMethodReplacement),
}

impl<'a> OutcomeReservation<'a> {
    const fn operation(self) -> ReservationOperation {
        match self {
            Self::Initial(_) => ReservationOperation::Initial,
            Self::Recovery(_) => ReservationOperation::Recovery,
            Self::Renewal(_) => ReservationOperation::Renewal,
            Self::PaymentMethodReplacement(_) => ReservationOperation::PaymentMethodReplacement,
        }
    }

    const fn identity(self) -> PaymentAttemptIdentity {
        match self {
            Self::Initial(reservation) => reservation.identity(),
            Self::Recovery(reservation) => reservation.identity(),
            Self::Renewal(reservation) => reservation.identity(),
            Self::PaymentMethodReplacement(reservation) => reservation.identity(),
        }
    }

    const fn plan_key(self) -> &'a PlanKey {
        match self {
            Self::Initial(reservation) => reservation.plan_key(),
            Self::Recovery(reservation) => reservation.plan_key(),
            Self::Renewal(reservation) => reservation.plan_key(),
            Self::PaymentMethodReplacement(reservation) => reservation.plan_key(),
        }
    }

    const fn provider_key(self) -> &'a GatewayProviderKey {
        match self {
            Self::Initial(reservation) => reservation.provider_key(),
            Self::Recovery(reservation) => reservation.provider_key(),
            Self::Renewal(reservation) => reservation.provider_key(),
            Self::PaymentMethodReplacement(reservation) => reservation.provider_key(),
        }
    }

    const fn expected_kind(self) -> PaymentAttemptKind {
        self.operation().expected_kind()
    }

    fn expected_attempt(self) -> ReservationAttemptExpectation<'a> {
        match self {
            Self::Initial(reservation) => ReservationAttemptExpectation::Initial {
                identity: reservation.identity(),
                plan_key: reservation.plan_key(),
                gateway_order_id: reservation.gateway_order_id(),
            },
            Self::Recovery(reservation) => ReservationAttemptExpectation::Exact {
                identity: reservation.identity(),
                kind: self.expected_kind(),
                request: reservation.request(),
            },
            Self::Renewal(reservation) => ReservationAttemptExpectation::Exact {
                identity: reservation.identity(),
                kind: self.expected_kind(),
                request: reservation.request(),
            },
            Self::PaymentMethodReplacement(reservation) => ReservationAttemptExpectation::Exact {
                identity: reservation.identity(),
                kind: self.expected_kind(),
                request: reservation.request(),
            },
        }
    }

    fn matches_attempt(self, attempt: &PaymentAttempt) -> bool {
        self.expected_attempt().matches(attempt)
    }
}

/// Initial enrollment preserves its historical application match: identity,
/// kind, plan, and gateway order. Every later operation validates its entire
/// request exactly.
enum ReservationAttemptExpectation<'a> {
    Initial {
        identity: PaymentAttemptIdentity,
        plan_key: &'a PlanKey,
        gateway_order_id: &'a GatewayOrderId,
    },
    Exact {
        identity: PaymentAttemptIdentity,
        kind: PaymentAttemptKind,
        request: &'a PaymentAttemptRequest,
    },
}

impl ReservationAttemptExpectation<'_> {
    const fn expected_kind(&self) -> PaymentAttemptKind {
        match self {
            Self::Initial { .. } => PaymentAttemptKind::SubscriptionInitial,
            Self::Exact { kind, .. } => *kind,
        }
    }

    fn matches(&self, attempt: &PaymentAttempt) -> bool {
        match self {
            Self::Initial {
                identity,
                plan_key,
                gateway_order_id,
            } => {
                attempt.identity() == *identity
                    && attempt.kind() == self.expected_kind()
                    && attempt.request().target().plan_key() == Some(*plan_key)
                    && attempt.request().gateway_order_id() == *gateway_order_id
            }
            Self::Exact {
                identity,
                kind,
                request,
            } => {
                attempt.identity() == *identity
                    && attempt.kind() == *kind
                    && attempt.request() == *request
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum OutcomeResolutionKind {
    NonApproved,
    Unknown,
}

/// Typed durable resolution inputs. This separates a provider outcome's
/// status/code/cooldown/boundary from the mechanics that persist it.
#[derive(Clone, Copy)]
struct OutcomeResolutionCommand {
    kind: OutcomeResolutionKind,
    status: AttemptResolutionStatus,
    resolution_code: Option<PaymentResolutionCode>,
    cooldown: Option<RateLimitCooldown>,
    boundary: OutcomeResolutionBoundary,
}

impl OutcomeResolutionCommand {
    const fn non_approved(
        status: AttemptResolutionStatus,
        resolution_code: Option<PaymentResolutionCode>,
        cooldown: Option<RateLimitCooldown>,
        boundary: OutcomeResolutionBoundary,
    ) -> Self {
        Self {
            kind: OutcomeResolutionKind::NonApproved,
            status,
            resolution_code,
            cooldown,
            boundary,
        }
    }

    const fn unknown(cooldown: Option<RateLimitCooldown>) -> Self {
        Self {
            kind: OutcomeResolutionKind::Unknown,
            status: AttemptResolutionStatus::Unknown,
            resolution_code: None,
            cooldown,
            boundary: OutcomeResolutionBoundary::Submitted,
        }
    }

    const fn may_resolve(self, status: PaymentAttemptStatus, submitted: bool) -> bool {
        status.is_resolvable()
            && match self.boundary {
                OutcomeResolutionBoundary::Prepared => !submitted,
                OutcomeResolutionBoundary::AdmittedNotSubmitted => submitted,
                OutcomeResolutionBoundary::Submitted => true,
            }
    }

    fn resolved_status(
        self,
        operation: ReservationOperation,
        current: PaymentAttemptStatus,
    ) -> AttemptResolutionStatus {
        if self.kind == OutcomeResolutionKind::Unknown
            && operation.preserves_review_required_for_unknown()
            && current == PaymentAttemptStatus::ReviewRequired
        {
            AttemptResolutionStatus::ReviewRequired
        } else {
            self.status
        }
    }

    fn clears_submitted_at(self) -> bool {
        self.boundary == OutcomeResolutionBoundary::AdmittedNotSubmitted
    }

    fn records_pending_evidence(self, status: AttemptResolutionStatus) -> bool {
        self.kind == OutcomeResolutionKind::Unknown
            && status != AttemptResolutionStatus::ReviewRequired
    }

    fn marks_renewal_past_due(self, status: AttemptResolutionStatus) -> bool {
        self.boundary == OutcomeResolutionBoundary::Submitted
            && matches!(
                status,
                AttemptResolutionStatus::Declined | AttemptResolutionStatus::Failed
            )
    }
}

async fn resolve_pool_outcome(
    pool: &PgPool,
    reservation: OutcomeReservation<'_>,
    evidence: &ProcessorEvidence,
    resolution: OutcomeResolutionCommand,
) -> Result<SubscriptionEnrollmentPaymentResult, SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let mut transaction = pool.begin().await?;
    set_application_timeouts(&mut transaction).await?;
    lock_subscription_aggregate(
        &mut transaction,
        identity.subscriber_id(),
        reservation.plan_key(),
    )
    .await?;
    let attempt = lock_expected_reservation_attempt(&mut transaction, reservation).await?;
    if resolution.may_resolve(
        attempt.status(),
        attempt.state().timestamps().submitted_at().is_some(),
    ) {
        let status = resolution.resolved_status(reservation.operation(), attempt.status());
        persist_attempt_transition(
            &mut transaction,
            &attempt,
            evidence,
            AttemptTransition::Resolved {
                status,
                resolution_code: resolution.resolution_code,
            },
        )
        .await
        .map_err(map_attempt_transition_error)?;
        if resolution.clears_submitted_at() {
            clear_attempt_submission(&mut transaction, &attempt).await?;
        }
        if resolution.records_pending_evidence(status) && evidence_looks_approved(evidence) {
            observe_processor_charge(
                &mut transaction,
                &attempt,
                evidence,
                ProcessorChargeProgression::Pending,
            )
            .await?;
        }
    }
    if let Some(cooldown) = resolution.cooldown {
        extend_rate_limit_cooldown(&mut transaction, reservation, cooldown).await?;
    }
    let result = payment_result_for_reservation_attempt(&mut transaction, reservation).await?;
    transaction.commit().await?;
    Ok(result)
}

async fn clear_attempt_submission(
    connection: &mut PgConnection,
    attempt: &PaymentAttempt,
) -> Result<(), SubscriptionEnrollmentApplicationError> {
    sqlx::query(
        "UPDATE billing_payment_attempts SET submitted_at = NULL, updated_at = clock_timestamp() WHERE id = $1",
    )
    .bind(attempt.identity().attempt_id().as_uuid())
    .execute(connection)
    .await?;
    Ok(())
}

async fn payment_result_for_reservation_attempt(
    connection: &mut PgConnection,
    reservation: OutcomeReservation<'_>,
) -> Result<SubscriptionEnrollmentPaymentResult, SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let attempt = find_payment_attempt_by_id_on_connection(
        connection,
        identity.billing_scope_id(),
        identity.attempt_id(),
    )
    .await?
    .ok_or(SubscriptionEnrollmentApplicationError::InvalidState(
        INVALID_APPLICATION_STATE,
    ))?;
    payment_result_for_attempt(connection, attempt).await
}

async fn extend_rate_limit_cooldown(
    connection: &mut PgConnection,
    reservation: OutcomeReservation<'_>,
    cooldown: RateLimitCooldown,
) -> Result<(), SubscriptionEnrollmentApplicationError> {
    let identity = reservation.identity();
    let result = match cooldown {
        RateLimitCooldown::Account => {
            sqlx::query(
                r#"
                UPDATE billing_gateway_accounts
                SET mutation_rate_limited_until = GREATEST(
                        COALESCE(mutation_rate_limited_until, '-infinity'::timestamptz),
                        clock_timestamp() + make_interval(secs => $4)
                    )
                WHERE id = $1 AND billing_scope_id = $2
                    AND gateway_configuration_id = $3
                "#,
            )
            .bind(identity.gateway_account_id().as_uuid())
            .bind(identity.billing_scope_id().as_uuid())
            .bind(identity.gateway_configuration_id().as_uuid())
            .bind(PROVIDER_RATE_LIMIT_RETRY_AFTER_SECONDS)
            .execute(&mut *connection)
            .await?
        }
        RateLimitCooldown::Provider => {
            sqlx::query(
                r#"
                UPDATE billing_gateway_provider_rate_limits
                SET rate_limited_until = GREATEST(
                        rate_limited_until,
                        clock_timestamp() + make_interval(secs => $2)
                    )
                WHERE provider_key = $1
                "#,
            )
            .bind(reservation.provider_key().as_str())
            .bind(PROVIDER_RATE_LIMIT_RETRY_AFTER_SECONDS)
            .execute(&mut *connection)
            .await?
        }
    };
    if result.rows_affected() != 1 {
        return Err(SubscriptionEnrollmentApplicationError::InvalidState(
            INVALID_APPLICATION_STATE,
        ));
    }
    Ok(())
}

pub(crate) fn mutation_error_evidence(detail: &GatewayDiagnostic) -> ProcessorEvidence {
    ProcessorEvidence::new(
        None,
        None,
        None,
        None,
        Some(detail.clone()),
        None,
        syrup_rail::GatewayPaymentDescriptor::default(),
    )
}

pub(crate) const fn not_submitted_resolution_code(
    error: &GatewayNotSubmittedError,
) -> PaymentResolutionCode {
    match error {
        GatewayNotSubmittedError::RequestRejected(_) => {
            PaymentResolutionCode::GatewayRequestRejectedBeforeSubmission
        }
        GatewayNotSubmittedError::Malformed(_) => {
            PaymentResolutionCode::GatewayMalformedBeforeSubmission
        }
        GatewayNotSubmittedError::Configuration(_) => {
            PaymentResolutionCode::GatewayConfigurationBeforeSubmission
        }
        GatewayNotSubmittedError::Unavailable(_) => {
            PaymentResolutionCode::GatewayUnavailableBeforeSubmission
        }
        GatewayNotSubmittedError::RateLimited(_) => {
            PaymentResolutionCode::GatewayProviderRateLimitedBeforeSubmission
        }
    }
}

async fn persist_approved_evidence_without_attempt_lock(
    pool: &PgPool,
    terms: LockFreeApprovedEvidenceTerms<'_>,
    evidence: &ProcessorEvidence,
) -> Result<(), SubscriptionEnrollmentApplicationError> {
    match crate::processor_charges::persist_approved_evidence_without_attempt_lock(
        pool, terms, evidence,
    )
    .await?
    {
        LockFreeApprovedEvidenceOutcome::Persisted
        | LockFreeApprovedEvidenceOutcome::ExactReplay
        | LockFreeApprovedEvidenceOutcome::OwnedByOtherAttempt => Ok(()),
        LockFreeApprovedEvidenceOutcome::NotDurable => {
            Err(SubscriptionEnrollmentApplicationError::ApprovedEvidenceNotDurable)
        }
    }
}

fn is_retryable_evidence_error(error: &SubscriptionEnrollmentApplicationError) -> bool {
    let sqlstate = match error {
        SubscriptionEnrollmentApplicationError::Sql(sqlx::Error::Database(error)) => error.code(),
        SubscriptionEnrollmentApplicationError::Attempt(PaymentAttemptStoreError::Sql(
            sqlx::Error::Database(error),
        )) => error.code(),
        _ => None,
    };
    matches!(
        sqlstate.as_deref(),
        Some("40001" | "40P01" | "55P03" | "57014")
    )
}

pub(crate) async fn set_application_timeouts(
    connection: &mut PgConnection,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        "SELECT set_config('lock_timeout', $1, true), set_config('statement_timeout', $2, true)",
    )
    .bind(BILLING_ROW_LOCK_TIMEOUT)
    .bind(BILLING_OPERATION_TIMEOUT)
    .execute(connection)
    .await?;
    Ok(())
}

async fn lock_payment_method_domain(
    connection: &mut PgConnection,
    subscriber_id: SubscriberId,
    gateway_account_id: &Uuid,
) -> Result<(), sqlx::Error> {
    sqlx::query(
        "SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':' || $2::uuid::text, 0))",
    )
    .bind(gateway_account_id)
    .bind(subscriber_id.as_uuid())
    .execute(connection)
    .await?;
    Ok(())
}

async fn lock_subscription_aggregate(
    connection: &mut PgConnection,
    subscriber_id: SubscriberId,
    plan_key: &PlanKey,
) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':' || $2, 0))")
        .bind(subscriber_id.as_uuid())
        .bind(plan_key.as_str())
        .execute(connection)
        .await?;
    Ok(())
}

async fn upsert_payment_method(
    connection: &mut PgConnection,
    attempt: &PaymentAttempt,
    evidence: &ProcessorEvidence,
) -> Result<PaymentMethodId, SubscriptionEnrollmentApplicationError> {
    let identity = attempt.identity();
    let reference = evidence.payment_method_reference().ok_or(
        SubscriptionEnrollmentApplicationError::InvalidState(INVALID_APPLICATION_STATE),
    )?;
    let descriptor = evidence.descriptor();
    let row_id: Uuid = sqlx::query_scalar(
        r#"
        INSERT INTO billing_payment_methods (
            id, billing_scope_id, subscriber_id, gateway_account_id,
            gateway_payment_method_reference, status, payment_type, card_brand,
            card_last4, card_exp_month, card_exp_year, billing_name, billing_email
        ) VALUES ($1, $2, $3, $4, $5, 'active', $6, $7, $8, $9, $10, $11, $12)
        ON CONFLICT (gateway_account_id, subscriber_id, gateway_payment_method_reference)
        DO UPDATE SET status = 'active', payment_type = EXCLUDED.payment_type,
            card_brand = EXCLUDED.card_brand, card_last4 = EXCLUDED.card_last4,
            card_exp_month = EXCLUDED.card_exp_month,
            card_exp_year = EXCLUDED.card_exp_year,
            billing_name = EXCLUDED.billing_name,
            billing_email = EXCLUDED.billing_email,
            updated_at = clock_timestamp()
        RETURNING id
        "#,
    )
    .bind(Uuid::now_v7())
    .bind(identity.billing_scope_id().as_uuid())
    .bind(identity.subscriber_id().as_uuid())
    .bind(identity.gateway_account_id().as_uuid())
    .bind(reference.expose())
    .bind(descriptor.payment_type().map(GatewayDiagnostic::expose))
    .bind(descriptor.card_brand().map(GatewayDiagnostic::expose))
    .bind(descriptor.card_last_four().map(|value| value.expose()))
    .bind(descriptor.card_exp_month())
    .bind(descriptor.card_exp_year())
    .bind(attempt.request().billing_contact().name())
    .bind(attempt.request().billing_contact().email())
    .fetch_one(connection)
    .await?;
    Ok(PaymentMethodId::new(row_id))
}

async fn mark_attempt_approved(
    connection: &mut PgConnection,
    attempt: &PaymentAttempt,
    evidence: &ProcessorEvidence,
    subscription_id: SubscriptionId,
    method_id: PaymentMethodId,
) -> Result<(), SubscriptionEnrollmentApplicationError> {
    persist_attempt_transition(
        connection,
        attempt,
        evidence,
        AttemptTransition::Approved(AttemptApproval::Subscription {
            subscription_id,
            payment_method_id: method_id,
        }),
    )
    .await
    .map_err(map_attempt_transition_error)
}

pub(crate) async fn park_locked_attempt(
    connection: &mut PgConnection,
    attempt: &PaymentAttempt,
    evidence: &ProcessorEvidence,
    resolution_code: Option<PaymentResolutionCode>,
    message: &'static str,
) -> Result<PaymentAttempt, SubscriptionEnrollmentApplicationError> {
    persist_attempt_transition(
        connection,
        attempt,
        evidence,
        AttemptTransition::LateApprovalReview {
            resolution_code,
            message,
        },
    )
    .await
    .map_err(map_attempt_transition_error)?;
    find_payment_attempt_by_id_on_connection(
        connection,
        attempt.identity().billing_scope_id(),
        attempt.identity().attempt_id(),
    )
    .await?
    .ok_or(SubscriptionEnrollmentApplicationError::InvalidState(
        INVALID_APPLICATION_STATE,
    ))
}

fn evidence_looks_approved(evidence: &ProcessorEvidence) -> bool {
    evidence.transaction_id().is_some()
        && (evidence
            .response()
            .is_some_and(|value| syrup_rail::gateway_response_is_approved(Some(value.expose())))
            || evidence
                .condition()
                .is_some_and(|value| syrup_rail::gateway_state_is_approved(value.expose())))
}

pub(crate) async fn payment_result_for_attempt(
    connection: &mut PgConnection,
    attempt: PaymentAttempt,
) -> Result<SubscriptionEnrollmentPaymentResult, SubscriptionEnrollmentApplicationError> {
    let subscription = match attempt.kind() {
        PaymentAttemptKind::SubscriptionRecovery
        | PaymentAttemptKind::SubscriptionPaymentMethodUpdate => {
            load_applied_subscription(connection, &attempt).await?
        }
        _ if attempt.status() == PaymentAttemptStatus::Approved => {
            load_applied_subscription(connection, &attempt).await?
        }
        _ => None,
    };
    Ok(SubscriptionEnrollmentPaymentResult::new(
        attempt,
        subscription,
    ))
}

async fn load_applied_subscription(
    connection: &mut PgConnection,
    attempt: &PaymentAttempt,
) -> Result<Option<Subscription>, SubscriptionEnrollmentApplicationError> {
    let Some(subscription_id) = attempt.request().target().subscription_id() else {
        return Ok(None);
    };
    load_subscription(
        connection,
        attempt.identity().billing_scope_id(),
        subscription_id,
    )
    .await
}

async fn load_subscription(
    connection: &mut PgConnection,
    billing_scope_id: BillingScopeId,
    subscription_id: SubscriptionId,
) -> Result<Option<Subscription>, SubscriptionEnrollmentApplicationError> {
    let row = sqlx::query(
        r#"
        SELECT id, plan_key, status, payment_method_id, amount_cents, currency,
            current_period_start_at, current_period_end_at, next_renewal_at,
            phase, recurring_period_kind, recurring_period_count,
            dunning_retry_delays_seconds, dunning_exhaustion, past_due_access,
            next_payment_attempt_at
        FROM billing_subscriptions
        WHERE billing_scope_id = $1 AND id = $2
        "#,
    )
    .bind(billing_scope_id.as_uuid())
    .bind(subscription_id.as_uuid())
    .fetch_optional(connection)
    .await?;
    row.map(|row| decode_subscription_row(&row).map_err(map_subscription_persistence_error))
        .transpose()
}

#[cfg(test)]
mod tests;