stillwater 1.0.1

Pragmatic effect composition and validation for Rust - pure core, imperative shell
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
//! IO Patterns Example
//!
//! Demonstrates the IO module's helpers for creating Effects from I/O operations.
//! Shows practical patterns including:
//! - Basic read/write operations
//! - Multiple services in environment
//! - Async operations
//! - Cache-aside pattern
//! - Effect composition with IO helpers

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use stillwater::{from_fn, pure, Effect, EffectExt, IO};

// ==================== Basic Read/Write Operations ====================

/// Example 1: Simple read operation
///
/// Demonstrates using IO::read() to query data without modification.
async fn example_basic_read() {
    println!("\n=== Example 1: Basic Read Operation ===");

    // Define a simple database service
    #[derive(Clone)]
    struct Database {
        users: Vec<String>,
    }

    impl Database {
        fn count_users(&self) -> usize {
            self.users.len()
        }
    }

    // Define environment with database
    #[derive(Clone)]
    struct Env {
        db: Database,
    }

    impl AsRef<Database> for Env {
        fn as_ref(&self) -> &Database {
            &self.db
        }
    }

    // Create environment
    let env = Env {
        db: Database {
            users: vec![
                "Alice".to_string(),
                "Bob".to_string(),
                "Charlie".to_string(),
            ],
        },
    };

    // Create effect using IO::read - type inference determines we need Database
    let effect = IO::read(|db: &Database| db.count_users());

    // Run effect
    let count = effect.run(&env).await.unwrap();
    println!("User count: {}", count);
}

/// Example 2: Write operation with interior mutability
///
/// Demonstrates using IO::write() for operations that modify state.
/// Note: Effect requires &Env, so we use Arc<Mutex<T>> for mutation.
async fn example_basic_write() {
    println!("\n=== Example 2: Basic Write Operation ===");

    // Logger service with interior mutability
    #[derive(Clone)]
    struct Logger {
        messages: Arc<Mutex<Vec<String>>>,
    }

    impl Logger {
        fn log(&self, msg: String) {
            self.messages.lock().unwrap().push(msg);
        }

        fn get_messages(&self) -> Vec<String> {
            self.messages.lock().unwrap().clone()
        }
    }

    #[derive(Clone)]
    struct Env {
        logger: Logger,
    }

    impl AsRef<Logger> for Env {
        fn as_ref(&self) -> &Logger {
            &self.logger
        }
    }

    let env = Env {
        logger: Logger {
            messages: Arc::new(Mutex::new(Vec::new())),
        },
    };

    // Create write effect
    let effect = IO::write(|logger: &Logger| {
        logger.log("Application started".to_string());
        logger.log("Processing request".to_string());
    });

    // Run effect
    effect.run(&env).await.unwrap();

    println!("Logged messages: {:?}", env.logger.get_messages());
}

// ==================== Multiple Services in Environment ====================

/// Example 3: Multiple services with type inference
///
/// Demonstrates how AsRef<T> allows the environment to provide multiple services,
/// with type inference automatically extracting the correct one.
async fn example_multiple_services() {
    println!("\n=== Example 3: Multiple Services ===");

    #[derive(Clone)]
    struct Database {
        name: String,
    }
    #[derive(Clone)]
    struct Cache {
        name: String,
    }
    #[derive(Clone)]
    struct Logger {
        name: String,
    }

    // Composite environment
    #[derive(Clone)]
    struct Env {
        db: Database,
        cache: Cache,
        logger: Logger,
    }

    // Implement AsRef for each service
    impl AsRef<Database> for Env {
        fn as_ref(&self) -> &Database {
            &self.db
        }
    }
    impl AsRef<Cache> for Env {
        fn as_ref(&self) -> &Cache {
            &self.cache
        }
    }
    impl AsRef<Logger> for Env {
        fn as_ref(&self) -> &Logger {
            &self.logger
        }
    }

    let env = Env {
        db: Database {
            name: "PostgreSQL".to_string(),
        },
        cache: Cache {
            name: "Redis".to_string(),
        },
        logger: Logger {
            name: "Syslog".to_string(),
        },
    };

    // Type inference figures out which service each effect needs
    let db_effect = IO::read(|db: &Database| db.name.clone());
    let cache_effect = IO::read(|cache: &Cache| cache.name.clone());
    let logger_effect = IO::read(|logger: &Logger| logger.name.clone());

    println!("Database: {}", db_effect.run(&env).await.unwrap());
    println!("Cache: {}", cache_effect.run(&env).await.unwrap());
    println!("Logger: {}", logger_effect.run(&env).await.unwrap());
}

// ==================== Async Operations ====================

/// Example 4: Async read and write operations
///
/// Demonstrates IO::read_async() and IO::write_async() for operations
/// that return futures, such as network calls or async database queries.
async fn example_async_operations() {
    use std::future::ready;

    println!("\n=== Example 4: Async Operations ===");

    #[derive(Clone)]
    struct ApiClient {
        base_url: String,
    }

    #[derive(Clone)]
    struct AuditLog {
        entries: Arc<Mutex<Vec<String>>>,
    }

    impl AuditLog {
        fn record_sync(&self, entry: String) {
            self.entries.lock().unwrap().push(entry);
        }
    }

    #[derive(Clone)]
    struct Env {
        api: ApiClient,
        audit: AuditLog,
    }

    impl AsRef<ApiClient> for Env {
        fn as_ref(&self) -> &ApiClient {
            &self.api
        }
    }

    impl AsRef<AuditLog> for Env {
        fn as_ref(&self) -> &AuditLog {
            &self.audit
        }
    }

    let env = Env {
        api: ApiClient {
            base_url: "https://api.example.com".to_string(),
        },
        audit: AuditLog {
            entries: Arc::new(Mutex::new(Vec::new())),
        },
    };

    // Async read operation - simulating an async query
    let fetch_effect = IO::read_async(|api: &ApiClient| {
        let base_url = api.base_url.clone();
        async move {
            // Simulate async work
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
            format!("User 42 from {}", base_url)
        }
    });
    let user = fetch_effect.run(&env).await.unwrap();
    println!("Fetched: {}", user);

    // Async write operation - using ready for demonstration
    let audit_effect = IO::write_async(|audit: &AuditLog| {
        audit.record_sync("User 42 accessed".to_string());
        ready(())
    });
    audit_effect.run(&env).await.unwrap();
    println!("Audit log: {:?}", env.audit.entries.lock().unwrap().clone());
}

// ==================== Cache-Aside Pattern ====================

/// Example 5: Real-world cache-aside pattern
///
/// Demonstrates a practical pattern combining multiple services:
/// 1. Check cache for data
/// 2. If miss, fetch from database
/// 3. Store in cache for next time
async fn example_cache_aside() {
    println!("\n=== Example 5: Cache-Aside Pattern ===");

    #[derive(Clone, Debug, PartialEq)]
    struct User {
        id: u64,
        name: String,
    }

    #[derive(Clone)]
    struct Database {
        users: HashMap<u64, User>,
    }

    #[derive(Clone)]
    struct Cache {
        data: Arc<Mutex<HashMap<u64, User>>>,
    }

    impl Cache {
        fn get(&self, id: u64) -> Option<User> {
            self.data.lock().unwrap().get(&id).cloned()
        }

        fn set(&self, id: u64, user: User) {
            self.data.lock().unwrap().insert(id, user);
        }
    }

    #[derive(Clone)]
    struct Env {
        db: Database,
        cache: Cache,
    }

    impl AsRef<Database> for Env {
        fn as_ref(&self) -> &Database {
            &self.db
        }
    }

    impl AsRef<Cache> for Env {
        fn as_ref(&self) -> &Cache {
            &self.cache
        }
    }

    // Setup environment
    let mut users = HashMap::new();
    users.insert(
        1,
        User {
            id: 1,
            name: "Alice".to_string(),
        },
    );
    users.insert(
        2,
        User {
            id: 2,
            name: "Bob".to_string(),
        },
    );

    let env = Env {
        db: Database { users },
        cache: Cache {
            data: Arc::new(Mutex::new(HashMap::new())),
        },
    };

    // Function to get user with cache-aside pattern
    fn get_user(
        user_id: u64,
    ) -> impl EffectExt<Output = Option<User>, Error = std::convert::Infallible, Env = Env> {
        // Check cache first
        IO::read(move |cache: &Cache| cache.get(user_id)).and_then(move |cached| {
            match cached {
                Some(user) => {
                    println!("Cache hit for user {}", user_id);
                    pure(Some(user)).boxed()
                }
                None => {
                    println!("Cache miss for user {}", user_id);
                    // Fetch from database (synchronous for simplicity)
                    IO::read(move |db: &Database| db.users.get(&user_id).cloned())
                        .and_then(move |user| {
                            from_fn(move |env: &Env| {
                                if let Some(ref u) = user {
                                    let user_clone = u.clone();
                                    // Store in cache
                                    let cache: &Cache = env.as_ref();
                                    cache.set(user_id, user_clone);
                                    Ok(user.clone())
                                } else {
                                    Ok(user)
                                }
                            })
                        })
                        .boxed()
                }
            }
        })
    }

    // First access - cache miss
    let user1 = get_user(1).run(&env).await.unwrap();
    println!("Got user: {:?}", user1);

    // Second access - cache hit
    let user1_again = get_user(1).run(&env).await.unwrap();
    println!("Got user again: {:?}", user1_again);

    // Different user - cache miss
    let user2 = get_user(2).run(&env).await.unwrap();
    println!("Got user: {:?}", user2);
}

// ==================== Effect Composition ====================

/// Example 6: Composing effects with map, and_then, etc.
///
/// Demonstrates how IO helpers integrate with Effect's combinators.
async fn example_effect_composition() {
    println!("\n=== Example 6: Effect Composition ===");

    #[derive(Clone)]
    struct Calculator {
        multiplier: i32,
    }

    #[derive(Clone)]
    struct Env {
        calc: Calculator,
    }

    impl AsRef<Calculator> for Env {
        fn as_ref(&self) -> &Calculator {
            &self.calc
        }
    }

    let env = Env {
        calc: Calculator { multiplier: 3 },
    };

    // Compose effects using map and and_then
    let effect = IO::read(|calc: &Calculator| calc.multiplier)
        .map(|x| x * 2) // Transform the value
        .and_then(|x| {
            // Chain another effect
            IO::read(move |calc: &Calculator| x + calc.multiplier)
        });

    let result = effect.run(&env).await.unwrap();
    println!("Result: {} (expected: {})", result, 3 * 2 + 3);
}

// ==================== Main ====================

#[tokio::main]
async fn main() {
    println!("IO Patterns Examples");
    println!("====================");

    example_basic_read().await;
    example_basic_write().await;
    example_multiple_services().await;
    example_async_operations().await;
    example_cache_aside().await;
    example_effect_composition().await;

    println!("\n=== All examples completed successfully! ===");
}