syrup-rail-postgres 0.5.0

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
use super::*;

#[tokio::test]
async fn active_grant_blocks_only_its_exact_plan() -> Result<(), Box<dyn Error>> {
    let database = TestDatabase::start("enroll_grant").await?;
    install_host_offers(&database).await?;
    let account = create_gateway_account(&database.pool, "nmi").await?;
    set_offer(&database, account.billing_scope_id, "basic", 1_000).await?;
    set_offer(&database, account.billing_scope_id, "premium", 2_000).await?;
    let subscriber_id = Uuid::now_v7();
    sqlx::query(
        r#"
            INSERT INTO billing_subscription_grants (
                id, billing_scope_id, subscriber_id, plan_key, grant_kind,
                reason, starts_at, ends_at, granted_by_actor_id
            ) VALUES (
                $1, $2, $3, 'basic', 'promotion', 'launch',
                clock_timestamp() - interval '1 minute',
                clock_timestamp() + interval '1 day', $4
            )
            "#,
    )
    .bind(Uuid::now_v7())
    .bind(account.billing_scope_id)
    .bind(subscriber_id)
    .bind(Uuid::now_v7())
    .execute(&database.pool)
    .await?;
    let gateway = resolved_gateway(account);

    let basic = SubscriptionEnrollmentReservation::from_command(
        &enrollment_command(
            account,
            subscriber_id,
            Uuid::now_v7(),
            "basic-grant",
            full_price("basic", 1_000),
        ),
        &gateway,
        GatewayAccountMode::Live,
    )?;
    let mut transaction = database.pool.begin().await?;
    assert_eq!(
        reserve_subscription_enrollment_in_transaction(&mut transaction, &TestOfferStore, &basic,)
            .await?,
        SubscriptionEnrollmentReservationOutcome::Rejected(
            SubscriptionEnrollmentReservationRejection::ActiveGrant,
        )
    );
    transaction.rollback().await?;

    let premium = SubscriptionEnrollmentReservation::from_command(
        &enrollment_command(
            account,
            subscriber_id,
            Uuid::now_v7(),
            "premium-with-basic-grant",
            full_price("premium", 2_000),
        ),
        &gateway,
        GatewayAccountMode::Live,
    )?;
    let mut transaction = database.pool.begin().await?;
    assert!(matches!(
            reserve_subscription_enrollment_in_transaction(
                &mut transaction,
                &TestOfferStore,
                &premium,
            )
            .await?,
            SubscriptionEnrollmentReservationOutcome::Reserved(_)
        ));
    transaction.commit().await?;
    database.cleanup().await
}

#[tokio::test]
async fn gateway_configuration_rotation_rejects_prepared_submission() -> Result<(), Box<dyn Error>>
{
    let database = TestDatabase::start("enroll_rotate").await?;
    install_host_offers(&database).await?;
    let account = create_gateway_account(&database.pool, "nmi").await?;
    let plan_key = "base_subscription";
    set_offer(&database, account.billing_scope_id, plan_key, 1_000).await?;
    let gateway = resolved_gateway(account);
    let reservation = SubscriptionEnrollmentReservation::from_command(
        &enrollment_command(
            account,
            Uuid::now_v7(),
            Uuid::now_v7(),
            "rotated-configuration",
            full_price(plan_key, 1_000),
        ),
        &gateway,
        GatewayAccountMode::Live,
    )?;
    let mut transaction = database.pool.begin().await?;
    assert!(matches!(
        reserve_subscription_enrollment_in_transaction(
            &mut transaction,
            &TestOfferStore,
            &reservation,
        )
        .await?,
        SubscriptionEnrollmentReservationOutcome::Reserved(_)
    ));
    transaction.commit().await?;

    sqlx::query(
            "UPDATE billing_gateway_accounts SET gateway_configuration_id = $2, updated_at = clock_timestamp() WHERE id = $1",
        )
        .bind(account.gateway_account_id)
        .bind(Uuid::now_v7())
        .execute(&database.pool)
        .await?;
    let mut transaction = database.pool.begin().await?;
    let rejected = admit_subscription_enrollment_submission_in_transaction(
        &mut transaction,
        &TestOfferStore,
        &reservation,
    )
    .await?;
    assert!(matches!(
        rejected,
        SubscriptionEnrollmentSubmissionOutcome::Rejected {
            ref attempt,
            reason: SubscriptionEnrollmentSubmissionRejection::GatewayConfigurationChanged,
        } if attempt.status() == PaymentAttemptStatus::Failed
            && attempt.state().timestamps().submitted_at().is_none()
    ));
    transaction.commit().await?;

    database.cleanup().await
}

#[tokio::test]
async fn enrollment_admission_returns_typed_rejection_for_changed_required_mode()
-> Result<(), Box<dyn Error>> {
    let database = TestDatabase::start("enr_mode_admit").await?;
    install_host_offers(&database).await?;
    let account = create_gateway_account(&database.pool, "nmi").await?;
    let plan_key = "base_subscription";
    set_offer(&database, account.billing_scope_id, plan_key, 1_000).await?;
    let gateway = resolved_gateway(account);
    let command = enrollment_command(
        account,
        Uuid::now_v7(),
        Uuid::now_v7(),
        "admission-mode-change",
        full_price(plan_key, 1_000),
    );
    let live_reservation = SubscriptionEnrollmentReservation::from_command(
        &command,
        &gateway,
        GatewayAccountMode::Live,
    )?;
    let mut transaction = database.pool.begin().await?;
    assert!(matches!(
        reserve_subscription_enrollment_in_transaction(
            &mut transaction,
            &TestOfferStore,
            &live_reservation,
        )
        .await?,
        SubscriptionEnrollmentReservationOutcome::Reserved(_)
    ));
    transaction.commit().await?;

    let test_reservation = SubscriptionEnrollmentReservation::from_command(
        &command,
        &gateway,
        GatewayAccountMode::Test,
    )?;
    let mut transaction = database.pool.begin().await?;
    let rejected = admit_subscription_enrollment_submission_in_transaction(
        &mut transaction,
        &TestOfferStore,
        &test_reservation,
    )
    .await?;
    assert!(matches!(
        rejected,
        SubscriptionEnrollmentSubmissionOutcome::Rejected {
            ref attempt,
            reason: SubscriptionEnrollmentSubmissionRejection::GatewayAccountModeChanged,
        } if attempt.status() == PaymentAttemptStatus::Pending
            && attempt.state().timestamps().submitted_at().is_none()
    ));
    transaction.commit().await?;
    let mut transaction = database.pool.begin().await?;
    assert!(matches!(
        admit_subscription_enrollment_submission_in_transaction(
            &mut transaction,
            &TestOfferStore,
            &live_reservation,
        )
        .await?,
        SubscriptionEnrollmentSubmissionOutcome::Admitted(_)
    ));
    transaction.rollback().await?;

    let withdrawn_command = enrollment_command(
        account,
        Uuid::now_v7(),
        Uuid::now_v7(),
        "withdrawn-offer-mode-change",
        full_price(plan_key, 1_000),
    );
    let withdrawn_live_reservation = SubscriptionEnrollmentReservation::from_command(
        &withdrawn_command,
        &gateway,
        GatewayAccountMode::Live,
    )?;
    let mut transaction = database.pool.begin().await?;
    assert!(matches!(
        reserve_subscription_enrollment_in_transaction(
            &mut transaction,
            &TestOfferStore,
            &withdrawn_live_reservation,
        )
        .await?,
        SubscriptionEnrollmentReservationOutcome::Reserved(_)
    ));
    transaction.commit().await?;
    sqlx::query(
        "DELETE FROM host_subscription_offers WHERE billing_scope_id = $1 AND plan_key = $2",
    )
    .bind(account.billing_scope_id)
    .bind(plan_key)
    .execute(&database.pool)
    .await?;
    let withdrawn_test_reservation = SubscriptionEnrollmentReservation::from_command(
        &withdrawn_command,
        &gateway,
        GatewayAccountMode::Test,
    )?;
    let mut transaction = database.pool.begin().await?;
    let rejected = admit_subscription_enrollment_submission_in_transaction(
        &mut transaction,
        &TestOfferStore,
        &withdrawn_test_reservation,
    )
    .await?;
    assert!(matches!(
        rejected,
        SubscriptionEnrollmentSubmissionOutcome::Rejected {
            ref attempt,
            reason: SubscriptionEnrollmentSubmissionRejection::GatewayAccountModeChanged,
        } if attempt.status() == PaymentAttemptStatus::Pending
            && attempt.state().timestamps().submitted_at().is_none()
    ));
    transaction.commit().await?;
    database.cleanup().await
}

#[tokio::test]
async fn loaders_preserve_exact_scope_and_redact_durable_values() -> Result<(), Box<dyn Error>> {
    let database = TestDatabase::start("attempt_owner").await?;
    let account = create_gateway_account(&database.pool, "nmi").await?;
    let attempt_id = Uuid::now_v7();
    let subscriber_id = Uuid::now_v7();
    sqlx::query(
        r#"
            INSERT INTO billing_payment_attempts (
                required_gateway_account_mode,
                id, billing_scope_id, subscriber_id, host_charge_target_id,
                attempt_kind, status, idempotency_key, request_fingerprint,
                amount_cents, currency, gateway_account_id,
                gateway_configuration_id, gateway_order_id,
                gateway_transaction_id, gateway_payment_method_reference,
                gateway_response, gateway_response_code, gateway_response_text,
                gateway_condition, billing_first_name, billing_last_name,
                billing_email
            ) VALUES (
                'live',
                $1, $2, $3, $4, 'host_charge', 'pending', $5, $6,
                1000, 'USD', $7, $8, $9, $10, $11, $12, $13, $14,
                $15, $16, $17, $18
            )
            "#,
    )
    .bind(attempt_id)
    .bind(account.billing_scope_id)
    .bind(subscriber_id)
    .bind(Uuid::now_v7())
    .bind("idempotency-secret")
    .bind("fingerprint-secret")
    .bind(account.gateway_account_id)
    .bind(account.gateway_configuration_id)
    .bind("order-secret")
    .bind("transaction-secret")
    .bind("method-secret")
    .bind("response-secret")
    .bind("code-secret")
    .bind("text-secret")
    .bind("condition-secret")
    .bind("Sensitive")
    .bind("Name")
    .bind("secret@example.test")
    .execute(&database.pool)
    .await?;

    let mut transaction = database.pool.begin().await?;
    assert!(
        find_payment_attempt_by_id_in_transaction(
            &mut transaction,
            BillingScopeId::new(Uuid::now_v7()),
            PaymentAttemptId::new(attempt_id),
        )
        .await?
        .is_none()
    );
    let attempt = lock_payment_attempt_by_idempotency_in_transaction(
        &mut transaction,
        BillingScopeId::new(account.billing_scope_id),
        SubscriberId::new(subscriber_id),
        &IdempotencyKey::new("idempotency-secret")?,
    )
    .await?
    .expect("exact owner row should load");
    assert_eq!(attempt.identity().attempt_id().as_uuid(), &attempt_id);
    assert_eq!(attempt.kind(), PaymentAttemptKind::HostCharge);
    assert_eq!(attempt.request().amount().cents(), 1_000);
    assert_eq!(
        attempt
            .state()
            .processor_evidence()
            .transaction_id()
            .expect("transaction ID")
            .expose(),
        "transaction-secret"
    );
    let debug = format!("{attempt:?}");
    for secret in [
        "idempotency-secret",
        "fingerprint-secret",
        "order-secret",
        "transaction-secret",
        "method-secret",
        "response-secret",
        "code-secret",
        "text-secret",
        "condition-secret",
        "Sensitive Name",
        "secret@example.test",
    ] {
        assert!(!debug.contains(secret), "debug leaked {secret}");
    }
    transaction.rollback().await?;
    database.cleanup().await
}

#[tokio::test]
async fn recovery_keeps_related_and_expected_payment_methods_distinct() -> Result<(), Box<dyn Error>>
{
    let database = TestDatabase::start("attempt_recovery").await?;
    let account = create_gateway_account(&database.pool, "nmi").await?;
    let subscriber_id = Uuid::now_v7();
    let expected_method_id = Uuid::now_v7();
    let related_method_id = Uuid::now_v7();
    for (method_id, reference) in [
        (expected_method_id, "vault-expected"),
        (related_method_id, "vault-related"),
    ] {
        sqlx::query(
            r#"
                INSERT INTO billing_payment_methods (
                    id, billing_scope_id, subscriber_id, gateway_account_id,
                    gateway_payment_method_reference, status
                ) VALUES ($1, $2, $3, $4, $5, 'active')
                "#,
        )
        .bind(method_id)
        .bind(account.billing_scope_id)
        .bind(subscriber_id)
        .bind(account.gateway_account_id)
        .bind(reference)
        .execute(&database.pool)
        .await?;
    }
    let subscription_id = Uuid::now_v7();
    let period_start = Utc::now();
    let period_end = period_start + Duration::days(30);
    sqlx::query(
        r#"
            INSERT INTO billing_subscriptions (
            required_gateway_account_mode,
                id, billing_scope_id, subscriber_id, plan_key, status,
                gateway_account_id, payment_method_id, amount_cents, currency,
                current_period_start_at, current_period_end_at, next_renewal_at,
                initial_transaction_id, phase, recurring_period_kind,
                recurring_period_count, dunning_retry_delays_seconds,
                dunning_exhaustion, past_due_access, next_payment_attempt_at
            ) VALUES (
                'live',
                $1, $2, $3, 'premium', 'active', $4, $5, 1000, 'USD',
                $6, $7, $7, 'txn-initial', 'recurring', 'calendar_months', 1,
                ARRAY[]::bigint[], 'remain_past_due', 'suspend_immediately', $7
            )
            "#,
    )
    .bind(subscription_id)
    .bind(account.billing_scope_id)
    .bind(subscriber_id)
    .bind(account.gateway_account_id)
    .bind(related_method_id)
    .bind(period_start)
    .bind(period_end)
    .execute(&database.pool)
    .await?;

    let attempt_id = Uuid::now_v7();
    let charge_start = period_end;
    let charge_end = charge_start + Duration::days(30);
    let order_id = format!("sr_recovery_{}", attempt_id.simple());
    sqlx::query(
        r#"
            INSERT INTO billing_payment_attempts (
                required_gateway_account_mode,
                id, billing_scope_id, subscriber_id, plan_key,
                subscription_id, payment_method_id, attempt_kind, status,
                idempotency_key, request_fingerprint, amount_cents, currency,
                billing_period_start_at, billing_period_end_at,
                gateway_account_id, gateway_configuration_id, gateway_order_id,
                gateway_transaction_id, submitted_at, resolved_at,
                subscription_expected_payment_method_id,
                subscription_expected_initial_transaction_id,
                subscription_expected_status
            ) VALUES (
                'live',
                $1, $2, $3, 'premium', $4, $5,
                'subscription_recovery', 'approved', $6, $7, 1000, 'USD',
                $8, $9, $10, $11, $12, 'txn-recovery', now(), now(),
                $13, 'txn-initial', 'past_due'
            )
            "#,
    )
    .bind(attempt_id)
    .bind(account.billing_scope_id)
    .bind(subscriber_id)
    .bind(subscription_id)
    .bind(related_method_id)
    .bind("recovery-key")
    .bind("recovery-fingerprint")
    .bind(charge_start)
    .bind(charge_end)
    .bind(account.gateway_account_id)
    .bind(account.gateway_configuration_id)
    .bind(order_id)
    .bind(expected_method_id)
    .execute(&database.pool)
    .await?;

    let mut transaction = database.pool.begin().await?;
    let attempt = find_payment_attempt_by_id_in_transaction(
        &mut transaction,
        BillingScopeId::new(account.billing_scope_id),
        PaymentAttemptId::new(attempt_id),
    )
    .await?
    .expect("recovery row should load");
    let target = attempt.request().target();
    assert_eq!(
        target.payment_method_id().unwrap().as_uuid(),
        &related_method_id
    );
    assert_eq!(
        target.subscription_id().unwrap().as_uuid(),
        &subscription_id
    );
    assert_eq!(
        target
            .subscription_payment_state_snapshot()
            .expect("expected state")
            .payment_method_id()
            .as_uuid(),
        &expected_method_id
    );
    assert_eq!(
        target
            .subscription_payment_state_snapshot()
            .expect("expected state")
            .status(),
        SubscriptionStatus::PastDue
    );
    transaction.rollback().await?;
    database.cleanup().await
}