#![warn(missing_docs)]
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use sapphire_backend::protocol as proto;
use sapphire_framework_service::ServiceSpec;
use sapphire_ipc::{Endpoint, ManagedBy, Router, ServerInfo, serve};
use sapphire_workspace::AppContext;
const SERVE_GRACE: Duration = Duration::from_secs(2);
mod command;
mod current;
mod error;
mod events;
mod handlers;
mod host;
mod selection;
pub mod sync;
#[cfg(test)]
mod test_support;
pub use command::{
DeviceCommand, FrameworkCommand, StatusReport, StatusRow, WorkgroupCommand, WorkspaceCommand,
render_workspace,
};
pub use current::Current;
pub use error::{Error, Result};
pub use events::subscribe_method;
pub use handlers::workspace_router;
pub use host::WorkspaceHost;
pub use selection::{SELECTION_FILE, Selection, SelectionFile};
pub use sync::{BackfillTiming, SyncRuntime, SyncStatus, sync_router};
pub struct AppServer {
ctx: &'static AppContext,
version: &'static str,
endpoint: Option<Endpoint>,
selection_file: Option<PathBuf>,
host: Arc<WorkspaceHost>,
sync: Option<Arc<SyncRuntime>>,
extend: Option<Box<dyn FnOnce(Router) -> Router + Send>>,
status_rows: Option<Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>>,
app_api: Option<u32>,
}
#[cfg(unix)]
struct Sigterm(tokio::signal::unix::Signal);
#[cfg(not(unix))]
struct Sigterm;
#[cfg(unix)]
impl Sigterm {
fn new() -> Result<Self> {
Ok(Self(tokio::signal::unix::signal(
tokio::signal::unix::SignalKind::terminate(),
)?))
}
async fn recv(&mut self) {
self.0.recv().await;
}
}
#[cfg(not(unix))]
impl Sigterm {
async fn recv(&mut self) {
std::future::pending::<()>().await
}
}
impl AppServer {
pub fn new(ctx: &'static AppContext, version: &'static str) -> AppServer {
AppServer {
ctx,
version,
endpoint: None,
selection_file: None,
host: Arc::new(WorkspaceHost::new(ctx)),
sync: None,
extend: None,
status_rows: None,
app_api: None,
}
}
pub fn app_name(&self) -> &'static str {
self.ctx.app_name
}
pub fn endpoint(mut self, endpoint: Endpoint) -> AppServer {
self.endpoint = Some(endpoint);
self
}
pub fn app_api(mut self, version: u32) -> AppServer {
self.app_api = Some(version);
self
}
pub fn selection_file(mut self, path: PathBuf) -> AppServer {
self.selection_file = Some(path);
self
}
pub fn sync(mut self, runtime: Arc<SyncRuntime>) -> AppServer {
runtime.set_host(Arc::clone(&self.host));
self.sync = Some(runtime);
self
}
pub fn status_rows(mut self, rows: Arc<dyn Fn() -> Vec<StatusRow> + Send + Sync>) -> AppServer {
self.status_rows = Some(rows);
self
}
pub fn service_spec(&self) -> ServiceSpec {
ServiceSpec {
app_name: self.ctx.app_name,
description: format!("{} server {}", self.ctx.app_name, self.version),
args: vec!["serve".to_owned()],
post_install: None,
}
}
pub fn extend(mut self, f: impl FnOnce(Router) -> Router + Send + 'static) -> AppServer {
self.extend = Some(Box::new(f));
self
}
pub fn host(&self) -> &Arc<WorkspaceHost> {
&self.host
}
pub async fn run(self) -> Result<()> {
let AppServer {
ctx,
version,
endpoint,
selection_file,
host,
sync,
extend,
status_rows,
app_api,
} = self;
let endpoint = match endpoint {
Some(e) => e,
None => Endpoint::for_app(ctx.app_name)?,
};
let info = ServerInfo {
version: version.to_owned(),
api: proto::API_VERSION,
app_api,
pid: std::process::id(),
managed_by: ManagedBy::Service,
};
let _log = sapphire_workspace::logging::install(ctx)?;
let (stop_tx, mut stop_rx) = tokio::sync::watch::channel(false);
let file = match selection_file {
Some(path) => SelectionFile::at(path),
None => SelectionFile::for_app(ctx),
};
let current = Arc::new(Current::new(ctx, Arc::clone(&host), sync.clone(), file));
let restoring = current.restore().await;
let mut router = subscribe_method(
Arc::clone(&host),
current::current_methods(Arc::clone(¤t), workspace_router(Arc::clone(¤t))),
);
if sync.is_some() {
router = sync_router(Arc::clone(¤t), router);
}
router = router
.method(proto::SERVER_INFO, {
let info = info.clone();
let status_rows = status_rows.clone();
move |_| {
let info = info.clone();
let status_rows = status_rows.clone();
async move {
let app = status_rows.as_ref().map(|rows| rows()).unwrap_or_default();
let report = StatusReport {
running: true,
version: Some(info.version),
pid: Some(info.pid),
managed_by: Some(match info.managed_by {
ManagedBy::Service => proto::ManagedBy::Service,
ManagedBy::Spawned => proto::ManagedBy::Spawned,
}),
app,
};
serde_json::to_value(report)
.map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
}
}
})
.method(sapphire_ipc::SHUTDOWN_METHOD, {
let stop_tx = stop_tx.clone();
move |_| {
let stop_tx = stop_tx.clone();
async move {
let _ = stop_tx.send(true);
serde_json::to_value(proto::Ack {})
.map_err(|e| sapphire_ipc::RpcError::internal(e.to_string()))
}
}
});
if let Some(extend) = extend {
router = extend(router);
}
let router = Arc::new(router);
#[cfg(unix)]
let mut sigterm = Sigterm::new()?;
#[cfg(not(unix))]
let mut sigterm = Sigterm;
#[cfg(unix)]
let listener = sapphire_ipc::bind(&endpoint).await?;
#[cfg(windows)]
let mut listener = sapphire_ipc::bind(&endpoint)?;
let _sync_tasks = match &sync {
Some(runtime) => {
let driver = Arc::clone(runtime);
let announcements = tokio::spawn(async move {
if let Err(err) = driver.run().await {
tracing::warn!("the bridge announcement loop ended: {err}");
}
});
let changing = Arc::clone(runtime);
let watching = tokio::spawn(async move {
if let Err(err) = changing.watch_changes().await {
tracing::warn!("the file watcher ended: {err}");
}
});
let dialling = Arc::clone(runtime);
let dialling = tokio::spawn(async move {
if let Err(err) = dialling.dial_loop().await {
tracing::warn!("the live dial loop ended: {err}");
}
});
Some((announcements, watching, dialling))
}
None => None,
};
let mut connections = tokio::task::JoinSet::new();
loop {
tokio::select! {
changed = stop_rx.changed() => {
if changed.is_err() || *stop_rx.borrow() {
break;
}
}
_ = tokio::signal::ctrl_c() => {
tracing::info!("interrupted; shutting down");
break;
}
_ = sigterm.recv() => {
tracing::info!("terminated; shutting down");
break;
}
accepted = listener.accept() => {
let conn = accepted?;
let router = Arc::clone(&router);
let app = ctx.app_name;
let info = info.clone();
connections.spawn(async move {
let _ = serve(conn, router, app, info).await;
});
}
}
}
if let Some(restoring) = restoring {
restoring.abort();
}
if let Some((announcements, watching, dialling)) = _sync_tasks {
announcements.abort();
watching.abort();
dialling.abort();
}
if let Some(runtime) = &sync {
runtime.drop_connections().await;
}
host.close();
drop(listener);
let _ = tokio::time::timeout(SERVE_GRACE, async {
while connections.join_next().await.is_some() {}
})
.await;
connections.abort_all();
while connections.join_next().await.is_some() {}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use sapphire_ipc::{ClientInfo, Endpoint, ManagedBy};
use sapphire_workspace::{AppContext, AppKind};
use std::ffi::OsString;
use crate::test_support;
static CTX: AppContext = AppContext::new("sapphire-appservertest");
const DIR_VARS: [&str; 3] = [
"SAPPHIRE_APPSERVERTEST_CACHE_DIR",
"SAPPHIRE_APPSERVERTEST_DATA_DIR",
"SAPPHIRE_APPSERVERTEST_CONFIG_DIR",
];
fn client_info() -> ClientInfo {
ClientInfo {
kind: "test".into(),
version: "0.0.0".into(),
api: sapphire_backend::protocol::API_VERSION,
app_api: None,
pid: std::process::id(),
}
}
struct EnvGuard {
previous: [Option<OsString>; 3],
_lock: std::sync::MutexGuard<'static, ()>,
}
impl EnvGuard {
fn set(lock: std::sync::MutexGuard<'static, ()>, tmp: &std::path::Path) -> EnvGuard {
let previous = DIR_VARS.map(std::env::var_os);
let dirs = ["cache", "data", "config"].map(|cat| tmp.join(cat));
for (name, dir) in DIR_VARS.iter().zip(dirs) {
test_support::set(name, &dir);
}
EnvGuard {
previous,
_lock: lock,
}
}
}
impl Drop for EnvGuard {
fn drop(&mut self) {
for (name, previous) in DIR_VARS.iter().zip(self.previous.iter_mut()) {
match previous.take() {
Some(value) => unsafe { std::env::set_var(name, value) },
None => test_support::remove(name),
}
}
}
}
struct Fixture {
_tmp: tempfile::TempDir,
_env: EnvGuard,
endpoint: Endpoint,
}
fn prepared() -> Fixture {
let lock = test_support::lock();
let tmp = tempfile::tempdir().unwrap();
let env = EnvGuard::set(lock, tmp.path());
CTX.init(AppKind::Server);
let endpoint = Endpoint::in_dir("sapphire-appservertest", tmp.path().to_path_buf());
Fixture {
_tmp: tmp,
_env: env,
endpoint,
}
}
async fn wait_until_listening(endpoint: &Endpoint) {
let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
while !sapphire_ipc::probe(endpoint).await.unwrap() {
assert!(
tokio::time::Instant::now() < deadline,
"the server never started listening"
);
tokio::time::sleep(Duration::from_millis(10)).await;
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_running_server_writes_its_log_file() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
tracing::info!("the server is serving, and this line belongs in its log");
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.expect("the server is listening");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
let text = std::fs::read_to_string(CTX.log_dir().join("app.log")).unwrap();
assert!(
text.contains("the server is serving, and this line belongs in its log"),
"{text}"
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_reports_itself_as_service_managed() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, info) =
sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.expect("the server is listening");
assert_eq!(info.managed_by, ManagedBy::Service);
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_server_reports_its_app_api_and_the_handshake_gates_on_it() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0")
.endpoint(endpoint.clone())
.app_api(7);
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let wants = |app_api| ClientInfo {
app_api,
..client_info()
};
let err = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(8)))
.await
.unwrap_err();
assert!(
matches!(
err,
sapphire_ipc::Error::AppApiVersionMismatch {
running: Some(7),
ours: 8,
..
}
),
"{err:?}"
);
let (client, info) =
sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, wants(Some(7)))
.await
.unwrap()
.expect("the server is listening");
assert_eq!(info.app_api, Some(7));
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn a_running_server_answers_server_info() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "1.2.3").endpoint(endpoint.clone());
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, info) = sapphire_ipc::connect_or_absent(
&endpoint,
CTX.app_name,
ClientInfo {
version: "1.2.3".into(),
..client_info()
},
)
.await
.unwrap()
.expect("the server is listening");
assert_eq!(info.version, "1.2.3");
let report: StatusReport = client
.call(
sapphire_backend::protocol::SERVER_INFO,
serde_json::json!({}),
)
.await
.unwrap();
assert!(report.running);
assert_eq!(report.version.as_deref(), Some("1.2.3"));
assert_eq!(report.pid, Some(std::process::id()));
assert_eq!(report.managed_by, Some(proto::ManagedBy::Service));
assert!(report.app.is_empty(), "no status rows were configured");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn shutdown_stops_the_server() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.expect("the server is listening");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
tokio::time::timeout(Duration::from_secs(5), handle)
.await
.expect("the server must stop")
.unwrap()
.unwrap();
assert!(!sapphire_ipc::probe(&endpoint).await.unwrap());
}
#[tokio::test(flavor = "multi_thread")]
async fn an_application_can_add_its_own_methods() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0")
.endpoint(endpoint.clone())
.extend(|r| {
r.method("sapphire-appservertest.greet", |_| async move {
Ok(serde_json::json!("hello"))
})
});
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.expect("the server is listening");
let greeting: String = client
.call("sapphire-appservertest.greet", serde_json::json!({}))
.await
.unwrap();
assert_eq!(greeting, "hello");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn workspace_init_creates_the_marker_and_tells_the_registry() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0").endpoint(endpoint.clone());
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.unwrap();
let dir = tempfile::tempdir().unwrap();
let result: proto::WorkspaceInitResult = client
.call(
proto::WORKSPACE_INIT,
proto::WorkspaceInitParams {
dir: dir.path().to_owned(),
},
)
.await
.unwrap();
assert!(result.created);
assert!(dir.path().join(format!(".{}", CTX.app_name)).is_dir());
let again: proto::WorkspaceInitResult = client
.call(
proto::WORKSPACE_INIT,
proto::WorkspaceInitParams {
dir: dir.path().to_owned(),
},
)
.await
.unwrap();
assert!(!again.created);
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn server_info_carries_the_app_rows() {
let f = prepared();
let endpoint = f.endpoint.clone();
let server = AppServer::new(&CTX, "0.0.0")
.endpoint(endpoint.clone())
.status_rows(std::sync::Arc::new(|| {
vec![StatusRow {
name: "sync".into(),
value: "enabled".into(),
}]
}));
let handle = tokio::spawn(async move { server.run().await });
wait_until_listening(&endpoint).await;
let (client, _) = sapphire_ipc::connect_or_absent(&endpoint, CTX.app_name, client_info())
.await
.unwrap()
.unwrap();
let report: StatusReport = client
.call(
sapphire_backend::protocol::SERVER_INFO,
serde_json::json!({}),
)
.await
.unwrap();
assert!(report.running);
assert_eq!(report.app.len(), 1);
assert_eq!(report.app[0].name, "sync");
let _: serde_json::Value = client
.call(sapphire_ipc::SHUTDOWN_METHOD, serde_json::json!({}))
.await
.unwrap();
handle.await.unwrap().unwrap();
}
}