adk-surface 3.0.0

Agent surfaces for ADK-Rust: one engine that turns a kernel's sessions, decisions and activity into plain words for every surface, and the surfaces that show them
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
//! The phone's doorbell (spec 3.3 §5.4, §7.3, §11 S-I5): a wake-up when a decision waits,
//! none during quiet time, one per phone when quiet time ends, each sent once across replicas.

use std::collections::HashSet;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind, AuditTrail};
use adk_core::principal::SubjectRef;
use adk_core::{
    ApprovalEventKind, ApprovalNotification, ApprovalNotifier, ApprovalRequest, ApprovalService,
    ApprovalState, Clock, InboxQuery,
};
use adk_kernel::pairing::{DeviceRecord, Pairing};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde_json::{Value, json};
use tokio::sync::mpsc;

use super::SURFACE_AUDIT_NOTIFY;
use super::push::{Deliveries, PushSender, Sent, Subscription, new_wake_id, wake_up};
use super::quiet::QuietTime;
use super::store::{Attachment, Attachments, Holder, PUSH, PUSH_KEY, WAKE};

/// The longest wait between tries of a wake-up the push service could not take.
const RETRY_AT_MOST: Duration = Duration::from_secs(60 * 60);
/// How often the claims no wake-up needs any more are removed.
const PRUNE_EVERY: chrono::TimeDelta = chrono::TimeDelta::hours(6);
/// How long a claim stays whatever it covers: a wake-up being sent keeps its own.
const PRUNE_AFTER: chrono::TimeDelta = chrono::TimeDelta::minutes(10);
/// How long the claim of a quiet time's end is kept, for the replicas that wake at that end.
const QUIET_CLAIM_KEPT: chrono::TimeDelta = chrono::TimeDelta::days(1);

/// Tells the phone's push task about every decision submitted (spec 3.3 §5.4). Add it to the
/// approval service with `StoreApprovalService::with_notifier`, beside Telegram's doorbell;
/// the decisions it hears about wait for [`Phone::start_push`](super::Phone::start_push).
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use adk_core::{InMemoryApprovalStore, StoreApprovalService};
/// use adk_surface::mobile::PushDoorbell;
///
/// let doorbell = Arc::new(PushDoorbell::new());
/// let service = StoreApprovalService::new(Arc::new(InMemoryApprovalStore::new()))
///     .with_notifier(doorbell.clone());
/// # let _ = service;
/// ```
pub struct PushDoorbell {
    sender: mpsc::UnboundedSender<ApprovalRequest>,
    receiver: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<ApprovalRequest>>>,
}

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

impl PushDoorbell {
    /// A doorbell whose push task has not started yet.
    pub fn new() -> Self {
        let (sender, receiver) = mpsc::unbounded_channel();
        Self { sender, receiver: Arc::new(tokio::sync::Mutex::new(receiver)) }
    }

    pub(crate) fn receiver(
        &self,
    ) -> Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<ApprovalRequest>>> {
        Arc::clone(&self.receiver)
    }
}

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

#[async_trait]
impl ApprovalNotifier for PushDoorbell {
    /// Passes each submitted decision on; every other change wakes nothing.
    async fn notify(&self, notification: &ApprovalNotification) -> adk_core::Result<()> {
        if notification.kind == ApprovalEventKind::Submitted
            && self.sender.send(notification.request.clone()).is_err()
        {
            tracing::warn!(approval.id = %notification.request.id, "the phone's doorbell is gone; the decision waits in the inbox");
        }
        Ok(())
    }
}

/// A phone that can be woken: an active device of the person with a push subscription.
#[derive(Debug, Clone)]
struct Phone {
    device: DeviceRecord,
    subscription: Subscription,
}

/// What a wake-up's claim covers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Claim {
    /// One decision at one version.
    Decision(String),
    /// The end of a quiet time.
    QuietEnded(DateTime<Utc>),
}

impl Claim {
    fn key(&self) -> String {
        match self {
            Self::Decision(key) => key.clone(),
            Self::QuietEnded(at) => format!("quiet:{}", at.to_rfc3339()),
        }
    }
}

fn decision_key(request: &ApprovalRequest) -> String {
    format!("{}:{}", request.id, request.version)
}

/// The push task's parts.
#[derive(Clone)]
pub(crate) struct Ringer {
    pub(crate) pairing: Pairing,
    pub(crate) store: Attachments,
    pub(crate) sender: PushSender,
    pub(crate) quiet: Arc<dyn QuietTime>,
    pub(crate) approvals: Arc<dyn ApprovalService>,
    pub(crate) audit: Option<AuditTrail>,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) deliveries: Arc<Deliveries>,
    pub(crate) poll: Duration,
}

impl Ringer {
    /// Runs until the doorbell is dropped: wakes for each decision it hears about, sweeps at
    /// the start and at each end of quiet time, and removes the claims no wake-up needs at the
    /// start and every six hours.
    pub(crate) async fn run(
        self,
        receiver: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<ApprovalRequest>>>,
    ) {
        let mut receiver = receiver.lock().await;
        let mut quiet_end = self.quiet.until(None, self.clock.now()).await;
        if quiet_end.is_none() {
            self.sweep(None).await;
        }
        self.prune().await;
        let mut pruned = self.clock.now();
        loop {
            let wait = match quiet_end {
                Some(end) => (end - self.clock.now()).to_std().unwrap_or_default().min(self.poll),
                None => self.poll,
            };
            tokio::select! {
                request = receiver.recv() => match request {
                    Some(request) => {
                        let ringer = self.clone();
                        tokio::spawn(async move { ringer.submitted(request).await });
                    }
                    None => return,
                },
                () = tokio::time::sleep(wait) => {
                    let now = self.clock.now();
                    match self.quiet.until(None, now).await {
                        Some(end) => quiet_end = Some(end),
                        None => {
                            if let Some(end) = quiet_end.take() {
                                self.sweep(Some(end)).await;
                            }
                        }
                    }
                    if now - pruned >= PRUNE_EVERY {
                        self.prune().await;
                        pruned = now;
                    }
                }
            }
        }
    }

    /// A decision was submitted: wake each of its person's phones now, or when its quiet time
    /// ends.
    pub(crate) async fn submitted(&self, request: ApprovalRequest) {
        if request.state != ApprovalState::Pending {
            return;
        }
        let phones = match self.phones_for(&request).await {
            Ok(phones) => phones,
            Err(error) => {
                tracing::warn!(approval.id = %request.id, error = %error, "the phones to wake could not be read");
                return;
            }
        };
        if phones.is_empty() {
            return;
        }
        let now = self.clock.now();
        if let Some(until) = self.quiet.until(request.run_id.as_deref(), now).await {
            for phone in &phones {
                self.record(&phone.device, std::slice::from_ref(&request.id), "held", None).await;
            }
            tracing::debug!(approval.id = %request.id, quiet.until = %until, "wake-up held for quiet time");
            // Its area's quiet time may end apart from the default area's, which the sweep
            // follows; ending together, they share one claim.
            let ringer = self.clone();
            tokio::spawn(async move {
                // Reads the clock and the quiet time again each poll, as the sweep does: a clock
                // set forward ends the wait, and a quiet time the person changed meanwhile holds
                // it to the new end, which names the claim.
                let mut until = until;
                loop {
                    let now = ringer.clock.now();
                    match ringer.quiet.until(request.run_id.as_deref(), now).await {
                        Some(end) => {
                            until = end;
                            let left = (end - now).to_std().unwrap_or_default();
                            tokio::time::sleep(left.clamp(Duration::from_millis(1), ringer.poll))
                                .await;
                        }
                        None => break,
                    }
                }
                let Ok(Some(current)) = ringer.approvals.get(&request.id).await else { return };
                if current.state != ApprovalState::Pending {
                    return;
                }
                for phone in ringer.phones_for(&current).await.unwrap_or_default() {
                    // Every decision the phone's person has waiting, as the sweep at the same end
                    // covers, so whichever takes the claim marks them all.
                    let waiting = match ringer.waiting(&phone.device).await {
                        Ok(waiting) if !waiting.is_empty() => waiting,
                        Ok(_) => vec![current.clone()],
                        Err(error) => {
                            tracing::warn!(device.id = %phone.device.id, error = %error, "the waiting decisions could not be read");
                            vec![current.clone()]
                        }
                    };
                    ringer.wake(&phone, &Claim::QuietEnded(until), &waiting).await;
                }
            });
            return;
        }
        for phone in &phones {
            self.wake(
                phone,
                &Claim::Decision(decision_key(&request)),
                std::slice::from_ref(&request),
            )
            .await;
        }
    }

    /// Each phone whose person has a waiting decision gets one wake-up: at the end of quiet
    /// time `ended`, claimed by that end; at the start, claimed by the first decision no
    /// wake-up covered yet, so a restart wakes no phone twice for one decision.
    pub(crate) async fn sweep(&self, ended: Option<DateTime<Utc>>) {
        let phones = match self.phones().await {
            Ok(phones) => phones,
            Err(error) => {
                tracing::warn!(error = %error, "the phones to wake could not be read");
                return;
            }
        };
        for phone in phones {
            let waiting = match self.waiting(&phone.device).await {
                Ok(waiting) => waiting,
                Err(error) => {
                    tracing::warn!(device.id = %phone.device.id, error = %error, "the waiting decisions could not be read");
                    continue;
                }
            };
            if waiting.is_empty() {
                continue;
            }
            let claim = match ended {
                Some(end) => Claim::QuietEnded(end),
                None => {
                    let holder = Holder::Device(phone.device.id.clone());
                    let covered: Vec<String> = match self.store.list(&holder, WAKE).await {
                        Ok(rows) => rows.into_iter().map(|row| row.key).collect(),
                        Err(error) => {
                            tracing::warn!(device.id = %phone.device.id, error = %error, "the wake-ups sent could not be read");
                            continue;
                        }
                    };
                    match waiting.iter().map(decision_key).find(|key| !covered.contains(key)) {
                        Some(first) => Claim::Decision(first),
                        None => continue,
                    }
                }
            };
            self.wake(&phone, &claim, &waiting).await;
        }
    }

    /// Sends `phone` one wake-up for `covers`, unless `claim` was taken here or on another
    /// replica. Every decision it covers is marked woken. One the push service could not take
    /// is tried again while its decisions wait (spec 3.3 §7.3).
    async fn wake(&self, phone: &Phone, claim: &Claim, covers: &[ApprovalRequest]) {
        let Some(marked) = self.claim(phone, claim, covers).await else { return };
        if self.ring(phone, claim, covers, &marked).await {
            let ringer = self.clone();
            let (phone, claim, covers) = (phone.clone(), claim.clone(), covers.to_vec());
            tokio::spawn(async move { ringer.ring_again(phone, claim, covers).await });
        }
    }

    /// Takes `claim` for `phone` and marks each decision of `covers` woken: the keys of the
    /// marks it made, or `None` when the claim was taken here or on another replica.
    async fn claim(
        &self,
        phone: &Phone,
        claim: &Claim,
        covers: &[ApprovalRequest],
    ) -> Option<Vec<String>> {
        let holder = Holder::Device(phone.device.id.clone());
        let now = self.clock.now();
        let ids: Vec<String> = covers.iter().map(|request| request.id.clone()).collect();
        let row =
            Attachment::new(holder.clone(), WAKE, claim.key(), json!({ "approvalIds": ids }), now);
        match self.store.put_if_absent(row).await {
            Ok(true) => {}
            Ok(false) => return None,
            Err(error) => {
                tracing::warn!(device.id = %phone.device.id, error = %error, "a wake-up could not be claimed; it is not sent");
                return None;
            }
        }
        let mut marked = Vec::new();
        for request in covers {
            let key = decision_key(request);
            let row = Attachment::new(holder.clone(), WAKE, key.clone(), json!({}), now);
            match self.store.put_if_absent(row).await {
                Ok(true) => marked.push(key),
                Ok(false) => {}
                Err(error) => {
                    tracing::warn!(device.id = %phone.device.id, error = %error, "a woken decision could not be marked");
                }
            }
        }
        Some(marked)
    }

    /// Sends one claimed wake-up and records what became of it. `true` when the push service
    /// could not take it now: the claim and the marks it made (`marked`) are removed, so a
    /// later try, the end of quiet time or a restart sends it.
    async fn ring(
        &self,
        phone: &Phone,
        claim: &Claim,
        covers: &[ApprovalRequest],
        marked: &[String],
    ) -> bool {
        let holder = Holder::Device(phone.device.id.clone());
        let ids: Vec<String> = covers.iter().map(|request| request.id.clone()).collect();
        let id = new_wake_id();
        match self.sender.send(&phone.subscription, &wake_up(&id)).await {
            Sent::Delivered => {
                self.deliveries.sent(&id, &phone.device.id, self.clock.now());
                self.record(&phone.device, &ids, "sent", None).await;
                false
            }
            Sent::Gone => {
                if let Err(error) = self.store.remove(&holder, PUSH, PUSH_KEY).await {
                    tracing::warn!(device.id = %phone.device.id, error = %error, "a gone subscription could not be removed");
                }
                self.record(&phone.device, &ids, "dropped", Some("the subscription is gone")).await;
                false
            }
            Sent::Failed(reason) => {
                tracing::warn!(device.id = %phone.device.id, reason = %reason, "a wake-up could not be sent");
                self.record(&phone.device, &ids, "dropped", Some(&reason)).await;
                false
            }
            Sent::Unavailable(reason) => {
                tracing::warn!(device.id = %phone.device.id, reason = %reason, "a wake-up could not be sent now; it is tried again");
                self.record(&phone.device, &ids, "dropped", Some(&reason)).await;
                for key in marked.iter().cloned().chain(std::iter::once(claim.key())) {
                    if let Err(error) = self.store.remove(&holder, WAKE, &key).await {
                        tracing::warn!(device.id = %phone.device.id, error = %error, "a wake-up's claim could not be released");
                    }
                }
                true
            }
        }
    }

    /// Tries a wake-up the push service could not take again, after a wait that doubles from
    /// the poll up to an hour, while its decisions wait, outside quiet time, and while the
    /// phone stays paired. The end of quiet time and the next start wake for what is left.
    async fn ring_again(self, phone: Phone, claim: Claim, covers: Vec<ApprovalRequest>) {
        let mut wait = self.poll;
        loop {
            tokio::time::sleep(wait).await;
            wait = wait.saturating_mul(2).min(RETRY_AT_MOST);
            let mut waiting = Vec::new();
            for request in &covers {
                if let Ok(Some(current)) = self.approvals.get(&request.id).await
                    && current.state == ApprovalState::Pending
                {
                    waiting.push(current);
                }
            }
            let Some(first) = waiting.first() else { return };
            if self.quiet.until(first.run_id.as_deref(), self.clock.now()).await.is_some() {
                return;
            }
            let Some(phone) = self.phones().await.ok().and_then(|phones| {
                phones.into_iter().find(|candidate| candidate.device.id == phone.device.id)
            }) else {
                return;
            };
            let Some(marked) = self.claim(&phone, &claim, &waiting).await else { return };
            if !self.ring(&phone, &claim, &waiting, &marked).await {
                return;
            }
        }
    }

    /// Removes what no wake-up needs any more (spec 3.3 §5.4): every attachment of a device
    /// whose pairing ended, and an active device's claims of decisions that no longer wait and
    /// of quiet times a day over. A claim younger than ten minutes stays, whatever it covers.
    pub(crate) async fn prune(&self) {
        let devices = match self.pairing.devices().await {
            Ok(devices) => devices,
            Err(error) => {
                tracing::warn!(error = %error, "the paired devices could not be read; nothing is pruned");
                return;
            }
        };
        let now = self.clock.now();
        for device in devices {
            let holder = Holder::Device(device.id.clone());
            if !device.is_active(now) {
                if let Err(error) = self.store.remove_all(&holder).await {
                    tracing::warn!(device.id = %device.id, error = %error, "an ended device's attachments could not be removed");
                }
                continue;
            }
            let rows = match self.store.list(&holder, WAKE).await {
                Ok(rows) => rows,
                Err(error) => {
                    tracing::warn!(device.id = %device.id, error = %error, "the wake-ups sent could not be read");
                    continue;
                }
            };
            if rows.iter().all(|row| now - row.updated_at < PRUNE_AFTER) {
                continue;
            }
            let waiting: HashSet<String> = match self.waiting(&device).await {
                Ok(waiting) => waiting.iter().map(decision_key).collect(),
                Err(error) => {
                    tracing::warn!(device.id = %device.id, error = %error, "the waiting decisions could not be read");
                    continue;
                }
            };
            for row in rows {
                let spent = match row.key.strip_prefix("quiet:") {
                    Some(_) => now - row.updated_at >= QUIET_CLAIM_KEPT,
                    None => !waiting.contains(&row.key),
                };
                if spent
                    && now - row.updated_at >= PRUNE_AFTER
                    && let Err(error) = self.store.remove(&holder, WAKE, &row.key).await
                {
                    tracing::warn!(device.id = %device.id, error = %error, "a spent wake-up claim could not be removed");
                }
            }
        }
    }

    /// Every phone that can be woken.
    async fn phones(&self) -> adk_core::Result<Vec<Phone>> {
        let now = self.clock.now();
        let mut phones = Vec::new();
        for device in self.pairing.devices().await.map_err(adk_core::AdkError::from)? {
            if !device.is_active(now) {
                continue;
            }
            let holder = Holder::Device(device.id.clone());
            let Some(row) = self.store.list(&holder, PUSH).await?.into_iter().next() else {
                continue;
            };
            match serde_json::from_value::<Subscription>(row.record) {
                Ok(subscription) => phones.push(Phone { device, subscription }),
                Err(error) => {
                    tracing::warn!(holder = %holder.key(), error = %error, "a push subscription could not be read");
                }
            }
        }
        Ok(phones)
    }

    /// The phones of `request`'s person that may answer it.
    async fn phones_for(&self, request: &ApprovalRequest) -> adk_core::Result<Vec<Phone>> {
        let mut phones = self.phones().await?;
        phones.retain(|phone| {
            phone.device.owner == request.scope.user_id && may_answer(request, &phone.device)
        });
        Ok(phones)
    }

    /// The decisions waiting for `device`'s person that it may answer.
    async fn waiting(&self, device: &DeviceRecord) -> adk_core::Result<Vec<ApprovalRequest>> {
        let mut waiting = Vec::new();
        let mut cursor = None;
        loop {
            let query = InboxQuery::for_approver(
                SubjectRef::human(device.owner.clone()),
                device.groups.clone(),
            )
            .with_cursor(cursor)
            .with_limit(200);
            let page = self.approvals.inbox(query).await?;
            waiting.extend(page.items.into_iter().filter(|request| {
                request.state == ApprovalState::Pending
                    && request.scope.user_id == device.owner
                    && may_answer(request, device)
            }));
            match page.next_cursor {
                Some(next) => cursor = Some(next),
                None => break,
            }
        }
        waiting.sort_by(|a, b| a.created_at.cmp(&b.created_at).then_with(|| a.id.cmp(&b.id)));
        Ok(waiting)
    }

    /// Writes `surface.notify` (spec 3.3 §11): the device, the decisions and what happened.
    async fn record(
        &self,
        device: &DeviceRecord,
        ids: &[String],
        outcome: &str,
        reason: Option<&str>,
    ) {
        let Some(trail) = &self.audit else { return };
        let mut draft = AuditRecordDraft::new(
            AuditRecordKind::Other("surface".to_string()),
            SURFACE_AUDIT_NOTIFY,
        )
        .actor(AuditActor::subject(SubjectRef::human(device.owner.clone())))
        .ext("surface", json!("phone"))
        .ext("device", json!(device.id))
        .ext("approvalIds", json!(ids))
        .ext("outcome", json!(outcome));
        if let Some(reason) = reason {
            draft = draft.ext("reason", Value::String(reason.to_string()));
        }
        if let Err(error) = trail.record(draft).await {
            tracing::warn!(device.id = %device.id, error = %error, "a wake-up's record failed");
        }
    }
}

/// Whether `device`'s person may answer `request`: an approver the policy names, and not its
/// requester when the policy forbids self-approval.
fn may_answer(request: &ApprovalRequest, device: &DeviceRecord) -> bool {
    let person = SubjectRef::human(device.owner.clone());
    request.is_eligible(&person, &device.groups)
        && !(request.policy.forbid_self_approval && request.is_self(&person))
}