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};
const RETRY_AT_MOST: Duration = Duration::from_secs(60 * 60);
const PRUNE_EVERY: chrono::TimeDelta = chrono::TimeDelta::hours(6);
const PRUNE_AFTER: chrono::TimeDelta = chrono::TimeDelta::minutes(10);
const QUIET_CLAIM_KEPT: chrono::TimeDelta = chrono::TimeDelta::days(1);
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 {
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 {
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(())
}
}
#[derive(Debug, Clone)]
struct Phone {
device: DeviceRecord,
subscription: Subscription,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Claim {
Decision(String),
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)
}
#[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 {
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;
}
}
}
}
}
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");
let ringer = self.clone();
tokio::spawn(async move {
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(¤t).await.unwrap_or_default() {
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;
}
}
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;
}
}
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 });
}
}
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)
}
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
}
}
}
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;
}
}
}
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");
}
}
}
}
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)
}
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)
}
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)
}
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");
}
}
}
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))
}