Lines
87.92 %
Functions
84.62 %
Branches
100 %
//! Config-domain natives. Wraps `server::command::{GetConfig, GetVersion,
//! GetBuildDate, SetConfig}`.
//!
//! `get-version` and `get-build-date` are the first server-command bindings
//! the rpc layer ships. Both return a `CmdResult::String(...)` from a body
//! that just reads `env!`-baked constants — no DB, no user_id, no real async
//! work — so they exercise the marshalling shape without yet needing a
//! tokio runtime or pool. The remaining commands wait until DB-touching
//! infrastructure (ScriptCtx::pool, sqlx::test fixtures) lands.
//! `select-column` is deliberately NOT exposed here: it runs caller-supplied
//! `field`/`table` against the global admin connection, so a script-callable
//! native would let any authenticated session read outside its user boundary.
//! It stays a CLI-only escape hatch (`sql selcol`, direct dispatch).
use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64;
use scripting::runtime::{
EvalValue, alloc_pair_chain, alloc_string_ref, alloc_value, read_string_arg,
};
use server::command::{
CmdError, CmdResult,
config::{GetBuildDate, GetConfig, GetVersion, ListConfig, SetConfig},
use wasmtime::{ArrayRef, Linker, Rooted};
use crate::host_failure::cmd_failure;
use crate::natives::args::{present, required};
use crate::natives::native::register_native;
use crate::session::SessionData;
pub const REGISTERED_COMMANDS: &[&str] = &[
"get-config",
"get-version",
"get-build-date",
"set-config",
"list-config",
];
pub fn register(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
register_native(linker, "config_get_version", |caller, ()| {
Box::pin(async move {
let bytes = command_string("get-version", GetVersion::new().run().await)?;
Ok(Some(alloc_string_ref(caller, bytes.as_bytes())?))
})
})?;
register_native(linker, "config_get_build_date", |caller, ()| {
let bytes = command_string("get-build-date", GetBuildDate::new().run().await)?;
register_native(
linker,
"config_get_config",
|caller, (name_arg,): (Option<Rooted<ArrayRef>>,)| {
let user_id = caller.data().ctx().user_id;
let name = read_string_arg(caller, name_arg)?;
let formatted = run_get_config(user_id, name).await?;
Ok(Some(alloc_string_ref(caller, formatted.as_bytes())?))
},
)?;
"config_set_config",
|caller, (name_arg, value_arg): (Option<Rooted<ArrayRef>>, Option<Rooted<ArrayRef>>)| {
let value = read_string_arg(caller, value_arg)?;
run_set_config(user_id, name, value).await
register_native(linker, "config_list_config", |caller, ()| {
let plists = run_list_config(user_id).await?;
let mut cars = Vec::with_capacity(plists.len());
for plist in &plists {
cars.push(alloc_value(caller, plist).await?);
}
alloc_pair_chain(caller, cars).await
Ok(())
/// Every config key as `((:KEY "k" :VALUE "v") …)`.
async fn run_list_config(user_id: uuid::Uuid) -> wasmtime::Result<Vec<EvalValue>> {
match ListConfig::new().user_id(user_id).run().await {
Ok(Some(CmdResult::ConfigEntries(entries))) => {
Ok(entries.into_iter().map(config_plist).collect())
Ok(other) => Err(wasmtime::Error::msg(format!(
"list-config: expected config entries, got {other:?}"
))),
Err(err) => Err(cmd_failure("list-config", err)),
fn config_plist((key, value): (String, String)) -> EvalValue {
EvalValue::List(vec![
EvalValue::Symbol(":KEY".to_string()),
EvalValue::String(key),
EvalValue::Symbol(":VALUE".to_string()),
EvalValue::String(value),
])
async fn run_set_config(
user_id: uuid::Uuid,
name_arg: Option<String>,
value_arg: Option<String>,
) -> wasmtime::Result<i32> {
let name = required("set-config", "name", name_arg)?;
let value = present("set-config", "value", value_arg)?;
SetConfig::new()
.user_id(user_id)
.name(name)
.value(value)
.run()
.await
.map(|_| 1)
.map_err(|err| cmd_failure("set-config", err))
/// Returns `(:config-value <val>)` on success, or propagates a
/// `wasmtime::Error` on any validation/command failure. The rpc envelope
/// layer turns traps into `(:id N :error ...)` responses.
async fn run_get_config(user_id: uuid::Uuid, name_arg: Option<String>) -> wasmtime::Result<String> {
let name = required("get-config", "name", name_arg)?;
match GetConfig::new().user_id(user_id).name(name).run().await {
Ok(Some(CmdResult::String(s))) => Ok(format!("(:config-value {})", quote_string(&s))),
Ok(Some(CmdResult::Data(bytes))) => {
Ok(format!("(:config-value #\"{}\")", BASE64.encode(&bytes)))
Ok(Some(other)) => Err(wasmtime::Error::msg(format!(
"get-config: expected String/Data, got {other:?}"
Ok(None) => Ok("(:config-value nil)".to_string()),
Err(err) => Err(cmd_failure("get-config", err)),
fn quote_string(s: &str) -> String {
let mut q = String::with_capacity(s.len() + 2);
q.push('"');
for ch in s.chars() {
match ch {
'"' => q.push_str("\\\""),
'\\' => q.push_str("\\\\"),
other => q.push(other),
q
/// Unwraps a `CmdResult::String(_)` result and surfaces every other shape
/// (Data/None/Err) as a `wasmtime::Error`. The rpc envelope layer catches
/// the trap and renders the `:error` form; callers compose the natives
/// expecting a typed `StringRef`, so anything else is a hard failure at
/// the point of use.
fn command_string(
name: &str,
result: Result<Option<CmdResult>, CmdError>,
) -> wasmtime::Result<String> {
match result {
Ok(Some(CmdResult::String(s))) => Ok(s),
"{name}: expected String result, got {other:?}"
Ok(None) => Err(wasmtime::Error::msg(format!(
"{name}: command returned no result"
Err(err) => Err(cmd_failure(name, err)),
#[cfg(test)]
mod tests {
use super::*;
// Arg-validation runs before any DB/user lookup, so a placeholder user id
// is fine here.
const TEST_USER: uuid::Uuid = uuid::Uuid::nil();
#[tokio::test]
async fn run_get_config_no_arg_returns_error() {
let err = run_get_config(TEST_USER, None).await.unwrap_err();
assert!(err.to_string().contains("missing or empty"));
async fn run_get_config_empty_arg_returns_error() {
let err = run_get_config(TEST_USER, Some(String::new()))
.unwrap_err();
async fn run_set_config_no_name_emits_error() {
let err = run_set_config(TEST_USER, None, Some("v".into()))
assert!(err.to_string().contains(":name"));
async fn run_set_config_no_value_emits_error() {
let err = run_set_config(TEST_USER, Some("k".into()), None)
assert!(err.to_string().contains(":value"));
#[test]
fn config_plist_pairs_the_key_with_its_value() {
let expected = EvalValue::List(vec![
EvalValue::Symbol(":KEY".into()),
EvalValue::String("a".into()),
EvalValue::Symbol(":VALUE".into()),
EvalValue::String("1".into()),
]);
assert_eq!(config_plist(("a".into(), "1".into())), expected);
fn quote_string_escapes_quotes_and_backslashes() {
assert_eq!(quote_string("plain"), "\"plain\"");
assert_eq!(quote_string("a\"b"), "\"a\\\"b\"");
assert_eq!(quote_string("c\\d"), "\"c\\\\d\"");