1use std::sync::Arc;
12use std::time::Duration;
13
14use sapphire_backend::protocol as proto;
15use sapphire_bridge_client::BridgeClient;
16use sapphire_framework_settings::{Op, Process, Registry, Scope, SettingDef, apply, get, list};
17use sapphire_ipc::{ClientInfo, Endpoint};
18use sapphire_workspace::AppContext;
19
20use crate::error::{Error, Result};
21use crate::settings::AppSettings;
22
23#[derive(Debug, clap::Subcommand)]
25pub enum AppConfigCommand {
26 List {
28 #[command(flatten)]
30 scope: AppScopeFlags,
31 #[arg(long)]
33 show_origin: bool,
34 },
35 Get {
37 key: String,
39 },
40 Set {
42 #[arg(required = true)]
44 entries: Vec<String>,
45 #[command(flatten)]
47 scope: AppScopeFlags,
48 #[arg(long)]
50 stdin: bool,
51 #[arg(long)]
54 restart: bool,
55 },
56 Unset {
58 #[arg(required = true)]
60 keys: Vec<String>,
61 #[command(flatten)]
63 scope: AppScopeFlags,
64 #[arg(long)]
67 restart: bool,
68 },
69}
70
71#[derive(Debug, Clone, Copy, clap::Args)]
73pub struct AppScopeFlags {
74 #[arg(long, conflicts_with_all = ["workgroup", "workspace"])]
76 device: bool,
77 #[arg(long, conflicts_with = "workspace")]
79 workgroup: bool,
80 #[arg(long)]
82 workspace: bool,
83}
84
85impl AppScopeFlags {
86 pub fn scope(&self) -> Option<Scope> {
88 if self.device {
89 Some(Scope::Device)
90 } else if self.workgroup {
91 Some(Scope::Workgroup)
92 } else if self.workspace {
93 Some(Scope::Workspace)
94 } else {
95 None
96 }
97 }
98}
99
100const BRIDGE_NOT_SHOWN: &str = "sapphire-bridge is not running; its settings are not shown";
102
103const RESTART_TIMEOUT: Duration = Duration::from_secs(30);
105
106const RESTART_POLL: Duration = Duration::from_millis(100);
108
109pub(super) async fn config<A: AppSettings + Clone>(
112 ctx: &'static AppContext,
113 owner: A,
114 command: AppConfigCommand,
115 version: &str,
116) -> Result<i32> {
117 let app = ctx.app_name;
118 let Some(client) = super::try_connect_app(app, version).await? else {
119 let bridge_running = matches!(command, AppConfigCommand::List { .. })
121 && sapphire_ipc::probe(&Endpoint::for_bridge()?)
122 .await
123 .unwrap_or(false);
124 let printed = offline(ctx, Arc::new(owner), command, bridge_running)?;
125 for line in printed.out {
126 println!("{line}");
127 }
128 for line in printed.err {
129 eprintln!("{line}");
130 }
131 return Ok(printed.code);
132 };
133 online(Arc::new(client), app, version, command).await
134}
135
136fn rejected_batch<T>(result: sapphire_ipc::Result<T>) -> Option<sapphire_ipc::Result<T>> {
141 use sapphire_bridge_client::ConfigFieldErrorsExt;
142 if let Err(err @ sapphire_ipc::Error::Rpc(rpc)) = &result
143 && let Some(fields) = sapphire_bridge_api::ConfigFieldErrors::from_rpc(rpc)
144 {
145 eprintln!("{err}");
146 for line in fields.lines() {
147 eprintln!("{line}");
148 }
149 return None;
150 }
151 Some(result)
152}
153
154async fn online(
156 client: Arc<sapphire_ipc::Client>,
157 app: &str,
158 version: &str,
159 command: AppConfigCommand,
160) -> Result<i32> {
161 let bridge = BridgeClient::relayed(Arc::clone(&client), sapphire_ipc::runtime_dir()?);
162 let (written, restart, schema) = match command {
163 AppConfigCommand::List { scope, show_origin } => {
164 let entries = bridge.config_list(scope.scope()).await?.entries;
165 for line in sapphire_bridge_api::describe_entries(&entries, show_origin) {
166 println!("{line}");
167 }
168 if scope.scope() != Some(Scope::Workspace)
170 && !has_bridge(&bridge.config_schema().await?.settings)
171 {
172 println!("{BRIDGE_NOT_SHOWN}");
173 }
174 return Ok(0);
175 }
176 AppConfigCommand::Get { key } => {
177 let lines = match bridge.config_get(&key).await {
178 Ok(entry) => sapphire_bridge_api::describe_entries(&[entry], false),
179 Err(sapphire_ipc::Error::NotRunning(_)) => {
180 eprintln!(
181 "unknown setting {key} (or sapphire-bridge, which may know it, is not running)"
182 );
183 return Ok(1);
184 }
185 Err(err) => {
187 eprintln!("{err}");
188 return Ok(1);
189 }
190 };
191 for line in lines {
192 println!("{line}");
193 }
194 return Ok(0);
195 }
196 AppConfigCommand::Set {
197 entries,
198 scope,
199 stdin,
200 restart,
201 } => {
202 let schema = bridge.config_schema().await?.settings;
203 if !has_bridge(&schema)
207 && let Some(key) = entries
208 .iter()
209 .map(|e| e.split_once('=').map_or(e.as_str(), |(key, _)| key))
210 .find(|key| !schema.iter().any(|d| d.key == *key))
211 {
212 return Err(Error::Config(format!(
213 "unknown setting {key} (or sapphire-bridge, which may know it, is not running)"
214 )));
215 }
216 let entries = sapphire_bridge_api::parse_entries(&schema, &entries, stdin)
217 .map_err(Error::Config)?;
218 (
219 {
220 let result = bridge.config_set(scope.scope(), entries).await;
221 let Some(result) = rejected_batch(result) else {
222 return Ok(1);
223 };
224 result?
225 },
226 restart,
227 Some(schema),
228 )
229 }
230 AppConfigCommand::Unset {
231 keys,
232 scope,
233 restart,
234 } => (
235 {
236 let result = bridge.config_unset(scope.scope(), keys).await;
237 let Some(result) = rejected_batch(result) else {
238 return Ok(1);
239 };
240 result?
241 },
242 restart,
243 None,
244 ),
245 };
246
247 let schema = match schema {
250 Some(schema) => schema,
251 None => bridge.config_schema().await?.settings,
252 };
253 let waits_on = |process: Process| {
254 written.pending_restart.iter().any(|key| {
255 schema
256 .iter()
257 .find(|d| d.key == *key)
258 .map_or(Process::Bridge, |d| d.process)
259 == process
260 })
261 };
262 let (bridge_waits, app_waits) = (waits_on(Process::Bridge), waits_on(Process::App));
263 if !restart {
264 if bridge_waits {
265 println!("restart required: sapphire-bridge");
266 }
267 if app_waits {
268 println!("restart required: {app} server");
269 }
270 return Ok(0);
271 }
272 if !bridge_waits && !app_waits {
273 println!("nothing awaits a restart");
274 return Ok(0);
275 }
276 if bridge_waits {
278 bridge.restart().await?;
280 println!("sapphire-bridge restarted");
281 }
282 if app_waits {
283 restart_app_server(&client, app, version).await?;
284 println!("the {app} server restarted");
285 }
286 Ok(0)
287}
288
289fn has_bridge(schema: &[SettingDef]) -> bool {
292 schema.iter().any(|d| d.process == Process::Bridge)
293}
294
295async fn restart_app_server(client: &sapphire_ipc::Client, app: &str, version: &str) -> Result<()> {
300 let _: proto::Ack = client
301 .call(proto::SERVER_RESTART, serde_json::json!({}))
302 .await?;
303 let endpoint = Endpoint::for_app(app)?;
304 let came_back = async {
305 client.closed().await;
306 loop {
307 if answers(&endpoint, app, version).await {
308 return;
309 }
310 tokio::time::sleep(RESTART_POLL).await;
311 }
312 };
313 tokio::time::timeout(RESTART_TIMEOUT, came_back)
314 .await
315 .map_err(|_| {
316 Error::Config(format!(
317 "the {app} server did not come back within {} s",
318 RESTART_TIMEOUT.as_secs()
319 ))
320 })
321}
322
323async fn answers(endpoint: &Endpoint, app: &str, version: &str) -> bool {
325 let info = ClientInfo {
326 kind: "cli".to_owned(),
327 version: version.to_owned(),
328 api: proto::API_VERSION,
329 app_api: None,
330 pid: std::process::id(),
331 };
332 let Ok(Some((client, _))) = sapphire_ipc::connect_or_absent(endpoint, app, info).await else {
333 return false;
334 };
335 client
336 .call::<_, proto::StatusReport>(proto::SERVER_INFO, serde_json::json!({}))
337 .await
338 .is_ok()
339}
340
341#[derive(Debug)]
345struct Printed {
346 code: i32,
348 out: Vec<String>,
350 err: Vec<String>,
352}
353
354impl Printed {
355 fn ok(out: Vec<String>) -> Printed {
356 Printed {
357 code: 0,
358 out,
359 err: Vec::new(),
360 }
361 }
362
363 fn failed(err: String) -> Printed {
364 Printed {
365 code: 1,
366 out: Vec::new(),
367 err: vec![err],
368 }
369 }
370}
371
372fn offline(
381 ctx: &'static AppContext,
382 owner: Arc<dyn AppSettings>,
383 command: AppConfigCommand,
384 bridge_running: bool,
385) -> Result<Printed> {
386 let app = ctx.app_name;
387 if let AppConfigCommand::Set { restart: true, .. }
390 | AppConfigCommand::Unset { restart: true, .. } = command
391 {
392 return Ok(Printed::failed(format!(
393 "the {app} server is not running; nothing to restart"
394 )));
395 }
396 let (reg, checked) = crate::settings::open_unchecked(ctx, owner)?;
397 let reg = ®
398 let warning = match (&command, checked) {
400 (AppConfigCommand::List { .. } | AppConfigCommand::Get { .. }, Err(e)) => {
401 Some(format!("warning: the {app} server would not start: {e}"))
402 }
403 _ => None,
404 };
405 let warned = |mut printed: Printed| {
406 printed.err.splice(0..0, warning.clone());
407 printed
408 };
409 let bridge_key = |key: &str| {
410 Printed::failed(format!(
411 "the {app} server is not running; start it, or use sapphire-bridge config for {key}"
412 ))
413 };
414 let written = || {
415 Ok(Printed::ok(vec![format!(
416 "the {app} server is not running; it applies these settings when it starts"
417 )]))
418 };
419 match command {
420 AppConfigCommand::List { scope, show_origin } => {
421 let entries = match scope.scope() {
423 Some(Scope::Workgroup) => Vec::new(),
424 scope => list(reg, scope, None)?,
425 };
426 let mut out = sapphire_bridge_api::describe_entries(&entries, show_origin);
427 if scope.scope() != Some(Scope::Workspace) {
429 out.push(if bridge_running {
430 format!("start the {app} server to see sapphire-bridge's settings")
431 } else {
432 BRIDGE_NOT_SHOWN.to_owned()
433 });
434 }
435 Ok(warned(Printed::ok(out)))
436 }
437 AppConfigCommand::Get { key } => {
438 if reg.def(&key).is_err() {
439 return Ok(warned(bridge_key(&key)));
440 }
441 Ok(warned(match get(reg, &key) {
442 Ok(entry) => Printed::ok(sapphire_bridge_api::describe_entries(&[entry], false)),
443 Err(err) => Printed::failed(err.to_string()),
444 }))
445 }
446 AppConfigCommand::Set {
447 entries,
448 scope,
449 stdin,
450 restart: _,
451 } => {
452 let keys = entries
453 .iter()
454 .map(|e| e.split_once('=').map_or(e.as_str(), |(key, _)| key));
455 if let Some(key) = keys.into_iter().find(|key| !own(reg, key)) {
456 return Ok(bridge_key(key));
457 }
458 let entries = sapphire_bridge_api::parse_entries(®.schema(), &entries, stdin)
459 .map_err(Error::Config)?;
460 let ops = entries
461 .into_iter()
462 .map(|e| Op::Set {
463 key: e.key,
464 value: e.value,
465 })
466 .collect();
467 apply(reg, scope.scope(), ops)?;
468 written()
469 }
470 AppConfigCommand::Unset { keys, scope, .. } => {
471 if let Some(key) = keys.iter().find(|key| !own(reg, key)) {
472 return Ok(bridge_key(key));
473 }
474 let ops = keys.into_iter().map(|key| Op::Unset { key }).collect();
475 apply(reg, scope.scope(), ops)?;
476 written()
477 }
478 }
479}
480
481fn own(reg: &Registry, key: &str) -> bool {
483 reg.def(key).is_ok() || !reg.under(key).is_empty()
484}
485
486#[cfg(test)]
487mod tests {
488 use super::*;
489 use clap::Parser;
490
491 #[derive(Parser)]
492 struct Probe {
493 #[command(subcommand)]
494 command: AppConfigCommand,
495 }
496
497 fn parse(args: &[&str]) -> std::result::Result<AppConfigCommand, clap::Error> {
498 Probe::try_parse_from(std::iter::once("config").chain(args.iter().copied()))
499 .map(|p| p.command)
500 }
501
502 #[test]
503 fn each_scope_flag_names_its_scope() {
504 for (flag, scope) in [
505 ("--device", Some(Scope::Device)),
506 ("--workgroup", Some(Scope::Workgroup)),
507 ("--workspace", Some(Scope::Workspace)),
508 ] {
509 let AppConfigCommand::List { scope: flags, .. } = parse(&["list", flag]).unwrap()
510 else {
511 panic!("not list");
512 };
513 assert_eq!(flags.scope(), scope, "{flag}");
514 }
515 let AppConfigCommand::List { scope, .. } = parse(&["list"]).unwrap() else {
516 panic!("not list");
517 };
518 assert_eq!(scope.scope(), None);
519 }
520
521 #[test]
522 fn the_scope_flags_exclude_each_other() {
523 for pair in [
524 ["--device", "--workgroup"],
525 ["--device", "--workspace"],
526 ["--workgroup", "--workspace"],
527 ] {
528 assert!(parse(&["list", pair[0], pair[1]]).is_err(), "{pair:?}");
529 }
530 }
531
532 #[test]
533 fn set_and_unset_take_restart() {
534 assert!(matches!(
535 parse(&["set", "a.b=1", "--restart", "--workspace"]).unwrap(),
536 AppConfigCommand::Set { restart: true, .. }
537 ));
538 assert!(matches!(
539 parse(&["unset", "a.b", "--restart"]).unwrap(),
540 AppConfigCommand::Unset { restart: true, .. }
541 ));
542 assert!(parse(&["set"]).is_err(), "set needs an entry");
543 }
544}