Skip to main content

rpc/natives/
config.rs

1//! Config-domain natives. Wraps `server::command::{GetConfig, GetVersion,
2//! GetBuildDate, SetConfig}`.
3//!
4//! `get-version` and `get-build-date` are the first server-command bindings
5//! the rpc layer ships. Both return a `CmdResult::String(...)` from a body
6//! that just reads `env!`-baked constants — no DB, no user_id, no real async
7//! work — so they exercise the marshalling shape without yet needing a
8//! tokio runtime or pool. The remaining commands wait until DB-touching
9//! infrastructure (ScriptCtx::pool, sqlx::test fixtures) lands.
10//!
11//! `select-column` is deliberately NOT exposed here: it runs caller-supplied
12//! `field`/`table` against the global admin connection, so a script-callable
13//! native would let any authenticated session read outside its user boundary.
14//! It stays a CLI-only escape hatch (`sql selcol`, direct dispatch).
15
16use base64::Engine;
17use base64::engine::general_purpose::STANDARD as BASE64;
18use scripting::runtime::{
19    EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value, read_string_arg,
20};
21use server::command::{
22    CmdError, CmdResult,
23    config::{GetBuildDate, GetConfig, GetVersion, ListConfig, SetConfig},
24};
25use wasmtime::{ArrayRef, Linker, Rooted};
26
27use crate::host_failure::cmd_failure;
28use crate::natives::args::{present, required};
29use crate::natives::native::register_native;
30use crate::session::SessionData;
31
32pub const REGISTERED_COMMANDS: &[&str] = &[
33    "get-config",
34    "get-version",
35    "get-build-date",
36    "set-config",
37    "list-config",
38];
39
40pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
41    register_native(linker, "config_get_version", |caller, ()| {
42        Box::pin(async move {
43            let bytes = command_string("get-version", GetVersion::new().run().await)?;
44            Ok(Some(alloc_string_ref(caller, bytes.as_bytes())?))
45        })
46    })?;
47    register_native(linker, "config_get_build_date", |caller, ()| {
48        Box::pin(async move {
49            let bytes = command_string("get-build-date", GetBuildDate::new().run().await)?;
50            Ok(Some(alloc_string_ref(caller, bytes.as_bytes())?))
51        })
52    })?;
53    register_native(
54        linker,
55        "config_get_config",
56        |caller, (name_arg,): (Option<Rooted<ArrayRef>>,)| {
57            Box::pin(async move {
58                let user_id = caller.data().ctx().user_id;
59                let name = read_string_arg(caller, name_arg)?;
60                let formatted = run_get_config(user_id, name).await?;
61                Ok(Some(alloc_string_ref(caller, formatted.as_bytes())?))
62            })
63        },
64    )?;
65    register_native(
66        linker,
67        "config_set_config",
68        |caller, (name_arg, value_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
69            Box::pin(async move {
70                let user_id = caller.data().ctx().user_id;
71                let name = read_string_arg(caller, name_arg)?;
72                let value = read_string_arg(caller, value_arg)?;
73                run_set_config(user_id, name, value).await
74            })
75        },
76    )?;
77    register_native(linker, "config_list_config", |caller, ()| {
78        Box::pin(async move {
79            let user_id = caller.data().ctx().user_id;
80            let plists = run_list_config(user_id).await?;
81            let mut cars = Vec::with_capacity(plists.len());
82            for plist in &plists {
83                cars.push(alloc_value(caller, plist).await?);
84            }
85            alloc_pair_chain(caller, cars).await
86        })
87    })?;
88    Ok(())
89}
90
91/// Every config key as `((:KEY "k" :VALUE "v") …)`.
92async fn run_list_config(user_id: uuid::Uuid) -> wasmtime::Result<Vec<EvalValue>> {
93    match ListConfig::new().user_id(user_id).run().await {
94        Ok(Some(CmdResult::ConfigEntries(entries))) => {
95            Ok(entries.into_iter().map(config_plist).collect())
96        }
97        Ok(other) => Err(wasmtime::Error::msg(format!(
98            "list-config: expected config entries, got {other:?}"
99        ))),
100        Err(err) => Err(cmd_failure("list-config", err)),
101    }
102}
103
104fn config_plist((key, value): (String, String)) -> EvalValue {
105    EvalValue::List(vec![
106        EvalValue::Symbol(":KEY".to_string()),
107        EvalValue::String(key),
108        EvalValue::Symbol(":VALUE".to_string()),
109        EvalValue::String(value),
110    ])
111}
112
113async fn run_set_config(
114    user_id: uuid::Uuid,
115    name_arg: Option<String>,
116    value_arg: Option<String>,
117) -> wasmtime::Result<i32> {
118    let name = required("set-config", "name", name_arg)?;
119    let value = present("set-config", "value", value_arg)?;
120    SetConfig::new()
121        .user_id(user_id)
122        .name(name)
123        .value(value)
124        .run()
125        .await
126        .map(|_| 1)
127        .map_err(|err| cmd_failure("set-config", err))
128}
129
130/// Returns `(:config-value <val>)` on success, or propagates a
131/// `wasmtime::Error` on any validation/command failure. The rpc envelope
132/// layer turns traps into `(:id N :error ...)` responses.
133async fn run_get_config(user_id: uuid::Uuid, name_arg: Option<String>) -> wasmtime::Result<String> {
134    let name = required("get-config", "name", name_arg)?;
135    match GetConfig::new().user_id(user_id).name(name).run().await {
136        Ok(Some(CmdResult::String(s))) => Ok(format!("(:config-value {})", quote_string(&s))),
137        Ok(Some(CmdResult::Data(bytes))) => {
138            Ok(format!("(:config-value #\"{}\")", BASE64.encode(&bytes)))
139        }
140        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
141            "get-config: expected String/Data, got {other:?}"
142        ))),
143        Ok(None) => Ok("(:config-value nil)".to_string()),
144        Err(err) => Err(cmd_failure("get-config", err)),
145    }
146}
147
148fn quote_string(s: &str) -> String {
149    let mut q = String::with_capacity(s.len() + 2);
150    q.push('"');
151    for ch in s.chars() {
152        match ch {
153            '"' => q.push_str("\\\""),
154            '\\' => q.push_str("\\\\"),
155            other => q.push(other),
156        }
157    }
158    q.push('"');
159    q
160}
161
162/// Unwraps a `CmdResult::String(_)` result and surfaces every other shape
163/// (Data/None/Err) as a `wasmtime::Error`. The rpc envelope layer catches
164/// the trap and renders the `:error` form; callers compose the natives
165/// expecting a typed `StringRef`, so anything else is a hard failure at
166/// the point of use.
167fn command_string(
168    name: &str,
169    result: Result<Option<CmdResult>, CmdError>,
170) -> wasmtime::Result<String> {
171    match result {
172        Ok(Some(CmdResult::String(s))) => Ok(s),
173        Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
174            "{name}: expected String result, got {other:?}"
175        ))),
176        Ok(None) => Err(wasmtime::Error::msg(format!(
177            "{name}: command returned no result"
178        ))),
179        Err(err) => Err(cmd_failure(name, err)),
180    }
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    // Arg-validation runs before any DB/user lookup, so a placeholder user id
188    // is fine here.
189    const TEST_USER: uuid::Uuid = uuid::Uuid::nil();
190
191    #[tokio::test]
192    async fn run_get_config_no_arg_returns_error() {
193        let err = run_get_config(TEST_USER, None).await.unwrap_err();
194        assert!(err.to_string().contains("missing or empty"));
195    }
196
197    #[tokio::test]
198    async fn run_get_config_empty_arg_returns_error() {
199        let err = run_get_config(TEST_USER, Some(String::new()))
200            .await
201            .unwrap_err();
202        assert!(err.to_string().contains("missing or empty"));
203    }
204
205    #[tokio::test]
206    async fn run_set_config_no_name_emits_error() {
207        let err = run_set_config(TEST_USER, None, Some("v".into()))
208            .await
209            .unwrap_err();
210        assert!(err.to_string().contains(":name"));
211    }
212
213    #[tokio::test]
214    async fn run_set_config_no_value_emits_error() {
215        let err = run_set_config(TEST_USER, Some("k".into()), None)
216            .await
217            .unwrap_err();
218        assert!(err.to_string().contains(":value"));
219    }
220
221    #[test]
222    fn config_plist_pairs_the_key_with_its_value() {
223        let expected = EvalValue::List(vec![
224            EvalValue::Symbol(":KEY".into()),
225            EvalValue::String("a".into()),
226            EvalValue::Symbol(":VALUE".into()),
227            EvalValue::String("1".into()),
228        ]);
229        assert_eq!(config_plist(("a".into(), "1".into())), expected);
230    }
231
232    #[test]
233    fn quote_string_escapes_quotes_and_backslashes() {
234        assert_eq!(quote_string("plain"), "\"plain\"");
235        assert_eq!(quote_string("a\"b"), "\"a\\\"b\"");
236        assert_eq!(quote_string("c\\d"), "\"c\\\\d\"");
237    }
238}