liveactivity 0.8.4

Framework-neutral Live Activities: one interface over ActivityKit, Android Live Updates and other backends
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
//! A kit that answers as activitykit 0.1 does, in memory. A write at a revision is taken when the revision is higher
//! than the accepted one, answered as done when it equals it with the same content, and refused when lower
//! (`STALE_REVISION`) or equal with other content (`CONFLICT`); an end without a revision ends at the next one with the
//! last values. A repeated keyed start with the same content, whatever its timestamp, returns the running activity,
//! and one with other content is `CONFLICT`. An update of an ended activity is `NOT_FOUND`; ending again is fine.
//!
//! As on iOS, an activity that ends at once leaves the system's list (here at once, the losing side of the race), and
//! `activity(id)` finds an id through a handle that is alive in the process, else through the list.

use super::{Acknowledge, Authorization, EndSpec, Handle, Kit, KitEvent, StartSpec, UpdateSpec};
use crate::layout::ActionEvent;
use activitykit::{Error, State, Values};
use std::{
    collections::HashMap,
    sync::{Arc, Mutex, MutexGuard, Weak, mpsc},
};

/// What the tests log: calls, handlers, emits and releases, in order.
pub(crate) type Log = Arc<Mutex<Vec<String>>>;

/// An acknowledgement that logs `released` when the tap's intent is let go.
pub(crate) struct FakeAck(pub(crate) Log);

impl Acknowledge for FakeAck {
    fn acknowledge(&self) {
        self.0.lock().unwrap().push("released".into());
    }
}

#[derive(Debug, Clone)]
pub(crate) struct Entry {
    pub(crate) id: String,
    pub(crate) start: StartSpec,
    pub(crate) state: State,
    pub(crate) values: Values,
    pub(crate) revision: u64,
    pub(crate) stale_at: Option<u64>,
    pub(crate) timestamp: Option<u64>,
    /// The score of the last content that gave one.
    pub(crate) relevance: Option<f64>,
    /// Whether the system lists it.
    pub(crate) listed: bool,
    /// What the system could not show of it.
    pub(crate) degraded: Vec<String>,
}

#[derive(Default)]
pub(crate) struct Book {
    pub(crate) entries: Vec<Entry>,
    /// Every call that reached the kit: `start key`, `activity id`, `update id`, `end id`, `list`, `image name`.
    pub(crate) calls: Vec<String>,
    pub(crate) starts: Vec<StartSpec>,
    pub(crate) updates: Vec<UpdateSpec>,
    pub(crate) ends: Vec<EndSpec>,
    /// The answer of the next call instead of its result.
    pub(crate) fail: Option<Error>,
    /// Whether the system's report that an activity left the screen reaches its handle before an end returns.
    pub(crate) dismisses_at_an_end: bool,
    pub(crate) authorization: Option<Authorization>,
    /// The handles alive in this process, by id; they share one token, as activitykit's share their state.
    alive: HashMap<String, Weak<()>>,
    /// Where the kit's events go, once the backend subscribed.
    events: Option<mpsc::Sender<KitEvent<FakeHandle, FakeAck>>>,
}

impl Book {
    fn alive(&self, id: &str) -> bool {
        self.alive
            .get(id)
            .is_some_and(|token| token.strong_count() > 0)
    }
}

#[derive(Clone, Default)]
pub(crate) struct FakeKit(pub(crate) Arc<Mutex<Book>>);

#[derive(Clone)]
pub(crate) struct FakeHandle {
    id: String,
    key: String,
    book: Arc<Mutex<Book>>,
    _alive: Arc<()>,
}

/// The handle of `id`, which shares the token of a handle alive in the process.
fn adopt(book: &Arc<Mutex<Book>>, guard: &mut Book, id: &str, key: &str) -> FakeHandle {
    let token = match guard.alive.get(id).and_then(Weak::upgrade) {
        Some(token) => token,
        None => {
            let token = Arc::new(());
            guard.alive.insert(id.to_owned(), Arc::downgrade(&token));
            token
        }
    };
    FakeHandle {
        id: id.to_owned(),
        key: key.to_owned(),
        book: book.clone(),
        _alive: token,
    }
}

impl FakeKit {
    pub(crate) fn book(&self) -> MutexGuard<'_, Book> {
        self.0.lock().unwrap()
    }

    pub(crate) fn calls(&self) -> Vec<String> {
        self.book().calls.clone()
    }

    pub(crate) fn fail_next(&self, error: Error) {
        self.book().fail = Some(error);
    }

    /// What the system does: the activity moves to `state`, as an event would tell the handle.
    pub(crate) fn set_state(&self, id: &str, state: State) {
        let mut book = self.book();
        book.entries
            .iter_mut()
            .filter(|entry| entry.id == id)
            .for_each(|entry| entry.state = state);
    }

    /// What an iPhone does after an end that removes the activity: its report of `dismissed` reaches the handle
    /// before the end returns, so the handle never says `ended` to the caller.
    pub(crate) fn dismiss_at_an_end(&self) {
        self.book().dismisses_at_an_end = true;
    }

    /// A tap as activitykit's events give it, to the subscriber of [`Kit::events`].
    pub(crate) fn send_tap(&self, event: ActionEvent, acknowledgement: FakeAck) {
        self.send_event(KitEvent::Tap(event, acknowledgement));
    }

    /// An event as activitykit gives it, to the subscriber of [`Kit::events`].
    pub(crate) fn send_event(&self, event: KitEvent<FakeHandle, FakeAck>) {
        let book = self.book();
        let events = book
            .events
            .as_ref()
            .expect("the backend subscribed to the events");
        events.send(event).unwrap();
    }

    /// The end of the kit's events.
    pub(crate) fn close_events(&self) {
        self.book().events = None;
    }

    /// What a push does to the activity `id`: it shows `values` at `revision`, above what it had.
    #[allow(dead_code)]
    pub(crate) fn pushed(&self, id: &str, revision: u64, values: Values) {
        let mut book = self.book();
        for entry in book.entries.iter_mut().filter(|entry| entry.id == id) {
            entry.values = values.clone();
            entry.revision = revision;
        }
    }

    /// What activitykit reports the system could not show of the activity `id`.
    pub(crate) fn degrade(&self, id: &str, features: &[&str]) {
        let mut book = self.book();
        for entry in book.entries.iter_mut().filter(|entry| entry.id == id) {
            entry.degraded = features.iter().map(|&feature| feature.to_owned()).collect();
        }
    }

    /// Whether the system lists the activity `id`.
    pub(crate) fn listed(&self, id: &str) -> bool {
        self.book()
            .entries
            .iter()
            .any(|entry| entry.id == id && entry.listed)
    }

    /// A kit of a later launch: the same activities, no handles of this launch.
    pub(crate) fn relaunched(&self) -> Self {
        let entries = self.book().entries.clone();
        Self(Arc::new(Mutex::new(Book {
            entries,
            ..Book::default()
        })))
    }

    /// The handle that an event would give: activitykit's tap names the activity's key.
    pub(crate) fn handle(&self, id: &str, key: &str) -> FakeHandle {
        adopt(&self.0, &mut self.book(), id, key)
    }
}

/// The fake's clock, in epoch milliseconds: it stands still.
pub(crate) const NOW: u64 = 1_800_000_000_000;

fn take(book: &mut Book, call: String) -> Result<(), Error> {
    book.calls.push(call);
    book.fail.take().map_or(Ok(()), Err)
}

fn live(state: State) -> bool {
    matches!(state, State::Active | State::Stale | State::Pending)
}

/// A start's content, as a repeated keyed start compares it: everything but the timestamp, the relevance, the
/// push and when and how the activity begins, which are no part of the request that ActivityKit's side compares.
fn content(start: &StartSpec) -> StartSpec {
    StartSpec {
        timestamp: None,
        relevance: None,
        push: None,
        transient: false,
        scheduled: None,
        ..start.clone()
    }
}

/// Swift's rules for content at `revision` against `entry`: `Ok(true)` to take it, `Ok(false)` when it is done.
fn takes(
    entry: &Entry,
    revision: u64,
    values: &Values,
    stale_at: Option<u64>,
) -> Result<bool, Error> {
    if revision < entry.revision {
        return Err(Error::StaleRevision(
            "The revision is older than the current activity state.".into(),
        ));
    }
    if revision > entry.revision {
        return Ok(true);
    }
    if *values == entry.values && stale_at == entry.stale_at {
        Ok(false)
    } else {
        Err(Error::Conflict(
            "This revision already contains different state.".into(),
        ))
    }
}

impl Kit for FakeKit {
    type Handle = FakeHandle;
    type Ack = FakeAck;

    fn events(&self) -> Box<dyn Iterator<Item = KitEvent<FakeHandle, FakeAck>> + Send> {
        let (sender, receiver) = mpsc::channel();
        let mut book = self.book();
        book.calls.push("events".into());
        book.events = Some(sender);
        Box::new(receiver.into_iter())
    }

    fn authorization(&self) -> Authorization {
        self.book().authorization.unwrap_or(Authorization {
            supported: true,
            enabled: true,
            buttons: true,
            frequent_pushes: true,
        })
    }

    fn start(
        &self,
        start: StartSpec,
    ) -> impl Future<Output = activitykit::Result<FakeHandle>> + Send {
        let book = self.0.clone();
        async move {
            let mut guard = book.lock().unwrap();
            take(&mut guard, format!("start {}", start.key))?;
            let key = start.key.clone();
            let running = guard
                .entries
                .iter()
                .find(|entry| entry.start.key == key && live(entry.state));
            if let Some(running) = running {
                if content(&running.start) != content(&start) {
                    return Err(Error::Conflict(
                        "An activity with this key already exists with different input.".into(),
                    ));
                }
                let id = running.id.clone();
                return Ok(adopt(&book, &mut guard, &id, &key));
            }
            let id = format!("la-ios-layout-{}", guard.entries.len() + 1);
            guard.entries.push(Entry {
                id: id.clone(),
                start: start.clone(),
                // A scheduled activity waits for its time; one whose time has passed begins at once.
                state: match &start.scheduled {
                    Some(scheduled) if scheduled.at > NOW => State::Pending,
                    _ => State::Active,
                },
                values: start.values.clone(),
                revision: start.revision,
                stale_at: start.stale_at,
                timestamp: Some(start.timestamp.unwrap_or(1_000)),
                relevance: start.relevance,
                listed: true,
                degraded: Vec::new(),
            });
            guard.starts.push(start);
            Ok(adopt(&book, &mut guard, &id, &key))
        }
    }

    fn activity(
        &self,
        id: &str,
    ) -> impl Future<Output = activitykit::Result<Option<FakeHandle>>> + Send {
        let (book, id) = (self.0.clone(), id.to_owned());
        async move {
            let mut guard = book.lock().unwrap();
            take(&mut guard, format!("activity {id}"))?;
            let alive = guard.alive(&id);
            let key = guard
                .entries
                .iter()
                .find(|entry| entry.id == id && (alive || entry.listed))
                .map(|entry| entry.start.key.clone());
            Ok(key.map(|key| adopt(&book, &mut guard, &id, &key)))
        }
    }

    fn activities(&self) -> impl Future<Output = activitykit::Result<Vec<FakeHandle>>> + Send {
        let book = self.0.clone();
        async move {
            let mut guard = book.lock().unwrap();
            take(&mut guard, "list".into())?;
            let named: Vec<(String, String)> = guard
                .entries
                .iter()
                .filter(|entry| entry.listed)
                .map(|entry| (entry.id.clone(), entry.start.key.clone()))
                .collect();
            Ok(named
                .iter()
                .map(|(id, key)| adopt(&book, &mut guard, id, key))
                .collect())
        }
    }

    fn write_image(&self, name: &str, _png: &[u8]) -> activitykit::Result<()> {
        take(&mut self.book(), format!("image {name}"))
    }
}

impl FakeHandle {
    fn entry(&self) -> Option<Entry> {
        self.book
            .lock()
            .unwrap()
            .entries
            .iter()
            .find(|entry| entry.id == self.id)
            .cloned()
    }
}

impl Handle for FakeHandle {
    fn id(&self) -> &str {
        &self.id
    }

    fn key(&self) -> &str {
        &self.key
    }

    fn state(&self) -> State {
        self.entry().map_or(State::Unknown, |entry| entry.state)
    }

    fn values(&self) -> Values {
        self.entry().map(|entry| entry.values).unwrap_or_default()
    }

    fn revision(&self) -> Option<u64> {
        self.entry().map(|entry| entry.revision)
    }

    fn stale_at(&self) -> Option<u64> {
        self.entry().and_then(|entry| entry.stale_at)
    }

    fn timestamp(&self) -> Option<u64> {
        self.entry().and_then(|entry| entry.timestamp)
    }

    fn relevance(&self) -> f64 {
        self.entry()
            .and_then(|entry| entry.relevance)
            .unwrap_or(0.0)
    }

    fn degraded_features(&self) -> Vec<String> {
        self.entry().map(|entry| entry.degraded).unwrap_or_default()
    }

    fn update(&self, update: UpdateSpec) -> impl Future<Output = activitykit::Result<()>> + Send {
        let (book, id) = (self.book.clone(), self.id.clone());
        async move {
            let mut guard = book.lock().unwrap();
            take(&mut guard, format!("update {id}"))?;
            // A pending activity begins with the content of its start, whatever is sent meanwhile.
            let pending = |entry: &Entry| entry.id == id && entry.state == State::Pending;
            if guard.entries.iter().any(pending) {
                return Err(Error::Conflict(
                    "A scheduled activity takes no update before it began.".into(),
                ));
            }
            let entry = guard.entries.iter_mut().find(|entry| {
                entry.id == id && matches!(entry.state, State::Active | State::Stale)
            });
            let Some(entry) = entry else {
                return Err(Error::NotFound(
                    "The activity is no longer available.".into(),
                ));
            };
            if takes(entry, update.revision, &update.values, update.stale_at)? {
                entry.revision = update.revision;
                entry.values = update.values.clone();
                entry.stale_at = update.stale_at;
                entry.timestamp = Some(update.timestamp.unwrap_or(2_000));
                // Without a score the activity keeps its own.
                entry.relevance = update.relevance.or(entry.relevance);
            }
            guard.updates.push(update);
            Ok(())
        }
    }

    fn end(&self, end: EndSpec) -> impl Future<Output = activitykit::Result<()>> + Send {
        let (book, id) = (self.book.clone(), self.id.clone());
        async move {
            let mut guard = book.lock().unwrap();
            take(&mut guard, format!("end {id}"))?;
            let dismisses = guard.dismisses_at_an_end;
            let Some(entry) = guard.entries.iter_mut().find(|entry| entry.id == id) else {
                return Err(Error::NotFound(
                    "The activity is no longer available.".into(),
                ));
            };
            if !matches!(entry.state, State::Ended | State::Dismissed) {
                let values = end.values.clone().unwrap_or_else(|| entry.values.clone());
                let revision = end.revision.unwrap_or(entry.revision + 1);
                takes(entry, revision, &values, end.stale_at).map(|_| ())?;
                entry.revision = revision;
                entry.values = values;
                entry.stale_at = end.stale_at;
                entry.timestamp = Some(end.timestamp.unwrap_or(3_000));
                entry.relevance = end.relevance.or(entry.relevance);
                entry.state = State::Ended;
                entry.listed = !matches!(end.policy, crate::models::EndPolicy::Immediate {});
            }
            if dismisses {
                entry.state = State::Dismissed;
            }
            guard.ends.push(end);
            Ok(())
        }
    }
}