use std::future::Future;
use std::sync::Arc;
use sapphire_bridge_api::{
BRIDGE_NOT_RUNNING, CONFIG_GET, CONFIG_LIST, CONFIG_SCHEMA, CONFIG_SET, CONFIG_UNSET,
ConfigEntry, ConfigGetParams, ConfigListParams, ConfigListResult, ConfigSchemaResult,
ConfigSetParams, ConfigUnsetParams, ConfigWriteResult,
};
use sapphire_bridge_client::BridgeClient;
use sapphire_framework_settings::{Entry, Op, Registry, Scope};
use sapphire_ipc::{Router, RpcError};
use serde_json::Value;
use crate::relay::{self, Relay};
use crate::settings::{self, Settings};
struct Config {
settings: Settings,
relay: Arc<Relay>,
writing: tokio::sync::Mutex<()>,
}
pub(crate) fn routes(router: Router, settings: Settings, relay: Arc<Relay>) -> Router {
let config = Arc::new(Config {
settings,
relay,
writing: tokio::sync::Mutex::new(()),
});
let router = answer(router, &config, CONFIG_SCHEMA, |config, _| async move {
encode(config.schema().await?)
});
let router = answer(router, &config, CONFIG_LIST, |config, params| async move {
let params: ConfigListParams = parse(params, CONFIG_LIST)?;
encode(config.list(params.scope).await?)
});
let router = answer(router, &config, CONFIG_GET, |config, params| async move {
let params: ConfigGetParams = parse(params, CONFIG_GET)?;
encode(config.get(¶ms.key).await?)
});
let router = answer(router, &config, CONFIG_SET, |config, params| async move {
let params: ConfigSetParams = parse(params, CONFIG_SET)?;
encode(
config
.write(params.scope, Batch::Set(params.entries), params.dry_run)
.await?,
)
});
answer(router, &config, CONFIG_UNSET, |config, params| async move {
let params: ConfigUnsetParams = parse(params, CONFIG_UNSET)?;
encode(
config
.write(params.scope, Batch::Unset(params.keys), params.dry_run)
.await?,
)
})
}
fn answer<F, Fut>(router: Router, config: &Arc<Config>, method: &'static str, f: F) -> Router
where
F: Fn(Arc<Config>, Value) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Value, RpcError>> + Send + 'static,
{
let config = Arc::clone(config);
let f = Arc::new(f);
router.method(method, move |ctx| {
let result = f(Arc::clone(&config), ctx.params);
async move {
let result = result.await;
match &result {
Ok(_) => tracing::debug!(method, outcome = "ok", "answered a config call"),
Err(e) => tracing::debug!(method, outcome = e.code, "answered a config call"),
}
result
}
})
}
enum Batch {
Set(Vec<ConfigEntry>),
Unset(Vec<String>),
}
impl Batch {
fn split(self, reg: &Registry) -> (Batch, Batch) {
let own = |key: &str| reg.def(key).is_ok() || !reg.under(key).is_empty();
match self {
Batch::Set(entries) => {
let (mine, theirs) = entries.into_iter().partition(|e| own(&e.key));
(Batch::Set(mine), Batch::Set(theirs))
}
Batch::Unset(keys) => {
let (mine, theirs) = keys.into_iter().partition(|k| own(k));
(Batch::Unset(mine), Batch::Unset(theirs))
}
}
}
fn is_empty(&self) -> bool {
match self {
Batch::Set(entries) => entries.is_empty(),
Batch::Unset(keys) => keys.is_empty(),
}
}
fn keys(&self) -> Vec<&str> {
match self {
Batch::Set(entries) => entries.iter().map(|e| e.key.as_str()).collect(),
Batch::Unset(keys) => keys.iter().map(String::as_str).collect(),
}
}
fn ops(&self) -> Vec<Op> {
match self {
Batch::Set(entries) => entries
.iter()
.map(|e| Op::Set {
key: e.key.clone(),
value: e.value.clone(),
})
.collect(),
Batch::Unset(keys) => keys
.iter()
.map(|key| Op::Unset { key: key.clone() })
.collect(),
}
}
async fn send(
&self,
bridge: &BridgeClient,
scope: Option<Scope>,
dry_run: bool,
) -> Result<ConfigWriteResult, RpcError> {
let result = match (self, dry_run) {
(Batch::Set(entries), true) => bridge.config_check_set(scope, entries.clone()).await,
(Batch::Set(entries), false) => bridge.config_set(scope, entries.clone()).await,
(Batch::Unset(keys), true) => bridge.config_check_unset(scope, keys.clone()).await,
(Batch::Unset(keys), false) => bridge.config_unset(scope, keys.clone()).await,
};
result.map_err(from_bridge)
}
}
impl Config {
async fn schema(&self) -> Result<ConfigSchemaResult, RpcError> {
let mut settings = self.settings.registry().schema();
if let Some(theirs) = self
.ask(|bridge| async move { bridge.config_schema().await })
.await?
{
settings.extend(theirs.settings);
}
Ok(ConfigSchemaResult { settings })
}
async fn list(&self, scope: Option<Scope>) -> Result<ConfigListResult, RpcError> {
let mut entries = Vec::new();
if scope != Some(Scope::Workgroup) {
entries = self.own_list(scope).map_err(failed)?;
}
if scope != Some(Scope::Workspace)
&& let Some(theirs) = self
.ask(|bridge| async move { bridge.config_list(scope).await })
.await?
{
entries.extend(theirs.entries);
}
Ok(ConfigListResult { entries })
}
async fn get(&self, key: &str) -> Result<Entry, RpcError> {
let reg = self.settings.registry();
if reg.def(key).is_ok() {
let entry = sapphire_framework_settings::get(reg, key).map_err(failed)?;
return Ok(self
.own_list(None)
.map_err(failed)?
.into_iter()
.find(|e| e.key == key)
.unwrap_or(entry));
}
let bridge = self.relay.bridge().await?;
bridge.config_get(key).await.map_err(from_bridge)
}
async fn write(
&self,
scope: Option<Scope>,
batch: Batch,
dry_run: bool,
) -> Result<ConfigWriteResult, RpcError> {
let _one = self.writing.lock().await;
let reg = self.settings.registry();
let (mine, theirs) = batch.split(reg);
let mut changed = Vec::new();
if !mine.is_empty() {
changed = sapphire_framework_settings::check(reg, scope, mine.ops())
.map_err(failed)?
.keys;
}
let mut bridge_result = None;
if !theirs.is_empty() {
let bridge = match self.relay.bridge().await {
Ok(bridge) => bridge,
Err(e) if e.code == BRIDGE_NOT_RUNNING => return Err(no_bridge_for(&theirs)),
Err(e) => return Err(e),
};
if !mine.is_empty() || dry_run {
let checked = theirs.send(&bridge, scope, true).await?;
if dry_run {
bridge_result = Some(checked);
}
}
if !dry_run {
bridge_result = Some(theirs.send(&bridge, scope, false).await?);
}
}
if !dry_run && !mine.is_empty() {
match sapphire_framework_settings::apply(reg, scope, mine.ops()) {
Ok(applied) => changed = applied.keys,
Err(e) if bridge_result.is_some() => {
return Err(RpcError::internal(format!(
"sapphire-bridge's settings were written, but this server's were not: {e}"
)));
}
Err(e) => return Err(failed(e)),
}
if self.settings.refresh().is_err() {
tracing::warn!("could not read the settings back after a write");
}
}
let mut pending_restart: Vec<String> = self
.own_list(None)
.map_err(failed)?
.into_iter()
.filter(|e| e.pending_restart)
.map(|e| e.key)
.collect();
match bridge_result {
Some(theirs) => {
changed.extend(theirs.changed);
pending_restart.extend(theirs.pending_restart);
}
None => {
if let Ok(Some(theirs)) = self
.ask(|bridge| async move { bridge.config_list(None).await })
.await
{
pending_restart.extend(
theirs
.entries
.into_iter()
.filter(|e| e.pending_restart)
.map(|e| e.key),
);
}
}
}
Ok(ConfigWriteResult {
changed,
pending_restart,
})
}
fn own_list(&self, scope: Option<Scope>) -> sapphire_framework_settings::Result<Vec<Entry>> {
sapphire_framework_settings::list(
self.settings.registry(),
scope,
Some(self.settings.start()),
)
}
async fn ask<T, F, Fut>(&self, call: F) -> Result<Option<T>, RpcError>
where
F: FnOnce(Arc<BridgeClient>) -> Fut,
Fut: Future<Output = sapphire_ipc::Result<T>>,
{
let Ok(bridge) = self.relay.bridge().await else {
return Ok(None);
};
match call(bridge).await {
Ok(answer) => Ok(Some(answer)),
Err(sapphire_ipc::Error::Rpc(e)) => Err(e),
Err(_) => Ok(None),
}
}
}
fn no_bridge_for(theirs: &Batch) -> RpcError {
let unknown = theirs.keys().into_iter().find(|key| {
let top = key.split('.').next().unwrap_or(key);
!settings::BRIDGE_NAMES.contains(&top)
});
match unknown {
Some(key) => {
let mut rpc = RpcError::internal(format!(
"unknown setting {key} (or sapphire-bridge, which may know it, is not running)"
));
rpc.data = Some(
sapphire_bridge_api::ConfigFieldErrors {
fields: vec![sapphire_bridge_api::ConfigFieldError {
key: key.to_owned(),
message: "unknown setting (or sapphire-bridge, which may know it, is not running)"
.to_owned(),
}],
}
.to_data(),
);
rpc
}
None => relay::not_running(),
}
}
fn from_bridge(err: sapphire_ipc::Error) -> RpcError {
match err {
sapphire_ipc::Error::Rpc(e) => e,
_ => relay::not_running(),
}
}
fn failed(err: sapphire_framework_settings::Error) -> RpcError {
let mut rpc = RpcError::internal(err.to_string());
let fields = err.field_errors();
if !fields.is_empty() {
rpc.data = Some(sapphire_bridge_api::ConfigFieldErrors { fields }.to_data());
}
rpc
}
fn parse<T: serde::de::DeserializeOwned>(params: Value, method: &str) -> Result<T, RpcError> {
serde_json::from_value(params)
.map_err(|e| RpcError::invalid_params(format!("malformed {method}: {e}")))
}
fn encode<T: serde::Serialize>(value: T) -> Result<Value, RpcError> {
serde_json::to_value(value).map_err(|e| RpcError::internal(e.to_string()))
}