refactor: close resource request dispatch and enforce core inventories

This commit is contained in:
cflmy committed 2026-11-22 20:26:26 +08:00
1 parent 099ff8ba02
commit 995f6026c9
5 files changed
+780 -731

No files matched your search

+32
View File
@@ -569,3 +569,35 @@ fn dispatch() -> i32 {
} }
} }
} }
#[cfg(test)]
#[test]
fn top_level_commands_are_reviewed() {
use clap::CommandFactory;
let cli = Cli::command();
let mut names: Vec<_> = cli
.get_subcommands()
.map(|command| command.get_name())
.collect();
names.sort_unstable();
assert_eq!(
names,
[
"__plugin-worker",
"add",
"call",
"check",
"fmt",
"init",
"inspect",
"lock",
"plugin",
"remove",
"run",
"sync",
"tool"
],
"review changes under ADR-0064"
);
}
+116 -116
View File
@@ -314,26 +314,90 @@ fn callable_binding_is_the_only_static_resolution_path() {
); );
} }
/// RFC-EXT-0001 §14.2/S4: no business-domain builtin or host-op branch may be /// ADR-0064 freezes the core catalogue until a new language primitive is reviewed.
/// added for an ecosystem feature. These must be implemented as `.mq.md`,
/// plugin exports or provider streams.
#[test] #[test]
fn no_business_domain_builtins_or_host_ops() { fn builtin_names_and_aliases_are_reviewed() {
let root = repo_root(); let builtins = marqdo_ir::builtins::BUILTINS;
let builtins = read(&root.join("crates/marqdo-ir/src/builtins.rs")); let mut names: Vec<_> = builtins
let host = read(&root.join("crates/marqdo-host/src/host.rs")); .iter()
for forbidden in ["quantum.", "ai.chat", "vendor.", "demo.sensor", "marqdo."] { .flat_map(|builtin| std::iter::once(builtin.name).chain(builtin.aliases.iter().copied()))
assert!( .collect();
!builtins.contains(forbidden), names.sort_unstable();
"business builtin namespace `{forbidden}` must not exist" assert_eq!(
); names,
} [
assert!( "float",
!host.contains("\"demo.sensor\""), "foreign.call",
"provider kinds must be data, not host-op string branches" "foreign.run",
"fs.read",
"fs.write",
"int",
"len",
"list.append",
"list.concat",
"map.get",
"map.has",
"map.keys",
"map.remove",
"map.set",
"memory.grow",
"memory.new",
"memory.size",
"print",
"ref",
"resource.accept",
"resource.close",
"resource.open",
"resource.read",
"resource.request",
"resource.write",
"str",
"table",
"table.cell",
"table.columns",
"table.row",
"text.codepoints",
"text.from_codepoint",
"type",
"小数",
"打印",
"整数",
"文本",
"类型",
"表",
"长度",
],
"review changes under ADR-0064"
); );
} }
// Exhaustive matches make a new HostOp or Value variant require review under ADR-0064.
const _: fn(marqdo_host::HostOp) = |operation| match operation {
marqdo_host::HostOp::ForeignRun
| marqdo_host::HostOp::ForeignCall
| marqdo_host::HostOp::FsRead
| marqdo_host::HostOp::FsWrite
| marqdo_host::HostOp::PluginInvoke => (),
};
const _: fn(marqdo_value::Value) = |value| match value {
marqdo_value::Value::Unit
| marqdo_value::Value::None
| marqdo_value::Value::Bool(_)
| marqdo_value::Value::Int(_)
| marqdo_value::Value::Float(_)
| marqdo_value::Value::Text(_)
| marqdo_value::Value::List(_)
| marqdo_value::Value::Map(_)
| marqdo_value::Value::Table(_)
| marqdo_value::Value::Formula(_)
| marqdo_value::Value::Code(_)
| marqdo_value::Value::FunctionRef(_)
| marqdo_value::Value::PluginHandle(_)
| marqdo_value::Value::Memory(_)
| marqdo_value::Value::Resource(_) => (),
};
/// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not /// RFC-EXT-0001 §8: official stdlib public aliases are verified metadata, not
/// hard-coded runtime names. Recompute the canonical metadata digest. /// hard-coded runtime names. Recompute the canonical metadata digest.
#[test] #[test]
@@ -386,110 +450,46 @@ fn official_stdlib_public_aliases_are_verified_metadata() {
} }
} }
/// Reviewed ownership of every `Host::resource_request` operation /// The outer match in the compatibility dispatcher is the operation catalogue.
/// (`docs/architecture/resource-operations.md`, ADR-0062).
///
/// The gate extracts the literal operation names dispatched inside
/// `resource_request` and compares them with this reviewed allowlist. Adding a new
/// domain operation requires updating the architecture doc, the ADR and this list —
/// a bare source change cannot silently widen the core/resource boundary.
#[test] #[test]
fn resource_request_operation_allowlist_is_reviewed() { fn resource_request_operation_allowlist_is_reviewed() {
use std::collections::BTreeSet; let source = read(&repo_root().join("crates/marqdo-host/src/host/resource_requests.rs"));
let dispatch = source
const DOMAIN_OPERATIONS: &[&str] = &[ .split_once(" match operation {\n")
"process.run", .expect("closed operation dispatch")
"regex.match", .1
"regex.captures", .split_once("\n _ =>")
"compress.gzip", .expect("unknown operations must reach a rejection arm")
"compress.gunzip", .0;
"random.bytes", let mut names: Vec<_> = dispatch
"env.get", .lines()
"clock.now", .filter_map(|line| line.strip_prefix(" "))
]; .filter(|line| line.starts_with('"') || line.starts_with('|'))
const FS_OPERATIONS: &[&str] = &[ .flat_map(|line| line.split('"').skip(1).step_by(2))
"read_at", "append", "walk", "exists", "metadata", "list", "mkdir", "remove", "rename",
];
let source = read(&repo_root().join("crates/marqdo-host/src/host.rs"));
let impl_start = source
.find("impl Host for StdHost {")
.expect("StdHost must implement Host");
let start = source[impl_start..]
.find(" fn resource_request(")
.expect("StdHost::resource_request must exist")
+ impl_start;
let rest = &source[start + 1..];
let end = rest
.find("\n fn consume_fuel(")
.expect("resource_request must end before consume_fuel");
let body = &rest[..end];
let mut domain = BTreeSet::new();
for line in body.lines() {
let mut cursor = line;
while let Some(index) = cursor.find("operation == \"") {
let text = &cursor[index + "operation == \"".len()..];
let name = text.split('"').next().expect("operation literal");
domain.insert(name.to_string());
cursor = &text[name.len()..];
}
}
let expected_domain: BTreeSet<String> = DOMAIN_OPERATIONS
.iter()
.map(|name| (*name).to_string())
.collect(); .collect();
names.sort_unstable();
assert_eq!( assert_eq!(
domain, expected_domain, names,
"new/changed resource_request domain operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist" [
); "clock.now",
"compress.gunzip",
assert!( "compress.gzip",
body.contains("strip_prefix(\"fs.\")"), "env.get",
"the fs.* operation group must stay the only unprefixed dispatch path" "fs.append",
); "fs.exists",
let mut fs = BTreeSet::new(); "fs.list",
for line in body.lines() { "fs.metadata",
let mut cursor = line; "fs.mkdir",
while let Some(index) = cursor.find("name == \"") { "fs.read_at",
let text = &cursor[index + "name == \"".len()..]; "fs.remove",
let name = text.split('"').next().expect("fs operation literal"); "fs.rename",
fs.insert(name.to_string()); "fs.walk",
cursor = &text[name.len()..]; "process.run",
} "random.bytes",
} "regex.captures",
// The remaining fs operations are grouped in the arity match block. "regex.match",
let arity_start = body ],
.find("let expected = match name {") "review changes under ADR-0062 and ADR-0064"
.expect("fs arity match block");
let arity_end = body[arity_start..]
.find(" };")
.expect("fs arity match block end");
for line in body[arity_start..arity_start + arity_end].lines() {
let Some(arrow) = line.find("=>") else {
continue;
};
let mut in_quote = false;
let mut name = String::new();
for ch in line[..arrow].chars() {
if ch == '"' {
if in_quote && !name.is_empty() {
fs.insert(name.clone());
}
name.clear();
in_quote = !in_quote;
} else if in_quote {
name.push(ch);
}
}
}
let expected_fs: BTreeSet<String> = FS_OPERATIONS
.iter()
.map(|name| (*name).to_string())
.collect();
assert_eq!(
fs, expected_fs,
"new/changed fs.* resource operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist"
); );
} }
+3 -613
View File
@@ -5,10 +5,9 @@
//! execution, not at parse/compile time. //! execution, not at parse/compile time.
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket}; use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use std::time::{Duration, Instant};
use marqdo_plugin_abi::{ use marqdo_plugin_abi::{
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest, ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
@@ -39,6 +38,7 @@ mod dispatch;
mod effects; mod effects;
mod providers; mod providers;
mod resource_ops; mod resource_ops;
mod resource_requests;
/// Host operations reachable from the language surface. /// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -751,14 +751,6 @@ impl StdHost {
} }
} }
fn result_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
impl Host for StdHost { impl Host for StdHost {
fn invoke( fn invoke(
&mut self, &mut self,
@@ -911,609 +903,7 @@ impl Host for StdHost {
args: Vec<Value>, args: Vec<Value>,
ctx: &ExecutionContext, ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> { ) -> Result<Value, RuntimeError> {
let started = Instant::now(); self.request_compatibility_operation(operation, args, ctx)
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource operations are available only in project mode",
));
}
if args.iter().any(Value::contains_memory) || args.iter().any(Value::contains_resource) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"resource operations accept only Text path arguments",
));
}
if operation == "process.run" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `process.run` expects 2 arguments, got {}",
args.len()
),
));
}
let program_type = args[0].type_name();
let Value::Text(program) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a Text program, got {program_type}"
),
));
};
let args_type = args[1].type_name();
let Value::List(values) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a List of Text arguments, got {args_type}"
),
));
};
let mut program_args = Vec::with_capacity(values.len());
for value in values {
let value_type = value.type_name();
let Value::Text(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!("process arguments must be Text, got {value_type}"),
));
};
program_args.push(value);
}
self.capabilities.check_process(&program, ctx.span)?;
let result = crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
return Ok(result);
}
if operation == "regex.match" || operation == "regex.captures" {
if operation == "regex.match" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `regex.match` expects 2 arguments, got {}",
args.len()
),
));
}
} else if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `regex.captures` expects 2 arguments, got {}",
args.len()
),
));
}
let pattern_type = args[0].type_name();
let Value::Text(pattern) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} pattern must be Text, got {pattern_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} text must be Text, got {text_type}"),
));
};
let regex = match regex::Regex::new(&pattern) {
Ok(regex) => regex,
Err(error) => {
return Ok(result_error(
"regex.invalid",
&format!("invalid regular expression: {error}"),
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" {
map.insert("value".to_string(), Value::Bool(regex.is_match(&text)));
} else {
let mut payload = BTreeMap::new();
let captures = regex.captures(&text);
payload.insert("matched".to_string(), Value::Bool(captures.is_some()));
let groups = match captures {
Some(captures) => captures
.iter()
.map(|group| match group {
Some(group) => Value::text(group.as_str()),
None => Value::None,
})
.collect(),
None => Vec::new(),
};
payload.insert("groups".to_string(), Value::List(groups));
map.insert("value".to_string(), Value::Map(payload));
}
return Ok(Value::Map(map));
}
if operation == "compress.gzip" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gzip` expects 1 argument, got {}",
args.len()
),
));
}
let text_type = args[0].type_name();
let Value::Text(text) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gzip expects Text, got {text_type}"),
));
};
if text.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gzip input exceeds 8 MiB",
));
}
let mut encoder =
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(text.as_bytes()).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let bytes = encoder.finish().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
return Ok(Value::Map(map));
}
if operation == "compress.gunzip" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gunzip` expects 1 argument, got {}",
args.len()
),
));
}
let list_type = args[0].type_name();
let Value::List(values) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gunzip expects List<Int>, got {list_type}"),
));
};
if values.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gunzip input exceeds 8 MiB",
));
}
let mut bytes = Vec::with_capacity(values.len());
for value in values {
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
"compress.gunzip bytes must be Int",
));
};
let Some(byte) = value.to_string().parse::<u8>().ok() else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("`{value}` is not a byte in 0..=255"),
));
};
bytes.push(byte);
}
let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
let mut output = Vec::new();
if let Err(error) = decoder
.by_ref()
.take(8 * 1024 * 1024 + 1)
.read_to_end(&mut output)
{
return Ok(result_error(
"compress.invalid",
&format!("gunzip failed: {error}"),
));
}
if output.len() > 8 * 1024 * 1024 {
return Ok(result_error(
"compress.too_large",
"gunzip output exceeds 8 MiB",
));
}
let text = match String::from_utf8(output) {
Ok(text) => text,
Err(_) => {
return Ok(result_error(
"compress.not_utf8",
"gunzip output is not UTF-8",
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text));
return Ok(Value::Map(map));
}
if operation == "random.bytes" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `random.bytes` expects 1 argument, got {}",
args.len()
),
));
}
let count = match &args[0] {
Value::Int(value) => value
.to_string()
.parse::<usize>()
.ok()
.filter(|count| (1..=65536).contains(count)),
_ => None,
};
let Some(count) = count else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
"random.bytes requires an Int in 1..=65536",
));
};
self.capabilities.check_random(ctx.span)?;
let mut bytes = vec![0u8; count];
getrandom::fill(&mut bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("OS entropy is unavailable: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
return Ok(Value::Map(map));
}
if operation == "env.get" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `env.get` expects 1 argument, got {}",
args.len()
),
));
}
let value_type = args[0].type_name();
let Value::Text(name) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("resource operation `env.get` expects a Text name, got {value_type}"),
));
};
self.capabilities.check_env(&name, ctx.span)?;
let mut map = BTreeMap::new();
match std::env::var(&name) {
Ok(value) => {
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(value));
}
Err(std::env::VarError::NotPresent) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_found"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not set")),
);
}
Err(std::env::VarError::NotUnicode(_)) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_unicode"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not valid UTF-8")),
);
}
}
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
return Ok(Value::Map(map));
}
if operation == "clock.now" {
if !args.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `clock.now` expects 0 arguments, got {}",
args.len()
),
));
}
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("system clock is before the Unix epoch: {error}"),
)
})?
.as_millis()
.min(i64::MAX as u128) as i64;
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis));
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
return Ok(Value::Map(map));
}
let Some(name) = operation.strip_prefix("fs.") else {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("unsupported resource operation `{operation}`"),
));
};
if name == "read_at" {
if args.len() != 3 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.read_at` expects 3 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at path must be Text, got {path_type}"),
));
};
let offset = match &args[1] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at offset must be Int, got {}", other.type_name()),
))
}
};
let length = match &args[2] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at length must be Int, got {}", other.type_name()),
))
}
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self
.fs
.request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
return Ok(result);
}
if name == "append" {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.append` expects 2 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append path must be Text, got {path_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append text must be Text, got {text_type}"),
));
};
self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
return Ok(result);
}
if name == "walk" {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.walk` expects 1 argument, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.walk path must be Text, got {path_type}"),
));
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
return Ok(result);
}
let expected = match name {
"exists" | "metadata" | "list" | "mkdir" | "remove" => 1,
"rename" => 2,
other => {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
format!("unsupported filesystem operation `{other}`"),
))
}
};
if args.len() != expected {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects {expected} argument(s), got {}",
args.len()
),
));
}
let mut paths = Vec::with_capacity(args.len());
for value in args {
let value_type = value.type_name();
let Value::Text(path) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `{operation}` expects Text paths, got {value_type}"
),
));
};
paths.push(path);
}
match name {
"exists" | "metadata" | "list" => {
self.capabilities.check_read(&paths[0], ctx.span)?;
}
"mkdir" | "remove" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
}
"rename" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
self.capabilities.check_write(&paths[1], ctx.span)?;
}
_ => unreachable!(),
}
let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect("resource.request", ctx, started, &format!("fs.{name}"));
Ok(result)
} }
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> { fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
@@ -0,0 +1,626 @@
//! Closed compatibility catalogue for non-streaming resource operations (ADR-0062).
use std::collections::BTreeMap;
use std::io::{Read, Write};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value};
impl StdHost {
pub(super) fn request_compatibility_operation(
&mut self,
operation: &str,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
let started = Instant::now();
if self.mode != SandboxMode::Project {
return Err(RuntimeError::new(
ErrorCategory::PermissionDenied,
ctx.span,
"resource operations are available only in project mode",
));
}
if args.iter().any(Value::contains_memory) || args.iter().any(Value::contains_resource) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
"resource operations accept only Text path arguments",
));
}
match operation {
"process.run" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `process.run` expects 2 arguments, got {}",
args.len()
),
));
}
let program_type = args[0].type_name();
let Value::Text(program) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a Text program, got {program_type}"
),
));
};
let args_type = args[1].type_name();
let Value::List(values) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `process.run` expects a List of Text arguments, got {args_type}"
),
));
};
let mut program_args = Vec::with_capacity(values.len());
for value in values {
let value_type = value.type_name();
let Value::Text(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!("process arguments must be Text, got {value_type}"),
));
};
program_args.push(value);
}
self.capabilities.check_process(&program, ctx.span)?;
let result =
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=process.run"),
);
self.record_resource_effect("resource.request", ctx, started, "process.run");
Ok(result)
}
"regex.match" | "regex.captures" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects 2 arguments, got {}",
args.len()
),
));
}
let pattern_type = args[0].type_name();
let Value::Text(pattern) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} pattern must be Text, got {pattern_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("{operation} text must be Text, got {text_type}"),
));
};
let regex = match regex::Regex::new(&pattern) {
Ok(regex) => regex,
Err(error) => {
return Ok(result_error(
"regex.invalid",
&format!("invalid regular expression: {error}"),
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(operation),
);
self.record_resource_effect("resource.request", ctx, started, operation);
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
if operation == "regex.match" {
map.insert("value".to_string(), Value::Bool(regex.is_match(&text)));
} else {
let mut payload = BTreeMap::new();
let captures = regex.captures(&text);
payload.insert("matched".to_string(), Value::Bool(captures.is_some()));
let groups = match captures {
Some(captures) => captures
.iter()
.map(|group| match group {
Some(group) => Value::text(group.as_str()),
None => Value::None,
})
.collect(),
None => Vec::new(),
};
payload.insert("groups".to_string(), Value::List(groups));
map.insert("value".to_string(), Value::Map(payload));
}
Ok(Value::Map(map))
}
"compress.gzip" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gzip` expects 1 argument, got {}",
args.len()
),
));
}
let text_type = args[0].type_name();
let Value::Text(text) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gzip expects Text, got {text_type}"),
));
};
if text.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gzip input exceeds 8 MiB",
));
}
let mut encoder =
flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
encoder.write_all(text.as_bytes()).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let bytes = encoder.finish().map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("gzip failed: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
Ok(Value::Map(map))
}
"compress.gunzip" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `compress.gunzip` expects 1 argument, got {}",
args.len()
),
));
}
let list_type = args[0].type_name();
let Value::List(values) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("compress.gunzip expects List<Int>, got {list_type}"),
));
};
if values.len() > 8 * 1024 * 1024 {
return Err(RuntimeError::new(
ErrorCategory::ResourceExhausted,
ctx.span,
"compress.gunzip input exceeds 8 MiB",
));
}
let mut bytes = Vec::with_capacity(values.len());
for value in values {
let Value::Int(value) = value else {
return Err(RuntimeError::type_error(
ctx.span,
"compress.gunzip bytes must be Int",
));
};
let Some(byte) = value.to_string().parse::<u8>().ok() else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
format!("`{value}` is not a byte in 0..=255"),
));
};
bytes.push(byte);
}
let mut decoder = flate2::read::GzDecoder::new(bytes.as_slice());
let mut output = Vec::new();
if let Err(error) = decoder
.by_ref()
.take(8 * 1024 * 1024 + 1)
.read_to_end(&mut output)
{
return Ok(result_error(
"compress.invalid",
&format!("gunzip failed: {error}"),
));
}
if output.len() > 8 * 1024 * 1024 {
return Ok(result_error(
"compress.too_large",
"gunzip output exceeds 8 MiB",
));
}
let text = match String::from_utf8(output) {
Ok(text) => text,
Err(_) => {
return Ok(result_error(
"compress.not_utf8",
"gunzip output is not UTF-8",
))
}
};
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=compress.gunzip"),
);
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(text));
Ok(Value::Map(map))
}
"random.bytes" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `random.bytes` expects 1 argument, got {}",
args.len()
),
));
}
let count = match &args[0] {
Value::Int(value) => value
.to_string()
.parse::<usize>()
.ok()
.filter(|count| (1..=65536).contains(count)),
_ => None,
};
let Some(count) = count else {
return Err(RuntimeError::new(
ErrorCategory::Type,
ctx.span,
"random.bytes requires an Int in 1..=65536",
));
};
self.capabilities.check_random(ctx.span)?;
let mut bytes = vec![0u8; count];
getrandom::fill(&mut bytes).map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("OS entropy is unavailable: {error}"),
)
})?;
let values = bytes
.into_iter()
.map(|byte| Value::int(byte as i64))
.collect();
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=random.bytes"),
);
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::List(values));
Ok(Value::Map(map))
}
"env.get" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `env.get` expects 1 argument, got {}",
args.len()
),
));
}
let value_type = args[0].type_name();
let Value::Text(name) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `env.get` expects a Text name, got {value_type}"
),
));
};
self.capabilities.check_env(&name, ctx.span)?;
let mut map = BTreeMap::new();
match std::env::var(&name) {
Ok(value) => {
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::text(value));
}
Err(std::env::VarError::NotPresent) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_found"));
map.insert(
"message".to_string(),
Value::text(format!("environment variable `{name}` is not set")),
);
}
Err(std::env::VarError::NotUnicode(_)) => {
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text("env.not_unicode"));
map.insert(
"message".to_string(),
Value::text(format!(
"environment variable `{name}` is not valid UTF-8"
)),
);
}
}
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=env.get"),
);
self.record_resource_effect("resource.request", ctx, started, "env.get");
Ok(Value::Map(map))
}
"clock.now" => {
if !args.is_empty() {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `clock.now` expects 0 arguments, got {}",
args.len()
),
));
}
let millis = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(|error| {
RuntimeError::new(
ErrorCategory::HostError,
ctx.span,
format!("system clock is before the Unix epoch: {error}"),
)
})?
.as_millis()
.min(i64::MAX as u128) as i64;
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(true));
map.insert("value".to_string(), Value::int(millis));
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=clock.now"),
);
self.record_resource_effect("resource.request", ctx, started, "clock.now");
Ok(Value::Map(map))
}
"fs.read_at" => {
if args.len() != 3 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.read_at` expects 3 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at path must be Text, got {path_type}"),
));
};
let offset = match &args[1] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at offset must be Int, got {}", other.type_name()),
))
}
};
let length = match &args[2] {
Value::Int(value) => value.to_string(),
other => {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.read_at length must be Int, got {}", other.type_name()),
))
}
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self
.fs
.request("read_at", &[path, offset, length], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.read_at"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
Ok(result)
}
"fs.append" => {
if args.len() != 2 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.append` expects 2 arguments, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append path must be Text, got {path_type}"),
));
};
let text_type = args[1].type_name();
let Value::Text(text) = args[1].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.append text must be Text, got {text_type}"),
));
};
self.capabilities.check_write(&path, ctx.span)?;
let result = self.fs.request("append", &[path, text], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.append"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.append");
Ok(result)
}
"fs.walk" => {
if args.len() != 1 {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `fs.walk` expects 1 argument, got {}",
args.len()
),
));
}
let path_type = args[0].type_name();
let Value::Text(path) = args[0].clone() else {
return Err(RuntimeError::type_error(
ctx.span,
format!("fs.walk path must be Text, got {path_type}"),
));
};
self.capabilities.check_read(&path, ctx.span)?;
let result = self.fs.request("walk", &[path], ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some("op=fs.walk"),
);
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
Ok(result)
}
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
let name = &operation["fs.".len()..];
let expected = if name == "rename" { 2 } else { 1 };
if args.len() != expected {
return Err(RuntimeError::new(
ErrorCategory::Arity,
ctx.span,
format!(
"resource operation `{operation}` expects {expected} argument(s), got {}",
args.len()
),
));
}
let mut paths = Vec::with_capacity(args.len());
for value in args {
let value_type = value.type_name();
let Value::Text(path) = value else {
return Err(RuntimeError::type_error(
ctx.span,
format!(
"resource operation `{operation}` expects Text paths, got {value_type}"
),
));
};
paths.push(path);
}
match name {
"exists" | "metadata" | "list" => {
self.capabilities.check_read(&paths[0], ctx.span)?;
}
"mkdir" | "remove" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
}
"rename" => {
self.capabilities.check_write(&paths[0], ctx.span)?;
self.capabilities.check_write(&paths[1], ctx.span)?;
}
_ => unreachable!(),
}
let result = self.fs.request(name, &paths, ctx.span)?;
self.record_semantic(
"resource.request",
None,
Some(&ctx.module_id),
ctx.span,
Some(&format!("op=fs.{name}")),
);
self.record_resource_effect(
"resource.request",
ctx,
started,
&format!("fs.{name}"),
);
Ok(result)
}
_ => {
let message = match operation.strip_prefix("fs.") {
Some(name) => format!("unsupported filesystem operation `{name}`"),
None => format!("unsupported resource operation `{operation}`"),
};
Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
ctx.span,
message,
))
}
}
}
}
fn result_error(code: &str, message: &str) -> Value {
let mut map = BTreeMap::new();
map.insert("ok".to_string(), Value::Bool(false));
map.insert("code".to_string(), Value::text(code));
map.insert("message".to_string(), Value::text(message));
Value::Map(map)
}
+3 -2
View File
@@ -14,8 +14,9 @@ extracts the literals from the host source and fails on any unreviewed change.
- `Memory`/resource handles never cross this API; path arguments are `Text`. - `Memory`/resource handles never cross this API; path arguments are `Text`.
- Operation-level grants are checked before any host action (`check_process`, - Operation-level grants are checked before any host action (`check_process`,
`check_read`, `check_write`, `check_entropy`, `check_env`, network grants). `check_read`, `check_write`, `check_entropy`, `check_env`, network grants).
- The `fs.*` family is the only prefix-dispatched group; its sub-operations are - The compatibility dispatcher matches exact names in
listed explicitly below. `crates/marqdo-host/src/host/resource_requests.rs`. The `fs.` prefix only
distinguishes unknown-operation diagnostics.
## Reviewed operation table ## Reviewed operation table