tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
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
//! Billing-specific error types.
//!
//! Provides granular error types for billing operations, enabling better
//! error handling and more informative error messages for API consumers.

use std::fmt;

/// Billing-specific errors.
///
/// These errors provide more context than generic errors and can be
/// converted to `TidewayError` for HTTP responses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BillingError {
    // Validation errors
    /// The billable ID is invalid.
    InvalidBillableId { id: String, reason: String },
    /// The plan ID is invalid.
    InvalidPlanId { id: String, reason: String },

    // Plan errors
    /// The specified plan was not found.
    PlanNotFound { plan_id: String },
    /// The plan does not support extra seats.
    PlanDoesNotSupportSeats { plan_id: String },
    /// The requested feature is not available on this plan.
    FeatureNotIncluded { feature: String, plan_id: String },
    /// Cannot delete a plan that has active subscriptions.
    PlanHasActiveSubscriptions {
        plan_id: String,
        subscription_count: u32,
    },
    /// The Stripe price ID is invalid or does not exist.
    InvalidStripePrice { price_id: String, reason: String },
    /// A plan is missing required Stripe pricing metadata.
    MissingStripePrice { plan_id: String },
    /// Duplicate plan ID encountered during plan construction.
    DuplicatePlanId { plan_id: String },

    // Subscription errors
    /// No subscription found for the billable entity.
    NoSubscription { billable_id: String },
    /// The subscription is not active.
    SubscriptionInactive { billable_id: String },
    /// The subscription is scheduled for cancellation but was expected to be active.
    SubscriptionCancelling { billable_id: String },
    /// Cannot find the Stripe subscription.
    StripeSubscriptionNotFound { subscription_id: String },

    // Customer errors
    /// No Stripe customer found for the billable entity.
    NoCustomer { billable_id: String },

    // Invoice errors
    /// Invoice not found or doesn't belong to the customer.
    InvoiceNotFound { invoice_id: String },

    // Payment method errors
    /// Payment method not found or doesn't belong to the customer.
    PaymentMethodNotFound { payment_method_id: String },

    // Refund errors
    /// Refund not found.
    RefundNotFound { refund_id: String },
    /// Refund operation failed.
    RefundFailed { reason: String },
    /// Charge not found for refund.
    ChargeNotFound { charge_id: String },

    // Seat errors
    /// Cannot remove more seats than are currently extra.
    InsufficientSeats { requested: u32, available: u32 },
    /// Seat count must be positive.
    InvalidSeatCount { message: String },
    /// Concurrent modification detected, retry the operation.
    ConcurrentModification { billable_id: String },

    // Trial errors
    /// Subscription is not in trialing state.
    SubscriptionNotTrialing { billable_id: String },

    // Pause errors
    /// Subscription is not paused.
    SubscriptionNotPaused { billable_id: String },
    /// Subscription is already paused.
    SubscriptionAlreadyPaused { billable_id: String },

    // Checkout errors
    /// Invalid redirect URL provided.
    InvalidRedirectUrl { url: String, reason: String },
    /// Redirect URL domain not in allowed list.
    RedirectDomainNotAllowed { domain: String },

    // Webhook errors
    /// Webhook signature is invalid.
    InvalidWebhookSignature,
    /// Webhook timestamp is too old (replay attack protection).
    WebhookTimestampExpired { age_seconds: i64 },
    /// Webhook event data is malformed.
    InvalidWebhookPayload { message: String },

    // Stripe API errors
    /// Stripe API returned an error.
    StripeApiError {
        operation: String,
        message: String,
        code: Option<String>,
        http_status: Option<u16>,
    },

    // General errors
    /// The operation failed after multiple retries.
    RetryLimitExceeded { operation: String },
    /// An unexpected internal error occurred.
    Internal { message: String },
}

impl fmt::Display for BillingError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidBillableId { id, reason } => {
                write!(f, "Invalid billable ID '{}': {}", id, reason)
            }
            Self::InvalidPlanId { id, reason } => {
                write!(f, "Invalid plan ID '{}': {}", id, reason)
            }
            Self::PlanNotFound { plan_id } => {
                write!(f, "Plan not found: {}", plan_id)
            }
            Self::PlanDoesNotSupportSeats { plan_id } => {
                write!(f, "Plan '{}' does not support extra seats", plan_id)
            }
            Self::FeatureNotIncluded { feature, plan_id } => {
                write!(
                    f,
                    "Feature '{}' is not included in plan '{}'",
                    feature, plan_id
                )
            }
            Self::PlanHasActiveSubscriptions {
                plan_id,
                subscription_count,
            } => {
                write!(
                    f,
                    "Cannot delete plan '{}': {} active subscription(s) exist",
                    plan_id, subscription_count
                )
            }
            Self::InvalidStripePrice { price_id, reason } => {
                write!(f, "Invalid Stripe price '{}': {}", price_id, reason)
            }
            Self::MissingStripePrice { plan_id } => {
                write!(f, "Plan '{}' is missing required stripe_price", plan_id)
            }
            Self::DuplicatePlanId { plan_id } => {
                write!(f, "Duplicate plan ID: '{}'", plan_id)
            }
            Self::NoSubscription { billable_id } => {
                write!(f, "No subscription found for '{}'", billable_id)
            }
            Self::SubscriptionInactive { billable_id } => {
                write!(f, "Subscription for '{}' is not active", billable_id)
            }
            Self::SubscriptionCancelling { billable_id } => {
                write!(
                    f,
                    "Subscription for '{}' is scheduled for cancellation",
                    billable_id
                )
            }
            Self::StripeSubscriptionNotFound { subscription_id } => {
                write!(f, "Stripe subscription not found: {}", subscription_id)
            }
            Self::NoCustomer { billable_id } => {
                write!(f, "No Stripe customer found for '{}'", billable_id)
            }
            Self::InvoiceNotFound { invoice_id } => {
                write!(f, "Invoice not found: {}", invoice_id)
            }
            Self::PaymentMethodNotFound { payment_method_id } => {
                write!(f, "Payment method not found: {}", payment_method_id)
            }
            Self::RefundNotFound { refund_id } => {
                write!(f, "Refund not found: {}", refund_id)
            }
            Self::RefundFailed { reason } => {
                write!(f, "Refund failed: {}", reason)
            }
            Self::ChargeNotFound { charge_id } => {
                write!(f, "Charge not found: {}", charge_id)
            }
            Self::InsufficientSeats {
                requested,
                available,
            } => {
                write!(
                    f,
                    "Cannot remove {} seats, only {} extra seats available",
                    requested, available
                )
            }
            Self::InvalidSeatCount { message } => {
                write!(f, "Invalid seat count: {}", message)
            }
            Self::ConcurrentModification { billable_id } => {
                write!(
                    f,
                    "Concurrent modification detected for '{}', please retry",
                    billable_id
                )
            }
            Self::SubscriptionNotTrialing { billable_id } => {
                write!(
                    f,
                    "Subscription for '{}' is not in trialing state",
                    billable_id
                )
            }
            Self::SubscriptionNotPaused { billable_id } => {
                write!(f, "Subscription for '{}' is not paused", billable_id)
            }
            Self::SubscriptionAlreadyPaused { billable_id } => {
                write!(f, "Subscription for '{}' is already paused", billable_id)
            }
            Self::InvalidRedirectUrl { url, reason } => {
                write!(f, "Invalid redirect URL '{}': {}", url, reason)
            }
            Self::RedirectDomainNotAllowed { domain } => {
                write!(f, "Redirect domain '{}' is not allowed", domain)
            }
            Self::InvalidWebhookSignature => {
                write!(f, "Invalid webhook signature")
            }
            Self::WebhookTimestampExpired { age_seconds } => {
                write!(f, "Webhook timestamp expired ({} seconds old)", age_seconds)
            }
            Self::InvalidWebhookPayload { message } => {
                write!(f, "Invalid webhook payload: {}", message)
            }
            Self::StripeApiError {
                operation,
                message,
                code,
                http_status,
            } => {
                write!(f, "Stripe API error during '{}': {}", operation, message)?;
                if let Some(code) = code {
                    write!(f, " (code: {})", code)?;
                }
                if let Some(status) = http_status {
                    write!(f, " [HTTP {}]", status)?;
                }
                Ok(())
            }
            Self::RetryLimitExceeded { operation } => {
                write!(f, "Operation '{}' failed after multiple retries", operation)
            }
            Self::Internal { message } => {
                write!(f, "Internal billing error: {}", message)
            }
        }
    }
}

impl std::error::Error for BillingError {}

impl From<BillingError> for crate::error::TidewayError {
    fn from(err: BillingError) -> Self {
        match &err {
            // Map to NotFound
            BillingError::PlanNotFound { .. }
            | BillingError::NoSubscription { .. }
            | BillingError::NoCustomer { .. }
            | BillingError::StripeSubscriptionNotFound { .. }
            | BillingError::InvoiceNotFound { .. }
            | BillingError::PaymentMethodNotFound { .. }
            | BillingError::RefundNotFound { .. }
            | BillingError::ChargeNotFound { .. } => {
                crate::error::TidewayError::NotFound(err.to_string())
            }

            // Map to Forbidden (subscription state issues)
            BillingError::SubscriptionInactive { .. }
            | BillingError::SubscriptionCancelling { .. }
            | BillingError::FeatureNotIncluded { .. } => {
                crate::error::TidewayError::Forbidden(err.to_string())
            }

            // Map to BadRequest (client errors)
            BillingError::InvalidBillableId { .. }
            | BillingError::InvalidPlanId { .. }
            | BillingError::PlanDoesNotSupportSeats { .. }
            | BillingError::PlanHasActiveSubscriptions { .. }
            | BillingError::InvalidStripePrice { .. }
            | BillingError::MissingStripePrice { .. }
            | BillingError::DuplicatePlanId { .. }
            | BillingError::InsufficientSeats { .. }
            | BillingError::InvalidSeatCount { .. }
            | BillingError::InvalidRedirectUrl { .. }
            | BillingError::RedirectDomainNotAllowed { .. }
            | BillingError::InvalidWebhookSignature
            | BillingError::WebhookTimestampExpired { .. }
            | BillingError::InvalidWebhookPayload { .. }
            | BillingError::SubscriptionNotTrialing { .. }
            | BillingError::SubscriptionNotPaused { .. }
            | BillingError::SubscriptionAlreadyPaused { .. } => {
                crate::error::TidewayError::BadRequest(err.to_string())
            }

            // Map to Internal (server errors)
            BillingError::ConcurrentModification { .. }
            | BillingError::RetryLimitExceeded { .. }
            | BillingError::Internal { .. }
            | BillingError::RefundFailed { .. } => {
                crate::error::TidewayError::Internal(err.to_string())
            }

            // Map Stripe API errors based on HTTP status
            BillingError::StripeApiError { http_status, .. } => match http_status {
                Some(400..=499) => crate::error::TidewayError::BadRequest(err.to_string()),
                _ => crate::error::TidewayError::Internal(err.to_string()),
            },
        }
    }
}

impl BillingError {
    /// Check if this is a client error (4xx).
    #[must_use]
    pub fn is_client_error(&self) -> bool {
        match self {
            Self::InvalidBillableId { .. }
            | Self::InvalidPlanId { .. }
            | Self::PlanNotFound { .. }
            | Self::NoSubscription { .. }
            | Self::NoCustomer { .. }
            | Self::StripeSubscriptionNotFound { .. }
            | Self::InvoiceNotFound { .. }
            | Self::PaymentMethodNotFound { .. }
            | Self::RefundNotFound { .. }
            | Self::ChargeNotFound { .. }
            | Self::SubscriptionInactive { .. }
            | Self::SubscriptionCancelling { .. }
            | Self::FeatureNotIncluded { .. }
            | Self::PlanDoesNotSupportSeats { .. }
            | Self::PlanHasActiveSubscriptions { .. }
            | Self::InvalidStripePrice { .. }
            | Self::MissingStripePrice { .. }
            | Self::DuplicatePlanId { .. }
            | Self::InsufficientSeats { .. }
            | Self::InvalidSeatCount { .. }
            | Self::InvalidRedirectUrl { .. }
            | Self::RedirectDomainNotAllowed { .. }
            | Self::InvalidWebhookSignature
            | Self::WebhookTimestampExpired { .. }
            | Self::InvalidWebhookPayload { .. }
            | Self::SubscriptionNotTrialing { .. }
            | Self::SubscriptionNotPaused { .. }
            | Self::SubscriptionAlreadyPaused { .. } => true,
            Self::StripeApiError { http_status, .. } => {
                matches!(http_status, Some(400..=499))
            }
            _ => false,
        }
    }

    /// Check if this is a server error (5xx).
    #[must_use]
    pub fn is_server_error(&self) -> bool {
        match self {
            Self::ConcurrentModification { .. }
            | Self::RetryLimitExceeded { .. }
            | Self::Internal { .. }
            | Self::RefundFailed { .. } => true,
            Self::StripeApiError { http_status, .. } => {
                matches!(http_status, Some(500..=599) | None)
            }
            _ => false,
        }
    }

    /// Check if this error is retryable.
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::ConcurrentModification { .. } => true,
            Self::StripeApiError { http_status, .. } => {
                // Rate limit (429) and server errors (5xx) are retryable
                matches!(http_status, Some(429) | Some(500..=599))
            }
            _ => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_error_display() {
        let err = BillingError::PlanNotFound {
            plan_id: "starter".to_string(),
        };
        assert_eq!(err.to_string(), "Plan not found: starter");

        let err = BillingError::InsufficientSeats {
            requested: 5,
            available: 2,
        };
        assert_eq!(
            err.to_string(),
            "Cannot remove 5 seats, only 2 extra seats available"
        );
    }

    #[test]
    fn test_error_classification() {
        let err = BillingError::PlanNotFound {
            plan_id: "test".to_string(),
        };
        assert!(err.is_client_error());
        assert!(!err.is_server_error());
        assert!(!err.is_retryable());

        let err = BillingError::ConcurrentModification {
            billable_id: "org_123".to_string(),
        };
        assert!(!err.is_client_error());
        assert!(err.is_server_error());
        assert!(err.is_retryable());
    }

    #[test]
    fn test_convert_to_tideway_error() {
        let err = BillingError::NoSubscription {
            billable_id: "org_123".to_string(),
        };
        let tideway_err: crate::error::TidewayError = err.into();
        assert!(matches!(
            tideway_err,
            crate::error::TidewayError::NotFound(_)
        ));

        let err = BillingError::InvalidWebhookSignature;
        let tideway_err: crate::error::TidewayError = err.into();
        assert!(matches!(
            tideway_err,
            crate::error::TidewayError::BadRequest(_)
        ));

        let err = BillingError::SubscriptionInactive {
            billable_id: "org_123".to_string(),
        };
        let tideway_err: crate::error::TidewayError = err.into();
        assert!(matches!(
            tideway_err,
            crate::error::TidewayError::Forbidden(_)
        ));
    }
}