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
//! Outer reactor: CLI handoff, signals, scheduling, event output, run totals.
use std::process::ExitCode;
use std::time::Duration;
use serde_json::json;
use tokio::sync::mpsc;
use crate::config::{EXIT_FATAL, EXIT_INTERRUPTED, EXIT_OK, RunConfig};
use crate::log::Logger;
use crate::metrics::RunTotals;
use crate::output::Output;
use crate::time::{RealTime, Time, utc_iso};
use super::MirrorRuntime;
use super::actions::Action;
use super::concurrent::WorkSet;
use super::events::{RuntimeEvent, cycle_completed_payload};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum MainWork {
Runtime,
Signal,
Scheduler,
}
enum MainItem {
RuntimeExited,
Signal,
TickDue,
}
pub async fn run(config: RunConfig, logger: Logger, output: Output) -> anyhow::Result<ExitCode> {
let (actions_tx, actions_rx) = mpsc::channel(64);
let (events_tx, mut events_rx) = mpsc::channel(256);
let runtime = MirrorRuntime::new(config.clone(), actions_rx, events_tx, logger.clone());
let mut work: WorkSet<MainWork, MainItem> = WorkSet::new();
let runtime_abort = work.spawn(MainWork::Runtime, async move {
runtime.run().await;
MainItem::RuntimeExited
});
work.spawn(MainWork::Signal, signal_task());
let started_at = utc_iso(RealTime.now_unix());
let mut totals = RunTotals::new();
let mut cycles = 0u64;
let mut fatal = false;
let mut forced = false;
let mut shutdown_sent = false;
let mut next_tick: Option<Duration> = None;
let mut respawn_signal = false;
loop {
// Spawn arms outside `select!` so the borrow of `work.next()` is not
// shared with `work.spawn()` in the same expression.
if let Some(delay) = next_tick.take() {
work.spawn(MainWork::Scheduler, async move {
tokio::time::sleep(delay).await;
MainItem::TickDue
});
}
if respawn_signal {
respawn_signal = false;
work.spawn(MainWork::Signal, signal_task());
}
tokio::select! {
biased;
maybe_event = events_rx.recv() => {
let Some(event) = maybe_event else { break };
match event {
RuntimeEvent::CycleCompleted { cycle, duration, stats } => {
cycles = cycle;
output.emit("cycle_stats", stats.to_value());
totals.accumulate(&stats);
output.emit(
"cycle_completed",
cycle_completed_payload(&stats, cycle, duration),
);
if config.once {
if actions_tx.send(Action::Shutdown).await.is_err() {
break;
}
shutdown_sent = true;
} else {
let delay = (config.poll_interval - duration).max(1.0);
next_tick = Some(Duration::from_secs_f64(delay.max(0.0)));
}
}
RuntimeEvent::CycleFailed { cycle, error } => {
cycles = cycle;
totals.add_error();
logger.error(
"cycle_failed",
Some("run"),
json!({ "cycle": cycle, "error": error }),
);
output.emit(
"cycle_failed",
json!({ "cycle": cycle, "error": error }),
);
if config.once {
fatal = true;
if actions_tx.send(Action::Shutdown).await.is_err() {
break;
}
shutdown_sent = true;
} else {
next_tick =
Some(Duration::from_secs_f64(config.poll_interval.max(1.0)));
}
}
RuntimeEvent::Fatal { error } => {
fatal = true;
logger.error("fatal", Some("run"), json!({ "error": error }));
output.emit("fatal", json!({ "error": error }));
// A fatal runtime event must stop the reactor; merely
// logging it would leave the loop waiting forever.
if !shutdown_sent {
shutdown_sent = true;
if actions_tx.send(Action::Shutdown).await.is_err() {
break;
}
}
}
RuntimeEvent::Done => {
output.emit("done", json!({}));
break;
}
RuntimeEvent::PdsResolved { seconds, .. } => {
totals.set_last(
"pds_resolve_seconds",
json!(crate::metrics::round6(seconds)),
);
output.emit(event.name(), event.payload());
}
other => output.emit(other.name(), other.payload()),
}
}
item = work.next() => {
match item {
Some((MainWork::Runtime, Ok(_))) => {}
Some((MainWork::Runtime, Err(error))) => {
fatal = true;
logger.error(
"runtime_task_failed",
Some("run"),
json!({ "error": error.to_string() }),
);
break;
}
Some((MainWork::Signal, Ok(MainItem::Signal))) => {
if shutdown_sent {
forced = true;
runtime_abort.abort();
break;
}
shutdown_sent = true;
if actions_tx.send(Action::Shutdown).await.is_err() {
break;
}
respawn_signal = true;
}
Some((MainWork::Signal, Err(error))) => {
fatal = true;
logger.error(
"signal_task_failed",
Some("run"),
json!({ "error": error.to_string() }),
);
break;
}
Some((MainWork::Scheduler, Ok(MainItem::TickDue))) => {
match actions_tx.try_send(Action::Tick) {
Ok(()) => {}
Err(mpsc::error::TrySendError::Full(_)) => {
// Coalesce: the runtime already has a queued tick.
}
Err(mpsc::error::TrySendError::Closed(_)) => break,
}
}
Some((MainWork::Scheduler, Err(error))) => {
fatal = true;
logger.error(
"scheduler_task_failed",
Some("run"),
json!({ "error": error.to_string() }),
);
break;
}
Some((_, Ok(_))) => {}
None => break,
}
}
}
}
let code = if forced {
EXIT_INTERRUPTED
} else if fatal {
EXIT_FATAL
} else {
EXIT_OK
};
output.emit("run_stats", totals.build_run_stats(cycles, &started_at));
Ok(ExitCode::from(code))
}
#[cfg(unix)]
async fn signal_task() -> MainItem {
use tokio::signal::unix::{SignalKind, signal};
let interrupt = signal(SignalKind::interrupt());
let terminate = signal(SignalKind::terminate());
match (interrupt, terminate) {
(Ok(mut interrupt), Ok(mut terminate)) => {
tokio::select! {
_ = interrupt.recv() => {}
_ = terminate.recv() => {}
}
MainItem::Signal
}
_ => {
std::future::pending::<()>().await;
unreachable!("signal handlers could not be installed")
}
}
}
#[cfg(not(unix))]
async fn signal_task() -> MainItem {
let _ = tokio::signal::ctrl_c().await;
MainItem::Signal
}