Protocol convergence for 3.0.0-rc.3 (issue #8) #9
No files matched your search
Generated
+12
-1
@@ -1,6 +1,6 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 3
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
@@ -491,6 +491,7 @@ dependencies = [
|
||||
"marqdo-sandbox",
|
||||
"marqdo-span",
|
||||
"marqdo-value",
|
||||
"marqdo-worker-ipc",
|
||||
"rcgen",
|
||||
"regex",
|
||||
"rustls",
|
||||
@@ -545,6 +546,7 @@ dependencies = [
|
||||
"libloading",
|
||||
"marqdo-span",
|
||||
"marqdo-value",
|
||||
"marqdo-worker-ipc",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"serde_yaml",
|
||||
@@ -569,6 +571,7 @@ dependencies = [
|
||||
"marqdo-host",
|
||||
"marqdo-sandbox",
|
||||
"marqdo-value",
|
||||
"marqdo-worker-ipc",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
]
|
||||
@@ -618,6 +621,14 @@ dependencies = [
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-worker-ipc"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"serde_json",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.3"
|
||||
|
||||
@@ -10,6 +10,7 @@ members = [
|
||||
"crates/marqdo-foreign",
|
||||
"crates/marqdo-plugin-abi",
|
||||
"crates/marqdo-provider-worker",
|
||||
"crates/marqdo-worker-ipc",
|
||||
"crates/marqdo-plugin-sdk",
|
||||
"crates/marqdo-host",
|
||||
"crates/marqdo-runtime",
|
||||
@@ -35,6 +36,7 @@ marqdo-ir = { path = "crates/marqdo-ir" }
|
||||
marqdo-frontend = { path = "crates/marqdo-frontend" }
|
||||
marqdo-foreign = { path = "crates/marqdo-foreign" }
|
||||
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
|
||||
marqdo-worker-ipc = { path = "crates/marqdo-worker-ipc" }
|
||||
marqdo-host = { path = "crates/marqdo-host" }
|
||||
marqdo-runtime = { path = "crates/marqdo-runtime" }
|
||||
marqdo-package = { path = "crates/marqdo-package" }
|
||||
|
||||
@@ -363,7 +363,8 @@ tests/ conformance/negative corpus (see tests/README.md)
|
||||
[`package-format.md`](spec/package-format.md),
|
||||
[`plugin-abi.md`](spec/plugin-abi.md), [`math.md`](spec/math.md),
|
||||
[`foreign.md`](spec/foreign.md), [`cli-tool.md`](spec/cli-tool.md),
|
||||
[`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md);
|
||||
[`analysis.md`](spec/analysis.md), [`observation.md`](spec/observation.md),
|
||||
[`worker-ipc.md`](spec/worker-ipc.md);
|
||||
JSON Schemas in [`spec/schemas/`](spec/schemas/).
|
||||
* [`tests/README.md`](tests/README.md) — conformance corpus and `UPDATE_GOLDENS`
|
||||
workflow.
|
||||
|
||||
@@ -33,6 +33,7 @@ const WORKSPACE_CRATES: &[&str] = &[
|
||||
"marqdo-foreign",
|
||||
"marqdo-plugin-abi",
|
||||
"marqdo-provider-worker",
|
||||
"marqdo-worker-ipc",
|
||||
"marqdo-plugin-sdk",
|
||||
"marqdo-host",
|
||||
"marqdo-runtime",
|
||||
@@ -140,6 +141,42 @@ fn stdlib_imports_resolve_inside_the_bundle() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_worker_transport_is_neutral_and_not_duplicated() {
|
||||
let root = repo_root();
|
||||
let transport = read(&root.join("crates/marqdo-worker-ipc/Cargo.toml"));
|
||||
for forbidden in ["marqdo-host", "marqdo-plugin-abi", "marqdo-provider-worker"] {
|
||||
assert!(
|
||||
!transport.contains(forbidden),
|
||||
"marqdo-worker-ipc must stay transport-only; it must not depend on `{forbidden}`"
|
||||
);
|
||||
}
|
||||
for user in [
|
||||
"crates/marqdo-host/Cargo.toml",
|
||||
"crates/marqdo-plugin-abi/Cargo.toml",
|
||||
"crates/marqdo-provider-worker/Cargo.toml",
|
||||
] {
|
||||
assert!(
|
||||
read(&root.join(user)).contains("marqdo-worker-ipc = {"),
|
||||
"{user} must use the one shared worker transport"
|
||||
);
|
||||
}
|
||||
// The four-byte length prefix and its bounds live in exactly one crate.
|
||||
for private in [
|
||||
"crates/marqdo-host/src/plugin_worker.rs",
|
||||
"crates/marqdo-host/src/provider_worker.rs",
|
||||
"crates/marqdo-plugin-abi/src/worker.rs",
|
||||
"crates/marqdo-provider-worker/src/main.rs",
|
||||
] {
|
||||
let text = read(&root.join(private));
|
||||
let implementation = text.split("#[cfg(test)]").next().unwrap_or(&text);
|
||||
assert!(
|
||||
!implementation.contains("from_be_bytes") && !implementation.contains("to_be_bytes"),
|
||||
"{private} reimplements worker framing instead of using marqdo-worker-ipc"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_keeps_the_documented_resource_endpoints() {
|
||||
let resource = read(&repo_root().join("crates/marqdo-host/src/resource.rs"));
|
||||
|
||||
@@ -13,6 +13,7 @@ libloading = { workspace = true }
|
||||
rustls = { workspace = true }
|
||||
rustls-native-certs = { workspace = true }
|
||||
marqdo-plugin-abi = { workspace = true }
|
||||
marqdo-worker-ipc = { workspace = true }
|
||||
flate2 = { workspace = true }
|
||||
getrandom = { workspace = true }
|
||||
regex = { workspace = true }
|
||||
|
||||
@@ -4,27 +4,30 @@
|
||||
//! `__plugin-worker` command. It isolates crashes and keeps native code out of
|
||||
//! the interpreter process. A plain process is **not** an OS sandbox; strict
|
||||
//! mode still refuses without a real isolation adapter.
|
||||
//!
|
||||
//! Framing, bounded reads, deadlines and teardown come from
|
||||
//! [`marqdo_worker_ipc`]. The invoke/capability vocabulary, capability limit and
|
||||
//! plugin error codes remain owned here: a shared transport never shares
|
||||
//! capabilities.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use marqdo_plugin_abi::worker::{
|
||||
read_frame, write_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, WORKER_COMMAND,
|
||||
response_from_frame, MAX_CAPABILITY_REQUESTS, MAX_CAPABILITY_REQUEST_BYTES, MAX_FRAME_BYTES,
|
||||
WORKER_COMMAND,
|
||||
};
|
||||
use marqdo_plugin_abi::{
|
||||
CapabilityHandler, PluginError, PluginManifest, WireRequest, WireResponse,
|
||||
};
|
||||
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
||||
use serde_json::json;
|
||||
|
||||
/// A native plugin running in an isolated worker process.
|
||||
pub struct WorkerPlugin {
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
frames: Receiver<Result<serde_json::Value, PluginError>>,
|
||||
connection: Connection,
|
||||
exports: BTreeMap<String, String>,
|
||||
dead: bool,
|
||||
capability_handler: Option<CapabilityHandler>,
|
||||
@@ -36,7 +39,7 @@ const CALL_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
impl std::fmt::Debug for WorkerPlugin {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("WorkerPlugin")
|
||||
.field("pid", &self.child.id())
|
||||
.field("pid", &self.connection.id())
|
||||
.field("exports", &self.exports.keys().collect::<Vec<_>>())
|
||||
.finish()
|
||||
}
|
||||
@@ -77,7 +80,7 @@ impl WorkerPlugin {
|
||||
format!("cannot find the current executable: {error}"),
|
||||
)
|
||||
})?;
|
||||
let mut child = match Command::new(executable)
|
||||
let child: Child = match Command::new(executable)
|
||||
.arg(WORKER_COMMAND)
|
||||
.arg(&manifest_path)
|
||||
.arg(base_dir)
|
||||
@@ -95,66 +98,33 @@ impl WorkerPlugin {
|
||||
));
|
||||
}
|
||||
};
|
||||
let Some(stdin) = child.stdin.take() else {
|
||||
let _ = child.kill();
|
||||
return Err(PluginError::load(
|
||||
"worker_spawn_failed",
|
||||
"worker stdin unavailable",
|
||||
));
|
||||
};
|
||||
let Some(mut stdout) = child.stdout.take() else {
|
||||
let _ = child.kill();
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
return Err(PluginError::load(
|
||||
"worker_spawn_failed",
|
||||
"worker stdout unavailable",
|
||||
));
|
||||
let connection = match Connection::attach(child, MAX_FRAME_BYTES) {
|
||||
Ok(connection) => connection,
|
||||
Err(error) => {
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
return Err(PluginError::load(
|
||||
"worker_spawn_failed",
|
||||
format!("cannot start plugin worker transport: {error}"),
|
||||
));
|
||||
}
|
||||
};
|
||||
let (sender, frames) = mpsc::channel();
|
||||
thread::Builder::new()
|
||||
.name("marqdo-plugin-worker-reader".to_string())
|
||||
.spawn(move || loop {
|
||||
match read_frame(&mut stdout) {
|
||||
Ok(Some(frame)) => {
|
||||
if sender.send(Ok(frame)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = sender.send(Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed its output stream",
|
||||
)));
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = sender.send(Err(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|error| {
|
||||
let _ = child.kill();
|
||||
PluginError::load(
|
||||
"worker_spawn_failed",
|
||||
format!("cannot start worker reader: {error}"),
|
||||
)
|
||||
})?;
|
||||
let ready = match frames.recv_timeout(HANDSHAKE_TIMEOUT) {
|
||||
let mut connection = connection;
|
||||
let ready = match connection.receive(Instant::now() + HANDSHAKE_TIMEOUT) {
|
||||
Ok(frame) => frame,
|
||||
Err(_) => {
|
||||
Err(TransportError::Timeout) => {
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
let _ = child.kill();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker handshake timed out",
|
||||
));
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
return Err(transport_error(error));
|
||||
}
|
||||
};
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
let ready = ready?;
|
||||
if ready.get("kind").and_then(serde_json::Value::as_str) != Some("ready") {
|
||||
let _ = child.kill();
|
||||
return Err(PluginError::load(
|
||||
"worker_handshake_failed",
|
||||
"worker did not report ready",
|
||||
@@ -182,16 +152,13 @@ impl WorkerPlugin {
|
||||
.collect();
|
||||
let actual: std::collections::BTreeSet<&str> = exports.keys().map(String::as_str).collect();
|
||||
if declared != actual {
|
||||
let _ = child.kill();
|
||||
return Err(PluginError::manifest(
|
||||
"worker_export_mismatch",
|
||||
"worker exports do not match the manifest",
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
child,
|
||||
stdin,
|
||||
frames,
|
||||
connection,
|
||||
exports,
|
||||
dead: false,
|
||||
capability_handler,
|
||||
@@ -208,36 +175,21 @@ impl WorkerPlugin {
|
||||
}
|
||||
let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?)
|
||||
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
|
||||
if let Err(error) = write_frame(
|
||||
&mut self.stdin,
|
||||
&json!({"kind": "invoke", "request": request_value}),
|
||||
let deadline = Instant::now() + CALL_TIMEOUT;
|
||||
if let Err(error) = self.connection.send(
|
||||
json!({"kind": "invoke", "request": request_value}),
|
||||
deadline,
|
||||
) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
return Err(invocation_error(error));
|
||||
}
|
||||
let deadline = std::time::Instant::now() + CALL_TIMEOUT;
|
||||
let mut capability_requests = 0usize;
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
|
||||
if remaining.is_zero() {
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
));
|
||||
}
|
||||
let frame = match self.frames.recv_timeout(remaining) {
|
||||
Ok(Ok(frame)) => frame,
|
||||
Ok(Err(error)) => {
|
||||
let frame = match self.connection.receive(deadline) {
|
||||
Ok(frame) => frame,
|
||||
Err(error) => {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Err(_) => {
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
));
|
||||
return Err(invocation_error(error));
|
||||
}
|
||||
};
|
||||
match frame.get("kind").and_then(serde_json::Value::as_str) {
|
||||
@@ -252,13 +204,13 @@ impl WorkerPlugin {
|
||||
),
|
||||
));
|
||||
}
|
||||
if let Err(error) = self.handle_capability_request(&frame) {
|
||||
if let Err(error) = self.handle_capability_request(&frame, deadline) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Some("response") => {
|
||||
return marqdo_plugin_abi::worker::response_from_frame(&frame);
|
||||
return response_from_frame(&frame);
|
||||
}
|
||||
Some("error") => {
|
||||
return Err(PluginError::invoke(
|
||||
@@ -283,7 +235,11 @@ impl WorkerPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_capability_request(&mut self, frame: &serde_json::Value) -> Result<(), PluginError> {
|
||||
fn handle_capability_request(
|
||||
&mut self,
|
||||
frame: &serde_json::Value,
|
||||
deadline: Instant,
|
||||
) -> Result<(), PluginError> {
|
||||
let id = frame
|
||||
.get("id")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
@@ -332,23 +288,53 @@ impl WorkerPlugin {
|
||||
"message":error.message,
|
||||
}),
|
||||
};
|
||||
if let Err(error) = write_frame(&mut self.stdin, &reply) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(())
|
||||
self.connection
|
||||
.send(reply, deadline)
|
||||
.map_err(invocation_error)
|
||||
}
|
||||
|
||||
fn mark_dead(&mut self) {
|
||||
self.dead = true;
|
||||
let _ = self.child.kill();
|
||||
self.connection.abort();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerPlugin {
|
||||
fn drop(&mut self) {
|
||||
let _ = write_frame(&mut self.stdin, &json!({"kind": "shutdown"}));
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
if !self.dead {
|
||||
let _ = self.connection.send(
|
||||
json!({"kind": "shutdown"}),
|
||||
Instant::now() + Duration::from_millis(500),
|
||||
);
|
||||
}
|
||||
self.connection.abort();
|
||||
}
|
||||
}
|
||||
|
||||
fn invocation_error(error: TransportError) -> PluginError {
|
||||
match error {
|
||||
TransportError::Timeout => PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
),
|
||||
other => transport_error(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn transport_error(error: TransportError) -> PluginError {
|
||||
match error {
|
||||
TransportError::Timeout => {
|
||||
PluginError::invoke("plugin.timeout", "plugin worker exceeded its timeout")
|
||||
}
|
||||
TransportError::Closed => {
|
||||
PluginError::invoke("plugin.crashed", "plugin worker closed its output stream")
|
||||
}
|
||||
TransportError::Frame(FrameError::Io(error)) => PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame I/O failed: {error}"),
|
||||
),
|
||||
TransportError::Frame(other) => {
|
||||
PluginError::wire("worker_frame_invalid", other.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,34 @@
|
||||
//! Host-managed worker resource provider (ADR-0035).
|
||||
//!
|
||||
//! This is a small, versioned framed-JSON transport for **trusted helper
|
||||
//! processes**. It is not a C ABI binding and not an OS sandbox: the helper
|
||||
//! runs as the host user. Registration is a host embedding API; language code
|
||||
//! only sees the normal `resource.*` operations.
|
||||
//! This is a bounded framed-JSON transport for **trusted helper processes**.
|
||||
//! It is not a C ABI binding and not an OS sandbox: the helper runs as the host
|
||||
//! user. Registration is a host embedding API; language code only sees the
|
||||
//! normal `resource.*` operations.
|
||||
//!
|
||||
//! Framing, bounded reads, request deadlines and teardown come from
|
||||
//! [`marqdo_worker_ipc`]. The `open`/`read`/`write`/`close` vocabulary, kind
|
||||
//! rights and error categories stay owned by the resource boundary, so a
|
||||
//! shared transport never widens provider authority.
|
||||
|
||||
use std::io::{BufReader, Read, Write};
|
||||
use std::path::Path;
|
||||
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use marqdo_span::Span;
|
||||
use marqdo_worker_ipc::{Connection, FrameError, TransportError};
|
||||
use serde_json::{json, Value as Json};
|
||||
|
||||
use crate::resource::{ResourceProvider, ResourceRead};
|
||||
use marqdo_value::{ErrorCategory, RuntimeError};
|
||||
|
||||
const MAX_FRAME_BYTES: usize = 1024 * 1024;
|
||||
const WORKER_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// A `ResourceProvider` backed by a child process speaking framed JSON.
|
||||
pub(crate) struct WorkerResourceProvider {
|
||||
name: String,
|
||||
kinds: Vec<String>,
|
||||
child: Child,
|
||||
stdin: ChildStdin,
|
||||
stdout: BufReader<ChildStdout>,
|
||||
connection: Connection,
|
||||
}
|
||||
|
||||
impl WorkerResourceProvider {
|
||||
@@ -33,7 +38,7 @@ impl WorkerResourceProvider {
|
||||
program: &Path,
|
||||
args: &[String],
|
||||
) -> Result<Self, RuntimeError> {
|
||||
let mut child = Command::new(program)
|
||||
let child = Command::new(program)
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
@@ -49,20 +54,12 @@ impl WorkerResourceProvider {
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let stdin = child
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| worker_error("missing stdin pipe"))?;
|
||||
let stdout = child
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| worker_error("missing stdout pipe"))?;
|
||||
let connection = Connection::attach(child, MAX_FRAME_BYTES)
|
||||
.map_err(|error| worker_error(&format!("cannot attach to worker: {error}")))?;
|
||||
let mut provider = Self {
|
||||
name: name.to_string(),
|
||||
kinds: kinds.to_vec(),
|
||||
child,
|
||||
stdin,
|
||||
stdout: BufReader::new(stdout),
|
||||
connection,
|
||||
};
|
||||
// Handshake: the helper must answer a ping before it is trusted.
|
||||
provider.request(json!({"op": "ping"}))?;
|
||||
@@ -70,30 +67,11 @@ impl WorkerResourceProvider {
|
||||
}
|
||||
|
||||
fn request(&mut self, request: Json) -> Result<Json, RuntimeError> {
|
||||
let bytes = serde_json::to_vec(&request)
|
||||
.map_err(|error| worker_error(&format!("cannot encode request: {error}")))?;
|
||||
if bytes.len() > MAX_FRAME_BYTES {
|
||||
return Err(worker_error("request frame is too large"));
|
||||
}
|
||||
self.stdin
|
||||
.write_all(&(bytes.len() as u32).to_be_bytes())
|
||||
.and_then(|()| self.stdin.write_all(&bytes))
|
||||
.and_then(|()| self.stdin.flush())
|
||||
.map_err(|error| worker_error(&format!("cannot write request frame: {error}")))?;
|
||||
let mut header = [0u8; 4];
|
||||
self.stdout
|
||||
.read_exact(&mut header)
|
||||
.map_err(|error| worker_error(&format!("cannot read response header: {error}")))?;
|
||||
let length = u32::from_be_bytes(header) as usize;
|
||||
if length == 0 || length > MAX_FRAME_BYTES {
|
||||
return Err(worker_error("invalid response frame length"));
|
||||
}
|
||||
let mut payload = vec![0u8; length];
|
||||
self.stdout
|
||||
.read_exact(&mut payload)
|
||||
.map_err(|error| worker_error(&format!("cannot read response frame: {error}")))?;
|
||||
let response: Json = serde_json::from_slice(&payload)
|
||||
.map_err(|error| worker_error(&format!("invalid response JSON: {error}")))?;
|
||||
let deadline = Instant::now() + WORKER_TIMEOUT;
|
||||
self.connection
|
||||
.send(request, deadline)
|
||||
.map_err(transport_error)?;
|
||||
let response = self.connection.receive(deadline).map_err(transport_error)?;
|
||||
if response.get("ok").and_then(Json::as_bool) != Some(true) {
|
||||
let code = response
|
||||
.get("code")
|
||||
@@ -192,9 +170,11 @@ impl ResourceProvider for WorkerResourceProvider {
|
||||
|
||||
impl Drop for WorkerResourceProvider {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.request(json!({"op": "shutdown"}));
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
let _ = self.connection.send(
|
||||
json!({"op": "shutdown"}),
|
||||
Instant::now() + Duration::from_millis(500),
|
||||
);
|
||||
self.connection.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,6 +185,21 @@ fn with_span(mut error: RuntimeError, span: Option<Span>) -> RuntimeError {
|
||||
error
|
||||
}
|
||||
|
||||
fn transport_error(error: TransportError) -> RuntimeError {
|
||||
match error {
|
||||
TransportError::Timeout => {
|
||||
worker_error("worker resource provider did not answer before the deadline")
|
||||
}
|
||||
TransportError::Closed => worker_error("worker resource provider closed its transport"),
|
||||
TransportError::Frame(FrameError::Io(error)) => {
|
||||
worker_error(&format!("worker resource provider I/O failed: {error}"))
|
||||
}
|
||||
TransportError::Frame(other) => {
|
||||
worker_error(&format!("worker resource provider frame error: {other}"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn worker_error(message: &str) -> RuntimeError {
|
||||
RuntimeError::new(ErrorCategory::HostError, None, message.to_string())
|
||||
}
|
||||
@@ -11,6 +11,7 @@ authors.workspace = true
|
||||
[dependencies]
|
||||
marqdo-span = { workspace = true }
|
||||
marqdo-value = { workspace = true }
|
||||
marqdo-worker-ipc = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_yaml = { workspace = true }
|
||||
|
||||
@@ -30,84 +30,42 @@ pub const MAX_CAPABILITY_REQUEST_BYTES: usize = 64 * 1024;
|
||||
/// Read one length-prefixed frame (4-byte big-endian length + JSON).
|
||||
///
|
||||
/// `Ok(None)` means a clean EOF at a frame boundary. A partial header or
|
||||
/// truncated payload is a protocol error, never EOF.
|
||||
/// truncated payload is a protocol error, never EOF. Framing itself is shared
|
||||
/// with other persistent workers; the plugin vocabulary stays in this module.
|
||||
pub fn read_frame<R: Read>(reader: &mut R) -> Result<Option<Value>, PluginError> {
|
||||
let mut length = [0_u8; 4];
|
||||
let mut read = 0usize;
|
||||
while read < length.len() {
|
||||
match reader.read(&mut length[read..]) {
|
||||
Ok(0) if read == 0 => return Ok(None),
|
||||
Ok(0) => {
|
||||
return Err(PluginError::wire(
|
||||
"worker_frame_invalid",
|
||||
"worker stream ended inside a frame header",
|
||||
))
|
||||
}
|
||||
Ok(count) => read += count,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => {
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame read failed: {error}"),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
let length = u32::from_be_bytes(length) as usize;
|
||||
if length == 0 || length > MAX_FRAME_BYTES {
|
||||
return Err(PluginError::wire(
|
||||
"worker_frame_invalid",
|
||||
format!("worker frame length {length} is invalid"),
|
||||
));
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(length.min(64 * 1024));
|
||||
let read = reader
|
||||
.take(length as u64)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|error| {
|
||||
PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame read failed: {error}"),
|
||||
)
|
||||
})?;
|
||||
if read != length {
|
||||
return Err(PluginError::wire(
|
||||
"worker_frame_invalid",
|
||||
format!("worker frame declared {length} bytes but only {read} arrived"),
|
||||
));
|
||||
}
|
||||
serde_json::from_slice(&bytes).map(Some).map_err(|error| {
|
||||
PluginError::wire(
|
||||
"worker_frame_invalid",
|
||||
format!("worker frame is not valid JSON: {error}"),
|
||||
)
|
||||
})
|
||||
marqdo_worker_ipc::read_frame(reader, MAX_FRAME_BYTES).map_err(frame_read_error)
|
||||
}
|
||||
|
||||
/// Write one length-prefixed frame.
|
||||
pub fn write_frame<W: Write>(writer: &mut W, value: &Value) -> Result<(), PluginError> {
|
||||
let bytes = serde_json::to_vec(value).map_err(|error| {
|
||||
PluginError::wire(
|
||||
"worker_encode_failed",
|
||||
format!("cannot encode worker frame: {error}"),
|
||||
)
|
||||
})?;
|
||||
if bytes.len() > MAX_FRAME_BYTES {
|
||||
return Err(PluginError::wire(
|
||||
marqdo_worker_ipc::write_frame(writer, value, MAX_FRAME_BYTES).map_err(frame_write_error)
|
||||
}
|
||||
|
||||
fn frame_read_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
|
||||
match error {
|
||||
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame read failed: {error}"),
|
||||
),
|
||||
other => PluginError::wire("worker_frame_invalid", other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_write_error(error: marqdo_worker_ipc::FrameError) -> PluginError {
|
||||
match error {
|
||||
marqdo_worker_ipc::FrameError::Io(error) => PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame write failed: {error}"),
|
||||
),
|
||||
marqdo_worker_ipc::FrameError::Encode(error) => {
|
||||
PluginError::wire("worker_encode_failed", error.to_string())
|
||||
}
|
||||
marqdo_worker_ipc::FrameError::Length(length) => PluginError::wire(
|
||||
"worker_frame_too_large",
|
||||
format!("worker frame is {} bytes", bytes.len()),
|
||||
));
|
||||
format!("worker frame is {length} bytes"),
|
||||
),
|
||||
other => PluginError::wire("worker_frame_invalid", other.to_string()),
|
||||
}
|
||||
writer
|
||||
.write_all(&(bytes.len() as u32).to_be_bytes())
|
||||
.and_then(|()| writer.write_all(&bytes))
|
||||
.and_then(|()| writer.flush())
|
||||
.map_err(|error| {
|
||||
PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
format!("worker frame write failed: {error}"),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Run one worker until shutdown/EOF. Returns a process exit code.
|
||||
|
||||
@@ -12,6 +12,7 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
libloading = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
marqdo-worker-ipc = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
marqdo-host = { path = "../marqdo-host" }
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
//! boundary, not a sandbox: the library runs with the worker's privileges.
|
||||
|
||||
use std::ffi::{c_char, CString};
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use libloading::Library;
|
||||
@@ -129,41 +128,16 @@ impl Provider {
|
||||
}
|
||||
|
||||
fn read_frame() -> Result<Option<Json>, String> {
|
||||
let mut header = [0u8; 4];
|
||||
let mut read = 0usize;
|
||||
while read < header.len() {
|
||||
match std::io::stdin().read(&mut header[read..]) {
|
||||
Ok(0) if read == 0 => return Ok(None),
|
||||
Ok(0) => return Err("stdin ended inside a frame header".to_string()),
|
||||
Ok(count) => read += count,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(format!("stdin read failed: {error}")),
|
||||
}
|
||||
}
|
||||
let length = u32::from_be_bytes(header) as usize;
|
||||
if length == 0 || length > MAX_FRAME_BYTES {
|
||||
return Err(format!("invalid frame length {length}"));
|
||||
}
|
||||
let mut payload = vec![0u8; length];
|
||||
std::io::stdin()
|
||||
.read_exact(&mut payload)
|
||||
.map_err(|error| format!("stdin read failed: {error}"))?;
|
||||
serde_json::from_slice(&payload)
|
||||
.map(Some)
|
||||
.map_err(|error| format!("invalid JSON frame: {error}"))
|
||||
let stdin = std::io::stdin();
|
||||
let mut input = stdin.lock();
|
||||
marqdo_worker_ipc::read_frame(&mut input, MAX_FRAME_BYTES).map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn write_frame(value: &Json) -> Result<(), String> {
|
||||
let bytes = serde_json::to_vec(value).map_err(|error| format!("encode failed: {error}"))?;
|
||||
if bytes.len() > MAX_FRAME_BYTES {
|
||||
return Err("response frame is too large".to_string());
|
||||
}
|
||||
let mut stdout = std::io::stdout();
|
||||
stdout
|
||||
.write_all(&(bytes.len() as u32).to_be_bytes())
|
||||
.and_then(|()| stdout.write_all(&bytes))
|
||||
.and_then(|()| stdout.flush())
|
||||
.map_err(|error| format!("stdout write failed: {error}"))
|
||||
let stdout = std::io::stdout();
|
||||
let mut output = stdout.lock();
|
||||
marqdo_worker_ipc::write_frame(&mut output, value, MAX_FRAME_BYTES)
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
fn fail(message: &str) -> Json {
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "marqdo-worker-ipc"
|
||||
description = "Bounded framed JSON and child transport for Marqdo workers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,370 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
//! Bounded length-prefixed JSON framing and child-process transport shared by
|
||||
//! persistent Marqdo workers.
|
||||
//!
|
||||
//! The crate owns only what is genuinely common to a plugin worker and a
|
||||
//! resource-provider worker: the four-byte big-endian length prefix, the
|
||||
//! maximum frame size, clean-EOF versus truncated-frame classification, a
|
||||
//! single reader and writer thread, request deadlines, and process teardown.
|
||||
//! Each caller still owns its own frame vocabulary, size limit, authority,
|
||||
//! capability bridge and error codes. Sharing this transport does not share
|
||||
//! capabilities or trust.
|
||||
//!
|
||||
//! Foreign kernels and CLI Tools do not use this transport: a foreign kernel
|
||||
//! is a one-shot stdin/stdout wire value, and a CLI Tool is an independent
|
||||
//! executable owning its standard streams.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::process::Child;
|
||||
use std::sync::mpsc::{self, Receiver, RecvTimeoutError, SyncSender, TrySendError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Read a bounded four-byte big-endian length and JSON value.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum FrameError {
|
||||
#[error("worker frame I/O failed: {0}")]
|
||||
Io(#[from] io::Error),
|
||||
#[error("worker stream ended inside a frame header")]
|
||||
PartialHeader,
|
||||
#[error("worker frame length {0} is invalid")]
|
||||
Length(usize),
|
||||
#[error("worker frame declared {expected} bytes but only {actual} arrived")]
|
||||
PartialPayload { expected: usize, actual: usize },
|
||||
#[error("worker frame is not valid JSON: {0}")]
|
||||
InvalidJson(serde_json::Error),
|
||||
#[error("cannot encode worker frame: {0}")]
|
||||
Encode(serde_json::Error),
|
||||
}
|
||||
|
||||
/// Read one bounded frame.
|
||||
///
|
||||
/// `Ok(None)` is a clean EOF at a frame boundary. A partial header, a
|
||||
/// truncated payload, an invalid length or invalid JSON is a protocol error and
|
||||
/// never EOF. `limit` is the caller's protocol frame budget, in bytes.
|
||||
pub fn read_frame(reader: &mut impl Read, limit: usize) -> Result<Option<Value>, FrameError> {
|
||||
let mut header = [0; 4];
|
||||
let mut offset = 0;
|
||||
while offset < header.len() {
|
||||
match reader.read(&mut header[offset..]) {
|
||||
Ok(0) if offset == 0 => return Ok(None),
|
||||
Ok(0) => return Err(FrameError::PartialHeader),
|
||||
Ok(count) => offset += count,
|
||||
Err(error) if error.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
let expected = u32::from_be_bytes(header) as usize;
|
||||
if expected == 0 || expected > limit {
|
||||
return Err(FrameError::Length(expected));
|
||||
}
|
||||
let mut payload = Vec::with_capacity(expected.min(64 * 1024));
|
||||
let actual = reader.take(expected as u64).read_to_end(&mut payload)?;
|
||||
if actual != expected {
|
||||
return Err(FrameError::PartialPayload { expected, actual });
|
||||
}
|
||||
serde_json::from_slice(&payload)
|
||||
.map(Some)
|
||||
.map_err(FrameError::InvalidJson)
|
||||
}
|
||||
|
||||
/// Write and flush one frame under the peer's configured size limit.
|
||||
pub fn write_frame(writer: &mut impl Write, value: &Value, limit: usize) -> Result<(), FrameError> {
|
||||
let payload = serde_json::to_vec(value).map_err(FrameError::Encode)?;
|
||||
if payload.len() > limit {
|
||||
return Err(FrameError::Length(payload.len()));
|
||||
}
|
||||
let length = u32::try_from(payload.len()).map_err(|_| FrameError::Length(payload.len()))?;
|
||||
writer.write_all(&length.to_be_bytes())?;
|
||||
writer.write_all(&payload)?;
|
||||
writer.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Failure of one configured request/response exchange.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum TransportError {
|
||||
#[error("worker transport reached its deadline")]
|
||||
Timeout,
|
||||
#[error("worker transport closed")]
|
||||
Closed,
|
||||
#[error(transparent)]
|
||||
Frame(#[from] FrameError),
|
||||
}
|
||||
|
||||
type WriteRequest = (Value, SyncSender<Result<(), FrameError>>);
|
||||
|
||||
/// Owns one configured child and its two dedicated protocol pipes.
|
||||
///
|
||||
/// A connection is sequential: one caller drives one exchange at a time, and
|
||||
/// the caller supplies the deadline for that exchange. Any transport error
|
||||
/// kills and reaps the child, so a dead worker is never reused.
|
||||
pub struct Connection {
|
||||
child: Option<Child>,
|
||||
writes: Option<SyncSender<WriteRequest>>,
|
||||
reads: Option<Receiver<Result<Value, FrameError>>>,
|
||||
}
|
||||
|
||||
impl Connection {
|
||||
/// Attach to a child with piped stdin/stdout, closing the child on failure.
|
||||
pub fn attach(child: Child, limit: usize) -> io::Result<Self> {
|
||||
let mut connection = Self {
|
||||
child: Some(child),
|
||||
writes: None,
|
||||
reads: None,
|
||||
};
|
||||
if let Err(error) = connection.attach_pipes(limit) {
|
||||
connection.abort();
|
||||
return Err(error);
|
||||
}
|
||||
Ok(connection)
|
||||
}
|
||||
|
||||
fn attach_pipes(&mut self, limit: usize) -> io::Result<()> {
|
||||
let instance = self.child.as_mut().expect("child present");
|
||||
let mut stdin = instance
|
||||
.stdin
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("worker stdin unavailable"))?;
|
||||
let mut stdout = instance
|
||||
.stdout
|
||||
.take()
|
||||
.ok_or_else(|| io::Error::other("worker stdout unavailable"))?;
|
||||
|
||||
let (writes, pending) = mpsc::sync_channel::<WriteRequest>(1);
|
||||
std::thread::Builder::new()
|
||||
.name("marqdo-worker-writer".into())
|
||||
.spawn(move || {
|
||||
while let Ok((value, reply)) = pending.recv() {
|
||||
if reply.send(write_frame(&mut stdin, &value, limit)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
self.writes = Some(writes);
|
||||
|
||||
let (received, reads) = mpsc::sync_channel(1);
|
||||
std::thread::Builder::new()
|
||||
.name("marqdo-worker-reader".into())
|
||||
.spawn(move || loop {
|
||||
match read_frame(&mut stdout, limit) {
|
||||
Ok(Some(value)) => {
|
||||
if received.send(Ok(value)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(None) => break,
|
||||
Err(error) => {
|
||||
let _ = received.send(Err(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
self.reads = Some(reads);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Process id of the attached child, if it is still owned here.
|
||||
pub fn id(&self) -> Option<u32> {
|
||||
self.child.as_ref().map(Child::id)
|
||||
}
|
||||
|
||||
/// Send one frame and wait for the write to complete before the deadline.
|
||||
pub fn send(&mut self, value: Value, deadline: Instant) -> Result<(), TransportError> {
|
||||
let result = (|| {
|
||||
let channel = self.writes.as_ref().ok_or(TransportError::Closed)?;
|
||||
let (response, result) = mpsc::sync_channel(1);
|
||||
let mut pending = Some((value, response));
|
||||
loop {
|
||||
match channel.try_send(pending.take().expect("pending frame")) {
|
||||
Ok(()) => break,
|
||||
Err(TrySendError::Full(returned)) => {
|
||||
pending = Some(returned);
|
||||
if Instant::now() >= deadline {
|
||||
return Err(TransportError::Timeout);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
Err(TrySendError::Disconnected(_)) => return Err(TransportError::Closed),
|
||||
}
|
||||
}
|
||||
wait(&result, deadline)?.map_err(Into::into)
|
||||
})();
|
||||
if result.is_err() {
|
||||
self.abort();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Receive one frame before the deadline.
|
||||
pub fn receive(&mut self, deadline: Instant) -> Result<Value, TransportError> {
|
||||
let result = self
|
||||
.reads
|
||||
.as_ref()
|
||||
.ok_or(TransportError::Closed)
|
||||
.and_then(|channel| wait(channel, deadline))
|
||||
.and_then(|frame| frame.map_err(Into::into));
|
||||
if result.is_err() {
|
||||
self.abort();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Make this peer unusable and reap the process.
|
||||
pub fn abort(&mut self) {
|
||||
self.writes.take();
|
||||
self.reads.take();
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Connection {
|
||||
fn drop(&mut self) {
|
||||
self.abort();
|
||||
}
|
||||
}
|
||||
|
||||
fn wait<T>(channel: &Receiver<T>, deadline: Instant) -> Result<T, TransportError> {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() {
|
||||
return Err(TransportError::Timeout);
|
||||
}
|
||||
channel
|
||||
.recv_timeout(remaining)
|
||||
.map_err(|error| match error {
|
||||
RecvTimeoutError::Timeout => TransportError::Timeout,
|
||||
RecvTimeoutError::Disconnected => TransportError::Closed,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn framing_distinguishes_boundary_eof_from_a_partial_record() {
|
||||
let mut bytes = Vec::new();
|
||||
write_frame(&mut bytes, &json!({"ok": true}), 64).unwrap();
|
||||
let mut input = bytes.as_slice();
|
||||
assert_eq!(
|
||||
read_frame(&mut input, 64).unwrap(),
|
||||
Some(json!({"ok": true}))
|
||||
);
|
||||
assert_eq!(read_frame(&mut input, 64).unwrap(), None);
|
||||
assert!(matches!(
|
||||
read_frame(&mut &bytes[..3], 64),
|
||||
Err(FrameError::PartialHeader)
|
||||
));
|
||||
assert!(matches!(
|
||||
read_frame(&mut &bytes[..6], 64),
|
||||
Err(FrameError::PartialPayload { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
read_frame(&mut &[0; 4][..], 64),
|
||||
Err(FrameError::Length(0))
|
||||
));
|
||||
assert!(matches!(
|
||||
read_frame(&mut &bytes[..4], 4),
|
||||
Err(FrameError::Length(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_past_the_peer_limit_is_a_frame_error() {
|
||||
let mut bytes = Vec::new();
|
||||
let error = write_frame(&mut bytes, &json!({"payload": "long"}), 4).unwrap_err();
|
||||
assert!(matches!(error, FrameError::Length(_)));
|
||||
assert!(bytes.is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
mod child {
|
||||
use super::*;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
fn connection(script: &str) -> Connection {
|
||||
let child = Command::new("python3")
|
||||
.arg("-c")
|
||||
.arg(script)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.expect("python3 is required for worker transport tests");
|
||||
Connection::attach(child, 1024).expect("attach child")
|
||||
}
|
||||
|
||||
const ECHO: &str = r#"
|
||||
import sys, json, struct
|
||||
def read_frame():
|
||||
header = sys.stdin.buffer.read(4)
|
||||
if len(header) < 4:
|
||||
return None
|
||||
return json.loads(sys.stdin.buffer.read(struct.unpack(">I", header)[0]))
|
||||
def write_frame(value):
|
||||
payload = json.dumps(value).encode()
|
||||
sys.stdout.buffer.write(struct.pack(">I", len(payload)) + payload)
|
||||
sys.stdout.buffer.flush()
|
||||
while True:
|
||||
frame = read_frame()
|
||||
if frame is None:
|
||||
break
|
||||
write_frame({"echo": frame})
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn connection_round_trips_frames_from_one_child() {
|
||||
let mut connection = connection(ECHO);
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
connection.send(json!({"n": 1}), deadline).unwrap();
|
||||
assert_eq!(
|
||||
connection.receive(deadline).unwrap(),
|
||||
json!({"echo": {"n": 1}})
|
||||
);
|
||||
connection.send(json!({"n": 2}), deadline).unwrap();
|
||||
assert_eq!(
|
||||
connection.receive(deadline).unwrap(),
|
||||
json!({"echo": {"n": 2}})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_child_hits_the_request_deadline_and_is_reaped() {
|
||||
let mut connection = connection("import time; time.sleep(30)");
|
||||
let deadline = Instant::now() + Duration::from_millis(200);
|
||||
assert!(matches!(
|
||||
connection.receive(deadline),
|
||||
Err(TransportError::Timeout)
|
||||
));
|
||||
assert!(connection.id().is_none());
|
||||
assert!(matches!(
|
||||
connection.receive(Instant::now() + Duration::from_secs(1)),
|
||||
Err(TransportError::Closed)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_eof_is_closed_and_a_truncated_frame_is_a_frame_error() {
|
||||
let mut silent = connection("pass");
|
||||
assert!(matches!(
|
||||
silent.receive(Instant::now() + Duration::from_secs(10)),
|
||||
Err(TransportError::Closed)
|
||||
));
|
||||
|
||||
let mut truncated = connection(
|
||||
"import sys, struct; sys.stdout.buffer.write(struct.pack('>I', 10) + b'{}'); sys.stdout.buffer.flush()",
|
||||
);
|
||||
assert!(matches!(
|
||||
truncated.receive(Instant::now() + Duration::from_secs(10)),
|
||||
Err(TransportError::Frame(FrameError::PartialPayload { .. }))
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ for replacing public interfaces before the first stable release.
|
||||
| Runtime facts | Interpreter and Host observation sink | [Observation](../../spec/observation.md) |
|
||||
| Installed CLI commands | Generic Tool registry | [CLI Tool](../../spec/cli-tool.md) |
|
||||
| Runtime extensions | Plugin, Resource Provider and Foreign each enforce their own grants | [Plugin ABI](../../spec/plugin-abi.md), [Resource Provider](../../spec/resource-provider-v2.md), [Foreign](../../spec/foreign.md) |
|
||||
| Persistent worker plumbing | Plugin and provider workers share one bounded framed transport; each keeps its vocabulary, limits and authority | [Shared worker transport](../../spec/worker-ipc.md) |
|
||||
| Values and package identities | Value Wire and project lock | [Value Wire](../../spec/value-wire.md), [Extension selection and lock](../../spec/extension-selection.md) |
|
||||
|
||||
`check --emit analysis.json` projects static facts from the prepared project.
|
||||
@@ -154,9 +155,17 @@ Current Rust dependency edges (documented, not proposed):
|
||||
marqdo-cli -> marqdo-runtime -> marqdo-host
|
||||
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ...
|
||||
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
|
||||
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox
|
||||
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-worker-ipc
|
||||
marqdo-plugin-abi -> marqdo-worker-ipc
|
||||
marqdo-provider-worker -> marqdo-worker-ipc
|
||||
```
|
||||
|
||||
`marqdo-worker-ipc` depends only on `serde_json` and `thiserror`: it is the one
|
||||
copy of bounded worker framing, deadlines and process teardown
|
||||
([spec/worker-ipc.md](../../spec/worker-ipc.md)). It must never depend on the
|
||||
host, the plugin ABI, or a worker binary; sharing plumbing must not share
|
||||
capabilities. Foreign kernels and CLI Tools stay outside it.
|
||||
|
||||
`marqdo-runtime -> marqdo-host` is the current direction. Do not add a second
|
||||
execution backend or a `marqdo-stdlib` crate by implication. A future embedded
|
||||
runtime or a second backend needs the thin `ExecutionPort` contract described in the
|
||||
|
||||
+4
-1
@@ -370,7 +370,10 @@ not an OS sandbox: the worker still runs as the user. Wasm, hot unload and worke
|
||||
Frames are a 4-byte big-endian length followed by one JSON object (max 8 MiB).
|
||||
A zero/oversized length, partial header, truncated payload or invalid JSON is a
|
||||
protocol error; clean EOF at a frame boundary is not. The host marks the worker
|
||||
dead after a transport failure and does not reuse it.
|
||||
dead after a transport failure and does not reuse it. Framing, bounded reads,
|
||||
deadlines and process teardown are implemented once in the
|
||||
[shared worker transport](worker-ipc.md); the frame vocabulary below, the
|
||||
capability limit and every grant remain owned by this boundary.
|
||||
Worker → host: `{"kind":"ready","exports":[...]}`. Host → worker:
|
||||
`{"kind":"invoke","request":<wire request>}` and `{"kind":"shutdown"}`.
|
||||
Worker → host responses are `{"kind":"response","response":<wire response>}` or
|
||||
|
||||
@@ -189,7 +189,9 @@ The helper is `marqdo-provider-worker <selected-artifact-path>`. It loads
|
||||
exactly one `c-abi-1` shared library, verifies
|
||||
`marqdo_resource_provider_abi_version() == 1`, and speaks the ADR-0035 framed
|
||||
protocol over stdin/stdout: 4-byte big-endian length + JSON, 1 MiB maximum per
|
||||
frame.
|
||||
frame. Framing and process plumbing come from the
|
||||
[shared worker transport](worker-ipc.md); the operation vocabulary, kind rights
|
||||
and token lifecycle below remain owned by this boundary.
|
||||
|
||||
```text
|
||||
{"op":"ping"} -> {"ok":true} (handshake)
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# Shared persistent-worker transport
|
||||
|
||||
Status: **implemented pre-stable internal transport**, owner crate
|
||||
`crates/marqdo-worker-ipc`, introduced by
|
||||
[ADR-0068](../docs/adr/0068-single-current-public-contracts.md) for issue #8.
|
||||
|
||||
This document is not a public product protocol and has no `schema_version`.
|
||||
It describes the one implementation of the framing and process plumbing that
|
||||
the two persistent worker boundaries — the plugin worker
|
||||
([plugin ABI](plugin-abi.md) §9) and the resource-provider worker
|
||||
([resource provider](resource-provider-v2.md) §5) — use instead of maintaining
|
||||
private copies.
|
||||
|
||||
## 1. What is shared, and what is not
|
||||
|
||||
Shared (`crates/marqdo-worker-ipc`):
|
||||
|
||||
- the four-byte big-endian length prefix followed by one JSON value;
|
||||
- maximum-frame bounding supplied by each caller (8 MiB plugins, 1 MiB
|
||||
providers) and rejection of zero/oversized lengths;
|
||||
- clean EOF at a frame boundary versus a partial header, truncated payload or
|
||||
invalid JSON;
|
||||
- one reader thread and one writer thread per child, so a caller never reads
|
||||
and writes the same pipe concurrently;
|
||||
- caller-supplied exchange deadlines, process kill/reap on any transport
|
||||
failure, and "a dead worker is never reused";
|
||||
- structured transport errors (`Timeout`, `Closed`, `Frame`).
|
||||
|
||||
Not shared — each boundary keeps its own:
|
||||
|
||||
- frame vocabulary and state machine (`ready`/`invoke`/`capability_*` versus
|
||||
`ping`/`open`/`read`/`write`/`close`/`shutdown`);
|
||||
- frame size limit and capability/budget policy;
|
||||
- authorization, grants, kind/rights checks and lifecycle;
|
||||
- error codes and public observation.
|
||||
|
||||
A shared transport never shares capabilities, trust or identity. Killing a
|
||||
worker after a transport failure is plumbing; deciding what a worker may do is
|
||||
a separate gate.
|
||||
|
||||
Foreign kernels and CLI Tools are deliberately excluded. A foreign kernel is a
|
||||
one-shot process whose stdout must be exactly one value-wire object
|
||||
([foreign](foreign.md)); a CLI Tool is an independent executable that owns its
|
||||
standard streams ([CLI tool](cli-tool.md)). Neither has a persistent framed
|
||||
channel, and neither may gain one by reusing this crate.
|
||||
|
||||
## 2. Framing rules
|
||||
|
||||
```text
|
||||
+--------------------------+---------------------------+
|
||||
| 4-byte big-endian length | exactly `length` bytes |
|
||||
| (1 ..= caller limit) | of one JSON value |
|
||||
+--------------------------+---------------------------+
|
||||
```
|
||||
|
||||
| Outcome | Classification |
|
||||
|---|---|
|
||||
| EOF before any header byte | clean `None` (not an error) |
|
||||
| EOF inside the four-byte header | `FrameError::PartialHeader` |
|
||||
| length `0` or above the caller limit | `FrameError::Length` |
|
||||
| EOF inside the payload | `FrameError::PartialPayload` |
|
||||
| payload is not UTF-8 JSON | `FrameError::InvalidJson` |
|
||||
| write larger than the caller limit | `FrameError::Length` (nothing written) |
|
||||
|
||||
Writers flush every frame. Readers bound the allocation before reading. There
|
||||
is no negotiation, no version field and no fallback: each boundary has exactly
|
||||
one current frame shape at its existing format identifier.
|
||||
|
||||
## 3. Exchange and deadline rules
|
||||
|
||||
The host-side `Connection` is sequential: one exchange is in flight at a time.
|
||||
The caller passes an `Instant` deadline with `send`/`receive`; a missed deadline
|
||||
kills and reaps the child and returns `TransportError::Timeout`. Clean EOF
|
||||
before a reply returns `Closed`; a malformed frame returns `Frame` with the
|
||||
classification above. Every transport error aborts the connection, so a worker
|
||||
that timed out, crashed or violated framing is never reused for a later call.
|
||||
|
||||
The worker side uses the same `read_frame`/`write_frame` functions on its own
|
||||
stdin/stdout. Worker processes still exit non-zero on malformed input rather
|
||||
than guessing at a retired format.
|
||||
|
||||
## 4. Boundary-specific deadlines (current values)
|
||||
|
||||
| Boundary | Handshake | One exchange | Quarantine |
|
||||
|---|---|---|---|
|
||||
| Plugin worker | 30 s | 10 s per invocation, covering capability round-trips | killed, `plugin.timeout` |
|
||||
| Resource-provider worker | 30 s (ping) | 30 s per request | killed, host error |
|
||||
|
||||
Timeouts classify a failed exchange; they do not change program semantics.
|
||||
The strict sandbox decision is still made by the OS isolation adapter, never by
|
||||
the fact that a worker is a child process.
|
||||
|
||||
## 5. Verification
|
||||
|
||||
`crates/marqdo-worker-ipc` owns the transport tests: framing round-trip,
|
||||
boundary/EOF classification, oversize rejection, a live two-frame exchange, a
|
||||
silent child hitting its deadline and being reaped, clean EOF, and a truncated
|
||||
payload. The plugin and provider suites keep testing their own vocabulary,
|
||||
grants, token lifecycle and error codes through the real worker binaries, so a
|
||||
transport refactor cannot hide a behaviour change at either boundary.
|
||||
Reference in new issue
Block a user