Files
netris-nestri/apps/nesinit/src/session.rs
T

2435 lines
94 KiB
Rust

// The guest end of the control channel.
//
// The shape of the exchange, and none of it is negotiable from this side: the
// guest speaks first with its version, is handed one document describing the
// box, brings the box's own services up, says so — and then takes commands for
// as long as the box lives. ref(d-0064)
//
// It is not a supervisor. Nothing here restarts anything of its own accord: a
// workload's exit is reported, a service's death is reported, and starting
// something again is the caller's decision, because the caller is the only end
// that can see whether restarting is repair or a loop. ref(d-0033)
//
// # Several launches at once
//
// A box is a person's machine with any of their games in it, and every launch
// in it is named by its id. ref(d-0085) A second launch runs beside the first
// rather than replacing it; only a second launch under an id that is already
// running is refused, because two processes answering to one id cannot be told
// apart by anything reported about them. Content for a launch may be mounted
// after boot (`Mount`), which is how a game the box did not boot with reaches it.
//
// # The box ends when its last terminal launch has gone
//
// A launch whose exit is terminal ends the session when it exits, as it always
// has -- unless other launches are still running. Then the box stays up for
// them, and ends when the last of them exits: closing every window is the
// person saying they are done, and closing one is not. A box with one launch
// behaves exactly as it did before there could be two.
use nesprotocol::lifecycle::{
CONTROL_VERSION, Exec, Exit, GuestToHost, HostToGuest, LaunchId, OnExit, Payload, from_line,
to_line,
};
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
use crate::payload::Ports;
use crate::services::{Died, Services};
use crate::workload::{Failure, Workload};
use std::collections::BTreeMap;
use tokio::task::JoinSet;
/// Every launch's exit, as it arrives, named by the launch.
type Exits = JoinSet<(LaunchId, std::io::Result<Exit>)>;
use tokio::sync::mpsc::Receiver;
/// How a session ended.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
/// A launch whose exit was terminal ended, and the exit was reported.
WorkloadExited(Exit),
/// The caller asked for a shutdown.
Shutdown,
/// The channel closed under us. Not an error by itself — a caller that has
/// stopped listening has also stopped being able to tell us to stop.
ChannelClosed,
/// The box could not be made. The reason is the operating system's,
/// verbatim.
///
/// This is the descriptor or the service stack, never a launch: a command
/// that will not run is reported and the box stays up, because a box that
/// dies of a bad `argv` cannot be told a better one.
Refused(Failure),
}
/// A launch that is running, and what it would take to start it again.
struct Current {
/// Kept so a restart is the same command rather than a new one the caller
/// has to re-send.
exec: Exec,
on_exit: OnExit,
/// Set by `restart`, read when the exit arrives. A restart is a kill
/// followed by a launch and this is the "followed by".
relaunch: bool,
}
/// Run one session over an already-connected channel.
///
/// Generic over the channel so the exchange can be driven from a test without
/// a VM: the transport contributes nothing to the protocol beyond ordering and
/// framing, which any byte stream has.
pub async fn run<C, W, S>(
channel: C,
workload: &mut W,
services: &mut S,
payload: &mut Ports,
addresses: &mut Receiver<crate::ticket::Found>,
untrusted: &crate::ticket::Untrusted,
) -> std::io::Result<Outcome>
where
C: AsyncRead + AsyncWrite,
W: Workload,
S: Services,
{
match converse(channel, workload, services, payload, addresses, untrusted).await {
Err(error) if channel_gone(&error) => {
// A caller that has stopped reading has also stopped being able to
// tell us to stop, which is the same situation as the channel
// closing under a read. One outcome, not two.
workload.signal_stop();
Ok(Outcome::ChannelClosed)
}
other => other,
}
}
/// Whether an error means the far end is gone rather than that something went
/// wrong here.
fn channel_gone(error: &std::io::Error) -> bool {
use std::io::ErrorKind::{BrokenPipe, ConnectionAborted, ConnectionReset, UnexpectedEof};
matches!(
error.kind(),
BrokenPipe | ConnectionReset | ConnectionAborted | UnexpectedEof
)
}
async fn converse<C, W, S>(
channel: C,
workload: &mut W,
services: &mut S,
payload: &mut Ports,
addresses: &mut Receiver<crate::ticket::Found>,
untrusted: &crate::ticket::Untrusted,
) -> std::io::Result<Outcome>
where
C: AsyncRead + AsyncWrite,
W: Workload,
S: Services,
{
let (reader, mut writer) = tokio::io::split(channel);
let mut lines = BufReader::new(reader).lines();
// First line on the connection, before anything is read. The version is
// here rather than in a round trip because the caller has to be able to
// refuse a guest it cannot talk to before it hands over a descriptor.
send(
&mut writer,
&GuestToHost::Ready {
protocol_version: CONTROL_VERSION,
},
)
.await?;
let mut running: BTreeMap<LaunchId, Current> = BTreeMap::new();
let mut exits: Exits = JoinSet::new();
// A terminal launch's exit, once it has ended while others were still
// running. The box stays up for them, still takes new launches (closing
// one window is not the person being done, ref(d-0085)), and ends with
// this exit when the last launch in it has gone.
let mut ending: Option<Exit> = None;
// Each launch's content mounted after boot, by launch, so it can be taken
// down with the launch. Recorded when asked for, before it has finished.
let mut mounted: Mounted = BTreeMap::new();
let mut mounting: JoinSet<(LaunchId, Result<(), Failure>)> = JoinSet::new();
let mut booted = false;
let mut relay_open = true;
let mut carrier_open = true;
// Guarded like the other two, and for the same reason: a closed channel
// resolves immediately and forever, so an unguarded branch on one turns
// this loop into a spin that still looks like it is waiting.
let mut services_open = true;
// The box's compositor exit, once there is a compositor.
let mut compositor_exit: Option<crate::workload::Exited> = None;
// The box's daemon exit and name, once there is a daemon.
let mut daemon_exit: Option<crate::workload::Exited> = None;
let mut daemon_name = String::new();
loop {
// The exits are guarded like the channels below: an empty set resolves
// at once, and an unguarded branch on it would spin.
let event = tokio::select! {
ended = exits.join_next(), if !exits.is_empty() => match ended {
Some(Ok((id, exit))) => Event::Ended(id, exit?),
Some(Err(error)) => return Err(std::io::Error::other(error)),
None => continue,
},
done = mounting.join_next(), if !mounting.is_empty() => match done {
Some(Ok((id, result))) => Event::MountDone(id, result),
Some(Err(error)) => return Err(std::io::Error::other(error)),
None => continue,
},
line = lines.next_line() => Event::Line(line?),
up = payload.from_workload.recv(), if relay_open => Event::FromWorkload(up),
found = addresses.recv(), if carrier_open => Event::Address(found),
gone = services.deaths().recv(), if services_open => Event::ServiceDied(gone),
gone = async { compositor_exit.as_mut().expect("guarded").await }, if compositor_exit.is_some() => {
Event::CompositorDied(gone)
},
gone = async { daemon_exit.as_mut().expect("guarded").await }, if daemon_exit.is_some() => {
Event::DaemonDied(gone)
},
};
let line = match event {
Event::Ended(id, exit) => {
// Taken before anything is sent: whatever happens next, this
// launch is no longer a running one, and a failure to
// relaunch must not leave a dead launch looking live.
let ended = running
.remove(&id)
.expect("an exit came from a running launch");
send(
&mut writer,
&GuestToHost::WorkloadExited {
id: id.clone(),
exit,
},
)
.await?;
if ended.relaunch {
// A restart is a kill followed by a launch of the same
// command, and this is the second half. The id is kept, so
// a caller sees the exit and then the same launch running
// again rather than having to correlate a new name.
let started = start(
&mut writer,
workload,
untrusted,
(&mut running, &mut exits),
id.clone(),
ended.exec,
ended.on_exit,
)
.await?;
if !started {
tear_down(workload, &mut mounted, &id);
// The last launch of an ending box would not come
// back, so nothing is left to wait for.
if let (Some(exit), true) = (ending, running.is_empty()) {
return Ok(Outcome::WorkloadExited(exit));
}
}
continue;
}
tear_down(workload, &mut mounted, &id);
// Terminal is the launch's own answer, not this end's. A
// non-terminal exit leaves the box up and waiting to be
// launched into again, which is the whole point of the box
// outliving what runs in it. ref(d-0064)
//
// A terminal one ends the box only once nothing else is
// running in it. ref(d-0085)
//
// The exit the box ends with is the terminal launch's own,
// whichever launch happens to be the last to go.
if ended.on_exit.terminal && ending.is_none() {
ending = Some(exit);
}
if let (Some(exit), true) = (ending, running.is_empty()) {
return Ok(Outcome::WorkloadExited(exit));
}
if ending.is_some() {
tracing::info!(
launch = %id,
still_running = running.len(),
"a terminal launch ended; the box stays up until the others have"
);
} else {
tracing::info!(launch = %id, "a launch ended and the box stays up");
}
continue;
}
Event::MountDone(id, result) => {
match result {
Ok(()) => {
tracing::info!(launch = %id, "mounted a launch's content");
send(&mut writer, &GuestToHost::LaunchMounted { id }).await?
}
Err(failure) => {
// Nothing of it is recorded as mounted: what did mount
// before the failure is taken down with it.
tear_down(workload, &mut mounted, &id);
tracing::warn!(launch = %id, reason = %failure.reason, "a launch's content would not mount");
send(
&mut writer,
&GuestToHost::LaunchMountFailed {
id,
reason: failure.reason,
},
)
.await?
}
}
continue;
}
Event::ServiceDied(Some(Died { name, exit })) => {
// Reported, never repaired. Nothing else in this guest is
// watching these, so a death that is not said here is a box
// that looks healthy and cannot work. ref(d-0064)
tracing::error!(service = %name, ?exit, "a service died");
send(&mut writer, &GuestToHost::ServiceDied { name, exit }).await?;
continue;
}
Event::CompositorDied(gone) => {
// Every launch draws on it, so with it gone nothing in this box
// can show a window: said as a service death, then the box
// ends rather than carrying on looking healthy.
let exit = gone.unwrap_or_else(|_| Exit::code(1));
tracing::error!(?exit, "the compositor has exited: no window in this box can draw");
send(&mut writer, &GuestToHost::ServiceDied { name: "nescope".into(), exit }).await?;
workload.signal_stop();
return Ok(Outcome::Refused(Failure::new(format!(
"the compositor exited ({exit:?}), so the box can no longer draw"
))));
}
Event::DaemonDied(gone) => {
// What every launch shares is gone with it (the box's one
// Steam sign-in), and a launch that carried on would have
// nothing to say why its game cannot reach it. Said as a
// service death, then the box ends.
let exit = gone.unwrap_or_else(|_| Exit::code(1));
let name = daemon_name.clone();
tracing::error!(?exit, %name, "the box's daemon has exited");
send(&mut writer, &GuestToHost::ServiceDied { name: name.clone(), exit }).await?;
workload.signal_stop();
return Ok(Outcome::Refused(Failure::new(format!(
"the {name} daemon exited ({exit:?}), so the box can no longer do what it is for"
))));
}
Event::ServiceDied(None) => {
// The supervisor is gone, which on the way down is ordinary.
// Nothing to report and nothing to end: a box with no service
// stack left can still be stopped and still has to report it.
services_open = false;
continue;
}
Event::FromWorkload(Some(payload)) => {
tracing::debug!(envelope = %payload.summary(), "sending an envelope on");
send(&mut writer, &GuestToHost::Payload { payload }).await?;
continue;
}
Event::Address(Some(crate::ticket::Found::Address(ticket))) => {
// Sent whenever a better one is found, not only the first time:
// a caller that keeps the first address it is given works on a
// local network and fails from anywhere else.
send(&mut writer, &GuestToHost::Ticket { ticket }).await?;
continue;
}
Event::Address(Some(crate::ticket::Found::Viewers(count))) => {
// Only when it changes: the host decides what an empty box
// means, and needs to hear when it became empty.
send(&mut writer, &GuestToHost::Viewers { count }).await?;
continue;
}
Event::Address(None) => {
// Nothing will look for an address again. Not an ending: the
// session has whatever it was already told, and the workload
// still has to be stopped and its exit reported.
carrier_open = false;
continue;
}
Event::FromWorkload(None) => {
// The relay is gone. The session is not: the workload can
// still be stopped, and its exit still has to be reported.
relay_open = false;
continue;
}
Event::Line(line) => line,
};
let Some(line) = line else {
// The far end is gone. Stop the workload rather than leave it
// running with nobody to report to.
workload.signal_stop();
return Ok(Outcome::ChannelClosed);
};
let message: HostToGuest = match from_line(&line) {
Ok(message) => message,
Err(error) => {
// Skipped rather than fatal: a line this build does not
// understand is not a reason to end a running session, and the
// version handshake is what catches a peer we cannot talk to.
tracing::warn!(%error, "ignoring an unreadable line");
continue;
}
};
match message {
HostToGuest::Boot { descriptor } => {
if booted {
tracing::warn!("ignoring a second descriptor: one is read per connection");
continue;
}
booted = true;
// The images, then the overlays, then the shares, then the
// services.
//
// **An image is the base the rest may sit on**, so it goes
// first, and its failure is reported the way an overlay's is:
// it is a filesystem this end mounts itself.
//
// **Overlays first, and one `Mounted` between them.** An
// overlay is a filesystem this end mounts itself, so a share
// whose target lives under one has to find it already there. The host is
// told once, after both, because `Mounted` answers "is the
// content where the descriptor said" and there is one answer to
// that -- sending it twice made the host read the second as a
// reply to something it had not asked.
let stacked = workload
.mount_images(&descriptor.images)
.and_then(|()| workload.mount_overlays(&descriptor.overlays));
if let Err(failure) = stacked {
// Said before it is returned. `Refused` ends the session
// either way; without the message the host sees a box that
// stopped and has to guess between an overlay, a share and a
// service -- which is the whole reason these are reported
// separately.
send(
&mut writer,
&GuestToHost::MountFailed {
reason: failure.reason.clone(),
},
)
.await?;
return Ok(Outcome::Refused(failure));
}
// The shares, then the services, and each reported separately.
// Which of the two failed decides what is worth looking at, so
// the two are never one message.
match workload.mount(&descriptor.mounts) {
Ok(()) => send(&mut writer, &GuestToHost::Mounted).await?,
Err(failure) => {
send(
&mut writer,
&GuestToHost::MountFailed {
reason: failure.reason.clone(),
},
)
.await?;
return Ok(Outcome::Refused(failure));
}
}
// A box whose own services will not come up cannot be launched
// into, so this is refused rather than reported and carried on
// from — unlike a launch, which is the caller's to correct.
match services.bring_up(descriptor.video).and_then(|mut up| {
// After the services and before the box is ready: the
// first launch joins it like every other. ref(d-0085)
if let Some(compositor) = &descriptor.compositor {
workload.start_compositor(compositor)?;
up.push("nescope".to_string());
}
// After the compositor: what it starts may draw. And the
// daemon is started, not waited on: it says itself when it
// works, to whoever needs it to.
if let Some(daemon) = &descriptor.daemon {
workload.start_daemon(daemon)?;
up.push(daemon.name.clone());
}
Ok(up)
}) {
Ok(up) => {
compositor_exit = workload.compositor_exit();
daemon_exit = workload.daemon_exit();
if let Some(daemon) = &descriptor.daemon {
daemon_name = daemon.name.clone();
}
tracing::info!(services = up.len(), "the box is ready to be launched into");
send(&mut writer, &GuestToHost::Initialized { services: up }).await?
}
Err(failure) => {
send(
&mut writer,
&GuestToHost::InitFailed {
reason: failure.reason.clone(),
},
)
.await?;
return Ok(Outcome::Refused(failure));
}
}
}
HostToGuest::Launch { id, exec, on_exit } => {
if !booted {
// Before the descriptor there are no shares and no
// services, so whatever this launch expects to find is not
// there yet. Refused with its own id rather than run into
// a box that is not finished.
refuse(&mut writer, id, "the box has not been told what it is").await?;
continue;
}
if running.contains_key(&id) {
// Two processes under one id could not be told apart by
// anything reported about either.
let reason = format!("a launch with this id is already running: {id}");
refuse(&mut writer, id, &reason).await?;
continue;
}
let started = start(
&mut writer,
workload,
untrusted,
(&mut running, &mut exits),
id.clone(),
exec,
on_exit,
)
.await?;
if !started {
tear_down(workload, &mut mounted, &id);
}
}
HostToGuest::Mount {
id,
images,
overlays,
} => {
// A launch's content, mounted into a box that is already up.
// Never ends the session: a game whose image will not mount is
// one launch that cannot start. ref(d-0085)
//
// Carried out off this loop, which also carries every other
// launch's exits and stops: a mount over a share can take a
// while, and nothing else should wait on it.
let refused = if !booted {
Some("the box has not been told what it is".to_string())
} else if mounted.contains_key(&id) {
Some(format!("content is already mounted for this launch: {id}"))
} else {
None
};
if let Some(reason) = refused {
tracing::warn!(launch = %id, reason, "refusing a mount");
send(&mut writer, &GuestToHost::LaunchMountFailed { id, reason }).await?;
continue;
}
mounted.insert(id.clone(), (images.clone(), overlays.clone()));
let pending = workload.mount_launch(images, overlays);
mounting.spawn(async move { (id, pending.await) });
}
HostToGuest::Attach { id, exec, size } => {
// A shell is not a launch: it does not touch `running`, takes no
// part in what an exit means, and a failure to start one is said
// about the shell and never about the session. The control
// channel is where it is said because nothing has connected to
// the data port yet.
if let Err(failure) = workload.attach(id.clone(), &exec, size) {
tracing::warn!(attach = %id, reason = %failure.reason, "a shell would not start");
send(
&mut writer,
&GuestToHost::AttachFailed {
id,
reason: failure.reason,
},
)
.await?;
}
}
HostToGuest::Stop { id } => match running.contains_key(&id) {
// Idempotent, and never ends the session by itself.
true => workload.stop_launch(&id),
// Not an error and not worth failing: a caller stopping
// something that has already stopped got what it asked for.
// Signalling anyway would aim a kill at whatever is running
// now, which is the one thing this must not do.
false => tracing::debug!(launch = %id, "nothing with that id is running to stop"),
},
HostToGuest::Restart { id } => match running.get_mut(&id) {
Some(current) => {
// Kill now, launch when the exit arrives. Doing both here
// would start the second before the first had gone.
current.relaunch = true;
workload.stop_launch(&id);
}
// Nothing is remembered about a launch that has already ended,
// so this cannot be a launch in disguise: the caller has the
// command and can send it.
_ => {
refuse(
&mut writer,
id,
"nothing with that id is running to restart",
)
.await?;
}
},
HostToGuest::Payload { payload: envelope } => hand_over(payload, envelope),
HostToGuest::Shutdown => return Ok(Outcome::Shutdown),
}
}
}
/// Start one launch, reporting which of the two things happened.
///
/// A launch that could not be started is reported and is not the end of the
/// session: a box that dies of a bad `argv` cannot be told a better one. One
/// that started is added to the running set, and its exit to `exits`.
#[allow(clippy::too_many_arguments)]
async fn start<W, Wr>(
writer: &mut Wr,
workload: &mut W,
untrusted: &crate::ticket::Untrusted,
(running, exits): (&mut BTreeMap<LaunchId, Current>, &mut Exits),
id: LaunchId,
exec: Exec,
on_exit: OnExit,
) -> std::io::Result<bool>
where
W: Workload,
Wr: AsyncWrite + Unpin,
{
// **A workload may not be the services' user.** Two things break at once if
// it is. The workload could replace a socket one of the services listens
// on and answer in its place -- which for the address a client is told to
// connect to means answering for the session. And the refusal below is by
// uid, so marking the workload untrusted marks the real hub untrusted too,
// and the session becomes unreachable by its own defence.
//
// Refused rather than silently moved to another uid: a launch that runs as
// somebody other than who it named is a launch whose files land in the
// wrong place, which is a worse day than a launch that did not start.
if exec.uid == crate::services::SERVICE_UID {
refuse(
writer,
id,
&format!(
"a launch may not run as uid {}: that is the box's own service \
user, and a workload sharing it can answer for the session",
crate::services::SERVICE_UID
),
)
.await?;
return Ok(false);
}
// Before the workload exists, so there is no window in which it is running
// and something else would still be trusted to serve this session's
// address.
untrusted.is(exec.uid);
match workload.start(&id, &exec) {
Ok(exited) => {
send(writer, &GuestToHost::Started { id: id.clone() }).await?;
running.insert(
id.clone(),
Current {
exec,
on_exit,
relaunch: false,
},
);
exits.spawn(async move { (id, exited.await) });
Ok(true)
}
Err(failure) => {
refuse(writer, id, &failure.reason).await?;
Ok(false)
}
}
}
/// Each launch's content mounted after boot: its images and its overlays.
type Mounted = BTreeMap<LaunchId, (Vec<nesprotocol::lifecycle::Image>, Vec<nesprotocol::lifecycle::Overlay>)>;
/// Take down what was mounted for a launch that has gone, so the loop devices
/// under it clear themselves. Off this loop, like the mount, and logged
/// rather than reported: the launch it was for has already been reported.
fn tear_down<W: Workload>(workload: &mut W, mounted: &mut Mounted, id: &LaunchId) {
let Some((images, overlays)) = mounted.remove(id) else {
return;
};
let pending = workload.unmount_launch(images, overlays);
let id = id.clone();
tokio::spawn(async move {
match pending.await {
Ok(()) => tracing::info!(launch = %id, "unmounted a launch's content"),
Err(failure) => {
tracing::warn!(launch = %id, reason = %failure.reason, "a launch's content did not unmount")
}
}
});
}
/// Say that a launch will not happen, in the words of whatever refused it.
async fn refuse<Wr>(writer: &mut Wr, id: LaunchId, reason: &str) -> std::io::Result<()>
where
Wr: AsyncWrite + Unpin,
{
tracing::warn!(launch = %id, reason, "refusing a launch");
send(
writer,
&GuestToHost::StartFailed {
id,
reason: reason.to_string(),
},
)
.await
}
/// What the session is waiting on.
enum Event {
Line(Option<String>),
Ended(LaunchId, Exit),
MountDone(LaunchId, Result<(), Failure>),
FromWorkload(Option<Payload>),
Address(Option<crate::ticket::Found>),
ServiceDied(Option<Died>),
CompositorDied(std::io::Result<Exit>),
DaemonDied(std::io::Result<Exit>),
}
/// Hand an envelope to the relay, and treat a relay that is not there as the
/// caller's problem rather than a failure of this session.
///
/// It never waits. This loop also carries stop, shutdown and the workload's
/// exit, and none of those may be held up by a workload that is slow to read
/// its own mail — or by one that never connected at all. What crosses this
/// layer is re-sent when it changes, so a dropped copy costs less than a
/// stalled session.
fn hand_over(ports: &mut Ports, envelope: Payload) {
use tokio::sync::mpsc::error::TrySendError;
let summary = envelope.summary();
match ports.to_workload.try_send(envelope) {
Ok(()) => tracing::debug!(envelope = %summary, "handed an envelope over"),
Err(TrySendError::Full(_)) => {
tracing::warn!(envelope = %summary, "dropped an envelope: the relay is behind")
}
Err(TrySendError::Closed(_)) => {
tracing::warn!(envelope = %summary, "dropped an envelope: the relay is gone")
}
}
}
async fn send<W>(writer: &mut W, message: &GuestToHost) -> std::io::Result<()>
where
W: AsyncWrite + Unpin,
{
let line = to_line(message).map_err(std::io::Error::other)?;
writer.write_all(line.as_bytes()).await?;
writer.flush().await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::services::double::Double as Stack;
use crate::workload::double::Double;
use nesprotocol::lifecycle::{BootDescriptor, Mount};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, DuplexStream};
use tokio::sync::mpsc;
/// The box: one share, and nothing about what runs in it.
fn descriptor() -> BootDescriptor {
BootDescriptor {
mounts: vec![Mount {
tag: "user".into(),
at: "/mnt/user".into(),
ro: false,
}],
overlays: Vec::new(),
images: Vec::new(),
video: Default::default(),
compositor: None,
daemon: None,
}
}
fn exec() -> Exec {
Exec {
argv: vec!["/usr/bin/workload".into(), "--windowed".into()],
env: Default::default(),
cwd: None,
uid: 1001,
gid: 1001,
}
}
fn launch(id: &str) -> HostToGuest {
HostToGuest::Launch {
id: LaunchId::new(id),
exec: exec(),
on_exit: OnExit { terminal: true },
}
}
/// A launch whose ending is not the session's ending, which is what lets a
/// box be launched into again.
fn launch_and_stay(id: &str) -> HostToGuest {
HostToGuest::Launch {
id: LaunchId::new(id),
exec: exec(),
on_exit: OnExit { terminal: false },
}
}
/// The relay's two ends, as the session sees them, plus the ends a
/// workload on the relay would hold.
fn ports() -> (Ports, mpsc::Receiver<Payload>, mpsc::Sender<Payload>) {
let (down_tx, down_rx) = mpsc::channel(4);
let (up_tx, up_rx) = mpsc::channel(4);
(
Ports {
to_workload: down_tx,
from_workload: up_rx,
},
down_rx,
up_tx,
)
}
/// A carrier that never finds an address, for the tests that are not
/// about one. Held open rather than closed: a closed channel is itself a
/// case, and it is tested on purpose below.
fn nowhere() -> mpsc::Receiver<crate::ticket::Found> {
let (tx, rx) = mpsc::channel(1);
// Kept alive for the process, so `recv` pends rather than resolving
// `None` and taking a branch these tests are not exercising.
Box::leak(Box::new(tx));
rx
}
/// What a session is given, so a test names only the part it is about.
struct Given {
workload: Double,
services: Stack,
ports: Ports,
addresses: mpsc::Receiver<crate::ticket::Found>,
}
impl Given {
fn new(workload: Double) -> Self {
let (ports, down_rx, up_tx) = ports();
// The workload's ends of the relay, kept alive so the relay is
// neither full nor gone in tests that are not about either.
Box::leak(Box::new((down_rx, up_tx)));
Self {
workload,
services: Stack::new(),
ports,
addresses: nowhere(),
}
}
}
/// Start a session and hand back what a test wants to assert against.
fn spawn(
guest: DuplexStream,
given: Given,
) -> tokio::task::JoinHandle<(Outcome, Double, Stack)> {
let Given {
mut workload,
mut services,
mut ports,
mut addresses,
} = given;
tokio::spawn(async move {
let outcome = run(
guest,
&mut workload,
&mut services,
&mut ports,
&mut addresses,
&crate::ticket::Untrusted::unknown(),
)
.await
.unwrap();
(outcome, workload, services)
})
}
/// The other end of the channel, as a caller would drive it.
struct Caller {
lines: tokio::io::Lines<BufReader<DuplexStream>>,
}
impl Caller {
fn new(stream: DuplexStream) -> Self {
Self {
lines: BufReader::new(stream).lines(),
}
}
async fn expect(&mut self) -> GuestToHost {
let line = self
.lines
.next_line()
.await
.unwrap()
.expect("the guest said nothing");
from_line(&line).unwrap()
}
async fn expect_ready(&mut self) {
assert_eq!(
self.expect().await,
GuestToHost::Ready {
protocol_version: CONTROL_VERSION
}
);
}
/// The descriptor being carried out: the shares, then the box's own
/// services. Nothing is launched by either.
async fn expect_booted(&mut self) {
assert_eq!(self.expect().await, GuestToHost::Mounted);
assert!(
matches!(self.expect().await, GuestToHost::Initialized { .. }),
"the box never said it was ready to be launched into"
);
}
async fn say(&mut self, message: &HostToGuest) {
let line = to_line(message).unwrap();
self.lines
.get_mut()
.write_all(line.as_bytes())
.await
.unwrap();
}
}
#[tokio::test]
async fn the_guest_speaks_first_and_says_its_version() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
// Nothing has been sent to the guest, so this can only be unprompted.
caller.expect_ready().await;
caller.say(&HostToGuest::Shutdown).await;
let (outcome, _, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
}
/// The descriptor makes the box; it does not run anything. This is the
/// property the whole resident arrangement rests on.
#[tokio::test]
async fn the_descriptor_mounts_and_starts_the_services_and_launches_nothing() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, services) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(workload.mounted, vec![descriptor().mounts]);
assert_eq!(services.brought_up, 1);
assert!(
workload.started.is_empty(),
"the descriptor started something, which is a launch's job"
);
}
/// The box's compositor is the box's, started once with the descriptor and
/// before anything is launched. ref(d-0085)
#[tokio::test]
async fn the_compositor_is_started_by_the_box_and_not_by_a_launch() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
let mut given = descriptor();
given.compositor = Some(nesprotocol::lifecycle::Compositor {
width: 1280,
height: 720,
fps: 30,
uid: 1001,
gid: 1001,
env: Default::default(),
});
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(given.clone()),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.compositors, vec![given.compositor.unwrap()]);
assert!(workload.started.is_empty());
}
/// A box whose compositor will not come up cannot be drawn on, so it is
/// refused like a box whose services will not.
#[tokio::test]
async fn a_compositor_that_will_not_start_refuses_the_box() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut double = Double::exits_when_stopped(Exit::code(0));
double.compositor_failure = Some(Failure::new("no gpu"));
let session = spawn(guest, Given::new(double));
let mut given = descriptor();
given.compositor = Some(nesprotocol::lifecycle::Compositor {
width: 1280,
height: 720,
fps: 30,
uid: 1001,
gid: 1001,
env: Default::default(),
});
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(given),
})
.await;
assert_eq!(caller.expect().await, GuestToHost::Mounted);
assert_eq!(
caller.expect().await,
GuestToHost::InitFailed {
reason: "no gpu".into()
}
);
let (outcome, _, _) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}");
}
/// A compositor that exits ends the box, and the host is told which
/// service it was.
#[tokio::test]
async fn a_compositor_that_exits_is_reported_and_ends_the_box() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (tx, rx) = tokio::sync::oneshot::channel();
let mut double = Double::exits_when_stopped(Exit::code(0));
double.compositor_exit = Some(rx);
let session = spawn(guest, Given::new(double));
let mut given = descriptor();
given.compositor = Some(nesprotocol::lifecycle::Compositor {
width: 1280,
height: 720,
fps: 30,
uid: 1001,
gid: 1001,
env: Default::default(),
});
caller.expect_ready().await;
caller.say(&HostToGuest::Boot { descriptor: Box::new(given) }).await;
caller.expect_booted().await;
tx.send(Exit::signal(11)).unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::ServiceDied { name: "nescope".into(), exit: Exit::signal(11) }
);
let (outcome, _, _) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}");
}
fn daemon_given() -> nesprotocol::lifecycle::Daemon {
nesprotocol::lifecycle::Daemon {
name: "steam".into(),
exec: Exec {
argv: vec!["/payload/client".into()],
env: Default::default(),
cwd: None,
uid: 1001,
gid: 1001,
},
}
}
/// The box's daemon is started by the box, after the compositor, and is
/// listed among its services. ref(d-0085)
#[tokio::test]
async fn the_daemon_is_started_by_the_box_after_the_compositor() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
let mut given = descriptor();
given.compositor = Some(nesprotocol::lifecycle::Compositor {
width: 1280, height: 720, fps: 30, uid: 1001, gid: 1001, env: Default::default(),
});
given.daemon = Some(daemon_given());
caller.expect_ready().await;
caller.say(&HostToGuest::Boot { descriptor: Box::new(given.clone()) }).await;
assert_eq!(caller.expect().await, GuestToHost::Mounted);
let GuestToHost::Initialized { services } = caller.expect().await else {
panic!("the box did not come up")
};
assert!(services.contains(&"steam".to_string()), "{services:?}");
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.daemons, vec![given.daemon.unwrap()]);
let order: Vec<_> = workload.order.iter().filter(|o| ["compositor", "daemon"].contains(o)).collect();
assert_eq!(order, vec![&"compositor", &"daemon"]);
}
/// A daemon that will not start refuses the box.
#[tokio::test]
async fn a_daemon_that_will_not_start_refuses_the_box() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut double = Double::exits_when_stopped(Exit::code(0));
double.daemon_failure = Some(Failure::new("no client"));
let session = spawn(guest, Given::new(double));
let mut given = descriptor();
given.daemon = Some(daemon_given());
caller.expect_ready().await;
caller.say(&HostToGuest::Boot { descriptor: Box::new(given) }).await;
assert_eq!(caller.expect().await, GuestToHost::Mounted);
assert_eq!(caller.expect().await, GuestToHost::InitFailed { reason: "no client".into() });
let (outcome, _, _) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}");
}
/// A daemon that exits is reported by name and ends the box.
#[tokio::test]
async fn a_daemon_that_exits_is_reported_and_ends_the_box() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (tx, rx) = tokio::sync::oneshot::channel();
let mut double = Double::exits_when_stopped(Exit::code(0));
double.daemon_exit = Some(rx);
let session = spawn(guest, Given::new(double));
let mut given = descriptor();
given.daemon = Some(daemon_given());
caller.expect_ready().await;
caller.say(&HostToGuest::Boot { descriptor: Box::new(given) }).await;
caller.expect_booted().await;
tx.send(Exit::code(3)).unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::ServiceDied { name: "steam".into(), exit: Exit::code(3) }
);
let (outcome, _, _) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}");
}
#[tokio::test]
async fn the_descriptors_video_limits_reach_the_services() {
// The ceiling is useless if it stops at the descriptor. `neshub` is the
// only thing that can enforce it and it is a service, so the number has
// to survive the whole way from the boot document to the spawn.
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
let mut given = descriptor();
given.video.bitrate_kbps = Some(8_000);
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(given),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
let (_, _, services) = session.await.unwrap();
assert_eq!(services.video.bitrate_kbps, Some(8_000));
}
#[tokio::test]
async fn a_box_told_nothing_about_video_says_so_rather_than_inventing_a_limit() {
// "Unsaid" must not arrive as a number. A stack that cannot tell the two
// apart cannot log that it was never told, and a ceiling nobody set is
// exactly how every session came to offer 10 Mbps.
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
let (_, _, services) = session.await.unwrap();
assert_eq!(services.video.bitrate_kbps, None);
}
#[tokio::test]
async fn a_launch_runs_what_it_names_and_is_reported_by_its_id() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
}
);
caller
.say(&HostToGuest::Stop {
id: LaunchId::new("l-1"),
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::code(0)
}
);
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(0)));
assert_eq!(workload.started, vec![exec()]);
}
/// A box the caller has not described has no shares and no services, so
/// whatever a launch expects to find is not there.
#[tokio::test]
async fn a_launch_before_the_box_exists_is_refused() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller.say(&launch("l-1")).await;
let GuestToHost::StartFailed { id, reason } = caller.expect().await else {
panic!("a launch into a box that does not exist was accepted")
};
assert_eq!(id, LaunchId::new("l-1"), "the refusal names another launch");
assert!(!reason.is_empty());
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown, "the box died of a bad launch");
assert!(workload.started.is_empty());
}
/// Boot a box and hand back the caller, ready to launch into.
async fn booted(given: Given) -> (Caller, tokio::task::JoinHandle<(Outcome, Double, Stack)>) {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, given);
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
(caller, session)
}
fn started(id: &str) -> GuestToHost {
GuestToHost::Started {
id: LaunchId::new(id),
}
}
fn exited(id: &str) -> GuestToHost {
GuestToHost::WorkloadExited {
id: LaunchId::new(id),
exit: Exit::code(0),
}
}
/// A box is a person's machine with any of their games in it: a second
/// launch runs beside the first. ref(d-0085)
#[tokio::test]
async fn a_second_launch_runs_beside_the_first() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(
workload.started_ids,
vec![LaunchId::new("l-1"), LaunchId::new("l-2")]
);
}
/// Two processes under one id could not be told apart, so the second is
/// refused, by its id, and the first keeps running.
#[tokio::test]
async fn a_launch_under_an_id_that_is_running_is_refused() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch("l-1")).await;
let GuestToHost::StartFailed { id, reason } = caller.expect().await else {
panic!("a second launch under a running id was accepted")
};
assert_eq!(id, LaunchId::new("l-1"));
assert!(reason.contains("already running"), "{reason}");
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.started.len(), 1);
assert!(workload.stopped.iter().all(|s| s.is_none()));
}
/// A stop names one launch and reaches that one only; the box and the
/// other launch carry on.
#[tokio::test]
async fn a_stop_reaches_its_own_launch_and_no_other() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch_and_stay("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller
.say(&HostToGuest::Stop {
id: LaunchId::new("l-2"),
})
.await;
assert_eq!(caller.expect().await, exited("l-2"));
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(workload.stopped, vec![Some(LaunchId::new("l-2"))]);
}
/// A terminal launch ending while another runs leaves the box up; the
/// box ends when the last launch has gone. ref(d-0085)
#[tokio::test]
async fn the_box_ends_when_its_last_launch_has_gone() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller
.say(&HostToGuest::Stop {
id: LaunchId::new("l-1"),
})
.await;
assert_eq!(caller.expect().await, exited("l-1"));
// Still up, for the launch still in it.
for id in ["l-2"] {
caller
.say(&HostToGuest::Stop {
id: LaunchId::new(id),
})
.await;
assert_eq!(caller.expect().await, exited(id));
}
let (outcome, _, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(0)));
}
/// The box ends with the terminal launch's exit, not with whichever
/// launch happened to go last.
#[tokio::test]
async fn an_ending_box_reports_the_exit_of_the_launch_that_ended_it() {
let mut double = Double::exits_when_stopped(Exit::code(0));
double.exit_for.insert(LaunchId::new("l-1"), Exit::code(7));
let (mut caller, session) = booted(Given::new(double)).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-1") }).await;
assert!(matches!(caller.expect().await, GuestToHost::WorkloadExited { .. }));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-2") }).await;
assert_eq!(caller.expect().await, exited("l-2"));
let (outcome, _, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(7)));
}
/// A terminal launch ending beside another is one window closed, not the
/// person done: the box still takes a new launch, and ends only once the
/// last launch in it has gone.
#[tokio::test]
async fn a_box_takes_a_new_launch_after_one_of_its_launches_ended() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-1") }).await;
assert_eq!(caller.expect().await, exited("l-1"));
caller.say(&launch_and_stay("l-3")).await;
assert_eq!(caller.expect().await, started("l-3"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-2") }).await;
assert_eq!(caller.expect().await, exited("l-2"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-3") }).await;
assert_eq!(caller.expect().await, exited("l-3"));
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(0)));
assert_eq!(workload.started.len(), 3);
}
/// The last launch of an ending box failing to restart leaves nothing to
/// wait for, and the box ends at once.
#[tokio::test]
async fn an_ending_box_whose_last_restart_fails_ends() {
let mut double = Double::exits_when_stopped(Exit::code(0));
double.exit_for.insert(LaunchId::new("l-1"), Exit::code(3));
double.fail_restart_of = Some(LaunchId::new("l-2"));
let (mut caller, session) = booted(Given::new(double)).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-1") }).await;
assert!(matches!(caller.expect().await, GuestToHost::WorkloadExited { .. }));
caller.say(&HostToGuest::Restart { id: LaunchId::new("l-2") }).await;
assert_eq!(caller.expect().await, exited("l-2"));
assert!(matches!(caller.expect().await, GuestToHost::StartFailed { .. }));
let (outcome, _, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(3)));
}
fn overlay_for(id: &str) -> nesprotocol::lifecycle::Overlay {
nesprotocol::lifecycle::Overlay {
lower: format!("/nestri/launch-images/{id}/build.erofs"),
upper: format!("/nestri/launches/{id}/upper.ext4"),
at: format!("/nestri/installs/{id}"),
}
}
/// A second mount for the same launch is refused, and what a launch
/// mounted is taken down when it ends.
#[tokio::test]
async fn a_launchs_content_is_mounted_once_and_taken_down_with_it() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
let mount = HostToGuest::Mount {
id: LaunchId::new("l-2"),
images: Vec::new(),
overlays: vec![overlay_for("l-2")],
};
caller.say(&mount).await;
assert_eq!(caller.expect().await, GuestToHost::LaunchMounted { id: LaunchId::new("l-2") });
caller.say(&mount).await;
let GuestToHost::LaunchMountFailed { reason, .. } = caller.expect().await else {
panic!("a second mount for one launch was accepted")
};
assert!(reason.contains("already mounted"), "{reason}");
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(caller.expect().await, started("l-2"));
caller.say(&HostToGuest::Stop { id: LaunchId::new("l-2") }).await;
assert_eq!(caller.expect().await, exited("l-2"));
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.unmounted, vec![(Vec::new(), vec![overlay_for("l-2")])]);
}
/// Content mounted for a launch that then will not start is taken down
/// too, rather than left for the life of the box.
#[tokio::test]
async fn content_for_a_launch_that_will_not_start_is_taken_down() {
let mut double = Double::exits_when_stopped(Exit::code(0));
double.start_failure = Some(Failure::new("ENOENT"));
let (mut caller, session) = booted(Given::new(double)).await;
caller
.say(&HostToGuest::Mount {
id: LaunchId::new("l-2"),
images: Vec::new(),
overlays: vec![overlay_for("l-2")],
})
.await;
assert_eq!(caller.expect().await, GuestToHost::LaunchMounted { id: LaunchId::new("l-2") });
caller.say(&launch("l-2")).await;
assert!(matches!(caller.expect().await, GuestToHost::StartFailed { .. }));
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.unmounted.len(), 1);
}
/// Content for a launch reaches a box that is already up, and the answer
/// names the launch.
#[tokio::test]
async fn a_running_box_mounts_a_launchs_content_on_request() {
let (mut caller, session) =
booted(Given::new(Double::exits_when_stopped(Exit::code(0)))).await;
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
let overlay = nesprotocol::lifecycle::Overlay {
lower: "/nestri/launch-images/l-2/build.erofs".into(),
upper: "/nestri/launches/l-2/upper.ext4".into(),
at: "/nestri/installs/l-2".into(),
};
caller
.say(&HostToGuest::Mount {
id: LaunchId::new("l-2"),
images: Vec::new(),
overlays: vec![overlay.clone()],
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::LaunchMounted {
id: LaunchId::new("l-2")
}
);
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.overlays.last(), Some(&vec![overlay]));
assert!(
workload.stopped.is_empty(),
"mounting for one launch touched another"
);
}
/// A launch's content that will not mount is that launch's failure, and
/// the box stays up.
#[tokio::test]
async fn content_that_will_not_mount_does_not_take_the_box_down() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut double = Double::exits_when_stopped(Exit::code(0));
double.named_image_failure = Some(Failure::new("/nestri/compat-2: ENOENT"));
let session = spawn(guest, Given::new(double));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller
.say(&HostToGuest::Mount {
id: LaunchId::new("l-2"),
images: vec![nesprotocol::lifecycle::Image {
device: "/nestri/launch-images/l-2/compat.erofs".into(),
at: "/nestri/compat-2".into(),
}],
overlays: Vec::new(),
})
.await;
let GuestToHost::LaunchMountFailed { id, reason } = caller.expect().await else {
panic!("a failed mount was not reported against its launch")
};
assert_eq!(id, LaunchId::new("l-2"));
assert!(reason.contains("ENOENT"), "{reason}");
caller.say(&launch("l-1")).await;
assert_eq!(caller.expect().await, started("l-1"));
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
/// Before the descriptor there is nothing to mount into.
#[tokio::test]
async fn a_mount_before_the_box_exists_is_refused_by_its_launch() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Mount {
id: LaunchId::new("l-2"),
images: Vec::new(),
overlays: Vec::new(),
})
.await;
assert!(matches!(
caller.expect().await,
GuestToHost::LaunchMountFailed { .. }
));
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
/// A launch that says its ending is not the session's leaves the box up and
/// able to be launched into again. This is the whole of what "the box
/// outlives what runs in it" means.
#[tokio::test]
async fn a_box_can_be_launched_into_again_after_a_launch_ends() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch_and_stay("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
}
);
caller
.say(&HostToGuest::Stop {
id: LaunchId::new("l-1"),
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::code(0)
}
);
// The session is still here, which is the assertion.
caller.say(&launch_and_stay("l-2")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-2")
}
);
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, services) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(workload.started.len(), 2);
assert_eq!(
services.brought_up, 1,
"the services were brought up again for a second launch"
);
}
/// A restart is a kill followed by a launch of the same command, and both
/// halves are visible: the exit is reported and then the same id runs
/// again. Nothing is restarted by this end on its own.
#[tokio::test]
async fn a_restart_reports_the_exit_and_runs_the_same_command_again() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
}
);
caller
.say(&HostToGuest::Restart {
id: LaunchId::new("l-1"),
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::code(0)
},
"a restart hid the exit it caused"
);
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
},
"a restart kept the id but did not run again"
);
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(
workload.started,
vec![exec(), exec()],
"a restart ran a different command than the one it restarted"
);
}
/// Nothing is remembered about a launch that has ended, so a restart of one
/// is refused rather than guessed at from a stale command.
#[tokio::test]
async fn a_restart_of_nothing_is_refused_and_does_not_end_the_session() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller
.say(&HostToGuest::Restart {
id: LaunchId::new("never-ran"),
})
.await;
let GuestToHost::StartFailed { id, .. } = caller.expect().await else {
panic!("a restart of nothing was accepted")
};
assert_eq!(id, LaunchId::new("never-ran"));
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
/// A stop for something that is not running is what a caller gets when it
/// stops a launch twice. Signalling anyway would aim a kill at whatever is
/// running now, which is the one thing it must not do.
#[tokio::test]
async fn a_stop_for_a_launch_that_is_not_running_signals_nothing() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch_and_stay("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
}
);
// Something else entirely, while l-1 runs.
caller
.say(&HostToGuest::Stop {
id: LaunchId::new("l-2"),
})
.await;
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(
workload.stops, 0,
"a stop aimed at one launch reached another"
);
}
/// A command that will not run is the caller's to correct, so the box stays
/// up and can be told a better one.
#[tokio::test]
async fn a_launch_that_will_not_run_does_not_take_the_box_down() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut workload = Double::exits_at_once(Exit::code(0));
workload.start_failure = Some(Failure::new("ENOENT: /usr/bin/workload"));
let session = spawn(guest, Given::new(workload));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::StartFailed {
id: LaunchId::new("l-1"),
reason: "ENOENT: /usr/bin/workload".into()
},
"the reason is passed through as the operating system wrote it",
);
// Still answering, which is the assertion.
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
/// The one uid a launch may not ask for is the one the box's own services
/// hold. A workload running as them can replace a socket they listen on and
/// answer for the session; and because the carrier refuses peers by uid,
/// marking the workload untrusted marks the real hub untrusted with it.
///
/// Refused, and nothing is started: a launch moved quietly to another user
/// writes its files somewhere nobody asked for.
#[tokio::test]
async fn a_launch_may_not_run_as_the_services_own_user() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
let HostToGuest::Launch { id, mut exec, .. } = launch("l-1") else {
unreachable!()
};
exec.uid = crate::services::SERVICE_UID;
exec.gid = crate::services::SERVICE_GID;
caller
.say(&HostToGuest::Launch {
id,
exec,
on_exit: OnExit { terminal: true },
})
.await;
let GuestToHost::StartFailed { id, reason } = caller.expect().await else {
panic!("a launch as the service user was accepted")
};
assert_eq!(id, LaunchId::new("l-1"));
assert!(
reason.contains(&crate::services::SERVICE_UID.to_string()),
"the refusal names the uid it is about: {reason}"
);
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown, "the refusal ended the box");
assert!(
workload.started.is_empty(),
"the workload was started anyway"
);
}
#[tokio::test]
async fn a_share_that_will_not_mount_is_refused_before_any_service_starts() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut workload = Double::exits_at_once(Exit::code(0));
workload.mount_failure = Some(Failure::new("EACCES: /mnt/user"));
let session = spawn(guest, Given::new(workload));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::MountFailed {
reason: "EACCES: /mnt/user".into()
},
"the reason is passed through as the operating system wrote it",
);
let (outcome, workload, services) = session.await.unwrap();
assert_eq!(outcome, Outcome::Refused(Failure::new("EACCES: /mnt/user")));
assert_eq!(
services.brought_up, 0,
"the services came up in a box whose shares are not there"
);
assert!(workload.started.is_empty());
}
/// A shell is handed to the workload layer with everything it was asked for,
/// and it is not a launch: nothing starts, nothing exits, and the session
/// carries on exactly as it was.
#[tokio::test]
async fn an_attach_goes_to_the_workload_layer_and_is_not_a_launch() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
let wanted = Exec {
argv: vec!["/bin/bash".into()],
env: [("TERM".to_string(), "xterm-256color".to_string())].into(),
cwd: None,
uid: 0,
gid: 0,
};
let size = Some(nesprotocol::lifecycle::Winsize {
cols: 132,
rows: 43,
});
caller
.say(&HostToGuest::Attach {
id: nesprotocol::lifecycle::AttachId::new("a-1"),
exec: wanted.clone(),
size,
})
.await;
caller.say(&HostToGuest::Shutdown).await;
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(
workload.attached,
vec![(nesprotocol::lifecycle::AttachId::new("a-1"), wanted, size)]
);
assert!(
workload.started.is_empty(),
"a shell was started as though it were the workload"
);
}
/// Said about the shell, by its id, on the channel the host is already
/// reading -- nothing has connected to the data port yet, and a host that
/// heard nothing would wait out a timeout to find out.
#[tokio::test]
async fn a_shell_that_will_not_start_is_reported_by_id_and_the_box_carries_on() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut workload = Double::exits_when_stopped(Exit::code(0));
workload.attach_failure = Some(Failure::new("/bin/nope as 0:0: No such file or directory"));
let session = spawn(guest, Given::new(workload));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller
.say(&HostToGuest::Attach {
id: nesprotocol::lifecycle::AttachId::new("a-2"),
exec: exec(),
size: None,
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::AttachFailed {
id: nesprotocol::lifecycle::AttachId::new("a-2"),
reason: "/bin/nope as 0:0: No such file or directory".into()
}
);
caller.say(&HostToGuest::Shutdown).await;
let (outcome, _, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown, "a failed shell ended the box");
}
/// The compatibility layer is the base the rest of a box is built on, so it
/// is mounted before anything that could sit inside it, and a box whose
/// image will not mount is refused rather than carried on with.
#[tokio::test]
async fn images_are_mounted_before_overlays_and_shares() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
let mut given = descriptor();
given.images = vec![nesprotocol::lifecycle::Image {
device: "/dev/vdd".into(),
at: "/nestri/compat".into(),
}];
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(given.clone()),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
let (_, workload, _) = session.await.unwrap();
assert_eq!(workload.images, vec![given.images]);
assert_eq!(workload.order, vec!["images", "overlays", "shares"]);
}
#[tokio::test]
async fn an_image_that_will_not_mount_refuses_the_box_before_anything_else_is_mounted() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut workload = Double::exits_at_once(Exit::code(0));
workload.image_failure = Some(Failure::new("/nestri/compat: the image /dev/vdd: EINVAL"));
let session = spawn(guest, Given::new(workload));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
assert_eq!(
caller.expect().await,
GuestToHost::MountFailed {
reason: "/nestri/compat: the image /dev/vdd: EINVAL".into()
},
);
let (outcome, workload, services) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)));
assert_eq!(
workload.order,
vec!["images"],
"something was mounted after the failure"
);
assert_eq!(services.brought_up, 0);
}
/// A box whose own services will not come up cannot be launched into, so it
/// is refused — and said with its own message, because a share that did not
/// appear and a box that could not be made want different things looked at.
#[tokio::test]
async fn a_service_stack_that_will_not_come_up_refuses_the_box() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let mut given = Given::new(Double::exits_at_once(Exit::code(0)));
given.services = Stack::refuses("neshub: ENOENT — the session has no address");
let session = spawn(guest, given);
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
assert_eq!(caller.expect().await, GuestToHost::Mounted);
let GuestToHost::InitFailed { reason } = caller.expect().await else {
panic!("a box with no services said it was ready to be launched into")
};
assert!(reason.contains("neshub"), "{reason}");
let (outcome, workload, _) = session.await.unwrap();
assert!(matches!(outcome, Outcome::Refused(_)), "{outcome:?}");
assert!(workload.started.is_empty());
}
/// Reported, never repaired, and it does not end the session: a box with a
/// dead service is still a box somebody has to be told about.
#[tokio::test]
async fn a_dead_service_is_reported_and_not_restarted() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let given = Given::new(Double::exits_when_stopped(Exit::code(0)));
let report = given.services.report.clone();
let session = spawn(guest, given);
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
report
.send(Died {
name: "pipewire".into(),
exit: Exit::signal(9),
})
.await
.unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::ServiceDied {
name: "pipewire".into(),
exit: Exit::signal(9)
}
);
// Still answering, and nothing was brought up again.
caller.say(&HostToGuest::Shutdown).await;
let (outcome, _, services) = session.await.unwrap();
assert_eq!(outcome, Outcome::Shutdown);
assert_eq!(
services.brought_up, 1,
"a dead service was restarted by the guest"
);
}
/// The address goes up the channel as it is found. This is the only way
/// out: standard output here is a log file inside a VM and the person who
/// needs the address is outside it.
#[tokio::test]
async fn an_address_that_is_found_is_reported_to_the_caller() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (found_tx, found_rx) = mpsc::channel(4);
let mut given = Given::new(Double::exits_when_stopped(Exit::code(0)));
given.addresses = found_rx;
let session = spawn(guest, given);
caller.expect_ready().await;
found_tx
.send(crate::ticket::Found::Address(
"nestri:local-only".to_string(),
))
.await
.unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::Ticket {
ticket: "nestri:local-only".into()
}
);
// And a better one replaces it rather than being the caller's problem
// to have missed.
found_tx
.send(crate::ticket::Found::Address(
"nestri:with-relays".to_string(),
))
.await
.unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::Ticket {
ticket: "nestri:with-relays".into()
}
);
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
/// Nothing looking for an address any more is not an ending. The session
/// keeps whatever it was already told and still has to report an exit.
#[tokio::test]
async fn a_carrier_that_stops_does_not_end_the_session() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (found_tx, found_rx) = mpsc::channel(4);
let mut given = Given::new(Double::exits_when_stopped(Exit::code(0)));
given.addresses = found_rx;
let session = spawn(guest, given);
caller.expect_ready().await;
drop(found_tx);
// Still answering, which is the whole assertion.
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
#[tokio::test]
async fn an_exit_is_reported_and_the_workload_is_not_started_again() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_at_once(Exit::code(3))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert_eq!(
caller.expect().await,
GuestToHost::Started {
id: LaunchId::new("l-1")
}
);
assert_eq!(
caller.expect().await,
GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::code(3)
},
);
let (outcome, workload, _) = session.await.unwrap();
assert_eq!(outcome, Outcome::WorkloadExited(Exit::code(3)));
assert_eq!(
workload.started.len(),
1,
"an exit is reported, never restarted"
);
}
#[tokio::test]
async fn a_signalled_workload_is_reported_as_signalled() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_at_once(Exit::signal(9))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert!(matches!(caller.expect().await, GuestToHost::Started { .. }));
assert_eq!(
caller.expect().await,
GuestToHost::WorkloadExited {
id: LaunchId::new("l-1"),
exit: Exit::signal(9)
},
);
assert_eq!(
session.await.unwrap().0,
Outcome::WorkloadExited(Exit::signal(9))
);
}
#[tokio::test]
async fn an_unreadable_line_does_not_end_a_session() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.lines
.get_mut()
.write_all(br#"{"type":"from_a_later_version"}"#)
.await
.unwrap();
caller.lines.get_mut().write_all(b"\n").await.unwrap();
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
#[tokio::test]
async fn a_closed_channel_stops_the_workload() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let session = spawn(guest, Given::new(Double::exits_when_stopped(Exit::code(0))));
caller.expect_ready().await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert!(matches!(caller.expect().await, GuestToHost::Started { .. }));
drop(caller);
let (outcome, workload, _) = session.await.unwrap();
assert!(
matches!(outcome, Outcome::ChannelClosed | Outcome::WorkloadExited(_)),
"unexpected outcome: {outcome:?}",
);
assert!(
workload.stops >= 1,
"the workload was left running with nobody listening"
);
}
#[tokio::test]
async fn an_envelope_crosses_the_session_in_both_directions_unread() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (down_tx, down_rx) = mpsc::channel(4);
let (up_tx, up_rx) = mpsc::channel(4);
let mut given = Given::new(Double::exits_when_stopped(Exit::code(0)));
given.ports = Ports {
to_workload: down_tx,
from_workload: up_rx,
};
let session = spawn(guest, given);
let mut to_relay = down_rx;
caller.expect_ready().await;
// Down: an envelope arrives before any descriptor does, and still
// reaches the relay — what crosses this layer is not the boot
// sequence's business.
let body = r#"{"looks":"structured"} and is not"#;
caller
.say(&HostToGuest::Payload {
payload: Payload::new("identity", body),
})
.await;
let handed_over = to_relay.recv().await.unwrap();
assert_eq!(handed_over.body, body, "the body arrived changed");
assert_eq!(handed_over.channel, "identity");
// Up: the same, in reverse.
up_tx
.send(Payload::new("identity", "opaque back"))
.await
.unwrap();
assert_eq!(
caller.expect().await,
GuestToHost::Payload {
payload: Payload::new("identity", "opaque back")
},
);
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
#[tokio::test]
async fn a_relay_nothing_is_on_does_not_end_a_session() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (down_tx, down_rx) = mpsc::channel(1);
let (_up_tx, up_rx) = mpsc::channel::<Payload>(1);
drop(down_rx); // nothing is on the relay
let mut given = Given::new(Double::exits_when_stopped(Exit::code(0)));
given.ports = Ports {
to_workload: down_tx,
from_workload: up_rx,
};
let session = spawn(guest, given);
caller.expect_ready().await;
caller
.say(&HostToGuest::Payload {
payload: Payload::new("identity", "dropped"),
})
.await;
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
#[tokio::test]
async fn a_relay_that_is_not_draining_does_not_stall_the_session() {
// Bounded, because the failure is a session that stops rather than one
// that answers wrongly.
tokio::time::timeout(std::time::Duration::from_secs(5), async {
a_backed_up_relay().await
})
.await
.expect("the session stalled on the relay");
}
async fn a_backed_up_relay() {
let (guest, host) = tokio::io::duplex(4096);
let mut caller = Caller::new(host);
let (down_tx, down_rx) = mpsc::channel(1);
let (_up_tx, up_rx) = mpsc::channel::<Payload>(1);
// Held and never read: a workload that is slow to read its own mail,
// or one that connected and stopped.
let _backed_up = down_rx;
let mut given = Given::new(Double::exits_when_stopped(Exit::code(0)));
given.ports = Ports {
to_workload: down_tx,
from_workload: up_rx,
};
let session = spawn(guest, given);
caller.expect_ready().await;
for _ in 0..8 {
caller
.say(&HostToGuest::Payload {
payload: Payload::new("identity", "backlog"),
})
.await;
}
// The lifecycle layer still moves: stop, shutdown and an exit are on
// this loop too, and none of them may wait on the relay.
caller
.say(&HostToGuest::Boot {
descriptor: Box::new(descriptor()),
})
.await;
caller.expect_booted().await;
caller.say(&launch("l-1")).await;
assert!(matches!(caller.expect().await, GuestToHost::Started { .. }));
caller.say(&HostToGuest::Shutdown).await;
assert_eq!(session.await.unwrap().0, Outcome::Shutdown);
}
}