typed_use_cases 0.1.2

Formalize use cases at the type level. Zero runtime overhead. Experimental proof-of-concept.
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
#![allow(dead_code, unused)]

use typed_use_cases::{Actor, Entity, UseCase};

// ============================================================================
// Actors
// ============================================================================

#[derive(Debug, Clone, Actor)]
struct Anonymous;

#[derive(Debug, Clone, Actor)]
struct Registered {
    user_id: u64,
}

#[derive(Debug, Clone, Actor)]
struct Authenticated {
    user_id: u64,
}

// ============================================================================
// Entities
// ============================================================================

#[derive(Debug, Clone)]
struct Product {
    id: u64,
    name: String,
    stock: u32,
    price: f64,
}

#[derive(Debug, Clone, Entity)]
struct Catalog {
    products: Vec<Product>,
}

impl Entity for Product {}

#[derive(Debug, Clone, Entity)]
struct Cart {
    owner: Authenticated,
    items: Vec<u64>,
}

#[derive(Debug, Clone, Entity)]
struct Order {
    owner: Authenticated,
    items: Vec<u64>,
    shipping_address: String,
    status: String,
}

// ============================================================================
// Services (Parametric Types)
// ============================================================================
// These demonstrate how Dependencies can be generic types

/// Repository trait for product persistence
trait ProductRepository {
    fn find_by_id(&self, id: u64) -> Option<Product>;
    fn find_all(&self) -> Vec<Product>;
}

/// Repository trait for cart persistence
trait CartRepository {
    fn save(&self, cart: &Cart) -> Result<(), String>;
    fn find_by_user(&self, user_id: u64) -> Option<Cart>;
}

/// Service for inventory management
trait InventoryService {
    fn check_availability(&self, product_id: u64, quantity: u32) -> bool;
    fn reserve(&self, product_id: u64, quantity: u32) -> Result<(), String>;
}

/// Payment processing service
trait PaymentService {
    fn process_payment(&self, amount: f64, user_id: u64) -> Result<String, String>;
}

// In-memory implementations for the example
struct InMemoryProductRepo;
struct InMemoryCartRepo;
struct MockInventoryService;
struct MockPaymentService;

impl ProductRepository for InMemoryProductRepo {
    fn find_by_id(&self, id: u64) -> Option<Product> {
        Some(Product {
            id,
            name: format!("Product {}", id),
            stock: 10,
            price: 99.99,
        })
    }
    
    fn find_all(&self) -> Vec<Product> {
        vec![
            Product { id: 1, name: "Laptop".to_string(), stock: 10, price: 999.99 },
            Product { id: 2, name: "Mouse".to_string(), stock: 50, price: 29.99 },
        ]
    }
}

impl CartRepository for InMemoryCartRepo {
    fn save(&self, _cart: &Cart) -> Result<(), String> {
        Ok(())
    }
    
    fn find_by_user(&self, user_id: u64) -> Option<Cart> {
        Some(Cart {
            owner: Authenticated { user_id },
            items: vec![],
        })
    }
}

impl InventoryService for MockInventoryService {
    fn check_availability(&self, _product_id: u64, _quantity: u32) -> bool {
        true
    }
    
    fn reserve(&self, _product_id: u64, _quantity: u32) -> Result<(), String> {
        Ok(())
    }
}

impl PaymentService for MockPaymentService {
    fn process_payment(&self, _amount: f64, _user_id: u64) -> Result<String, String> {
        Ok("payment_id_123".to_string())
    }
}

// ============================================================================
// Use Cases - Declarative Named Traits
// ============================================================================
// Each use case is a named trait that extends UseCase and fixes all type parameters.
// The trait acts as both a marker and a compile-time contract.

trait BrowseCatalog: UseCase<
    Anonymous,
    Catalog,
    Input = (),
    Output = Catalog,
    Dependencies = (),
> {}

trait AddItemToCart: UseCase<
    Authenticated,
    Cart,
    Input = Product,
    Output = Result<Cart, String>,
    Dependencies = (Box<dyn InventoryService>, Box<dyn CartRepository>),
> {}

trait Checkout: UseCase<
    Authenticated,
    Order,
    Input = String,  // shipping address
    Output = Result<Order, String>,
    Dependencies = (Box<dyn PaymentService>, Box<dyn CartRepository>),
> {}

// ============================================================================
// System (Zero-Sized Type) - User-defined, not part of the library
// ============================================================================
// The System type belongs to the user's application, not to the typed_use_cases library.
// It acts as a compile-time witness that all use cases are implemented.

struct System;

// ============================================================================
// UseCase Implementations on System
// ============================================================================

impl UseCase<Anonymous, Catalog> for System {
    const NAME: &'static str = "Browse catalog";
    const DESCRIPTION: &'static str = "An anonymous user can browse the product catalog";

    type Input = ();
    type Output = Catalog;
    type Dependencies = ();

    fn satisfy(
        _actor: Anonymous,
        entity: Catalog,
        _input: Self::Input,
        _deps: Self::Dependencies,
    ) -> Self::Output {
        // Return the catalog as-is for browsing
        entity
    }
}

impl BrowseCatalog for System {}

impl UseCase<Authenticated, Cart> for System {
    const NAME: &'static str = "Add item to cart";
    const DESCRIPTION: &'static str = "An authenticated user can add a product to their cart";

    type Input = Product;
    type Output = Result<Cart, String>;
    type Dependencies = (Box<dyn InventoryService>, Box<dyn CartRepository>);

    fn satisfy(
        actor: Authenticated,
        mut entity: Cart,
        input: Self::Input,
        deps: Self::Dependencies,
    ) -> Self::Output {
        let (inventory_service, cart_repo) = deps;
        
        // Verify the cart belongs to the actor
        if entity.owner.user_id != actor.user_id {
            return Err("Cart does not belong to user".to_string());
        }
        
        // Check inventory availability
        if !inventory_service.check_availability(input.id, 1) {
            return Err("Product not available".to_string());
        }
        
        // Reserve the item
        inventory_service.reserve(input.id, 1)
            .map_err(|e| format!("Failed to reserve item: {}", e))?;
        
        // Add the product to the cart
        entity.items.push(input.id);
        
        // Save the cart
        cart_repo.save(&entity)
            .map_err(|e| format!("Failed to save cart: {}", e))?;
        
        Ok(entity)
    }
}

impl AddItemToCart for System {}

impl UseCase<Authenticated, Order> for System {
    const NAME: &'static str = "Checkout";
    const DESCRIPTION: &'static str = "An authenticated user can checkout with at least one item";

    type Input = String; // shipping address
    type Output = Result<Order, String>;
    type Dependencies = (Box<dyn PaymentService>, Box<dyn CartRepository>);

    fn satisfy(
        actor: Authenticated,
        mut entity: Order,
        input: Self::Input,
        deps: Self::Dependencies,
    ) -> Self::Output {
        let (payment_service, _cart_repo) = deps;
        
        // Verify the order belongs to the actor
        if entity.owner.user_id != actor.user_id {
            return Err("Order does not belong to user".to_string());
        }
        
        // Verify order has at least one item
        if entity.items.is_empty() {
            return Err("Cannot checkout with empty cart".to_string());
        }
        
        // Calculate total (simplified - in real app would look up prices)
        let total = entity.items.len() as f64 * 100.0;
        
        // Process payment
        let payment_id = payment_service.process_payment(total, actor.user_id)
            .map_err(|e| format!("Payment failed: {}", e))?;
        
        // Update order
        entity.shipping_address = input;
        entity.status = format!("paid:{}", payment_id);
        
        Ok(entity)
    }
}

impl Checkout for System {}

// ============================================================================
// Verification
// ============================================================================

typed_use_cases::implement_all_use_cases!(System: [
    BrowseCatalog,
    AddItemToCart,
    Checkout,
]);

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn system_is_zero_sized() {
        assert_eq!(std::mem::size_of::<System>(), 0);
    }

    #[test]
    fn print_use_case_metadata() {
        println!("\n=== Use Cases ===");
        println!("1. {} - {}", 
            <System as UseCase<Anonymous, Catalog>>::NAME,
            <System as UseCase<Anonymous, Catalog>>::DESCRIPTION
        );
        println!("2. {} - {}", 
            <System as UseCase<Authenticated, Cart>>::NAME,
            <System as UseCase<Authenticated, Cart>>::DESCRIPTION
        );
        println!("3. {} - {}", 
            <System as UseCase<Authenticated, Order>>::NAME,
            <System as UseCase<Authenticated, Order>>::DESCRIPTION
        );
    }

    #[test]
    fn browse_catalog_works() {
        let actor = Anonymous;
        let catalog = Catalog {
            products: vec![
                Product {
                    id: 1,
                    name: "Laptop".to_string(),
                    stock: 10,
                    price: 999.99,
                },
                Product {
                    id: 2,
                    name: "Mouse".to_string(),
                    stock: 50,
                    price: 29.99,
                },
            ],
        };

        let result = <System as UseCase<Anonymous, Catalog>>::satisfy(
            actor,
            catalog.clone(),
            (),
            (),
        );

        assert_eq!(result.products.len(), 2);
    }

    #[test]
    fn add_item_to_cart_works() {
        let actor = Authenticated { user_id: 1 };
        let cart = Cart {
            owner: actor.clone(),
            items: vec![],
        };
        let product = Product {
            id: 1,
            name: "Laptop".to_string(),
            stock: 10,
            price: 999.99,
        };

        let inventory = Box::new(MockInventoryService) as Box<dyn InventoryService>;
        let cart_repo = Box::new(InMemoryCartRepo) as Box<dyn CartRepository>;

        let result = <System as UseCase<Authenticated, Cart>>::satisfy(
            actor,
            cart,
            product,
            (inventory, cart_repo),
        );

        assert!(result.is_ok());
        let cart = result.unwrap();
        assert_eq!(cart.items.len(), 1);
        assert_eq!(cart.items[0], 1);
    }

    #[test]
    fn checkout_works() {
        let actor = Authenticated { user_id: 1 };
        let order = Order {
            owner: actor.clone(),
            items: vec![1, 2],
            shipping_address: String::new(),
            status: String::new(),
        };

        let payment = Box::new(MockPaymentService) as Box<dyn PaymentService>;
        let cart_repo = Box::new(InMemoryCartRepo) as Box<dyn CartRepository>;

        let result = <System as UseCase<Authenticated, Order>>::satisfy(
            actor,
            order,
            "123 Main St".to_string(),
            (payment, cart_repo),
        );

        assert!(result.is_ok());
        let order = result.unwrap();
        assert_eq!(order.items.len(), 2);
        assert_eq!(order.shipping_address, "123 Main St");
        assert!(order.status.starts_with("paid:"));
    }

    #[test]
    fn checkout_fails_with_empty_cart() {
        let actor = Authenticated { user_id: 1 };
        let order = Order {
            owner: actor.clone(),
            items: vec![],
            shipping_address: String::new(),
            status: String::new(),
        };

        let payment = Box::new(MockPaymentService) as Box<dyn PaymentService>;
        let cart_repo = Box::new(InMemoryCartRepo) as Box<dyn CartRepository>;

        let result = <System as UseCase<Authenticated, Order>>::satisfy(
            actor,
            order,
            "123 Main St".to_string(),
            (payment, cart_repo),
        );

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Cannot checkout with empty cart");
    }

    #[test]
    fn add_item_fails_for_wrong_user() {
        let actor = Authenticated { user_id: 1 };
        let wrong_owner = Authenticated { user_id: 2 };
        let cart = Cart {
            owner: wrong_owner,
            items: vec![],
        };
        let product = Product {
            id: 1,
            name: "Laptop".to_string(),
            stock: 10,
            price: 999.99,
        };

        let inventory = Box::new(MockInventoryService) as Box<dyn InventoryService>;
        let cart_repo = Box::new(InMemoryCartRepo) as Box<dyn CartRepository>;

        let result = <System as UseCase<Authenticated, Cart>>::satisfy(
            actor,
            cart,
            product,
            (inventory, cart_repo),
        );

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Cart does not belong to user");
    }
}

fn main() {
    println!("E-commerce example - see tests for usage");
    println!("\nUse Cases:");
    println!("1. {} - {}", 
        <System as UseCase<Anonymous, Catalog>>::NAME,
        <System as UseCase<Anonymous, Catalog>>::DESCRIPTION
    );
    println!("2. {} - {}", 
        <System as UseCase<Authenticated, Cart>>::NAME,
        <System as UseCase<Authenticated, Cart>>::DESCRIPTION
    );
    println!("3. {} - {}", 
        <System as UseCase<Authenticated, Order>>::NAME,
        <System as UseCase<Authenticated, Order>>::DESCRIPTION
    );
}