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 => true,
251 Some(g) => g.check(auth, &plexus_auth_core::grants::Grant::new(CRITICAL_GRANT), None).is_ok(),
252 }
253}
254
255#[plexus_macros::activation(namespace = "config_key", description = "A setting: get, set, reset, confirm")]
257impl ConfigKeyActivation {
258 #[plexus_macros::method]
261 pub async fn get(&self) -> SettingEvent {
262 match self.is_key() {
263 Ok(_) => SettingEvent::Setting(self.info()),
264 Err(e) => e,
265 }
266 }
267
268 #[plexus_macros::method]
274 pub async fn set(&self, auth: Option<&AuthContext>, value: Value, confirm_within: Option<String>) -> SettingEvent {
275 let within = match confirm_within.as_deref().map(parse_duration).transpose() {
276 Ok(w) => w,
277 Err(why) => return refused(ConfigRefusal::Invalid, &self.path, format!("confirm_within: {why}")),
278 };
279 if let Err(e) = self.may_write(auth, Some(within.is_some())) {
280 return e;
281 }
282 match self.config.set_value(&self.path, value, within, current_actor()) {
283 Ok((previous, previous_source)) => {
284 let setting = self.info();
285 let secret = setting.value.is_none();
286 let previous_hash = if secret { String::new() } else { crate::plexus::content_hash::hash16(crate::plexus::content_hash::canonical_json(&previous).as_bytes()) };
287 SettingEvent::Set { key: self.path.clone(), previous: (!secret).then_some(previous), previous_hash, previous_source, setting }
288 }
289 Err(e) => of_error(e),
290 }
291 }
292
293 #[plexus_macros::method]
296 pub async fn reset(&self, auth: Option<&AuthContext>) -> SettingEvent {
297 if let Err(e) = self.may_write(auth, None) {
298 return e;
299 }
300 match self.config.reset_key(&self.path, current_actor()) {
301 Ok(()) => SettingEvent::Reset { setting: self.info() },
302 Err(e) => of_error(e),
303 }
304 }
305
306 #[plexus_macros::method]
308 pub async fn confirm(&self, auth: Option<&AuthContext>) -> SettingEvent {
309 if let Err(e) = self.may_write(auth, None) {
310 return e;
311 }
312 match self.config.confirm(&self.path, current_actor()) {
313 Ok(()) => SettingEvent::Confirmed { key: self.path.clone() },
314 Err(e) => of_error(e),
315 }
316 }
317
318 #[plexus_macros::method]
320 pub async fn names(&self) -> impl Stream<Item = String> + Send + 'static {
321 futures::stream::iter(names_below(&self.config, &self.path))
322 }
323
324 #[plexus_macros::child(list = names)]
326 fn key(&self, name: &str) -> Option<ConfigKeyActivation> {
327 let path = format!("{}.{name}", self.path);
328 let prefix = format!("{path}.");
329 self.config.keys().iter().any(|k| *k == path || k.starts_with(&prefix)).then(|| ConfigKeyActivation { config: self.config.clone(), path })
330 }
331}