syrup-rail 0.5.0

Validated domain types and lifecycle policy for Syrup Rail billing
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
use chrono::{DateTime, Utc};

use crate::{
    ApprovedProcessorEvidence, BillingContact, BillingContactSnapshot, BillingScopeId,
    ChargeAmount, GatewayAccountMode, GatewayConfigurationId, GatewayPaymentDiagnostic,
    HostChargeTargetId, IdempotencyKey, PaymentAttempt, PaymentAttemptFingerprint,
    PaymentAttemptId, PaymentAttemptIdentity, PaymentAttemptKind, PaymentAttemptRequest,
    PaymentAttemptStatus, PaymentAttemptTarget, PaymentReversalKind, PaymentToken,
    ProcessorEvidence, ResolvedGateway, SubscriberId,
};
use thiserror::Error;

/// Provider-neutral request to charge one host-owned target.
///
/// The host extension supplies the authoritative price and eligibility; the
/// caller cannot choose either value.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ChargeHostTarget {
    billing_scope_id: BillingScopeId,
    subscriber_id: SubscriberId,
    target_id: HostChargeTargetId,
    gateway_configuration_id: GatewayConfigurationId,
    payment_token: PaymentToken,
    idempotency_key: IdempotencyKey,
    billing_contact: Option<BillingContact>,
}

impl ChargeHostTarget {
    #[allow(clippy::too_many_arguments)]
    pub const fn new(
        billing_scope_id: BillingScopeId,
        subscriber_id: SubscriberId,
        target_id: HostChargeTargetId,
        gateway_configuration_id: GatewayConfigurationId,
        payment_token: PaymentToken,
        idempotency_key: IdempotencyKey,
        billing_contact: Option<BillingContact>,
    ) -> Self {
        Self {
            billing_scope_id,
            subscriber_id,
            target_id,
            gateway_configuration_id,
            payment_token,
            idempotency_key,
            billing_contact,
        }
    }

    pub const fn billing_scope_id(&self) -> BillingScopeId {
        self.billing_scope_id
    }

    pub const fn subscriber_id(&self) -> SubscriberId {
        self.subscriber_id
    }

    pub const fn target_id(&self) -> HostChargeTargetId {
        self.target_id
    }

    pub const fn gateway_configuration_id(&self) -> GatewayConfigurationId {
        self.gateway_configuration_id
    }

    pub const fn payment_token(&self) -> &PaymentToken {
        &self.payment_token
    }

    pub const fn idempotency_key(&self) -> &IdempotencyKey {
        &self.idempotency_key
    }

    pub const fn billing_contact(&self) -> Option<&BillingContact> {
        self.billing_contact.as_ref()
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HostChargeTargetSnapshot {
    target_id: HostChargeTargetId,
    charge: ChargeAmount,
}

impl HostChargeTargetSnapshot {
    pub const fn new(target_id: HostChargeTargetId, charge: ChargeAmount) -> Self {
        Self { target_id, charge }
    }

    pub const fn target_id(self) -> HostChargeTargetId {
        self.target_id
    }

    pub const fn charge(self) -> ChargeAmount {
        self.charge
    }
}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum HostChargeReservationBuildError {
    #[error("resolved gateway identity does not match the host charge command")]
    GatewayIdentityMismatch,
    #[error("host target snapshot does not match the command target")]
    TargetIdentityMismatch,
    #[error("payment attempt is not a host charge")]
    AttemptKindMismatch,
    #[error("host charge attempt has invalid economics")]
    InvalidCharge,
}

/// Token-free durable reservation assembled after gateway resolution.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HostChargeReservation {
    identity: PaymentAttemptIdentity,
    request: PaymentAttemptRequest,
    snapshot: HostChargeTargetSnapshot,
}

impl HostChargeReservation {
    pub fn from_command(
        command: &ChargeHostTarget,
        snapshot: HostChargeTargetSnapshot,
        gateway: &ResolvedGateway,
        attempt_id: PaymentAttemptId,
        required_gateway_account_mode: GatewayAccountMode,
    ) -> Result<Self, HostChargeReservationBuildError> {
        if snapshot.target_id() != command.target_id() {
            return Err(HostChargeReservationBuildError::TargetIdentityMismatch);
        }
        if gateway.billing_scope_id() != command.billing_scope_id()
            || gateway.gateway_configuration_id() != command.gateway_configuration_id()
        {
            return Err(HostChargeReservationBuildError::GatewayIdentityMismatch);
        }
        let identity = PaymentAttemptIdentity::new(
            attempt_id,
            command.billing_scope_id(),
            command.subscriber_id(),
            gateway.gateway_account_id(),
            command.gateway_configuration_id(),
            required_gateway_account_mode,
        );
        let amount = snapshot.charge().money();
        let request = PaymentAttemptRequest::new(
            PaymentAttemptTarget::HostCharge {
                target_id: command.target_id(),
            },
            command.idempotency_key().clone(),
            PaymentAttemptFingerprint::for_host_charge(command.target_id(), amount),
            amount,
            gateway
                .mutation_reference_factory()
                .for_attempt(PaymentAttemptKind::HostCharge, attempt_id),
            command
                .billing_contact()
                .map(BillingContactSnapshot::from_billing_contact)
                .unwrap_or_else(|| BillingContactSnapshot::new(None, None)),
        );
        Ok(Self {
            identity,
            request,
            snapshot,
        })
    }

    pub const fn identity(&self) -> PaymentAttemptIdentity {
        self.identity
    }

    pub const fn request(&self) -> &PaymentAttemptRequest {
        &self.request
    }

    pub const fn snapshot(&self) -> HostChargeTargetSnapshot {
        self.snapshot
    }

    pub fn from_attempt(attempt: &PaymentAttempt) -> Result<Self, HostChargeReservationBuildError> {
        let target_id = attempt
            .request()
            .target()
            .host_charge_target_id()
            .ok_or(HostChargeReservationBuildError::AttemptKindMismatch)?;
        let charge = ChargeAmount::try_from(attempt.request().amount())
            .map_err(|_| HostChargeReservationBuildError::InvalidCharge)?;
        Ok(Self {
            identity: attempt.identity(),
            request: attempt.request().clone(),
            snapshot: HostChargeTargetSnapshot::new(target_id, charge),
        })
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HostChargeTargetRejection {
    TargetUnavailable,
    ChargeChanged,
    LedgerUnsafe,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HostChargeTargetTransitionKind {
    Paid,
    /// Releases a claimed target after the provider mutation was provably not
    /// submitted. This can occur before or after submission admission.
    ReleasedBeforeSubmission,
    PaymentFailed,
    ReleasedAfterExternalReversal {
        kind: PaymentReversalKind,
    },
    Reversed {
        kind: PaymentReversalKind,
    },
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HostChargeTargetTransition {
    billing_scope_id: BillingScopeId,
    subscriber_id: SubscriberId,
    attempt_id: PaymentAttemptId,
    target_id: HostChargeTargetId,
    kind: HostChargeTargetTransitionKind,
    effective_at: DateTime<Utc>,
}

impl HostChargeTargetTransition {
    pub const fn new(
        billing_scope_id: BillingScopeId,
        subscriber_id: SubscriberId,
        attempt_id: PaymentAttemptId,
        target_id: HostChargeTargetId,
        kind: HostChargeTargetTransitionKind,
        effective_at: DateTime<Utc>,
    ) -> Self {
        Self {
            billing_scope_id,
            subscriber_id,
            attempt_id,
            target_id,
            kind,
            effective_at,
        }
    }

    pub const fn billing_scope_id(self) -> BillingScopeId {
        self.billing_scope_id
    }

    pub const fn subscriber_id(self) -> SubscriberId {
        self.subscriber_id
    }

    pub const fn attempt_id(self) -> PaymentAttemptId {
        self.attempt_id
    }

    pub const fn target_id(self) -> HostChargeTargetId {
        self.target_id
    }

    pub const fn kind(self) -> HostChargeTargetTransitionKind {
        self.kind
    }

    pub const fn effective_at(self) -> DateTime<Utc> {
        self.effective_at
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HostChargeTargetNoChange {
    Missing,
    InapplicableState,
    ReleaseUnsafe,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HostChargeTargetTransitionOutcome {
    Applied,
    ExactReplay,
    StaleTarget,
    Unchanged { reason: HostChargeTargetNoChange },
}

impl HostChargeTargetTransitionOutcome {
    /// Returns whether the requested transition is durably reflected in host state.
    pub const fn is_applied(self) -> bool {
        matches!(self, Self::Applied | Self::ExactReplay)
    }
}

/// Durable result of applying one host-target payment outcome.
///
/// Equality compares the durable attempt and pending-confirmation evidence.
/// Call-scoped gateway diagnostics are intentionally excluded because an exact
/// replay may not reproduce them.
#[derive(Clone, Debug)]
pub struct HostChargePaymentResult {
    attempt: PaymentAttempt,
    pending_confirmation_evidence: Option<ApprovedProcessorEvidence>,
    gateway_diagnostics: Vec<GatewayPaymentDiagnostic>,
}

impl PartialEq for HostChargePaymentResult {
    fn eq(&self, other: &Self) -> bool {
        self.attempt == other.attempt
            && self.pending_confirmation_evidence == other.pending_confirmation_evidence
    }
}

impl Eq for HostChargePaymentResult {}

#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
pub enum HostChargePaymentResultBuildError {
    #[error("a host-charge payment result requires a host-charge attempt")]
    AttemptNotHostCharge,
    #[error("an approved attempt cannot produce a confirmation-pending payment result")]
    ConfirmationPendingAttemptApproved,
}

impl HostChargePaymentResult {
    pub fn new(attempt: PaymentAttempt) -> Result<Self, HostChargePaymentResultBuildError> {
        require_host_charge_attempt(&attempt)?;
        Ok(Self {
            attempt,
            pending_confirmation_evidence: None,
            gateway_diagnostics: Vec::new(),
        })
    }

    pub fn confirmation_pending(
        attempt: PaymentAttempt,
        evidence: ApprovedProcessorEvidence,
    ) -> Result<Self, HostChargePaymentResultBuildError> {
        require_host_charge_attempt(&attempt)?;
        if attempt.status() == PaymentAttemptStatus::Approved {
            return Err(HostChargePaymentResultBuildError::ConfirmationPendingAttemptApproved);
        }
        Ok(Self {
            attempt,
            pending_confirmation_evidence: Some(evidence),
            gateway_diagnostics: Vec::new(),
        })
    }

    /// Attaches payload-free diagnostics from the gateway observation applied
    /// by the current call.
    ///
    /// These diagnostics are foreground routing facts, not durable attempt
    /// state. A later replay reconstructs the canonical payment result from
    /// persisted processor evidence and may not contain them.
    pub fn with_gateway_diagnostics(mut self, diagnostics: Vec<GatewayPaymentDiagnostic>) -> Self {
        self.gateway_diagnostics = diagnostics;
        self
    }

    /// Returns payload-free diagnostics from the gateway observation applied
    /// by the current call.
    pub fn gateway_diagnostics(&self) -> &[GatewayPaymentDiagnostic] {
        &self.gateway_diagnostics
    }

    pub const fn attempt(&self) -> &PaymentAttempt {
        &self.attempt
    }

    pub const fn status(&self) -> PaymentAttemptStatus {
        if self.pending_confirmation_evidence.is_some() {
            PaymentAttemptStatus::Unknown
        } else {
            self.attempt.status()
        }
    }

    pub fn processor_evidence(&self) -> &ProcessorEvidence {
        self.pending_confirmation_evidence
            .as_ref()
            .map(ApprovedProcessorEvidence::evidence)
            .unwrap_or_else(|| self.attempt.state().processor_evidence())
    }

    pub const fn is_confirmation_pending(&self) -> bool {
        self.pending_confirmation_evidence.is_some()
    }
}

fn require_host_charge_attempt(
    attempt: &PaymentAttempt,
) -> Result<(), HostChargePaymentResultBuildError> {
    if attempt.kind() == PaymentAttemptKind::HostCharge {
        Ok(())
    } else {
        Err(HostChargePaymentResultBuildError::AttemptNotHostCharge)
    }
}

#[cfg(test)]
mod tests {
    use uuid::Uuid;

    use super::*;
    use crate::{CurrencyCode, Money, PaymentAttemptFingerprint};

    #[test]
    fn host_charge_fingerprint_is_target_and_economics_exact() {
        let target = HostChargeTargetId::new(Uuid::from_u128(1));
        let money = Money::new(1_250, CurrencyCode::new("USD").unwrap()).unwrap();
        let fingerprint = PaymentAttemptFingerprint::for_host_charge(target, money);

        assert_eq!(
            fingerprint.expose(),
            "host_charge:00000000-0000-0000-0000-000000000001:1250:USD"
        );
        assert_eq!(fingerprint.to_string(), "[redacted]");
    }

    #[test]
    fn target_transition_outcome_identifies_durable_application() {
        assert!(HostChargeTargetTransitionOutcome::Applied.is_applied());
        assert!(HostChargeTargetTransitionOutcome::ExactReplay.is_applied());
        assert!(!HostChargeTargetTransitionOutcome::StaleTarget.is_applied());
        assert!(
            !HostChargeTargetTransitionOutcome::Unchanged {
                reason: HostChargeTargetNoChange::ReleaseUnsafe,
            }
            .is_applied()
        );
    }
}