icedwright-probe 0.1.3

What an iced app links for icedwright: semantic annotations, typed test ids and named tasks, all pass-through unless a feature turns them on
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! The endpoint's controller for named tasks.
//!
//! The probe's controller is installed per thread, and a live app polls its tasks on the
//! executor's worker threads. [`RemoteExecutor`] wraps the app's executor and installs a
//! controller around every poll of every future it spawns, all backed by one process-wide
//! [`TaskHub`].

use std::collections::{BTreeMap, VecDeque};
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::task::{Context, Poll, Waker};

use iced_program::futures::{Executor, MaybeSend};
use icedwright_protocol::{TaskChange, TaskOutput, WireRuleId, WireTaskId};
use serde::de::DeserializeOwned;

use crate::TaskName;
use crate::control::{self, Controller, Finish, Gate, Payload, ProbeId, ProbeMeta};

/// Rebuilds a task's output from the JSON a client sent. One is registered per task name
/// that clients may resolve, with [`Remote::resolvable`](super::Remote::resolvable).
pub type Resolver = fn(&TaskOutput) -> Result<Payload, String>;

/// The resolver for tasks named `N`. An error output is read as `Err(..)` of a `Result`.
#[must_use]
pub fn resolver<N: TaskName>() -> Resolver
where
    N::Output: DeserializeOwned,
{
    decode::<N>
}

fn decode<N: TaskName>(output: &TaskOutput) -> Result<Payload, String>
where
    N::Output: DeserializeOwned,
{
    let parsed = match output {
        TaskOutput::Value(json) => serde_json::from_str::<N::Output>(json),
        TaskOutput::Error(json) => {
            serde_json::from_str::<N::Output>(&format!("{{\"Err\":{json}}}"))
        }
    };
    parsed
        .map(Payload::new::<N>)
        .map_err(|error| format!("{} cannot take this output: {error}", N::NAME))
}

/// A named task changed, as the app's `update` learns of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskEvent {
    /// The task name.
    pub name: String,
    /// The task.
    pub task: WireTaskId,
    /// What happened.
    pub change: TaskChange,
}

struct Entry {
    name: &'static str,
    held: bool,
    waker: Option<Waker>,
    resolve: Option<Payload>,
}

#[derive(Default)]
struct Book {
    next_task: u64,
    next_rule: u64,
    rules: BTreeMap<WireRuleId, String>,
    tasks: BTreeMap<WireTaskId, Entry>,
    resolvers: BTreeMap<String, Resolver>,
}

type Listener = Box<dyn Fn(TaskEvent) + Send>;

/// Every named task the app has running, and the rules clients installed.
#[derive(Default)]
pub struct TaskHub {
    book: Mutex<Book>,
    listener: Mutex<Option<Listener>>,
}

impl std::fmt::Debug for TaskHub {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TaskHub").finish_non_exhaustive()
    }
}

fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex.lock().unwrap_or_else(PoisonError::into_inner)
}

impl TaskHub {
    /// An empty hub.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Lets clients resolve tasks named `name`.
    pub fn register(&self, name: &'static str, resolver: Resolver) {
        lock(&self.book).resolvers.insert(name.to_owned(), resolver);
    }

    /// Where task changes go.
    pub fn listen(&self, listener: impl Fn(TaskEvent) + Send + 'static) {
        *lock(&self.listener) = Some(Box::new(listener));
    }

    fn emit(&self, events: Vec<TaskEvent>) {
        let listener = lock(&self.listener);
        let Some(listener) = listener.as_ref() else {
            return;
        };
        for event in events {
            listener(event);
        }
    }

    /// Holds every task of `name` that starts from now on.
    pub fn hold(&self, name: String) -> WireRuleId {
        let mut book = lock(&self.book);
        book.next_rule += 1;
        let rule = WireRuleId(book.next_rule);
        book.rules.insert(rule, name);
        rule
    }

    /// Removes a rule and lets go every task no remaining rule holds. False when the rule
    /// does not exist.
    pub fn remove_rule(&self, rule: WireRuleId) -> bool {
        let mut book = lock(&self.book);
        let Some(name) = book.rules.remove(&rule) else {
            return false;
        };
        let still_held = book.rules.values().any(|n| *n == name);
        let mut events = Vec::new();
        if !still_held {
            for (task, entry) in book
                .tasks
                .iter_mut()
                .filter(|(_, e)| e.name == name && e.held)
            {
                entry.held = false;
                wake(entry);
                events.push(event(entry.name, *task, TaskChange::Released));
            }
        }
        drop(book);
        self.emit(events);
        true
    }

    /// Lets a held task run.
    pub fn release(&self, task: WireTaskId) -> Result<(), String> {
        let mut book = lock(&self.book);
        let entry = book
            .tasks
            .get_mut(&task)
            .ok_or_else(|| format!("no task {} is running", task.0))?;
        entry.held = false;
        wake(entry);
        let released = event(entry.name, task, TaskChange::Released);
        drop(book);
        self.emit(vec![released]);
        Ok(())
    }

    /// Completes a task with `output` without running the rest of it.
    pub fn resolve(&self, task: WireTaskId, output: &TaskOutput) -> Result<(), String> {
        let mut book = lock(&self.book);
        let Some(name) = book.tasks.get(&task).map(|entry| entry.name) else {
            return Err(format!("no task {} is running", task.0));
        };
        let Some(resolver) = book.resolvers.get(name).copied() else {
            return Err(format!(
                "{name} cannot be resolved remotely; the app registers it with \
                 Remote::resolvable::<{}>()",
                name.rsplit("::").next().unwrap_or(name)
            ));
        };
        let payload = resolver(output)?;
        let Some(entry) = book.tasks.get_mut(&task) else {
            return Err(format!("no task {} is running", task.0));
        };
        entry.resolve = Some(payload);
        entry.held = false;
        wake(entry);
        Ok(())
    }

    fn start(&self, meta: &ProbeMeta) -> ProbeId {
        let mut book = lock(&self.book);
        book.next_task += 1;
        let task = WireTaskId(book.next_task);
        let held = book.rules.values().any(|name| name == meta.name);
        book.tasks.insert(
            task,
            Entry {
                name: meta.name,
                held,
                waker: None,
                resolve: None,
            },
        );
        drop(book);
        let mut events = vec![event(meta.name, task, TaskChange::Started)];
        if held {
            events.push(event(meta.name, task, TaskChange::Held));
        }
        self.emit(events);
        ProbeId(task.0)
    }

    fn gate(&self, id: ProbeId, cx: &Context<'_>) -> Gate {
        let mut book = lock(&self.book);
        let Some(entry) = book.tasks.get_mut(&WireTaskId(id.0)) else {
            return Gate::Run;
        };
        if let Some(payload) = entry.resolve.take() {
            return Gate::Resolve(payload);
        }
        entry.waker = Some(cx.waker().clone());
        if entry.held { Gate::Hold } else { Gate::Run }
    }

    fn finish(&self, id: ProbeId, how: Finish) {
        let task = WireTaskId(id.0);
        let Some(entry) = lock(&self.book).tasks.remove(&task) else {
            return;
        };
        let change = match how {
            Finish::Completed => TaskChange::Finished,
            Finish::Resolved => TaskChange::Resolved,
            Finish::Dropped => TaskChange::Failed {
                error: "the task was dropped before it finished".to_owned(),
            },
        };
        self.emit(vec![event(entry.name, task, change)]);
    }

    /// Ids of running tasks, for tests and diagnostics.
    #[must_use]
    pub fn running(&self) -> VecDeque<WireTaskId> {
        lock(&self.book).tasks.keys().copied().collect()
    }
}

fn wake(entry: &mut Entry) {
    if let Some(waker) = entry.waker.take() {
        waker.wake();
    }
}

fn event(name: &str, task: WireTaskId, change: TaskChange) -> TaskEvent {
    TaskEvent {
        name: name.to_owned(),
        task,
        change,
    }
}

struct Shim(Arc<TaskHub>);

impl Controller for Shim {
    fn start(&self, meta: ProbeMeta) -> ProbeId {
        self.0.start(&meta)
    }

    fn gate(&self, id: ProbeId, cx: &mut Context<'_>) -> Gate {
        self.0.gate(id, cx)
    }

    fn finish(&self, id: ProbeId, how: Finish) {
        self.0.finish(id, how);
    }
}

static HUB: OnceLock<Arc<TaskHub>> = OnceLock::new();

/// Makes `hub` the one [`RemoteExecutor`] installs. Only the first call in a process wins.
pub(crate) fn install_global(hub: Arc<TaskHub>) -> Arc<TaskHub> {
    Arc::clone(HUB.get_or_init(|| hub))
}

/// Polls a spawned future with the hub's controller installed on the polling thread.
struct Controlled<F> {
    hub: Arc<TaskHub>,
    future: Option<Pin<Box<F>>>,
}

impl<F: Future<Output = ()>> Future for Controlled<F> {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let this = self.get_mut();
        let Some(future) = this.future.as_mut() else {
            return Poll::Ready(());
        };
        let _installed = control::install(Rc::new(Shim(Arc::clone(&this.hub))));
        let polled = future.as_mut().poll(cx);
        if polled.is_ready() {
            this.future = None;
        }
        polled
    }
}

impl<F> Drop for Controlled<F> {
    fn drop(&mut self) {
        let Some(future) = self.future.take() else {
            return;
        };
        let _installed = control::install(Rc::new(Shim(Arc::clone(&self.hub))));
        drop(future);
    }
}

/// The app's executor, with the endpoint's controller around every future it runs.
#[derive(Debug)]
pub struct RemoteExecutor<E> {
    inner: E,
}

impl<E: Executor> Executor for RemoteExecutor<E> {
    fn new() -> Result<Self, std::io::Error> {
        Ok(Self { inner: E::new()? })
    }

    fn spawn(&self, future: impl Future<Output = ()> + MaybeSend + 'static) {
        match HUB.get() {
            Some(hub) => self.inner.spawn(Controlled {
                hub: Arc::clone(hub),
                future: Some(Box::pin(future)),
            }),
            None => self.inner.spawn(future),
        }
    }

    fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
        self.inner.block_on(future)
    }

    /// `iced_winit` polls each new task once inside `enter`, on the event loop's thread,
    /// before it spawns what is left, so the controller is installed here too.
    fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
        let Some(hub) = HUB.get() else {
            return self.inner.enter(f);
        };
        let _installed = control::install(Rc::new(Shim(Arc::clone(hub))));
        self.inner.enter(f)
    }
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::task::Wake;

    use super::*;
    use crate::task_name;

    task_name!(Load: String);
    task_name!(Save: Result<u32, String>);

    struct Flag(AtomicBool);

    impl Wake for Flag {
        fn wake(self: Arc<Self>) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    fn poll_once<F: Future + Unpin>(future: &mut F, flag: &Arc<Flag>) -> Poll<F::Output> {
        let waker = Waker::from(Arc::clone(flag));
        let mut cx = Context::from_waker(&waker);
        Pin::new(future).poll(&mut cx)
    }

    fn events(hub: &TaskHub) -> Arc<Mutex<Vec<TaskEvent>>> {
        let seen = Arc::new(Mutex::new(Vec::new()));
        let sink = Arc::clone(&seen);
        hub.listen(move |event| lock(&sink).push(event));
        seen
    }

    #[test]
    fn a_held_task_waits_until_released() {
        let hub = Arc::new(TaskHub::new());
        let seen = events(&hub);
        let _rule = hub.hold(Load::NAME.to_owned());
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async {
                let _ = Load::task(async { "real".to_owned() }).await;
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        let changes: Vec<_> = lock(&seen).iter().map(|e| e.change.clone()).collect();
        assert_eq!(changes, vec![TaskChange::Started, TaskChange::Held]);
        let task = lock(&seen)[0].task;
        assert_eq!(hub.release(task), Ok(()));
        assert!(flag.0.load(Ordering::SeqCst));
        assert!(poll_once(&mut future, &flag).is_ready());
        assert_eq!(
            lock(&seen).last().map(|e| e.change.clone()),
            Some(TaskChange::Finished)
        );
    }

    #[test]
    fn a_resolved_task_finishes_with_the_client_value() {
        let hub = Arc::new(TaskHub::new());
        hub.register(Load::NAME, resolver::<Load>());
        let seen = events(&hub);
        let _rule = hub.hold(Load::NAME.to_owned());
        let out = Arc::new(Mutex::new(None));
        let sink = Arc::clone(&out);
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async move {
                let value = Load::task(async { "real".to_owned() }).await;
                *lock(&sink) = Some(value);
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        let task = lock(&seen)[0].task;
        assert_eq!(
            hub.resolve(task, &TaskOutput::Value("\"Loaded\"".to_owned())),
            Ok(())
        );
        assert!(poll_once(&mut future, &flag).is_ready());
        assert_eq!(lock(&out).clone(), Some("Loaded".to_owned()));
        assert_eq!(
            lock(&seen).last().map(|e| e.change.clone()),
            Some(TaskChange::Resolved)
        );
    }

    #[test]
    fn an_error_output_becomes_err_of_a_result() {
        let payload = decode::<Save>(&TaskOutput::Error("\"disk full\"".to_owned()));
        let value = payload.ok().and_then(|p| p.take::<Save>().ok());
        assert_eq!(value, Some(Err("disk full".to_owned())));
    }

    #[test]
    fn a_value_of_the_wrong_shape_names_the_task() {
        let error = decode::<Load>(&TaskOutput::Value("17".to_owned())).err();
        assert!(error.is_some_and(|e| e.contains(Load::NAME)));
    }

    #[test]
    fn resolving_an_unregistered_or_missing_task_is_an_error() {
        let hub = Arc::new(TaskHub::new());
        let seen = events(&hub);
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let _rule = hub.hold(Load::NAME.to_owned());
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async {
                let _ = Load::task(async { String::new() }).await;
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        let task = lock(&seen)[0].task;
        let unregistered = hub.resolve(task, &TaskOutput::Value("\"x\"".to_owned()));
        assert!(unregistered.is_err_and(|e| e.contains("resolvable")));
        assert!(hub.release(WireTaskId(99)).is_err());
        assert!(!hub.remove_rule(WireRuleId(99)));
    }

    #[test]
    fn removing_the_rule_lets_held_tasks_go() {
        let hub = Arc::new(TaskHub::new());
        let seen = events(&hub);
        let rule = hub.hold(Load::NAME.to_owned());
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async {
                let _ = Load::task(async { String::new() }).await;
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        assert!(hub.remove_rule(rule));
        assert!(poll_once(&mut future, &flag).is_ready());
        assert!(lock(&seen).iter().any(|e| e.change == TaskChange::Released));
    }

    #[test]
    fn wait_idle_is_answered_once_the_held_task_lets_go() {
        use icedwright_protocol::RequestId;

        use super::super::dispatch::{ClientId, Effect, ProbeState, dispatch};

        let hub = Arc::new(TaskHub::new());
        let mut state = ProbeState::new("demo", 1, Arc::clone(&hub), false);
        let answered = |effects: &[Effect], want: u64| {
            effects.iter().any(
                |effect| matches!(effect, Effect::Reply { id, result: Ok(_), .. } if id.0 == want),
            )
        };
        let hello = serde_json::json!({ "protocol": icedwright_protocol::PROTOCOL, "client": "t" });
        let greeted = dispatch(&mut state, ClientId(1), RequestId(1), "hello", hello);
        assert!(answered(&greeted, 1));

        let rule = hub.hold(Load::NAME.to_owned());
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async {
                let _ = Load::task(async { String::new() }).await;
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        let waiting = dispatch(
            &mut state,
            ClientId(1),
            RequestId(2),
            "wait_idle",
            serde_json::json!({}),
        );
        assert!(!answered(&waiting, 2));

        assert!(hub.remove_rule(rule));
        assert!(poll_once(&mut future, &flag).is_ready());
        let finished = TaskEvent {
            name: Load::NAME.to_owned(),
            task: WireTaskId(1),
            change: TaskChange::Finished,
        };
        assert!(answered(&state.task_event(finished), 2));
    }

    struct Inline;

    impl Executor for Inline {
        fn new() -> Result<Self, std::io::Error> {
            Ok(Inline)
        }

        fn spawn(&self, _future: impl Future<Output = ()> + MaybeSend + 'static) {}

        fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
            futures::executor::block_on(future)
        }
    }

    #[test]
    fn a_task_first_polled_inside_enter_is_seen_by_the_hub() {
        let hub = install_global(Arc::new(TaskHub::new()));
        let seen = events(&hub);
        let rule = hub.hold(Load::NAME.to_owned());
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Box::pin(Load::task(async { String::new() }));
        let executor = RemoteExecutor { inner: Inline };
        let polled = executor.enter(|| poll_once(&mut future, &flag));
        assert!(polled.is_pending());
        let changes: Vec<_> = lock(&seen).iter().map(|e| e.change.clone()).collect();
        assert_eq!(changes, vec![TaskChange::Started, TaskChange::Held]);
        assert!(hub.remove_rule(rule));
    }

    #[test]
    fn a_task_dropped_while_held_is_reported() {
        let hub = Arc::new(TaskHub::new());
        let seen = events(&hub);
        let _rule = hub.hold(Load::NAME.to_owned());
        let flag = Arc::new(Flag(AtomicBool::new(false)));
        let mut future = Controlled {
            hub: Arc::clone(&hub),
            future: Some(Box::pin(async {
                let _ = Load::task(async { String::new() }).await;
            })),
        };
        assert!(poll_once(&mut future, &flag).is_pending());
        drop(future);
        assert!(matches!(
            lock(&seen).last().map(|e| e.change.clone()),
            Some(TaskChange::Failed { .. })
        ));
        assert!(hub.running().is_empty());
    }
}