feat(rfc-cm): baseline P0-P3 compute machine, stdlib and resource slices
Implements the first vertical slices of RFC-CM-0001/0002 on top of a113d89:
- P1: opaque Memory regions (64 KiB pages, budgets, grow-only), byte
read/write, Memory-index place assignment, wire/host-boundary rejection.
- CM-A04/A05: value-semantics List/Map/Text/Table primitives and the
recoverable Result map convention.
- CM-A06: opaque Resource handles, resource.open/read/write/close, stdout
write, granted project-file read and buffered write, strict fail-closed.
- CM-A07 Compat-A: explicit .mq.md format/utf8/io chain matching builtin
print for the covered value types; builtin remains default.
- P2 fixtures: allocators, list/tree/graph/hash, integer codecs, UTF-8
encode/decode, CSV/JSON subsets, table filter/sort/join, bytecode VM.
- ADRs 0022-0027, spec updates, evidence reports and 68 semantic goldens.
Gate: cargo fmt --check, clippy -D warnings, 407 tests passed.
This commit is contained in:
1 parent
a113d89496
commit
92bfbf2568
127 files changed
+11351
-141
No files matched your search
@@ -83,6 +83,22 @@ impl ProjectFs {
|
||||
|
||||
/// Read a UTF-8 file, bounded by [`MAX_READ_BYTES`].
|
||||
pub fn read(&self, user_path: &str, span: Option<Span>) -> Result<String, RuntimeError> {
|
||||
let bytes = self.read_bytes(user_path, span)?;
|
||||
String::from_utf8(bytes).map_err(|_| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
span,
|
||||
format!("`{user_path}` is not valid UTF-8"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Read a file as raw bytes, bounded by [`MAX_READ_BYTES`].
|
||||
///
|
||||
/// Used by the resource stream provider; path/capability checks are the
|
||||
/// caller's responsibility for grants, while this method still rejects
|
||||
/// traversal and symlink escapes.
|
||||
pub fn read_bytes(&self, user_path: &str, span: Option<Span>) -> Result<Vec<u8>, RuntimeError> {
|
||||
let (absolute, relative) = self.resolve(user_path, span)?;
|
||||
let metadata = std::fs::metadata(&absolute).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
@@ -118,19 +134,12 @@ impl ProjectFs {
|
||||
if !canonical.starts_with(&self.root) {
|
||||
return Err(invalid_path(span, "path escapes the project root"));
|
||||
}
|
||||
let bytes = std::fs::read(&canonical).map_err(|error| {
|
||||
std::fs::read(&canonical).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
format!("cannot read `{relative}`: {error}"),
|
||||
)
|
||||
})?;
|
||||
String::from_utf8(bytes).map_err(|_| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
span,
|
||||
format!("`{relative}` is not valid UTF-8"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -140,6 +149,18 @@ impl ProjectFs {
|
||||
user_path: &str,
|
||||
contents: &str,
|
||||
span: Option<Span>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
self.write_bytes(user_path, contents.as_bytes(), span)
|
||||
}
|
||||
|
||||
/// Write raw bytes inside the project root, creating parent directories.
|
||||
///
|
||||
/// This is a single validated write, not a transactional replace.
|
||||
pub fn write_bytes(
|
||||
&self,
|
||||
user_path: &str,
|
||||
bytes: &[u8],
|
||||
span: Option<Span>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let (absolute, relative) = self.resolve(user_path, span)?;
|
||||
// Validate the closest existing ancestor stays inside the root.
|
||||
@@ -169,7 +190,7 @@ impl ProjectFs {
|
||||
)
|
||||
})?;
|
||||
}
|
||||
std::fs::write(&absolute, contents).map_err(|error| {
|
||||
std::fs::write(&absolute, bytes).map_err(|error| {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::HostError,
|
||||
span,
|
||||
|
||||
@@ -12,7 +12,7 @@ use marqdo_plugin_abi::{
|
||||
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
|
||||
};
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError, Value};
|
||||
|
||||
use crate::budget::Budget;
|
||||
use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
||||
@@ -20,6 +20,7 @@ use crate::context::ExecutionContext;
|
||||
use crate::fs::ProjectFs;
|
||||
use crate::handles::{contains_plugin_handle, PluginHandleTable};
|
||||
use crate::plugin_worker::WorkerPlugin;
|
||||
use crate::resource::{ResourceRead, ResourceTable};
|
||||
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
|
||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
||||
|
||||
@@ -79,6 +80,65 @@ pub trait Host {
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError>;
|
||||
|
||||
/// Open a resource/stream by kind, descriptor and requested rights.
|
||||
///
|
||||
/// Default: unavailable. Only the standard host implements the first
|
||||
/// resource kinds (ADR-0025).
|
||||
fn resource_open(
|
||||
&mut self,
|
||||
_kind: &str,
|
||||
_descriptor: &str,
|
||||
_rights: &[String],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide resource streams",
|
||||
))
|
||||
}
|
||||
|
||||
/// Read up to `max_bytes` from a resource into host memory.
|
||||
fn resource_read(
|
||||
&mut self,
|
||||
_handle: ResourceHandle,
|
||||
_max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<ResourceRead, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide resource streams",
|
||||
))
|
||||
}
|
||||
|
||||
/// Write bytes to a resource; returns the accepted count.
|
||||
fn resource_write(
|
||||
&mut self,
|
||||
_handle: ResourceHandle,
|
||||
_bytes: &[u8],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide resource streams",
|
||||
))
|
||||
}
|
||||
|
||||
/// Close a resource handle.
|
||||
fn resource_close(
|
||||
&mut self,
|
||||
_handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<(), RuntimeError> {
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"this host does not provide resource streams",
|
||||
))
|
||||
}
|
||||
|
||||
/// Consume evaluation fuel.
|
||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError>;
|
||||
|
||||
@@ -143,6 +203,8 @@ pub struct StdHost {
|
||||
broker_audit: Arc<Mutex<Vec<CapabilityAudit>>>,
|
||||
/// Host-issued opaque plugin handles.
|
||||
pub handles: PluginHandleTable,
|
||||
/// Host-owned resource/stream table (ADR-0025).
|
||||
resources: ResourceTable,
|
||||
semantic_events: Vec<SemanticEvent>,
|
||||
next_event_seq: u64,
|
||||
trace_state: TraceState,
|
||||
@@ -203,6 +265,7 @@ impl StdHost {
|
||||
vendor_capabilities: BTreeSet::new(),
|
||||
broker_audit: Arc::new(Mutex::new(Vec::new())),
|
||||
handles: PluginHandleTable::default(),
|
||||
resources: ResourceTable::new(),
|
||||
semantic_events: Vec::new(),
|
||||
next_event_seq: 0,
|
||||
trace_state: TraceState::default(),
|
||||
@@ -526,6 +589,96 @@ impl StdHost {
|
||||
self.fs.write(&path, &contents, ctx.span)?;
|
||||
Ok(Value::Unit)
|
||||
}
|
||||
|
||||
fn open_resource_stream(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
descriptor: &str,
|
||||
rights: &[String],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
if self.mode == SandboxMode::Strict {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"resource streams are not verified in strict mode and are refused",
|
||||
));
|
||||
}
|
||||
if self.mode == SandboxMode::Pure && kind == "file" {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"pure mode does not provide project file resources",
|
||||
));
|
||||
}
|
||||
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
|
||||
match kind {
|
||||
"stdio" => {
|
||||
if descriptor != "stdout" || requested != BTreeSet::from(["write"]) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"the first stream slice supports only stdio/stdout with rights [write]",
|
||||
));
|
||||
}
|
||||
if !self.capabilities.console {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
ctx.span,
|
||||
"the console capability is required for stdio/stdout",
|
||||
));
|
||||
}
|
||||
let handle = self.resources.open_stdout();
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=stdio descriptor=stdout"),
|
||||
);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"file" => {
|
||||
if requested == BTreeSet::from(["read"]) {
|
||||
self.capabilities.check_read(descriptor, ctx.span)?;
|
||||
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
|
||||
let bytes = self.fs.read_bytes(descriptor, ctx.span)?;
|
||||
let handle = self.resources.open_file(relative, bytes);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=file rights=read"),
|
||||
);
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
if requested == BTreeSet::from(["write"]) {
|
||||
self.capabilities.check_write(descriptor, ctx.span)?;
|
||||
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
|
||||
let handle = self.resources.open_file_writer(relative);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=file rights=write"),
|
||||
);
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
"project file streams support exactly [read] or [write] in this build",
|
||||
))
|
||||
}
|
||||
other => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
ctx.span,
|
||||
format!("resource kind `{other}` is not implemented in this build"),
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Host for StdHost {
|
||||
@@ -535,6 +688,31 @@ impl Host for StdHost {
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
// Addressable memory is language-local state. Handles must not reach a
|
||||
// plugin, foreign kernel or file adapter, where they could not be
|
||||
// interpreted safely (RFC-CM-0001 §8, ADR-0022 §4).
|
||||
if args.iter().any(Value::contains_memory) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Memory values cannot cross the host boundary (`{}`); copy bytes into \
|
||||
Text explicitly first",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
if args.iter().any(Value::contains_resource) {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Type,
|
||||
ctx.span,
|
||||
format!(
|
||||
"Resource handles cannot cross the generic host boundary (`{}`); use \
|
||||
resource.* operations",
|
||||
op.name()
|
||||
),
|
||||
));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = self.dispatch(op, args, ctx);
|
||||
let summary = match &result {
|
||||
@@ -562,6 +740,84 @@ impl Host for StdHost {
|
||||
result
|
||||
}
|
||||
|
||||
fn resource_open(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
descriptor: &str,
|
||||
rights: &[String],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
self.open_resource_stream(kind, descriptor, rights, ctx)
|
||||
}
|
||||
|
||||
fn resource_read(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<ResourceRead, RuntimeError> {
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let read = self.resources.read(handle, max_bytes, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.read",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!(
|
||||
"kind={kind} count={} eof={}",
|
||||
read.bytes.len(),
|
||||
read.eof
|
||||
)),
|
||||
);
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
fn resource_write(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
bytes: &[u8],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let count = self.resources.write(handle, bytes, ctx.span)?;
|
||||
if kind == "stdio" {
|
||||
self.budget.consume_output(count, ctx.span)?;
|
||||
self.output.extend_from_slice(bytes);
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.write",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind={kind} count={count}")),
|
||||
);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
fn resource_close(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let pending = self.resources.pending_file_write(handle, ctx.span)?;
|
||||
let count = match pending {
|
||||
Some((relative, bytes)) => {
|
||||
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
|
||||
bytes.len()
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
self.resources.close(handle, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.close",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("flushed_bytes={count}")),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
|
||||
self.budget.consume_fuel(amount, span)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ pub mod handles;
|
||||
pub mod host;
|
||||
pub mod kernels;
|
||||
mod plugin_worker;
|
||||
pub mod resource;
|
||||
pub mod trace;
|
||||
|
||||
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
|
||||
@@ -21,4 +22,5 @@ pub use fs::ProjectFs;
|
||||
pub use handles::{contains_plugin_handle, PluginHandleTable};
|
||||
pub use host::{arity, expect_text, Host, HostOp, StdHost};
|
||||
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
|
||||
pub use resource::{ResourceRead, ResourceTable};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Host-owned resource/stream table (ADR-0025).
|
||||
//!
|
||||
//! The first slice deliberately supports only stdout writes and bounded
|
||||
//! project-file reads loaded at open. Handles are run-scoped and opaque; the
|
||||
//! table validates run identity, slot identity and generation on every call.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
|
||||
|
||||
static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// Bytes returned by one stream read.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResourceRead {
|
||||
/// Bytes actually read (may be empty at EOF).
|
||||
pub bytes: Vec<u8>,
|
||||
/// Whether the stream has reached EOF.
|
||||
pub eof: bool,
|
||||
}
|
||||
|
||||
enum Stream {
|
||||
Stdout {
|
||||
closed: bool,
|
||||
},
|
||||
File {
|
||||
relative: String,
|
||||
bytes: Vec<u8>,
|
||||
position: usize,
|
||||
closed: bool,
|
||||
},
|
||||
FileWriter {
|
||||
relative: String,
|
||||
bytes: Vec<u8>,
|
||||
closed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
generation: u64,
|
||||
stream: Stream,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
fn closed(&self) -> bool {
|
||||
match &self.stream {
|
||||
Stream::Stdout { closed } => *closed,
|
||||
Stream::File { closed, .. } => *closed,
|
||||
Stream::FileWriter { closed, .. } => *closed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Host resource table for one run.
|
||||
pub struct ResourceTable {
|
||||
run_id: u64,
|
||||
next_resource: u64,
|
||||
slots: BTreeMap<u64, Slot>,
|
||||
}
|
||||
|
||||
impl Default for ResourceTable {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ResourceTable {
|
||||
/// Create an empty table with a fresh run identity.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
run_id: NEXT_RUN_ID.fetch_add(1, Ordering::Relaxed),
|
||||
next_resource: 1,
|
||||
slots: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Number of live (not necessarily open) slots.
|
||||
pub fn slot_count(&self) -> usize {
|
||||
self.slots.len()
|
||||
}
|
||||
|
||||
/// Register the pre-opened stdout stream.
|
||||
pub fn open_stdout(&mut self) -> ResourceHandle {
|
||||
self.insert(Stream::Stdout { closed: false })
|
||||
}
|
||||
|
||||
/// Register a project-file read stream opened from already-bounded bytes.
|
||||
pub fn open_file(&mut self, relative: impl Into<String>, bytes: Vec<u8>) -> ResourceHandle {
|
||||
self.insert(Stream::File {
|
||||
relative: relative.into(),
|
||||
bytes,
|
||||
position: 0,
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Register an empty buffered project-file write stream.
|
||||
pub fn open_file_writer(&mut self, relative: impl Into<String>) -> ResourceHandle {
|
||||
self.insert(Stream::FileWriter {
|
||||
relative: relative.into(),
|
||||
bytes: Vec::new(),
|
||||
closed: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn insert(&mut self, stream: Stream) -> ResourceHandle {
|
||||
let id = self.next_resource;
|
||||
self.next_resource += 1;
|
||||
self.slots.insert(
|
||||
id,
|
||||
Slot {
|
||||
generation: 1,
|
||||
stream,
|
||||
},
|
||||
);
|
||||
ResourceHandle::from_host(self.run_id, id, 1)
|
||||
}
|
||||
|
||||
fn slot(&self, handle: ResourceHandle, span: Option<Span>) -> Result<&Slot, RuntimeError> {
|
||||
if handle.run_id() != self.run_id {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceFault,
|
||||
span,
|
||||
"Resource handle belongs to a different host run",
|
||||
));
|
||||
}
|
||||
let Some(slot) = self.slots.get(&handle.resource_id()) else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceFault,
|
||||
span,
|
||||
"unknown Resource handle",
|
||||
));
|
||||
};
|
||||
if slot.generation != handle.generation() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceFault,
|
||||
span,
|
||||
"stale Resource handle",
|
||||
));
|
||||
}
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn slot_mut(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
span: Option<Span>,
|
||||
) -> Result<&mut Slot, RuntimeError> {
|
||||
self.slot(handle, span)?;
|
||||
self.slots
|
||||
.get_mut(&handle.resource_id())
|
||||
.ok_or_else(|| unknown_handle(span))
|
||||
}
|
||||
|
||||
/// Read up to `max_bytes` from a file stream.
|
||||
///
|
||||
/// Reads at EOF return `count=0, eof=true`. A read on a closed stream is
|
||||
/// `resource.closed`; stdout is not readable.
|
||||
pub fn read(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
max_bytes: usize,
|
||||
span: Option<Span>,
|
||||
) -> Result<ResourceRead, RuntimeError> {
|
||||
let slot = self.slot_mut(handle, span)?;
|
||||
if slot.closed() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceClosed,
|
||||
span,
|
||||
"Resource handle is closed",
|
||||
));
|
||||
}
|
||||
match &mut slot.stream {
|
||||
Stream::File {
|
||||
bytes, position, ..
|
||||
} => {
|
||||
let start = *position;
|
||||
let end = start.saturating_add(max_bytes).min(bytes.len());
|
||||
let chunk = bytes[start..end].to_vec();
|
||||
*position = end;
|
||||
Ok(ResourceRead {
|
||||
bytes: chunk,
|
||||
eof: end >= bytes.len(),
|
||||
})
|
||||
}
|
||||
Stream::Stdout { .. } => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
"stdout does not support resource.read",
|
||||
)),
|
||||
Stream::FileWriter { .. } => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
"a file write stream does not support resource.read",
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate a stdout write and return the accepted byte count.
|
||||
///
|
||||
/// The caller performs the output-budget accounting and buffer append; this
|
||||
/// method only checks handle identity, closed state and stream kind.
|
||||
pub fn write(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
bytes: &[u8],
|
||||
span: Option<Span>,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
let slot = self.slot_mut(handle, span)?;
|
||||
if slot.closed() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceClosed,
|
||||
span,
|
||||
"Resource handle is closed",
|
||||
));
|
||||
}
|
||||
match &mut slot.stream {
|
||||
Stream::Stdout { .. } => Ok(bytes.len()),
|
||||
Stream::File { relative, .. } => Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceUnsupported,
|
||||
span,
|
||||
format!("project file `{relative}` was opened read-only"),
|
||||
)),
|
||||
Stream::FileWriter {
|
||||
relative,
|
||||
bytes: buffer,
|
||||
..
|
||||
} => {
|
||||
let next = buffer.len().checked_add(bytes.len());
|
||||
let Some(next) = next else {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
format!("file write buffer for `{relative}` overflows"),
|
||||
));
|
||||
};
|
||||
if next > crate::fs::MAX_READ_BYTES as usize {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceExhausted,
|
||||
span,
|
||||
format!(
|
||||
"file write buffer for `{relative}` exceeds the {} byte limit",
|
||||
crate::fs::MAX_READ_BYTES
|
||||
),
|
||||
));
|
||||
}
|
||||
buffer.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Close a stream. A second close is `resource.closed`.
|
||||
pub fn close(
|
||||
&mut self,
|
||||
handle: ResourceHandle,
|
||||
span: Option<Span>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let slot = self.slot_mut(handle, span)?;
|
||||
if slot.closed() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceClosed,
|
||||
span,
|
||||
"Resource handle is already closed",
|
||||
));
|
||||
}
|
||||
match &mut slot.stream {
|
||||
Stream::Stdout { closed } => *closed = true,
|
||||
Stream::File { closed, .. } => *closed = true,
|
||||
Stream::FileWriter { closed, .. } => *closed = true,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the buffered bytes of a file write stream without closing it.
|
||||
///
|
||||
/// `None` means the handle is not a file writer (stdout or a reader). The
|
||||
/// caller must call [`Self::close`] only after the flush succeeds, so a
|
||||
/// failed flush leaves the writer open with its buffer intact.
|
||||
pub fn pending_file_write(
|
||||
&self,
|
||||
handle: ResourceHandle,
|
||||
span: Option<Span>,
|
||||
) -> Result<Option<(String, Vec<u8>)>, RuntimeError> {
|
||||
let slot = self.slot(handle, span)?;
|
||||
if slot.closed() {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::ResourceClosed,
|
||||
span,
|
||||
"Resource handle is closed",
|
||||
));
|
||||
}
|
||||
match &slot.stream {
|
||||
Stream::FileWriter {
|
||||
relative, bytes, ..
|
||||
} => Ok(Some((relative.clone(), bytes.clone()))),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Descriptor kind for diagnostics/trace, if the handle is valid.
|
||||
pub fn kind(
|
||||
&self,
|
||||
handle: ResourceHandle,
|
||||
span: Option<Span>,
|
||||
) -> Result<&'static str, RuntimeError> {
|
||||
let slot = self.slot(handle, span)?;
|
||||
Ok(match slot.stream {
|
||||
Stream::Stdout { .. } => "stdio",
|
||||
Stream::File { .. } | Stream::FileWriter { .. } => "file",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn unknown_handle(span: Option<Span>) -> RuntimeError {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::ResourceFault,
|
||||
span,
|
||||
"unknown Resource handle",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn file_reads_are_chunked_with_eof() {
|
||||
let mut table = ResourceTable::new();
|
||||
let handle = table.open_file("data.txt", b"abcdef".to_vec());
|
||||
assert_eq!(
|
||||
table.read(handle, 2, None).unwrap(),
|
||||
ResourceRead {
|
||||
bytes: b"ab".to_vec(),
|
||||
eof: false
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
table.read(handle, 8, None).unwrap(),
|
||||
ResourceRead {
|
||||
bytes: b"cdef".to_vec(),
|
||||
eof: true
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
table.read(handle, 1, None).unwrap(),
|
||||
ResourceRead {
|
||||
bytes: Vec::new(),
|
||||
eof: true
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forged_and_closed_handles_are_rejected() {
|
||||
let mut table = ResourceTable::new();
|
||||
let handle = table.open_stdout();
|
||||
let forged = ResourceHandle::from_host(handle.run_id() + 1, handle.resource_id(), 1);
|
||||
assert_eq!(
|
||||
table.write(forged, b"x", None).unwrap_err().code(),
|
||||
"runtime.resource"
|
||||
);
|
||||
table.close(handle, None).unwrap();
|
||||
assert_eq!(
|
||||
table.write(handle, b"x", None).unwrap_err().code(),
|
||||
"resource.closed"
|
||||
);
|
||||
assert_eq!(
|
||||
table.close(handle, None).unwrap_err().code(),
|
||||
"resource.closed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_is_not_readable_and_file_is_not_writable() {
|
||||
let mut table = ResourceTable::new();
|
||||
let stdout = table.open_stdout();
|
||||
assert_eq!(
|
||||
table.read(stdout, 1, None).unwrap_err().code(),
|
||||
"resource.unsupported"
|
||||
);
|
||||
let file = table.open_file("x.txt", Vec::new());
|
||||
assert_eq!(
|
||||
table.write(file, b"x", None).unwrap_err().code(),
|
||||
"resource.unsupported"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user