tears 0.9.0

A simple and elegant framework for building TUI applications using The Elm Architecture (TEA)
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
use std::any::Any;
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicU64, Ordering},
};
use std::time::{Duration, Instant};

use tokio::sync::watch;

use super::config::QueryConfig;
use super::query::QueryError;
use super::reconcile::{FetchDecisionInput, ReconcileReason, should_fetch};
use super::result::{FetchStatus, QueryResult, QueryStatus};

/// Type-erased operations needed by the heterogeneous query cell map.
pub(super) trait AnyCell: Any + Send + Sync + 'static {
    fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
    fn invalidate(&self, config: &QueryConfig);
    fn gc_inactive_data_and_should_evict(&self, cache_time: Duration) -> bool;
}

#[allow(dead_code)]
pub(super) struct Cell<T> {
    state: Mutex<CellState<T>>,
    tx: watch::Sender<QueryResult<T>>,
    // Tokio watch does not let a sender mark a receiver's current value as
    // seen. Keep our own version so a subscription can skip snapshots it has
    // already returned directly from reconcile/fetch completion paths.
    version: AtomicU64,
    lifecycle: Mutex<CellLifecycle>,
}

#[derive(Debug)]
struct CellLifecycle {
    subscribers: usize,
    inactive_since: Option<Instant>,
}

#[allow(dead_code)]
pub(super) struct CellSubscription<T>
where
    T: Clone + Send + Sync + 'static,
{
    cell: Arc<Cell<T>>,
    rx: watch::Receiver<QueryResult<T>>,
    // Last cell-level version this subscription emitted or intentionally
    // consumed. This is separate from tokio watch's internal receiver version.
    seen_version: u64,
}

#[derive(Debug)]
#[allow(dead_code)]
struct CellState<T> {
    data: Option<T>,
    error: Option<QueryError>,
    current_generation: u64,
    data_generation: Option<u64>,
    data_timestamp: Option<Instant>,
    status: QueryStatus,
    fetch_status: FetchStatus,
    in_flight_generation: Option<u64>,
    last_error_generation: Option<u64>,
}

impl<T> Cell<T>
where
    T: Clone + Send + Sync + 'static,
{
    #[allow(dead_code)]
    pub(super) fn new() -> Self {
        let result = QueryResult::pending(FetchStatus::Idle);
        let (tx, _) = watch::channel(result);
        Self {
            state: Mutex::new(CellState {
                data: None,
                error: None,
                current_generation: 0,
                data_generation: None,
                data_timestamp: None,
                status: QueryStatus::Pending,
                fetch_status: FetchStatus::Idle,
                in_flight_generation: None,
                last_error_generation: None,
            }),
            tx,
            version: AtomicU64::new(0),
            lifecycle: Mutex::new(CellLifecycle {
                subscribers: 0,
                inactive_since: Some(Instant::now()),
            }),
        }
    }

    #[allow(dead_code)]
    pub(super) fn new_subscribed() -> (Arc<Self>, CellSubscription<T>) {
        let cell = Arc::new(Self::new());
        {
            let mut lifecycle = cell
                .lifecycle
                .lock()
                .expect("cell lifecycle mutex should not be poisoned");
            lifecycle.subscribers = 1;
            lifecycle.inactive_since = None;
        }
        let subscription = CellSubscription {
            cell: cell.clone(),
            rx: cell.tx.subscribe(),
            seen_version: cell.version(),
        };
        (cell, subscription)
    }

    #[allow(dead_code)]
    pub(super) fn subscribe(self: &Arc<Self>) -> CellSubscription<T> {
        {
            let mut lifecycle = self
                .lifecycle
                .lock()
                .expect("cell lifecycle mutex should not be poisoned");
            lifecycle.subscribers += 1;
            lifecycle.inactive_since = None;
        }

        CellSubscription {
            cell: self.clone(),
            rx: self.tx.subscribe(),
            seen_version: self.version(),
        }
    }

    #[allow(dead_code)]
    pub(super) fn snapshot(&self, config: &QueryConfig) -> QueryResult<T> {
        self.state
            .lock()
            .expect("cell state mutex should not be poisoned")
            .snapshot(config)
    }

    pub(super) fn reconcile(
        &self,
        reason: ReconcileReason,
        config: &QueryConfig,
    ) -> (QueryResult<T>, Option<u64>, Option<u64>) {
        let (snapshot, generation) = {
            let mut state = self
                .state
                .lock()
                .expect("cell state mutex should not be poisoned");
            let generation_stale = state.data_generation < Some(state.current_generation);
            let input = FetchDecisionInput {
                has_data: state.data.is_some(),
                generation_stale,
                time_since_data: state.data_timestamp.map(|timestamp| timestamp.elapsed()),
                stale_time: config.stale_time,
                has_in_flight: state.in_flight_generation.is_some(),
                last_error_generation_matches_current: state.last_error_generation
                    == Some(state.current_generation),
            };

            let generation = if should_fetch(reason, input) {
                let generation = state.current_generation;
                state.in_flight_generation = Some(generation);
                state.fetch_status = FetchStatus::Fetching;
                if state.data.is_none() {
                    state.status = QueryStatus::Pending;
                }
                Some(generation)
            } else {
                None
            };

            (state.snapshot(config), generation)
        };

        let sent_version = generation
            .is_some()
            .then(|| self.send_snapshot(snapshot.clone()));

        (snapshot, generation, sent_version)
    }

    pub(super) fn complete_success(
        &self,
        generation: u64,
        data: T,
        config: &QueryConfig,
    ) -> (QueryResult<T>, bool, u64) {
        let (snapshot, committed) = {
            let mut state = self
                .state
                .lock()
                .expect("cell state mutex should not be poisoned");
            if state.in_flight_generation == Some(generation) {
                state.in_flight_generation = None;
            }

            let committed = state.current_generation == generation;
            if committed {
                state.data = Some(data);
                state.error = None;
                state.data_generation = Some(generation);
                state.data_timestamp = Some(Instant::now());
                state.status = QueryStatus::Success;
                state.fetch_status = FetchStatus::Idle;
                state.last_error_generation = None;
            }

            (state.snapshot(config), committed)
        };
        let sent_version = self.send_snapshot(snapshot.clone());
        (snapshot, committed, sent_version)
    }

    pub(super) fn complete_error(
        &self,
        generation: u64,
        error: QueryError,
        config: &QueryConfig,
    ) -> (QueryResult<T>, bool, u64) {
        let (snapshot, committed) = {
            let mut state = self
                .state
                .lock()
                .expect("cell state mutex should not be poisoned");
            if state.in_flight_generation == Some(generation) {
                state.in_flight_generation = None;
            }

            let committed = state.current_generation == generation;
            if committed {
                state.error = Some(error);
                state.status = QueryStatus::Error;
                state.fetch_status = FetchStatus::Idle;
                state.last_error_generation = Some(generation);
            }

            (state.snapshot(config), committed)
        };
        let sent_version = self.send_snapshot(snapshot.clone());
        (snapshot, committed, sent_version)
    }

    pub(super) fn version(&self) -> u64 {
        self.version.load(Ordering::Acquire)
    }

    fn send_snapshot(&self, snapshot: QueryResult<T>) -> u64 {
        let version = self.version.fetch_add(1, Ordering::AcqRel) + 1;
        let _ = self.tx.send(snapshot);
        version
    }
}

#[cfg(test)]
impl<T> Cell<T> {
    pub(super) fn subscriber_count(&self) -> usize {
        self.lifecycle
            .lock()
            .expect("cell lifecycle mutex should not be poisoned")
            .subscribers
    }

    pub(super) fn inactive_since(&self) -> Option<Instant> {
        self.lifecycle
            .lock()
            .expect("cell lifecycle mutex should not be poisoned")
            .inactive_since
    }
}

impl<T> CellSubscription<T>
where
    T: Clone + Send + Sync + 'static,
{
    #[allow(dead_code)]
    pub(super) const fn receiver(&self) -> &watch::Receiver<QueryResult<T>> {
        &self.rx
    }

    #[allow(dead_code)]
    pub(super) const fn receiver_mut(&mut self) -> &mut watch::Receiver<QueryResult<T>> {
        &mut self.rx
    }

    pub(super) const fn seen_version(&self) -> u64 {
        self.seen_version
    }

    pub(super) const fn mark_seen_version(&mut self, version: u64) {
        self.seen_version = version;
    }
}

impl<T> Drop for CellSubscription<T>
where
    T: Clone + Send + Sync + 'static,
{
    fn drop(&mut self) {
        let mut lifecycle = self
            .cell
            .lifecycle
            .lock()
            .expect("cell lifecycle mutex should not be poisoned");

        debug_assert!(
            lifecycle.subscribers > 0,
            "cell subscription count should not underflow"
        );

        lifecycle.subscribers = lifecycle.subscribers.saturating_sub(1);
        if lifecycle.subscribers == 0 {
            lifecycle.inactive_since = Some(Instant::now());
        }
    }
}

impl<T> AnyCell for Cell<T>
where
    T: Clone + Send + Sync + 'static,
{
    fn into_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
        self
    }

    fn invalidate(&self, config: &QueryConfig) {
        let snapshot = {
            let mut state = self
                .state
                .lock()
                .expect("cell state mutex should not be poisoned");
            state.current_generation = state.current_generation.saturating_add(1);
            state.snapshot(config)
        };
        self.send_snapshot(snapshot);
    }

    fn gc_inactive_data_and_should_evict(&self, cache_time: Duration) -> bool {
        let lifecycle = self
            .lifecycle
            .lock()
            .expect("cell lifecycle mutex should not be poisoned");

        let should_clear = lifecycle.subscribers == 0
            && lifecycle
                .inactive_since
                .is_some_and(|inactive_since| inactive_since.elapsed() >= cache_time);

        if !should_clear {
            return false;
        }

        let cleared = {
            let mut state = self
                .state
                .lock()
                .expect("cell state mutex should not be poisoned");

            if state.data.is_none() && state.error.is_none() {
                false
            } else {
                state.data = None;
                state.error = None;
                state.data_generation = None;
                state.data_timestamp = None;
                state.status = QueryStatus::Pending;
                state.fetch_status = FetchStatus::Idle;
                state.in_flight_generation = None;
                state.last_error_generation = None;
                true
            }
        };
        drop(lifecycle);

        if cleared {
            self.send_snapshot(QueryResult::pending(FetchStatus::Idle));
        }

        true
    }
}

impl<T> CellState<T>
where
    T: Clone,
{
    #[allow(dead_code)]
    fn snapshot(&self, config: &QueryConfig) -> QueryResult<T> {
        let is_stale = self.data.is_some()
            && (self.data_generation < Some(self.current_generation)
                || self
                    .data_timestamp
                    .is_some_and(|timestamp| timestamp.elapsed() >= config.stale_time));

        match self.status {
            QueryStatus::Pending => QueryResult::pending(self.fetch_status),
            QueryStatus::Success => {
                let data = self
                    .data
                    .clone()
                    .expect("success cell state should contain data");
                QueryResult::success(data, is_stale, self.fetch_status)
            }
            QueryStatus::Error => QueryResult::failed(
                self.error
                    .clone()
                    .expect("error cell state should contain error"),
                self.data.clone(),
                is_stale,
                self.fetch_status,
            ),
        }
    }
}