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
use std::{
fmt,
panic::{AssertUnwindSafe, catch_unwind},
sync::{
Arc, Mutex, PoisonError,
atomic::{AtomicBool, Ordering},
},
};
use super::handler::panic_text;
use crate::tasks::{AsyncTasks, unix_seconds};
/// The health that `GET /ping` reports to AgentCore Runtime.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PingStatus {
/// The agent is idle. The service may end an idle session.
Healthy,
/// The agent is working in the background. The service keeps the session.
HealthyBusy,
}
impl PingStatus {
/// The text of the status in the ping reply.
pub fn as_str(self) -> &'static str {
match self {
Self::Healthy => "Healthy",
Self::HealthyBusy => "HealthyBusy",
}
}
}
impl fmt::Display for PingStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// `None` means the automatic status.
pub(crate) type PingHandler = Arc<dyn Fn() -> Option<PingStatus> + Send + Sync>;
/// What the last ping reported.
#[derive(Clone, Copy)]
struct Last {
status: PingStatus,
/// The Unix seconds of the last change of the status.
changed: u64,
/// Whether the status came from the custom handler.
custom: bool,
}
/// The status of the last ping and the time when it last changed.
#[derive(Clone)]
pub(crate) struct PingState {
handler: Option<PingHandler>,
tasks: AsyncTasks,
last: Arc<Mutex<Last>>,
// Whether the last call of the custom handler panicked.
panicking: Arc<AtomicBool>,
}
impl PingState {
pub(crate) fn new(handler: Option<PingHandler>, tasks: AsyncTasks) -> Self {
let last = Last { status: PingStatus::Healthy, changed: unix_seconds(), custom: false };
let last = Arc::new(Mutex::new(last));
Self { handler, tasks, last, panicking: Arc::default() }
}
/// The result of the custom handler. `None` when there is no handler, when it
/// leaves the status to the registry, and when it panics.
fn custom(&self) -> Option<PingStatus> {
// The custom handler is user code. It runs before the lock is taken.
let handler = self.handler.as_ref()?;
let outcome = catch_unwind(AssertUnwindSafe(|| handler()));
// The service pings a session every two seconds. One line is written when
// the handler starts to panic and one when it returns again.
match (&outcome, self.panicking.swap(outcome.is_err(), Ordering::Relaxed)) {
(Err(panic), false) => tracing::warn!(
panic = panic_text(panic.as_ref()),
"the custom ping handler panicked, using the automatic status until it returns a status"
),
(Ok(_), true) => tracing::info!("the custom ping handler no longer panics"),
_ => {}
}
outcome.ok().flatten()
}
/// The status now and the Unix time in seconds of its last change. The time
/// must not move while the status stays the same: the service reads it to find
/// out how long a session has been idle.
pub(crate) fn current(&self) -> (PingStatus, u64) {
let (status, tasks_changed) = match self.custom() {
Some(status) => (status, None),
None => {
let (active, changed) = self.tasks.activity();
(if active > 0 { PingStatus::HealthyBusy } else { PingStatus::Healthy }, Some(changed))
}
};
let (previous, current) = {
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
let previous = last.status;
if previous != status {
// The automatic status changed when the registry changed, which can be
// long before this ping. After a status of the custom handler the
// time is the time of this ping: the service saw that status at the
// ping before, which can be later than the change of the registry.
last.changed = tasks_changed.filter(|_| !last.custom).unwrap_or_else(unix_seconds);
last.status = status;
}
last.custom = tasks_changed.is_none();
// Work that started and ended between two pings changed the status twice.
// No ping saw it, and the session was still not idle during that time.
last.changed = last.changed.max(tasks_changed.unwrap_or(0));
(previous, (last.status, last.changed))
};
// On AgentCore Runtime only the service can call /ping. This line tells a
// developer why a session was kept. It is written after the lock is released.
if previous != status {
let active_tasks = self.tasks.active_count();
tracing::info!(from = %previous, to = %status, active_tasks, "ping status changed");
}
current
}
}