plexus_core/plexus/config/
activation.rs1use async_stream::stream;
26use futures::Stream;
27use schemars::JsonSchema;
28use serde::{Deserialize, Serialize};
29use serde_json::Value;
30
31use super::{current_actor, parse_duration, Config, ConfigChange, ConfigError, KeyInfo, Source};
32use crate::plexus::AuthContext;
33
34pub const CRITICAL_GRANT: &str = "config.critical";
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
41#[serde(rename_all = "snake_case")]
42pub enum ConfigRefusal {
43 UnknownKey,
45 NotAKey,
47 Invalid,
50 NotRemote,
52 Critical,
54 ConfirmRequired,
56 NothingToConfirm,
58 Store,
60}
61
62#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
64#[serde(tag = "type", rename_all = "snake_case")]
65pub enum SettingEvent {
66 Setting(KeyInfo),
68 Set {
71 key: String,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 previous: Option<Value>,
74 previous_hash: String,
75 previous_source: Source,
76 setting: KeyInfo,
77 },
78 Reset { setting: KeyInfo },
80 Confirmed { key: String },
82 Refused { reason: ConfigRefusal, key: String, message: String },
84 Error { message: String },
86}
87
88impl plexus_client::FromClientError for SettingEvent {
89 fn from_client_error(e: plexus_client::ClientError) -> Self {
90 SettingEvent::Error { message: e.to_string() }
91 }
92}
93
94fn refused(reason: ConfigRefusal, key: &str, message: impl Into<String>) -> SettingEvent {
95 SettingEvent::Refused { reason, key: key.into(), message: message.into() }
96}
97
98fn of_error(e: ConfigError) -> SettingEvent {
99 let reason = match &e {
100 ConfigError::Unknown { keys, .. } if !keys.is_empty() => ConfigRefusal::NotAKey,
101 ConfigError::Unknown { .. } => ConfigRefusal::UnknownKey,
102 ConfigError::Invalid { .. } => ConfigRefusal::Invalid,
103 ConfigError::NothingToConfirm { .. } => ConfigRefusal::NothingToConfirm,
104 ConfigError::Store { .. } => ConfigRefusal::Store,
105 };
106 let key = match &e {
107 ConfigError::Unknown { key, .. } | ConfigError::Invalid { key, .. } | ConfigError::NothingToConfirm { key } => key.clone(),
108 ConfigError::Store { .. } => String::new(),
109 };
110 refused(reason, &key, e.to_string())
111}
112
113fn names_below(config: &Config, prefix: &str) -> Vec<String> {
115 let mut out: Vec<String> = config
116 .keys()
117 .into_iter()
118 .filter_map(|k| {
119 let rest = if prefix.is_empty() { Some(k.as_str()) } else { k.strip_prefix(prefix).and_then(|r| r.strip_prefix('.')) }?;
120 Some(rest.split('.').next().unwrap_or(rest).to_string())
121 })
122 .collect();
123 out.dedup();
124 out
125}
126
127#[derive(Clone)]
129pub struct ConfigActivation {
130 config: Config,
131}
132
133impl ConfigActivation {
134 pub fn new(config: Config) -> Self {
138 Self { config }
139 }
140
141 pub fn config(&self) -> &Config {
143 &self.config
144 }
145
146 fn node(&self, name: &str) -> Option<ConfigKeyActivation> {
147 let path = name.to_string();
148 let prefix = format!("{path}.");
149 self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
150 }
151}
152
153#[plexus_macros::activation(namespace = "config", description = "A service's settings at runtime: each key a node, on its own grant")]
156impl ConfigActivation {
157 #[plexus_macros::method]
159 pub async fn list(&self) -> impl Stream<Item = KeyInfo> + Send + 'static {
160 futures::stream::iter(self.config.list())
161 }
162
163 #[plexus_macros::method]
166 pub async fn watch(&self, key: Option<String>) -> impl Stream<Item = ConfigChange> + Send + 'static {
167 let mut rx = self.config.changes();
168 stream! {
169 loop {
170 match rx.recv().await {
171 Ok(c) => {
172 if key.as_deref().is_none_or(|k| c.key == k || c.key.starts_with(&format!("{k}."))) {
173 yield c;
174 }
175 }
176 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
177 Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
178 }
179 }
180 }
181 }
182
183 #[plexus_macros::method]
185 pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
186 futures::stream::iter(names_below(&self.config, ""))
187 }
188
189 #[plexus_macros::child(list = names)]
191 fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
192 self.node(name)
193 }
194}
195
196#[derive(Clone)]
199pub struct ConfigKeyActivation {
200 config: Config,
201 path: String,
202}
203
204impl ConfigKeyActivation {
205 pub fn path(&self) -> &str {
207 &self.path
208 }
209
210 fn is_key(&self) -> Result<(bool, bool), SettingEvent> {
211 match self.config.flags(&self.path) {
212 Some(f) => Ok(f),
213 None => Err(of_error(ConfigError::Unknown { key: self.path.clone(), keys: self.config.keys().into_iter().filter(|k| k.starts_with(&format!("{}.", self.path))).collect() })),
214 }
215 }
216
217 fn may_write(&self, auth: Option<&AuthContext>, confirming: Option<bool>) -> Result<(), SettingEvent> {
221 let (remote, critical) = self.is_key()?;
222 let refuse = |reason, why: String| {
223 self.config.refused(&self.path, current_actor(), &why);
224 Err(refused(reason, &self.path, why))
225 };
226 if !remote {
227 return refuse(ConfigRefusal::NotRemote, format!("`{}` is not settable over the wire: the host's code or its file sets it", self.path));
228 }
229 if critical {
230 if !holds_critical(auth) {
231 return refuse(ConfigRefusal::Critical, format!("`{}` is critical: an admin's (the grant `{CRITICAL_GRANT}`)", self.path));
232 }
233 if confirming == Some(false) {
234 return refuse(ConfigRefusal::ConfirmRequired, format!("`{}` is critical: set it with confirm_within (a confirmed commit), then confirm", self.path));
235 }
236 }
237 Ok(())
238 }
239
240 fn info(&self) -> KeyInfo {
241 self.config.info(&self.path).expect("a key")
242 }
243}
244
245fn holds_critical(auth: Option<&AuthContext>) -> bool {
248 let gate = crate::plexus::service_scope::current().and_then(|w| w.upgrade()).and_then(|s| s.gate().cloned());
249 match gate {
250 None => match crate::call::context() {
254 Ok(ctx) if ctx.hop().is_some() => ctx.reach().is_some_and(|r| r.is_everywhere()),
255 _ => true,
256 },
257 Some(g) => g.check_everywhere(auth, &plexus_auth_core::grants::Grant::new(CRITICAL_GRANT)).is_ok(),
259 }
260}
261
262pub const EVERYWHERE: &[&str] = &["set", "reset", "confirm"];
265
266pub(crate) fn require_everywhere() -> Result<(), String> {
268 let schema = <ConfigKeyActivation as crate::plexus::Activation>::slot_schema()
269 .ok_or_else(|| "config_key: no schema to check".to_string())?;
270 crate::plexus::grant_gate::require_everywhere(&schema, EVERYWHERE)
271}
272
273#[plexus_macros::activation(namespace = "config_key", description = "A setting: get, set, reset, confirm")]
275impl ConfigKeyActivation {
276 #[plexus_macros::method]
279 pub async fn get(&self) -> SettingEvent {
280 match self.is_key() {
281 Ok(_) => SettingEvent::Setting(self.info()),
282 Err(e) => e,
283 }
284 }
285
286 #[plexus_macros::method(everywhere)]
292 pub async fn set(&self, auth: Option<&AuthContext>, value: Value, confirm_within: Option<String>) -> SettingEvent {
293 let within = match confirm_within.as_deref().map(parse_duration).transpose() {
294 Ok(w) => w,
295 Err(why) => return refused(ConfigRefusal::Invalid, &self.path, format!("confirm_within: {why}")),
296 };
297 if let Err(e) = self.may_write(auth, Some(within.is_some())) {
298 return e;
299 }
300 match self.config.set_value(&self.path, value, within, current_actor()) {
301 Ok((previous, previous_source)) => {
302 let setting = self.info();
303 let secret = setting.value.is_none();
304 let previous_hash = if secret { String::new() } else { crate::plexus::content_hash::hash16(crate::plexus::content_hash::canonical_json(&previous).as_bytes()) };
305 SettingEvent::Set { key: self.path.clone(), previous: (!secret).then_some(previous), previous_hash, previous_source, setting }
306 }
307 Err(e) => of_error(e),
308 }
309 }
310
311 #[plexus_macros::method(everywhere)]
314 pub async fn reset(&self, auth: Option<&AuthContext>) -> SettingEvent {
315 if let Err(e) = self.may_write(auth, None) {
316 return e;
317 }
318 match self.config.reset_key(&self.path, current_actor()) {
319 Ok(()) => SettingEvent::Reset { setting: self.info() },
320 Err(e) => of_error(e),
321 }
322 }
323
324 #[plexus_macros::method(everywhere)]
326 pub async fn confirm(&self, auth: Option<&AuthContext>) -> SettingEvent {
327 if let Err(e) = self.may_write(auth, None) {
328 return e;
329 }
330 match self.config.confirm(&self.path, current_actor()) {
331 Ok(()) => SettingEvent::Confirmed { key: self.path.clone() },
332 Err(e) => of_error(e),
333 }
334 }
335
336 #[plexus_macros::method]
338 pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
339 futures::stream::iter(names_below(&self.config, &self.path))
340 }
341
342 #[plexus_macros::child(list = names)]
344 fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
345 let path = format!("{}.{name}", self.path);
346 let prefix = format!("{path}.");
347 self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
348 }
349}