hojicha-core 0.2.2

Core Elm Architecture abstractions for terminal UIs in Rust
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
//! Concurrency safety utilities and patterns
//!
//! This module provides utilities for safe concurrent programming in Hojicha applications.
//!
//! ## Key Principles
//!
//! 1. **Message passing over shared state**: Use messages to communicate between tasks
//! 2. **Request tracking**: Track async operations with unique IDs
//! 3. **Cancellation support**: Cancel operations when they're no longer needed
//! 4. **State machines**: Use enums to represent valid states and transitions
//!
//! ## Core Types
//!
//! - [`RequestId`]: Unique identifier for async operations
//! - [`RequestIdGenerator`]: Thread-safe generator for `RequestIds`
//! - [`RequestTracker`]: Manages multiple in-flight async requests
//! - [`StateMachine`]: Trait for implementing type-safe state machines
//!
//! ## Examples
//!
//! ### Tracking Async Operations
//!
//! ```rust
//! use hojicha_core::concurrency::{RequestId, RequestTracker};
//! use hojicha_core::{Model, Cmd, Event, commands};
//!
//! struct MyApp {
//!     requests: RequestTracker,
//!     request_urls: std::collections::HashMap<RequestId, String>,
//! }
//!
//! enum MyMessage {
//!     StartFetch(String),
//!     FetchComplete(RequestId, String),
//!     FetchFailed(RequestId),
//! }
//!
//! impl Model for MyApp {
//!     type Message = MyMessage;
//!
//!     fn init(&mut self) -> Cmd<Self::Message> {
//!         Cmd::noop()
//!     }
//!
//!     fn update(&mut self, event: Event<Self::Message>) -> Cmd<Self::Message> {
//!         match event {
//!             Event::User(MyMessage::StartFetch(url)) => {
//!                 let id = RequestId::new();
//!                 self.requests.track(id);
//!                 self.request_urls.insert(id, url.clone());
//!                 
//!                 // Start async operation with the ID
//!                 commands::spawn(async move {
//!                     // Perform fetch...
//!                     Some(MyMessage::FetchComplete(id, "data".to_string()))
//!                 })
//!             }
//!             Event::User(MyMessage::FetchComplete(id, data)) => {
//!                 if self.requests.complete(id) {
//!                     let url = self.request_urls.remove(&id).unwrap_or_default();
//!                     println!("Completed fetch from {}: {}", url, data);
//!                 }
//!                 Cmd::noop()
//!             }
//!             _ => Cmd::noop()
//!         }
//!     }
//!     
//!     fn view(&self) -> String { String::new() }
//! }
//! ```
//!
//! ### State Machine Pattern
//!
//! ```rust
//! use hojicha_core::concurrency::StateMachine;
//!
//! #[derive(Debug, Clone, PartialEq)]
//! enum LoadingState {
//!     Idle,
//!     Loading,
//!     Success(String),
//!     Error(String),
//! }
//!
//! #[derive(Debug, Clone)]
//! enum LoadingEvent {
//!     Start,
//!     Complete(String),
//!     Fail(String),
//!     Reset,
//! }
//!
//! impl StateMachine for LoadingState {
//!     type Event = LoadingEvent;
//!
//!     fn transition(self, event: Self::Event) -> Option<Self> {
//!         match (&self, &event) {
//!             (LoadingState::Idle, LoadingEvent::Start) => {
//!                 Some(LoadingState::Loading)
//!             }
//!             (LoadingState::Loading, LoadingEvent::Complete(data)) => {
//!                 Some(LoadingState::Success(data.clone()))
//!             }
//!             (LoadingState::Loading, LoadingEvent::Fail(err)) => {
//!                 Some(LoadingState::Error(err.clone()))
//!             }
//!             (_, LoadingEvent::Reset) => {
//!                 Some(LoadingState::Idle)
//!             }
//!             _ => None, // Invalid transition
//!         }
//!     }
//!     
//!     fn can_transition(&self, event: &Self::Event) -> bool {
//!         self.clone().transition(event.clone()).is_some()
//!     }
//! }
//! ```

use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;

/// Unique identifier for async requests
///
/// Use this to track async operations and match responses to requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RequestId(u64);

impl Default for RequestId {
    fn default() -> Self {
        Self::new()
    }
}

impl RequestId {
    /// Create a new unique request ID
    pub fn new() -> Self {
        static COUNTER: AtomicU64 = AtomicU64::new(1);
        Self(COUNTER.fetch_add(1, Ordering::SeqCst))
    }

    /// Get the underlying ID value
    #[must_use]
    pub fn value(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for RequestId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Request#{}", self.0)
    }
}

/// Tracks pending async requests
///
/// Use this to manage concurrent operations and prevent processing
/// responses from cancelled or outdated requests.
///
/// # Example
/// ```
/// use hojicha_core::concurrency::{RequestTracker, RequestId};
///
/// let mut tracker = RequestTracker::new();
///
/// // Start a request
/// let id = RequestId::new();
/// tracker.track(id);
///
/// // Later, when response arrives
/// if tracker.complete(id) {
///     // Process valid response
/// } else {
///     // Ignore cancelled/unknown request
/// }
/// ```
#[derive(Debug, Clone)]
pub struct RequestTracker {
    pending: HashMap<RequestId, RequestInfo>,
}

#[derive(Debug, Clone)]
struct RequestInfo {
    started_at: Instant,
}

impl RequestTracker {
    /// Create a new request tracker
    #[must_use]
    pub fn new() -> Self {
        Self {
            pending: HashMap::new(),
        }
    }

    /// Track a new request
    pub fn track(&mut self, id: RequestId) {
        self.pending.insert(
            id,
            RequestInfo {
                started_at: Instant::now(),
            },
        );
    }

    /// Complete a request and return true if it was being tracked
    pub fn complete(&mut self, id: RequestId) -> bool {
        self.pending.remove(&id).is_some()
    }

    /// Check if a request is currently being tracked
    #[must_use]
    pub fn is_pending(&self, id: RequestId) -> bool {
        self.pending.contains_key(&id)
    }

    /// Cancel a specific request
    pub fn cancel(&mut self, id: RequestId) -> bool {
        self.pending.remove(&id).is_some()
    }

    /// Cancel all pending requests
    pub fn cancel_all(&mut self) {
        self.pending.clear();
    }

    /// Get the number of pending requests
    #[must_use]
    pub fn pending_count(&self) -> usize {
        self.pending.len()
    }

    /// Get how long a request has been pending
    #[must_use]
    pub fn elapsed(&self, id: RequestId) -> Option<std::time::Duration> {
        self.pending.get(&id).map(|info| info.started_at.elapsed())
    }

    /// Get all pending request IDs
    #[must_use]
    pub fn pending_ids(&self) -> Vec<RequestId> {
        self.pending.keys().copied().collect()
    }
}

impl Default for RequestTracker {
    fn default() -> Self {
        Self::new()
    }
}

/// Generator for unique request IDs
///
/// Use this when you need to generate multiple IDs in a structured way.
///
/// # Example
/// ```
/// use hojicha_core::concurrency::RequestIdGenerator;
///
/// let mut gen = RequestIdGenerator::new();
/// let id1 = gen.generate();
/// let id2 = gen.generate();
/// assert_ne!(id1, id2);
/// ```
#[derive(Debug, Clone)]
pub struct RequestIdGenerator {
    next_id: u64,
}

impl RequestIdGenerator {
    /// Create a new ID generator
    #[must_use]
    pub fn new() -> Self {
        Self { next_id: 1 }
    }

    /// Generate the next unique ID
    pub fn generate(&mut self) -> RequestId {
        let id = RequestId(self.next_id);
        self.next_id += 1;
        id
    }

    /// Get the next ID without incrementing
    #[must_use]
    pub fn peek(&self) -> RequestId {
        RequestId(self.next_id)
    }
}

impl Default for RequestIdGenerator {
    fn default() -> Self {
        Self::new()
    }
}

/// State machine helper for managing application states
///
/// This trait helps enforce valid state transitions.
pub trait StateMachine: Sized {
    /// The event type that triggers state transitions
    type Event;

    /// Attempt to transition to a new state based on an event
    ///
    /// Returns `Some(new_state)` if the transition is valid,
    /// or `None` if the transition is invalid.
    fn transition(self, event: Self::Event) -> Option<Self>;

    /// Check if a transition would be valid without consuming self
    fn can_transition(&self, event: &Self::Event) -> bool;
}

/// Example state machine implementation
///
/// ```
/// use hojicha_core::concurrency::StateMachine;
///
/// #[derive(Debug, Clone)]
/// enum AppState {
///     Idle,
///     Loading,
///     Ready,
///     Error,
/// }
///
/// #[derive(Debug)]
/// enum AppEvent {
///     StartLoad,
///     LoadSuccess,
///     LoadError,
///     Reset,
/// }
///
/// impl StateMachine for AppState {
///     type Event = AppEvent;
///     
///     fn transition(self, event: Self::Event) -> Option<Self> {
///         match (self, event) {
///             (AppState::Idle, AppEvent::StartLoad) => Some(AppState::Loading),
///             (AppState::Loading, AppEvent::LoadSuccess) => Some(AppState::Ready),
///             (AppState::Loading, AppEvent::LoadError) => Some(AppState::Error),
///             (_, AppEvent::Reset) => Some(AppState::Idle),
///             _ => None, // Invalid transition
///         }
///     }
///     
///     fn can_transition(&self, event: &Self::Event) -> bool {
///         matches!(
///             (self, event),
///             (AppState::Idle, AppEvent::StartLoad) |
///             (AppState::Loading, AppEvent::LoadSuccess) |
///             (AppState::Loading, AppEvent::LoadError) |
///             (_, AppEvent::Reset)
///         )
///     }
/// }
/// ```
pub struct StateTransition<S, E> {
    _from: S,
    _to: S,
    _event: E,
}

impl<S, E> StateTransition<S, E> {
    /// Create a new state transition
    pub fn new(from: S, to: S, event: E) -> Self {
        Self {
            _from: from,
            _to: to,
            _event: event,
        }
    }
}

// Actor pattern utilities require tokio and are available in hojicha-runtime
// Users should use hojicha_runtime for actor patterns with async support

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

    #[test]
    fn test_request_id_uniqueness() {
        let id1 = RequestId::new();
        let id2 = RequestId::new();
        assert_ne!(id1, id2);
    }

    #[test]
    fn test_request_tracker() {
        let mut tracker = RequestTracker::new();
        let id = RequestId::new();

        // Track a request
        tracker.track(id);
        assert!(tracker.is_pending(id));
        assert_eq!(tracker.pending_count(), 1);

        // Complete the request
        assert!(tracker.complete(id));
        assert!(!tracker.is_pending(id));
        assert_eq!(tracker.pending_count(), 0);

        // Completing again returns false
        assert!(!tracker.complete(id));
    }

    #[test]
    fn test_request_id_generator() {
        let mut gen = RequestIdGenerator::new();

        let id1 = gen.generate();
        let id2 = gen.generate();
        let id3 = gen.generate();

        assert_eq!(id1.value(), 1);
        assert_eq!(id2.value(), 2);
        assert_eq!(id3.value(), 3);
    }

    #[test]
    fn test_state_machine_example() {
        #[derive(Debug, Clone, PartialEq)]
        enum State {
            A,
            B,
            C,
        }

        #[derive(Debug)]
        enum Event {
            Next,
            Reset,
        }

        impl StateMachine for State {
            type Event = Event;

            fn transition(self, event: Self::Event) -> Option<Self> {
                match (self, event) {
                    (State::A, Event::Next) => Some(State::B),
                    (State::B, Event::Next) => Some(State::C),
                    (_, Event::Reset) => Some(State::A),
                    _ => None,
                }
            }

            fn can_transition(&self, event: &Self::Event) -> bool {
                matches!(
                    (self, event),
                    (State::A | State::B, Event::Next) | (_, Event::Reset)
                )
            }
        }

        let state = State::A;
        assert!(state.can_transition(&Event::Next));

        let state = state.transition(Event::Next).unwrap();
        assert_eq!(state, State::B);

        let state = state.transition(Event::Next).unwrap();
        assert_eq!(state, State::C);

        let state = state.transition(Event::Reset).unwrap();
        assert_eq!(state, State::A);
    }
}