use shep_core::config::{AppConfig, LevelRule, LineLevel, ProbeConfig, ProbeKind, normalize};
use shep_core::protocol::DogSource;
use shep_core::status::ProcStatus;
use shep_core::values::{MemSize, UpDuration};
use super::*;
use crate::cron::{DEFAULT_MAX_CRON_SLEEP, SystemClock};
use crate::extras::{ExtrasReports, spawn_extras_reporter};
use crate::fake::{ProcScript, ScriptedRunner};
use crate::limits::LimitEnforcer;
use crate::testing::capture_logs;
use crate::testing::{
Harness, RecordingEnforcer, ScriptedProber, SharedRunner, app_with, armed_entry, harness,
idle_stats, probe_config, test_paths,
};
#[cfg(unix)]
use crate::tokio_runner::TokioRunner;
use tokio::sync::watch;
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
mod actions;
#[cfg(unix)]
mod adopt;
#[cfg(unix)]
mod adopt_restart;
#[cfg(unix)]
mod adopt_swap;
mod config_load;
mod config_promote;
mod config_rearm;
mod config_report;
mod config_reset;
mod credentials;
mod dogs;
mod env_batch;
mod flush;
#[cfg(unix)]
mod handover;
mod interleaving;
mod readiness;
mod reload_bus;
mod reload_drain;
mod reload_drainee;
mod reload_swap;
mod reopen;
mod restart_races;
mod scale;
mod secrets;
mod shutdown;
mod signals;
mod start_stop;
mod triggers;
fn drained_process_kinds(
rx: &mut tokio::sync::broadcast::Receiver<SharedEvent>,
) -> Vec<ProcessEventKind> {
let mut kinds = Vec::new();
while let Ok(BusEvent::Process { event, .. }) = rx.try_recv().map(|event| event.to_event()) {
kinds.push(event);
}
kinds
}
async fn await_event(
rx: &mut tokio::sync::broadcast::Receiver<SharedEvent>,
id: u32,
kind: ProcessEventKind,
) -> bool {
loop {
match rx.recv().await.map(|event| event.to_event()) {
Ok(BusEvent::Process {
event,
info,
manually,
..
}) if info.id == id && event == kind => {
return manually;
}
Ok(_) => continue,
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(e) => panic!("event stream closed before {kind:?} for id {id}: {e}"),
}
}
}
async fn assert_no_event_within(
rx: &mut tokio::sync::broadcast::Receiver<SharedEvent>,
id: u32,
kind: ProcessEventKind,
window: Duration,
) {
match tokio::time::timeout(window, await_event(rx, id, kind)).await {
Err(_elapsed) => {} Ok(_manually) => panic!("unexpected {kind:?} for id {id} within {window:?}"),
}
}
fn test_actor(
paths: ShepPaths,
scripts: Vec<ProcScript>,
sheep: HashMap<u32, SheepSlot>,
tx: mpsc::Sender<Msg>,
) -> Actor<ScriptedRunner> {
let (events, _events_rx) = crate::bus::test_bus(64);
let provider_secrets = Arc::new(ProviderSecrets::load(&paths.secrets_cache));
Actor {
runner: ScriptedRunner::new(scripts),
next_id: sheep.len() as u32,
paths,
events,
host_environment: DEFAULT_ENVIRONMENT.to_string(),
provider_secrets,
tx,
sheep,
next_deadline: 0,
next_action_stamp: 0,
pending: Vec::new(),
shutting_down: false,
extras: None,
registry: ExtrasRegistry::default(),
reloads: HashMap::new(),
smits: Smits::new(),
}
}
fn actor_with_stopping_drainee(
dir: &tempfile::TempDir,
pid: u32,
epoch: u64,
) -> (Actor<ScriptedRunner>, mpsc::Receiver<SheepCtl>) {
let paths = test_paths(dir);
let app = normalize(AppConfig::minimal("web", "./srv")).unwrap();
let mut entry = armed_entry(0, 0, pid, app, &paths);
entry.status = ProcStatus::Stopping;
let (ctl_tx, ctl_rx) = mpsc::channel(1);
let slot = SheepSlot {
ctl: Some(ctl_tx),
epoch,
..SheepSlot::new(entry)
};
let mut sheep = HashMap::new();
sheep.insert(0, slot);
let (tx, _rx) = mpsc::channel(16);
let actor = test_actor(paths, Vec::new(), sheep, tx);
(actor, ctl_rx)
}
fn actor_with_a_drainee_holding_a_signal_mailbox(
dir: &tempfile::TempDir,
) -> (Actor<ScriptedRunner>, mpsc::Receiver<SignalRequest>) {
let (mut actor, _mailbox) = actor_with_one_online_sheep(dir, vec![]);
let slot = actor.sheep.get_mut(&0).expect("the fixture registers id 0");
slot.entry.status = ProcStatus::Stopping;
slot.entry.reload = ReloadState::Drainee { new_id: Some(1) };
let (signals, signal_rx) = mpsc::channel(16);
slot.signals = Some(signals);
(actor, signal_rx)
}
const SWAP_WINDOW: Duration = Duration::from_secs(30);
async fn expect_event(
rx: &mut tokio::sync::broadcast::Receiver<SharedEvent>,
id: u32,
kind: ProcessEventKind,
) {
assert!(
tokio::time::timeout(SWAP_WINDOW, await_event(rx, id, kind))
.await
.is_ok(),
"no {kind:?} for id {id} within {SWAP_WINDOW:?}"
);
}
async fn started(
dir: &tempfile::TempDir,
app: AppConfig,
scripts: Vec<ProcScript>,
) -> (
SupervisorHandle,
Arc<ScriptedRunner>,
tokio::sync::broadcast::Receiver<SharedEvent>,
) {
let (events, rx) = crate::bus::test_bus(256);
let runner = Arc::new(ScriptedRunner::new(scripts));
let handle = spawn_supervisor(SharedRunner(Arc::clone(&runner)), test_paths(dir), events);
handle.start(vec![normalize(app).unwrap()]).await.unwrap();
(handle, runner, rx)
}
fn actor_with_one_online_sheep(
dir: &tempfile::TempDir,
scripts: Vec<ProcScript>,
) -> (Actor<ScriptedRunner>, mpsc::Receiver<Msg>) {
actor_with_one_online_sheep_of(dir, AppConfig::minimal("web", "./srv"), scripts)
}
fn actor_with_one_online_sheep_of(
dir: &tempfile::TempDir,
app: AppConfig,
scripts: Vec<ProcScript>,
) -> (Actor<ScriptedRunner>, mpsc::Receiver<Msg>) {
let paths = test_paths(dir);
let app = normalize(app).unwrap();
let mut sheep = HashMap::new();
sheep.insert(0, SheepSlot::new(armed_entry(0, 0, 1111, app, &paths)));
let (tx, rx) = mpsc::channel(MAILBOX_CAPACITY);
let actor = test_actor(paths, scripts, sheep, tx);
(actor, rx)
}
const SHEEP_ID: u32 = 0;
const DOG_ID: u32 = 1;
fn actor_with_a_sheep_and_a_dog(
dir: &tempfile::TempDir,
) -> (Actor<ScriptedRunner>, mpsc::Receiver<Msg>) {
let paths = test_paths(dir);
let mut sheep = HashMap::new();
for (id, name, dog) in [
(SHEEP_ID, "web", None),
(DOG_ID, "bark", Some(DogSource::BuiltIn)),
] {
let app = app_with(name, |config| config.fold = Some("svc".to_string()));
let mut entry = armed_entry(id, 0, 1111 + id, app, &paths);
entry.dog = dog;
sheep.insert(id, SheepSlot::new(entry));
}
let (tx, rx) = mpsc::channel(MAILBOX_CAPACITY);
let actor = test_actor(paths, Vec::new(), sheep, tx);
(actor, rx)
}
#[test]
fn a_wildcard_passes_a_dog_by_and_its_own_name_still_reaches_it() {
let dir = tempfile::tempdir().unwrap();
let (actor, _mailbox) = actor_with_a_sheep_and_a_dog(&dir);
assert_eq!(
actor.matching_ids(&ProcessSelector::All),
vec![SHEEP_ID],
"`all` is the flock, not the kennel"
);
assert_eq!(
actor.matching_ids(&ProcessSelector::parse("/^(web|bark)$/").unwrap()),
vec![SHEEP_ID],
"a sweep that spells both names out is still a sweep"
);
assert_eq!(
actor.matching_ids(&ProcessSelector::Fold("svc".into())),
vec![SHEEP_ID],
"a dog shares its fold with the flock and is still not swept by it"
);
assert_eq!(
actor.matching_ids(&ProcessSelector::Name("bark".into())),
vec![DOG_ID]
);
assert_eq!(
actor.matching_ids(&ProcessSelector::Id(DOG_ID)),
vec![DOG_ID]
);
}
#[test]
fn a_listing_reports_where_a_dog_came_from() {
let dir = tempfile::tempdir().unwrap();
let (actor, _mailbox) = actor_with_a_sheep_and_a_dog(&dir);
assert_eq!(
to_info(&actor.sheep[&DOG_ID].entry, &actor.smits).dog,
Some(DogSource::BuiltIn)
);
assert_eq!(
to_info(&actor.sheep[&SHEEP_ID].entry, &actor.smits).dog,
None
);
}
async fn start_app(h: &Harness, app: AppConfig) -> Vec<ProcessInfo> {
h.ctx
.supervisor
.start(vec![normalize(app).unwrap()])
.await
.unwrap()
}
fn dog_app(name: &str) -> ResolvedApp {
normalize(AppConfig::minimal(name, "/nonexistent/shep")).unwrap()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Seen {
id: u32,
kind: ProcessEventKind,
status: ProcStatus,
manually: bool,
}
async fn events_through(
rx: &mut tokio::sync::broadcast::Receiver<SharedEvent>,
id: u32,
kind: ProcessEventKind,
) -> Vec<Seen> {
let collect = async {
let mut seen = Vec::new();
loop {
match rx.recv().await.map(|event| event.to_event()) {
Ok(BusEvent::Process {
event,
info,
manually,
..
}) => {
seen.push(Seen {
id: info.id,
kind: event,
status: info.status,
manually,
});
if info.id == id && event == kind {
return seen;
}
}
Ok(_) => continue,
Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
panic!("the event stream lagged by {n}; no ordering claim survives that")
}
Err(e) => panic!("event stream closed before {kind:?} for id {id}: {e}"),
}
}
};
tokio::time::timeout(SWAP_WINDOW, collect)
.await
.unwrap_or_else(|_| panic!("no {kind:?} for id {id} within {SWAP_WINDOW:?}"))
}
fn at(seen: &[Seen], id: u32, kind: ProcessEventKind) -> usize {
seen.iter()
.position(|e| e.id == id && e.kind == kind)
.unwrap_or_else(|| panic!("no {kind:?} for id {id} in {seen:?}"))
}
const ACTION_TIMEOUT: Duration = Duration::from_secs(20);
const ACTION_WINDOW: Duration = Duration::from_secs(120);
fn actor_with_an_open_channel(
dir: &tempfile::TempDir,
) -> (
Actor<ScriptedRunner>,
mpsc::Receiver<Msg>,
mpsc::Receiver<ShepherdMessage>,
) {
let (mut actor, mailbox) = actor_with_one_online_sheep(dir, vec![]);
let (to_child, child_rx) = mpsc::channel(16);
actor
.sheep
.get_mut(&0)
.expect("the fixture registers id 0")
.to_child = Some(to_child);
(actor, mailbox, child_rx)
}
fn trigger_action(
actor: &mut Actor<ScriptedRunner>,
action: &str,
) -> oneshot::Receiver<ActionOutcome> {
let to_child = actor.sheep[&0]
.to_child
.clone()
.expect("the fixture's sheep holds the daemon's end of a channel");
actor.arm_action(0, to_child, action.to_string(), None, ACTION_TIMEOUT)
}
async fn settle_action(
actor: &mut Actor<ScriptedRunner>,
mailbox: &mut mpsc::Receiver<Msg>,
) -> ActionOutcome {
let msg = tokio::time::timeout(ACTION_WINDOW, mailbox.recv())
.await
.expect("an action wait reported nothing within the window")
.expect("the actor's mailbox closed");
match msg {
Msg::ActionResult { id, stamp, outcome } => {
actor.handle_action_result(id, stamp, outcome.clone());
outcome
}
other => panic!("expected an action result, got {other:?}"),
}
}
async fn sent_action(child_rx: &mut mpsc::Receiver<ShepherdMessage>) -> ShepherdMessage {
tokio::time::timeout(ACTION_WINDOW, child_rx.recv())
.await
.expect("nothing reached the child's end of the channel")
.expect("the child's end of the channel closed")
}
async fn triggered(
answer: oneshot::Receiver<Result<Vec<ActionReply>, SupervisorError>>,
) -> Result<Vec<ActionReply>, SupervisorError> {
tokio::time::timeout(ACTION_WINDOW, answer)
.await
.expect("a trigger reported nothing within the window")
.expect("the trigger's reply channel was dropped")
}
fn row(id: u32, name: &str, outcome: ActionOutcome) -> ActionReply {
ActionReply {
id,
name: name.to_string(),
outcome,
}
}
struct SilentPumpRunner {
inner: ScriptedRunner,
seen: watch::Sender<u32>,
}
impl SilentPumpRunner {
fn new(scripts: Vec<ProcScript>) -> (Self, watch::Receiver<u32>) {
let (seen, requests) = watch::channel(0);
(
Self {
inner: ScriptedRunner::new(scripts),
seen,
},
requests,
)
}
}
impl fmt::Debug for SilentPumpRunner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SilentPumpRunner").finish_non_exhaustive()
}
}
impl ProcessRunner for SilentPumpRunner {
type Proc = crate::fake::FakeProc;
fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), crate::runner::RunnerError> {
let (proc, mut io) = self.inner.spawn(spec)?;
let (tx, mut rx) = mpsc::channel(SHEEP_CTL_CAPACITY);
io.log_ctl = tx;
let seen = self.seen.clone();
tokio::spawn(async move {
let mut held = Vec::new();
while let Some(request) = rx.recv().await {
held.push(request);
seen.send_modify(|count| *count += 1);
}
});
Ok((proc, io))
}
}
const PUMP_REFUSAL: &str = "/gone/web-out.log: No such file or directory";
const REFUSING_SHEEP: &str = "web";
#[derive(Debug)]
struct FailingPumpRunner {
inner: Arc<ScriptedRunner>,
}
impl FailingPumpRunner {
fn new(inner: Arc<ScriptedRunner>) -> Self {
Self { inner }
}
}
impl ProcessRunner for FailingPumpRunner {
type Proc = crate::fake::FakeProc;
fn spawn(&self, spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), crate::runner::RunnerError> {
let (proc, mut io) = self.inner.spawn(spec)?;
if spec.name != REFUSING_SHEEP {
return Ok((proc, io));
}
let (tx, mut rx) = mpsc::channel(SHEEP_CTL_CAPACITY);
io.log_ctl = tx;
tokio::spawn(async move {
while let Some(ctl) = rx.recv().await {
match ctl {
LogCtl::Reopen { done } => {
let _ = done.send(Err(ReopenError {
message: PUMP_REFUSAL.to_string(),
}));
}
LogCtl::Flush { done } => {
let _ = done.send(Err(FlushError {
message: PUMP_REFUSAL.to_string(),
}));
}
#[cfg(unix)]
LogCtl::ReportFds { done } => {
let _ = done.send(CarriedFds::none());
}
#[cfg(unix)]
LogCtl::Resume => {}
}
}
});
Ok((proc, io))
}
}
fn log_ctl_spec() -> SpawnSpec {
SpawnSpec {
name: "svc".to_string(),
program: "./svc".to_string(),
args: Vec::new(),
cwd: None,
env: std::collections::BTreeMap::new(),
out_file: std::path::PathBuf::from("out.log"),
err_file: std::path::PathBuf::from("err.log"),
channel: false,
stdin: false,
credentials: None,
}
}
fn actor_with_an_empty_flock(
dir: &tempfile::TempDir,
scripts: Vec<ProcScript>,
) -> Actor<ScriptedRunner> {
let (tx, _rx) = mpsc::channel(MAILBOX_CAPACITY);
let paths = test_paths(dir);
test_actor(paths, scripts, HashMap::new(), tx)
}
#[cfg(unix)]
fn own_user_name() -> String {
nix::unistd::User::from_uid(nix::unistd::geteuid())
.unwrap()
.expect("this process has a passwd entry")
.name
}
const NO_SUCH_USER: &str = "definitely-not-a-real-shep-user";
#[cfg(unix)]
fn daemon_fds(dir: &tempfile::TempDir) -> (DaemonFds, [std::fs::File; 2]) {
use std::os::fd::AsRawFd as _;
let listener = std::fs::File::create(dir.path().join("listener.stand-in")).unwrap();
let pidfile = std::fs::File::create(dir.path().join("pidfile.stand-in")).unwrap();
let fds = DaemonFds {
listener: listener.as_raw_fd(),
pidfile: pidfile.as_raw_fd(),
};
(fds, [listener, pidfile])
}
#[cfg(unix)]
#[derive(Debug, Default)]
struct AdoptingRunner;
#[cfg(unix)]
const STAND_IN_SPAWN_PID: u32 = 7000;
#[cfg(unix)]
#[derive(Debug)]
struct StandInProc {
pid: u32,
}
#[cfg(unix)]
impl RunningProcess for StandInProc {
fn pid(&self) -> u32 {
self.pid
}
async fn wait(&mut self) -> ExitOutcome {
core::future::pending().await
}
fn signal(&mut self, _sig: crate::runner::StopSignal) -> Result<(), RunnerError> {
Ok(())
}
fn kill_tree(&mut self) -> Result<(), RunnerError> {
Ok(())
}
}
#[cfg(unix)]
fn stand_in_io() -> ProcIo {
let (_logs_tx, logs) = mpsc::channel(1);
let (_from_child_tx, from_child) = mpsc::channel(1);
let (to_child, to_child_rx) = mpsc::channel(1);
drop(to_child_rx);
let (log_ctl, log_ctl_rx) = mpsc::channel(1);
drop(log_ctl_rx);
let (to_stdin, to_stdin_rx) = mpsc::channel(1);
drop(to_stdin_rx);
ProcIo {
logs,
from_child,
to_child,
log_ctl,
to_stdin,
}
}
#[cfg(unix)]
impl ProcessRunner for AdoptingRunner {
type Proc = StandInProc;
fn spawn(&self, _spec: &SpawnSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
Ok((
StandInProc {
pid: STAND_IN_SPAWN_PID,
},
stand_in_io(),
))
}
fn adopt(&self, spec: crate::runner::AdoptSpec) -> Result<(Self::Proc, ProcIo), RunnerError> {
Ok((StandInProc { pid: spec.pid }, stand_in_io()))
}
}
#[cfg(unix)]
fn carried(
name: &str,
id: u32,
pid: Option<u32>,
mutate: impl FnOnce(&mut ProcessEntry),
) -> CarriedSheep {
carried_marked(name, id, pid, false, None, false, mutate)
}
#[cfg(unix)]
fn carried_ready_failed(
name: &str,
id: u32,
pid: Option<u32>,
mutate: impl FnOnce(&mut ProcessEntry),
) -> CarriedSheep {
carried_marked(name, id, pid, false, None, true, mutate)
}
#[cfg(unix)]
fn carried_marked(
name: &str,
id: u32,
pid: Option<u32>,
pending_delete: bool,
manual: Option<PendingManual>,
ready_failed: bool,
mutate: impl FnOnce(&mut ProcessEntry),
) -> CarriedSheep {
let mut app = AppConfig::minimal(name, "./srv");
app.autorestart = false;
let mut entry = ProcessEntry {
id,
spec: normalize(app).unwrap(),
pending: None,
pending_reidentifies: false,
overridden: Vec::new(),
instance: 0,
status: ProcStatus::Online,
pid,
restarts: 0,
started_at: None,
budget: RestartBudget::default(),
reload: ReloadState::None,
credentials: SpawnIdentity::Resolved(None),
out_file: PathBuf::new(),
err_file: PathBuf::new(),
dog: None,
last_exit: None,
};
mutate(&mut entry);
CarriedSheep::from_entry(
&entry,
0,
CarriedFds::none(),
pending_delete,
manual,
ready_failed,
None,
)
}
#[cfg(unix)]
fn carried_owed_a_restart(
name: &str,
id: u32,
delay: shep_core::values::UpDuration,
due: Option<SystemTime>,
) -> CarriedSheep {
let mut app = AppConfig::minimal(name, "./srv");
app.restart_delay = Some(delay);
let entry = ProcessEntry {
id,
spec: normalize(app).unwrap(),
pending: None,
pending_reidentifies: false,
overridden: Vec::new(),
instance: 0,
status: ProcStatus::WaitingRestart,
pid: None,
restarts: 1,
started_at: None,
budget: RestartBudget::default(),
reload: ReloadState::None,
credentials: SpawnIdentity::Resolved(None),
out_file: PathBuf::new(),
err_file: PathBuf::new(),
dog: None,
last_exit: None,
};
CarriedSheep::from_entry(&entry, 0, CarriedFds::none(), false, None, false, due)
}
#[cfg(unix)]
fn without_handles(carried: CarriedSheep) -> crate::handover::adopt::AdoptedSheep {
crate::handover::adopt::AdoptedSheep {
carried,
out_pipe: None,
err_pipe: None,
out_log: None,
err_log: None,
stdin_pipe: None,
channel: None,
}
}
#[cfg(unix)]
const fn counters(next_id: u32) -> Counters {
Counters {
next_id,
next_deadline: 0,
next_action_stamp: 0,
}
}
#[cfg(unix)]
fn adoptable_child(script: &str) -> u32 {
use std::os::unix::process::CommandExt as _;
std::process::Command::new("/bin/sh")
.args(["-c", script])
.process_group(0)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.expect("a test host can spawn a shell")
.id()
}
#[cfg(unix)]
fn respawnable(mutate: impl FnOnce(&mut AppConfig)) -> impl FnOnce(&mut ProcessEntry) {
move |entry: &mut ProcessEntry| {
let mut app = AppConfig::minimal("web", "/bin/sh");
app.args = vec!["-c".to_owned(), "sleep 30".to_owned()];
mutate(&mut app);
entry.spec = normalize(app).unwrap();
}
}
#[cfg(unix)]
async fn flock_until(
sup: &SupervisorHandle,
done: impl Fn(&[ProcessInfo]) -> bool,
what: &str,
) -> Vec<ProcessInfo> {
tokio::time::timeout(Duration::from_secs(20), async {
loop {
let info = sup.list().await;
if done(&info) {
return info;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
})
.await
.unwrap_or_else(|_| panic!("{what}"))
}
const APPLY_FIRST_PID: u32 = 7100;
fn actor_over(
dir: &tempfile::TempDir,
apps: &[ResolvedApp],
) -> (Actor<ScriptedRunner>, Arc<RecordingEnforcer>) {
let paths = test_paths(dir);
let mut sheep = HashMap::new();
let mut next_id = 0;
for app in apps {
for instance in 0..app.config().instances {
let id = next_id;
next_id += 1;
sheep.insert(
id,
SheepSlot::new(armed_entry(
id,
instance,
APPLY_FIRST_PID + id,
app.clone(),
&paths,
)),
);
}
}
let enforcer = Arc::new(RecordingEnforcer::default());
let (breach_tx, _breaches) = mpsc::channel(1);
let (live_tx, _liveness) = mpsc::channel(1);
let extras = Extras {
clock: Arc::new(SystemClock),
enforcer: Arc::clone(&enforcer) as Arc<dyn LimitEnforcer>,
max_cron_sleep: DEFAULT_MAX_CRON_SLEEP,
reports: ExtrasReports {
breaches: breach_tx,
liveness: live_tx,
},
stats: idle_stats(),
};
let (tx, _rx) = mpsc::channel(MAILBOX_CAPACITY);
let scripts = vec![ProcScript::never_exits(); 4];
let actor = Actor {
extras: Some(extras),
..test_actor(paths, scripts, sheep, tx)
};
(actor, enforcer)
}
fn declared_app(config: AppConfig, keys: &[&str]) -> DeclaredApp {
let declared: BTreeSet<String> = keys.iter().map(|key| (*key).to_string()).collect();
let declared_env = if declared.contains("env") {
config.env.keys().cloned().collect()
} else {
BTreeSet::new()
};
DeclaredApp {
config,
declared,
declared_env,
}
}
fn established(
keys: &[&str],
fields: Vec<(&str, serde_json::Value)>,
) -> shep_core::overrides::AppOverrides {
shep_core::overrides::AppOverrides {
fields: fields
.into_iter()
.map(|(key, value)| (key.to_string(), value))
.collect(),
declared: keys.iter().map(|key| (*key).to_string()).collect(),
declared_env: BTreeSet::new(),
}
}
async fn apply_config(
actor: &mut Actor<ScriptedRunner>,
apps: Vec<DeclaredApp>,
reset: ResetDepth,
) -> Vec<Applied> {
let (reply, answer) = oneshot::channel();
actor.handle_command(Command::ApplyConfig { apps, reset, reply });
answer
.await
.expect("the actor answers an apply before it returns")
.expect("the fixture flock is registered")
}