use std::fmt;
use std::sync::Arc;
use askama::Template;
use crate::command::CommandBlocked;
use crate::job_registry::UnchangedTaskRead;
use crate::monitor::{MAX_TIMEOUT_SECS, MonitorRefusal};
use crate::terminal::TimeoutKill;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MonitorStarted<'a> {
pub task_id: &'a str,
pub interval_secs: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReservedForMain<'a> {
pub command: &'a str,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandKilled<'a> {
TimedOut(&'a TimeoutKill),
BeforeTimeout,
}
#[derive(Template)]
#[template(path = "unchanged_task_read.txt")]
struct UnchangedTaskReadTemplate<'a> {
task_id: &'a str,
}
#[derive(Template)]
#[template(path = "command_blocked.txt")]
struct Blocked<'a> {
reason: &'a str,
}
#[derive(Template)]
#[template(path = "monitor_refused.txt", escape = "none")]
struct MonitorRefused<'a> {
refusal: &'a MonitorRefusal,
max_timeout_secs: u64,
}
#[derive(Template)]
#[template(path = "monitor_started.txt", escape = "none")]
struct MonitorStartedTemplate<'a> {
task_id: &'a str,
interval_secs: u64,
}
#[derive(Template)]
#[template(path = "reserved_for_main.txt", escape = "none")]
struct Reserved<'a> {
name: &'a str,
}
#[derive(Template)]
#[template(path = "command_timed_out.txt", escape = "none")]
struct Killed<'a> {
killed: CommandKilled<'a>,
}
fn rendered(template: &impl Template) -> String {
template
.render()
.expect("a sandbox notice template renders typed input")
}
pub trait SandboxNotices: Send + Sync + 'static {
fn unchanged_task_read(&self, read: &UnchangedTaskRead) -> String {
rendered(&UnchangedTaskReadTemplate {
task_id: &read.task_id,
})
}
fn command_blocked(&self, blocked: &CommandBlocked) -> String {
rendered(&Blocked {
reason: &blocked.reason,
})
}
fn monitor_refusal(&self, refusal: &MonitorRefusal) -> String {
rendered(&MonitorRefused {
refusal,
max_timeout_secs: MAX_TIMEOUT_SECS,
})
}
fn monitor_started(&self, started: &MonitorStarted<'_>) -> String {
rendered(&MonitorStartedTemplate {
task_id: started.task_id,
interval_secs: started.interval_secs,
})
}
fn reserved_for_main(&self, reserved: &ReservedForMain<'_>) -> String {
rendered(&Reserved {
name: reserved.command,
})
}
fn command_killed(&self, killed: &CommandKilled<'_>) -> String {
rendered(&Killed { killed: *killed })
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DefaultSandboxNotices;
impl SandboxNotices for DefaultSandboxNotices {}
#[derive(Clone)]
pub struct AnySandboxNotices(Arc<dyn SandboxNotices>);
impl AnySandboxNotices {
#[must_use]
pub fn new(notices: impl SandboxNotices) -> Self {
Self(Arc::new(notices))
}
}
impl From<Arc<dyn SandboxNotices>> for AnySandboxNotices {
fn from(notices: Arc<dyn SandboxNotices>) -> Self {
Self(notices)
}
}
impl Default for AnySandboxNotices {
fn default() -> Self {
Self::new(DefaultSandboxNotices)
}
}
impl std::ops::Deref for AnySandboxNotices {
type Target = dyn SandboxNotices;
fn deref(&self) -> &Self::Target {
&*self.0
}
}
impl fmt::Debug for AnySandboxNotices {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnySandboxNotices").finish_non_exhaustive()
}
}
#[derive(Debug)]
pub struct Refused<R> {
reason: R,
text: String,
}
impl<R> Refused<R> {
pub fn rendered(reason: R, render: impl FnOnce(&R) -> String) -> Self {
let text = render(&reason);
Self { reason, text }
}
pub const fn reason(&self) -> &R {
&self.reason
}
#[must_use]
pub fn text(&self) -> &str {
&self.text
}
pub fn into_reason(self) -> R {
self.reason
}
}
impl<R> fmt::Display for Refused<R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.text)
}
}
impl<R: fmt::Debug> std::error::Error for Refused<R> {}
#[cfg(test)]
mod tests {
use super::*;
struct Terse;
impl SandboxNotices for Terse {
fn unchanged_task_read(&self, read: &UnchangedTaskRead) -> String {
format!("no news from {}", read.task_id)
}
}
fn unchanged() -> UnchangedTaskRead {
UnchangedTaskRead {
task_id: "amber-forest-thunder-pearl".into(),
}
}
#[test]
fn an_override_replaces_its_family_and_keeps_the_rest() {
let notices = AnySandboxNotices::new(Terse);
assert_eq!(
notices.unchanged_task_read(&unchanged()),
"no news from amber-forest-thunder-pearl"
);
let blocked = CommandBlocked {
reason: "not today".into(),
};
assert_eq!(
notices.command_blocked(&blocked),
DefaultSandboxNotices.command_blocked(&blocked),
);
}
#[test]
fn a_refusal_carries_its_reason_and_rendered_text() {
let notices = AnySandboxNotices::default();
let refused = Refused::rendered(unchanged(), |read| notices.unchanged_task_read(read));
assert_eq!(refused.reason(), &unchanged());
assert!(
refused
.to_string()
.contains("'amber-forest-thunder-pearl' produced no new output")
);
}
#[test]
fn default_monitor_refusal_names_the_cap() {
let text = DefaultSandboxNotices.monitor_refusal(&MonitorRefusal::TimeoutOutOfRange);
assert_eq!(
text,
"The monitor call was refused: timeout_secs must be between 1 and 7200."
);
}
#[test]
fn default_kill_notice_without_a_bound_passing() {
assert_eq!(
DefaultSandboxNotices.command_killed(&CommandKilled::BeforeTimeout),
"Killed before its timeout bound passed."
);
}
}