Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/dim-agent-capabilities/src/file_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ pub struct FilePath {
/// stores it.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
pub struct DirectoryEntry {
#[serde(serialize_with = "face::serialize_name")]
#[serde(serialize_with = "crate::os_string::serialize")]
pub name: OsString,
pub kind: EntryKind,
}
Expand Down
37 changes: 2 additions & 35 deletions crates/dim-agent-capabilities/src/file_storage/face.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rutis::Ctx;
use rutis_bridge::session::{Error, HostDispatch, Reply, Value};
use serde::{Deserialize, Serialize};
use std::{
ffi::{OsStr, OsString},
ffi::OsString,
path::{Component, Path},
sync::Arc,
};
Expand All @@ -18,39 +18,6 @@ pub struct OpenRead {
pub size: u64,
}

pub(super) fn serialize_name<S: serde::Serializer>(
name: &OsStr,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
match name.to_str() {
Some(text) => serializer.serialize_str(text),
#[cfg(any(unix, windows))]
None => name.serialize(serializer),
#[cfg(not(any(unix, windows)))]
None => Err(serde::ser::Error::custom(
"unsupported filesystem name encoding",
)),
}
}

#[derive(Deserialize)]
#[serde(untagged)]
enum EntryName {
Text(String),
#[cfg(any(unix, windows))]
Native(OsString),
}

fn deserialize_name<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<OsString, D::Error> {
Ok(match EntryName::deserialize(deserializer)? {
EntryName::Text(text) => text.into(),
#[cfg(any(unix, windows))]
EntryName::Native(name) => name,
})
}

#[derive(Debug, Deserialize)]
#[serde(untagged, deny_unknown_fields)]
pub enum FsRemove {
Expand All @@ -59,7 +26,7 @@ pub enum FsRemove {
},
Entry {
parent: String,
#[serde(deserialize_with = "deserialize_name")]
#[serde(deserialize_with = "crate::os_string::deserialize")]
name: OsString,
},
}
Expand Down
21 changes: 16 additions & 5 deletions crates/dim-agent-capabilities/src/input_queue.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
mod face;
mod pending;
mod recovery;

Expand Down Expand Up @@ -450,7 +451,8 @@ impl DynPlugin for InputQueuePlugin {
pub const INPUT_METHODS: &str = "session.input";

/// The operator-input entry that asks the submit checks (Hooks A.6.2).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SubmitEntry {
/// Rpc `session.submit`.
Submit,
Expand All @@ -471,7 +473,8 @@ impl SubmitEntry {
}

/// The input an entry is about to write, as its checks see it (Hooks A.6.2).
#[derive(Clone, Debug)]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SubmitCheckRequest {
pub entry: SubmitEntry,
pub branch_id: String,
Expand All @@ -481,7 +484,8 @@ pub struct SubmitCheckRequest {
}

/// What one check decided for the input (Hooks A.6.2).
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SubmitCheckReply {
/// The input may be written; these contexts go after the operator's own
/// content, in name order. `warnings` are for the caller to show, never
Expand All @@ -497,7 +501,8 @@ pub enum SubmitCheckReply {
/// What the table decided for the input (Hooks A.6.2): every check that ran,
/// combined in name order. A block ends the table's work and carries neither
/// blocks nor warnings.
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum SubmitDecision {
/// The input may be written.
Proceed {
Expand Down Expand Up @@ -527,7 +532,7 @@ pub struct CheckInterrupted;
/// the operator-input entries call them before writing anything. No check is
/// registered unless a part registers one, and then the entries write
/// unchecked.
#[derive(Default)]
#[derive(Clone, Default)]
pub struct SubmitChecks {
checks: Arc<Registrations<Arc<dyn CheckSubmission>>>,
}
Expand Down Expand Up @@ -645,13 +650,15 @@ struct WithdrawParams {
/// Serves `session.input.withdraw` for every branch of its Session through
/// the branch's InputQueue, so Rpc names no owning service.
pub struct InputMethodsPlugin {
session: rutis::host::InstanceId,
tree: Key<TreeCommands>,
methods: Key<SessionMethods>,
checks: Key<SubmitChecks>,
}
impl InputMethodsPlugin {
pub fn new(names: &Names<'_>) -> std::result::Result<Self, Error> {
Ok(Self {
session: names.instance(dim_agent_runtime::SESSION_GROUP)?,
tree: names.key()?,
methods: names.key()?,
checks: names.key()?,
Expand All @@ -671,6 +678,10 @@ impl DynPlugin for InputMethodsPlugin {
let methods = ctx.require_at(&self.methods)?;
let checks = Arc::new(SubmitChecks::default());
ctx.provide_at(self.checks.clone(), checks.clone())?;
ctx.provide_at::<dyn rutis_bridge::session::HostDispatch>(
rutis_bridge::session::host_key_in("submitChecks", self.session),
checks.clone(),
)?;
methods.register(
ctx,
INPUT_METHODS,
Expand Down
134 changes: 134 additions & 0 deletions crates/dim-agent-capabilities/src/input_queue/face.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
use super::{CheckSubmission, SubmitCheckReply, SubmitCheckRequest, SubmitChecks};
use crate::{
host::{HostError, HostFuture},
port_faces::{invalid, unknown_method},
};
use rutis::host::CtxHost;
use rutis_bridge::session::{HostDispatch, Reference, Reply, Value, arg, decode_value, settle};
use std::sync::Arc;
use tokio_util::sync::CancellationToken;

struct ForeignCheck {
callback: Reference,
closing: CancellationToken,
}

impl CheckSubmission for ForeignCheck {
fn check(
&self,
request: SubmitCheckRequest,
cancel: CancellationToken,
) -> HostFuture<'_, SubmitCheckReply> {
Box::pin(async move {
let stop = cancel.child_token();
let _finish = stop.clone().drop_guard();
let cancelled = Value::callback(move |_| {
let stop = stop.clone();
Ok(Value::future(async move {
stop.cancelled().await;
Ok(Value::Undefined)
}))
});
let reply = async {
let result = self
.callback
.call_async(Value::List(vec![arg(&request)?, cancelled]))
.await?;
decode_value(settle(result).await?)
};
tokio::select! {
biased;
_ = cancel.cancelled() => Err(HostError::Cancelled("submit check interrupted".into())),
_ = self.closing.cancelled() => Err(HostError::failed("submit check unloaded")),
result = reply => result.map_err(|error| HostError::failed(error.to_string())),
}
})
}
}

impl HostDispatch for SubmitChecks {
fn methods(&self) -> Option<serde_json::Value> {
Some(serde_json::json!({"register":"async","check":"async"}))
}

fn invoke(&self, method: &str, args: Value) -> Reply {
match method {
"register" => {
let [name, Value::Reference(callback)] = <[_; 2]>::try_from(args.list()?)
.map_err(|_| invalid("submitChecks", "register expects a name and a check"))?
else {
return Err(invalid("submitChecks", "expected a check function"));
};
if !callback.is_function() {
return Err(invalid("submitChecks", "expected a check function"));
}
let name: String = decode_value(name)?;
let row = rutis_bridge::session::caller_row()
.ok_or_else(|| invalid("submitChecks", "register requires a calling row"))?;
let registered = self
.register(
row.ctx(),
&name,
Arc::new(ForeignCheck {
callback,
closing: row.ctx().cancellation_token(),
}),
)
.map(|()| Value::Undefined)
.map_err(|error| {
rutis_bridge::exports::failure(
"SubmitCheckError",
"failed",
error.to_string(),
None,
)
});
Ok(Value::future(async move { registered }))
}
"check" => {
let [request, Value::Reference(cancelled)] = <[_; 2]>::try_from(args.list()?)
.map_err(|_| {
invalid(
"submitChecks",
"check expects a request and cancellation function",
)
})?
else {
return Err(invalid("submitChecks", "expected a cancellation function"));
};
if !cancelled.is_function() {
return Err(invalid("submitChecks", "expected a cancellation function"));
}
let request: SubmitCheckRequest = decode_value(request)?;
let owner = self.clone();
let stop = rutis_bridge::session::caller_row()
.map(|row| row.ctx().cancellation_token().child_token())
.unwrap_or_default();
Ok(Value::cancellable_future(async move {
let _finish = stop.clone().drop_guard();
let run = owner.check(&request, &stop);
tokio::pin!(run);
let cancellation =
async { settle(cancelled.call_async(Value::List(vec![])).await?).await };
let result = tokio::select! {
result = &mut run => result,
_ = cancellation => {
stop.cancel();
run.await
}
}
.map_err(|_| {
rutis_bridge::exports::failure(
"SubmitCheckError",
"cancelled",
"submit check interrupted".into(),
None,
)
})?;
arg(&result)
}))
}
_ => Err(unknown_method("submitChecks", method)),
}
}
}
1 change: 1 addition & 0 deletions crates/dim-agent-capabilities/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub mod images;
pub mod input_queue;
pub mod methods;
pub mod model_provider;
mod os_string;
mod output;
pub mod permission;
mod port_faces;
Expand Down
37 changes: 37 additions & 0 deletions crates/dim-agent-capabilities/src/os_string.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use serde::{Deserialize, Serialize};
use std::ffi::{OsStr, OsString};

pub(crate) fn serialize<S: serde::Serializer>(
name: &impl AsRef<OsStr>,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
let name = name.as_ref();
match name.to_str() {
Some(text) => serializer.serialize_str(text),
#[cfg(any(unix, windows))]
None => name.serialize(serializer),
#[cfg(not(any(unix, windows)))]
None => Err(serde::ser::Error::custom(
"unsupported filesystem name encoding",
)),
}
}

#[derive(Deserialize)]
#[serde(untagged)]
enum OsValue {
Text(String),
#[cfg(any(unix, windows))]
Native(OsString),
}

pub(crate) fn deserialize<'de, T: From<OsString>, D: serde::Deserializer<'de>>(
deserializer: D,
) -> std::result::Result<T, D::Error> {
Ok(match OsValue::deserialize(deserializer)? {
OsValue::Text(text) => text.into(),
#[cfg(any(unix, windows))]
OsValue::Native(name) => name,
}
.into())
}
Loading