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

            
16
use base64::Engine;
17
use base64::engine::general_purpose::STANDARD as BASE64;
18
use scripting::runtime::{
19
    EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value, read_string_arg,
20
};
21
use server::command::{
22
    CmdError, CmdResult,
23
    config::{GetBuildDate, GetConfig, GetVersion, ListConfig, SetConfig},
24
};
25
use wasmtime::{ArrayRef, Linker, Rooted};
26

            
27
use crate::host_failure::cmd_failure;
28
use crate::natives::args::{present, required};
29
use crate::natives::native::register_native;
30
use crate::session::SessionData;
31

            
32
pub const REGISTERED_COMMANDS: &[&str] = &[
33
    "get-config",
34
    "get-version",
35
    "get-build-date",
36
    "set-config",
37
    "list-config",
38
];
39

            
40
230200
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
41
230200
    register_native(linker, "config_get_version", |caller, ()| {
42
321
        Box::pin(async move {
43
321
            let bytes = command_string("get-version", GetVersion::new().run().await)?;
44
321
            Ok(Some(alloc_string_ref(caller, bytes.as_bytes())?))
45
321
        })
46
321
    })?;
47
230200
    register_native(linker, "config_get_build_date", |caller, ()| {
48
1
        Box::pin(async move {
49
1
            let bytes = command_string("get-build-date", GetBuildDate::new().run().await)?;
50
1
            Ok(Some(alloc_string_ref(caller, bytes.as_bytes())?))
51
1
        })
52
1
    })?;
53
230200
    register_native(
54
230200
        linker,
55
230200
        "config_get_config",
56
14723
        |caller, (name_arg,): (Option<Rooted<ArrayRef>>,)| {
57
14723
            Box::pin(async move {
58
14723
                let user_id = caller.data().ctx().user_id;
59
14723
                let name = read_string_arg(caller, name_arg)?;
60
14723
                let formatted = run_get_config(user_id, name).await?;
61
13441
                Ok(Some(alloc_string_ref(caller, formatted.as_bytes())?))
62
14723
            })
63
14723
        },
64
    )?;
65
230200
    register_native(
66
230200
        linker,
67
230200
        "config_set_config",
68
1281
        |caller, (name_arg, value_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
69
1281
            Box::pin(async move {
70
1281
                let user_id = caller.data().ctx().user_id;
71
1281
                let name = read_string_arg(caller, name_arg)?;
72
1281
                let value = read_string_arg(caller, value_arg)?;
73
1281
                run_set_config(user_id, name, value).await
74
1281
            })
75
1281
        },
76
    )?;
77
230200
    register_native(linker, "config_list_config", |caller, ()| {
78
640
        Box::pin(async move {
79
640
            let user_id = caller.data().ctx().user_id;
80
640
            let plists = run_list_config(user_id).await?;
81
640
            let mut cars = Vec::with_capacity(plists.len());
82
640
            for plist in &plists {
83
960
                cars.push(alloc_value(caller, plist).await?);
84
            }
85
640
            alloc_pair_chain(caller, cars).await
86
640
        })
87
640
    })?;
88
230200
    Ok(())
89
230200
}
90

            
91
/// Every config key as `((:KEY "k" :VALUE "v") …)`.
92
640
async fn run_list_config(user_id: uuid::Uuid) -> wasmtime::Result<Vec<EvalValue>> {
93
640
    match ListConfig::new().user_id(user_id).run().await {
94
        Ok(Some(CmdResult::ConfigEntries(entries))) => {
95
640
            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
640
}
103

            
104
961
fn config_plist((key, value): (String, String)) -> EvalValue {
105
961
    EvalValue::List(vec![
106
961
        EvalValue::Symbol(":KEY".to_string()),
107
961
        EvalValue::String(key),
108
961
        EvalValue::Symbol(":VALUE".to_string()),
109
961
        EvalValue::String(value),
110
961
    ])
111
961
}
112

            
113
1283
async fn run_set_config(
114
1283
    user_id: uuid::Uuid,
115
1283
    name_arg: Option<String>,
116
1283
    value_arg: Option<String>,
117
1283
) -> wasmtime::Result<i32> {
118
1283
    let name = required("set-config", "name", name_arg)?;
119
1282
    let value = present("set-config", "value", value_arg)?;
120
1281
    SetConfig::new()
121
1281
        .user_id(user_id)
122
1281
        .name(name)
123
1281
        .value(value)
124
1281
        .run()
125
1281
        .await
126
        .map(|_| 1)
127
        .map_err(|err| cmd_failure("set-config", err))
128
1283
}
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.
133
14725
async fn run_get_config(user_id: uuid::Uuid, name_arg: Option<String>) -> wasmtime::Result<String> {
134
14725
    let name = required("get-config", "name", name_arg)?;
135
14721
    match GetConfig::new().user_id(user_id).name(name).run().await {
136
1121
        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
12320
        Ok(None) => Ok("(:config-value nil)".to_string()),
144
1280
        Err(err) => Err(cmd_failure("get-config", err)),
145
    }
146
14725
}
147

            
148
1124
fn quote_string(s: &str) -> String {
149
1124
    let mut q = String::with_capacity(s.len() + 2);
150
1124
    q.push('"');
151
1124
    for ch in s.chars() {
152
5295
        match ch {
153
1
            '"' => q.push_str("\\\""),
154
1
            '\\' => q.push_str("\\\\"),
155
5293
            other => q.push(other),
156
        }
157
    }
158
1124
    q.push('"');
159
1124
    q
160
1124
}
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.
167
322
fn command_string(
168
322
    name: &str,
169
322
    result: Result<Option<CmdResult>, CmdError>,
170
322
) -> wasmtime::Result<String> {
171
322
    match result {
172
322
        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
322
}
182

            
183
#[cfg(test)]
184
mod 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
1
    async fn run_get_config_no_arg_returns_error() {
193
1
        let err = run_get_config(TEST_USER, None).await.unwrap_err();
194
1
        assert!(err.to_string().contains("missing or empty"));
195
1
    }
196

            
197
    #[tokio::test]
198
1
    async fn run_get_config_empty_arg_returns_error() {
199
1
        let err = run_get_config(TEST_USER, Some(String::new()))
200
1
            .await
201
            .unwrap_err();
202
1
        assert!(err.to_string().contains("missing or empty"));
203
1
    }
204

            
205
    #[tokio::test]
206
1
    async fn run_set_config_no_name_emits_error() {
207
1
        let err = run_set_config(TEST_USER, None, Some("v".into()))
208
1
            .await
209
            .unwrap_err();
210
1
        assert!(err.to_string().contains(":name"));
211
1
    }
212

            
213
    #[tokio::test]
214
1
    async fn run_set_config_no_value_emits_error() {
215
1
        let err = run_set_config(TEST_USER, Some("k".into()), None)
216
1
            .await
217
            .unwrap_err();
218
1
        assert!(err.to_string().contains(":value"));
219
1
    }
220

            
221
    #[test]
222
1
    fn config_plist_pairs_the_key_with_its_value() {
223
1
        let expected = EvalValue::List(vec![
224
1
            EvalValue::Symbol(":KEY".into()),
225
1
            EvalValue::String("a".into()),
226
1
            EvalValue::Symbol(":VALUE".into()),
227
1
            EvalValue::String("1".into()),
228
1
        ]);
229
1
        assert_eq!(config_plist(("a".into(), "1".into())), expected);
230
1
    }
231

            
232
    #[test]
233
1
    fn quote_string_escapes_quotes_and_backslashes() {
234
1
        assert_eq!(quote_string("plain"), "\"plain\"");
235
1
        assert_eq!(quote_string("a\"b"), "\"a\\\"b\"");
236
1
        assert_eq!(quote_string("c\\d"), "\"c\\\\d\"");
237
1
    }
238
}