use std::collections::{HashMap, VecDeque};
use serde::{Deserialize, Serialize};
pub use window_actions::{
APPLICATION_ACTIVATE_ACTION, APPLICATION_ACTIVATE_TYPE, APPLICATION_OPEN_LINK_ACTION,
APPLICATION_OPEN_LINK_TYPE, APPLICATION_OPEN_TYPE, APPLICATION_OUTLINE_ACTION,
APPLICATION_OUTLINE_TYPE, OPEN_LINK_PARAM, OUTLINE_ANCHOR_PARAM, OUTLINE_PICTURE_UNAVAILABLE,
activate_spec, activation_requested, link_scheme, open_link_arguments, outline_anchor,
outline_asked, outline_spec,
};
pub mod admitted;
pub use admitted::{Admits, Admitted, LiveRead, LiveView, Outcome, ReportsProgress, Serving};
mod application;
pub mod asked;
pub mod audio_output;
pub mod call;
mod caller;
pub mod native_media;
pub mod shell;
pub use caller::{Caller, Invited, KeptCaller, KeyCall, PlacedCaller, device_agent_id};
pub mod signed_invocation;
pub use signed_invocation::{CallAllowed, SignedCall, SignedInvocation};
mod catalogue;
mod changes;
mod confirmation;
mod content_get;
mod content_link;
mod content_put;
pub mod device_tickets;
mod pending;
pub mod session_actions;
mod vault;
pub use vault::{
ItemRef, KEEP_SEALED, KEEP_USES, REMOVE_SEALED, VAULT_DEVICE_KEY, VAULT_FIND,
VAULT_FORGET_PAGE_LOGIN, VAULT_ITEM_KIND, VAULT_KEEP, VAULT_KEEP_PAGE_LOGIN, VAULT_KIND,
VAULT_LIST, VAULT_PAGE_FILL, VAULT_PAGE_LOGINS, VAULT_PROVIDER, VAULT_RECORD, VAULT_RELEASE,
VAULT_RESOURCE, VAULT_SECRET_ANSWERS, answers_secret, calls_answering_a_secret,
calls_by_address, item_param, takes_item, vault_target,
};
pub mod press_points;
mod providers;
mod resource_read;
pub mod secret_arguments;
mod session_state;
mod shared_provider;
mod store_commands;
mod surfaces;
pub use session_state::{SessionState, SyncState, WorkspaceState};
mod wait;
mod watch;
pub use watch::{CHANGED_UNAVAILABLE, Here, HereWindow, KEY_GRANTS, PRESENCE, WatchScope};
mod window_actions;
mod within;
pub mod workspace_activity;
pub use application::{
APPLICATION_PROVIDER, ApplicationLaunch, CONTENT_HASH_ARGUMENT, NAME_ARGUMENT,
application_action_target, application_open_target, application_provider,
application_provider_resource, application_provider_token, application_resource_target,
valid_file_name,
};
pub use confirmation::{
ASK, ASK_PROVIDER, ASK_RESOURCE, ASK_WITH_CHOICES, Confirmation, ConfirmationQuestion,
ConfirmationReply, MAX_ASK_CHARS, MAX_ASK_CHOICES, MAX_CHOICE_CHARS, PersonAnswer, PersonAsk,
argument_digest, ask_target, is_ask,
};
pub use providers::{
APPLICATION_OPEN_ACTION, APPLICATION_RESOURCE_KIND, APPLICATION_RESOURCE_PREFIX,
APPLICATION_START_ACTION, OWN_PROVIDER, RESOURCE_PROVIDER, SHARE_LINK_ACTION,
WORKSPACE_PROVIDER, is_resource_provider, resource_parts,
};
pub use catalogue::{
CanonicalActionRoute, CatalogueLimits, CataloguePage, CatalogueProvider, CatalogueQuery,
CatalogueResource, CatalogueRow, MAX_BY_RESOURCE_PAGE, MAX_CATALOGUE_PAGE,
MAX_CATALOGUE_PAGE_BYTES, Offered, ProvidedPackage, ProvidedResource, ResourceViewLocator,
RowVisibility, ViewResourceQuery, compact, expand, rows_weight, stem_word, truncate_bytes,
truncate_resources, truncate_rows,
};
pub use changes::{CHANGE_FEED_UNAVAILABLE, ChangeFeed, ChangePage, ResourceChanged, What};
pub use content_get::{CONTENT_GETS_UNAVAILABLE, ContentGetAnswer, ContentGets, ContentPiece};
pub use content_link::{
CONTENT_LINK_TTL_SECS, CONTENT_LINKS_UNAVAILABLE, ContentLink, ContentLinkAsk, ContentLinkFile,
MAX_CONTENT_LINK_FILES, viewable,
};
pub use content_put::{
CONTENT_PUTS_UNAVAILABLE, CONTENT_REFERENCE, ContentPut, ContentPutAnswer, ContentPutStep,
ContentPuts, HostedContentPuts, MAX_CONTENT_PUT_AHEAD, MAX_CONTENT_PUT_CHUNK, MAX_HAVE_HASHES,
MAX_HOSTED_CONTENT_PUTS, MAX_OPEN_CONTENT_PUTS, MAX_PUT_MANY_BYTES, MAX_PUT_MANY_FILES,
content_hash,
};
pub use store_commands::{STORE_COMMANDS_UNAVAILABLE, StoreCommands};
mod execution_lease;
pub use execution_lease::ExecutionLease;
pub use pending::{Abandoned, Completer, Pending, PendingPoll, pending};
pub use resource_read::{
DEVICE_JOBS, DEVICE_SETTINGS, DEVICE_SETTINGS_REFUSED, Decided, HeldCopies, ListedResource,
RESOURCE_READ_REFUSED, RESOURCE_READS_FOR_AGENTS, RESOURCE_READS_UNAVAILABLE,
RESOURCE_WRITE_REFUSED, ReadingAnswer, ReadsAnswer, ResourceAddress, ResourceAsk, ResourceCopy,
ResourceReadings, ResourceReads, ResourceWake, answer_read, answered, device_job_address,
device_job_path, device_record_address, device_record_space, parse_device_record_space,
parse_job_path, read_resources, readings_from, readings_of, reads_answer,
};
pub use wait::{MAX_REMOTE_WAIT, MAX_REMOTE_WAIT_MS, UpdateMark, settle_with};
use crate::api::ActionAddress;
use crate::context::ActionContext;
use crate::outcome::{ActionFailure, ActionOutput, InvocationId, InvocationUpdate};
use crate::params::ARGUMENTS_JSON_PREFIX;
pub const REMOTE_ACTIONS_VERSION: u16 = 5;
pub const MAX_REMOTE_ACTION_FRAME_BYTES: usize = 1024 * 1024;
pub const MAX_CONTENT_FRAME_BYTES: usize = 384 * 1024;
pub const DEFAULT_LOG_CAPACITY: usize = 1024;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RemoteActionTarget {
pub provider: String,
pub address: ActionAddress,
}
pub const WORKSPACE_GOVERNANCE_PROVIDER: &str = tilo_action_policy::agent_answers::WORKSPACE_APP;
pub const WORKSPACE_GOVERNANCE_KIND: &str = "workspace.permissions";
impl RemoteActionTarget {
#[must_use]
pub fn workspace_governance(workspace: &str, verb: &str) -> Self {
Self {
provider: WORKSPACE_GOVERNANCE_PROVIDER.to_owned(),
address: workspace_governance_address(workspace, verb),
}
}
}
#[must_use]
pub fn workspace_governance_resource(workspace: &str) -> String {
format!("{WORKSPACE_GOVERNANCE_KIND}:{workspace}")
}
pub const WORKSPACE_SERVERS: &str = "servers";
pub const WORKSPACE_APPS: &str = "apps";
pub const WORKSPACE_TRUST: &str = "trust";
pub const WORKSPACE_REGISTRIES: &str = "registries";
pub const WORKSPACE_CONTENT: &str = "content";
pub const WORKSPACE_APP: &str = "apps/*";
pub const WORKSPACE_MAIL_ACCOUNTS: &str = "mail-accounts";
pub const WORKSPACE_VAULT: &str = "vault";
pub const WORKSPACE_MODELS: &str = "models";
pub const WORKSPACE_MEMBERS: &str = "members";
pub const WORKSPACE_MEMBER: &str = "members/*";
pub const WORKSPACE_INVITE: &str = "invite";
pub const WORKSPACE_MEMBER_ADMITTED: &str = "admit";
pub const WORKSPACE_MEMBER_PLACED: &str = "role";
pub const WORKSPACE_MEMBER_REMOVED: &str = "remove";
pub const WORKSPACE_INVITATIONS: &str = "invitations";
pub const WORKSPACE_WAITING: &str = "waiting";
pub const WORKSPACE_PERMISSIONS: &str = "permissions";
pub const WORKSPACE_PERMISSION: &str = "permissions/*";
pub const WORKSPACE_GRANT_REVOKE: &str = "grant.revoke";
pub const WORKSPACE_READ_GRANT: &str = "reading.grant";
pub const WORKSPACE_READ_REVOKE: &str = "reading.revoke";
pub const WORKSPACE_AGENTS: &str = "agents";
pub const WORKSPACE_AGENT_CREATE: &str = "agent.create";
pub const WORKSPACE_AGENT_UPDATE: &str = "agent.update";
pub const WORKSPACE_AGENT_DELETE: &str = "agent.delete";
pub const WORKSPACE_AGENTS_APP: &str = "so.tilo.workspace";
pub const WORKSPACE_AGENTS_KIND: &str = "tilo.workspace.agent";
pub const WORKSPACE_AGENT_CHANGES: [&str; 15] = [
"set-agent-spend-limit",
"record-agent-spend",
"rename-agent",
"set-agent-avatar",
"set-agent-model",
"set-agent-instruction",
"pause-agent",
"resume-agent",
"start-sub-agent",
"note-sub-agent",
"stop-sub-agent",
"sub-agent-stands",
"sub-agent-produced",
"sub-agent-coding",
"set-sub-agent-limits",
];
#[must_use]
pub fn workspace_agent_effects(operation: &str) -> Vec<crate::ActionEffect> {
let step =
|verb: &str| crate::ActionEffect::new(WORKSPACE_AGENTS_APP, WORKSPACE_AGENTS_KIND, verb);
match operation {
WORKSPACE_AGENT_CREATE => vec![step("create-agent")],
WORKSPACE_AGENT_UPDATE => WORKSPACE_AGENT_CHANGES
.iter()
.map(|verb| step(verb))
.collect(),
WORKSPACE_AGENT_DELETE => vec![step("retire-agent")],
_ => Vec::new(),
}
}
pub const WORKSPACE_MEMBER_LIST_PUBLISHED: [(&str, Option<&str>, &str); 47] = [
("member.list", Some(WORKSPACE_MEMBERS), "list"),
(
"member.add",
Some(WORKSPACE_MEMBERS),
WORKSPACE_MEMBER_ADMITTED,
),
(
"member.add",
Some(WORKSPACE_MEMBER),
WORKSPACE_MEMBER_PLACED,
),
(
"remove-member",
Some(WORKSPACE_MEMBER),
WORKSPACE_MEMBER_REMOVED,
),
("member.name", Some(WORKSPACE_MEMBERS), "name"),
("ban", Some(WORKSPACE_MEMBERS), "ban"),
("unban", Some(WORKSPACE_MEMBERS), "unban"),
("invite", Some(WORKSPACE_INVITATIONS), "invite"),
("invitation.list", Some(WORKSPACE_INVITATIONS), "list"),
("invitation.cancel", Some(WORKSPACE_INVITATIONS), "cancel"),
("wait-list.list", Some(WORKSPACE_WAITING), "list"),
("wait-list.remove", Some(WORKSPACE_WAITING), "unlist"),
("wait-list.mail", Some(WORKSPACE_WAITING), "mail"),
("server.list", Some(WORKSPACE_SERVERS), "list"),
("server.add", Some(WORKSPACE_SERVERS), "add"),
("server.remove", Some(WORKSPACE_SERVERS), "remove"),
("server.move", Some(WORKSPACE_SERVERS), "move"),
("copies.set", Some(WORKSPACE_SERVERS), "copies"),
("copies.read", Some(WORKSPACE_SERVERS), "keeps"),
("content.held", Some(WORKSPACE_SERVERS), "content"),
("content.policy", Some(WORKSPACE_CONTENT), "policy"),
("content.set-policy", Some(WORKSPACE_CONTENT), "set-policy"),
("trust.list", Some(WORKSPACE_TRUST), "list"),
("trust.revoked", Some(WORKSPACE_TRUST), "revoked"),
("trust.add", Some(WORKSPACE_TRUST), "add"),
("trust.remove", Some(WORKSPACE_TRUST), "remove"),
("trust.revoke", Some(WORKSPACE_TRUST), "revoke"),
("registry.list", Some(WORKSPACE_REGISTRIES), "list"),
("registry.add", Some(WORKSPACE_REGISTRIES), "add"),
("registry.remove", Some(WORKSPACE_REGISTRIES), "remove"),
("registry.enable", Some(WORKSPACE_REGISTRIES), "enable"),
("registry.disable", Some(WORKSPACE_REGISTRIES), "disable"),
("registry.channel", Some(WORKSPACE_REGISTRIES), "channel"),
("install-app", Some(WORKSPACE_APPS), "install"),
("upload-app-file", Some(WORKSPACE_APPS), "upload"),
("app.offers", Some(WORKSPACE_APPS), "offers"),
("install-app", Some(WORKSPACE_APP), "update"),
("app.pin", Some(WORKSPACE_APP), "pin"),
("app.unpin", Some(WORKSPACE_APP), "unpin"),
("uninstall-app", Some(WORKSPACE_APP), "uninstall"),
("app.earlier", Some(WORKSPACE_APP), "earlier"),
(WORKSPACE_GRANT_REVOKE, Some(WORKSPACE_PERMISSION), "revoke"),
(WORKSPACE_READ_GRANT, Some(WORKSPACE_MEMBERS), "grant-read"),
(
WORKSPACE_READ_REVOKE,
Some(WORKSPACE_MEMBERS),
"revoke-read",
),
(WORKSPACE_AGENT_CREATE, Some(WORKSPACE_AGENTS), "create"),
(WORKSPACE_AGENT_UPDATE, Some(WORKSPACE_AGENTS), "update"),
(WORKSPACE_AGENT_DELETE, Some(WORKSPACE_AGENTS), "delete"),
];
pub const WORKSPACE_INVOCATIONS_PROVIDER: &str = "tilo.invocations";
pub const MACHINES_PROVIDER: &str = "tilo.machines";
pub const SERVER_ACCOUNT_PROVIDER: &str = "tilo.server";
pub const WORKSPACE_EVENTS_PROVIDER: &str = "tilo.events";
pub const MODERATION_PROVIDER: &str = "tilo.moderation";
pub const MODERATION_HISTORY: &str = "moderation.history";
pub const MODERATION_UNDO: &str = "undo";
pub const MODERATED_APP: &str = "so.tilo.chat";
pub const MODELS_PROVIDER: &str = "tilo.models";
pub const TELLING_PROVIDER: &str = "tilo.telling";
pub const ACCOUNTS_PROVIDER: &str = "tilo.accounts";
pub const CONNECTIONS_PROVIDER: &str = "tilo.connections";
#[must_use]
pub fn workspace_governance_child(workspace: &str, child: Option<&str>) -> String {
let root = workspace_governance_resource(workspace);
match child {
Some(child) => format!("{root}/{child}"),
None => root,
}
}
#[must_use]
pub fn workspace_permission(workspace: &str, grant: &str) -> String {
format!(
"{}/{grant}",
workspace_governance_child(workspace, Some(WORKSPACE_PERMISSIONS))
)
}
#[must_use]
pub fn workspace_member(workspace: &str, person: &str) -> String {
format!(
"{}/{person}",
workspace_governance_child(workspace, Some(WORKSPACE_MEMBERS))
)
}
#[must_use]
pub fn workspace_app(workspace: &str, app: &str) -> String {
format!(
"{}/{app}",
workspace_governance_child(workspace, Some(WORKSPACE_APPS))
)
}
#[must_use]
pub fn workspace_governance_address(workspace: &str, operation: &str) -> ActionAddress {
match WORKSPACE_MEMBER_LIST_PUBLISHED
.iter()
.find(|(granted, child, _)| {
*granted == operation
&& *child != Some(WORKSPACE_MEMBER)
&& *child != Some(WORKSPACE_APP)
&& *child != Some(WORKSPACE_PERMISSION)
}) {
Some((_, child, action)) => {
ActionAddress::new(workspace_governance_child(workspace, *child), *action)
}
None => ActionAddress::new(workspace_governance_resource(workspace), operation),
}
}
#[must_use]
pub fn workspace_governance_operation(address: &ActionAddress) -> Option<(&str, &str)> {
let named = address
.resource
.strip_prefix(workspace_governance_resource("").as_str())?;
let (workspace, child) = match named.split_once('/') {
Some((workspace, child)) => (workspace, Some(child)),
None => (named, None),
};
if workspace.is_empty() {
return None;
}
let action = address.action.as_str();
let child = if workspace_person(address).is_some() {
Some(WORKSPACE_MEMBER)
} else if workspace_app_named(address).is_some() {
Some(WORKSPACE_APP)
} else if workspace_grant(address).is_some() {
Some(WORKSPACE_PERMISSION)
} else {
child
};
let published = WORKSPACE_MEMBER_LIST_PUBLISHED
.iter()
.find(|(_, at, published)| *at == child && *published == action);
match published {
Some((granted, _, _)) => Some((workspace, granted)),
None if child.is_none()
&& !WORKSPACE_MEMBER_LIST_PUBLISHED
.iter()
.any(|(granted, _, _)| *granted == action) =>
{
Some((workspace, action))
}
None => None,
}
}
#[must_use]
pub fn workspace_person(address: &ActionAddress) -> Option<&str> {
let named = address
.resource
.strip_prefix(workspace_governance_resource("").as_str())?;
let (members, person) = named.split_once('/')?.1.split_once('/')?;
(members == WORKSPACE_MEMBERS
&& person.len() == 64
&& person.bytes().all(|byte| byte.is_ascii_hexdigit()))
.then_some(person)
}
#[must_use]
pub fn workspace_app_named(address: &ActionAddress) -> Option<&str> {
let named = address
.resource
.strip_prefix(workspace_governance_resource("").as_str())?;
let (apps, app) = named.split_once('/')?.1.split_once('/')?;
(apps == WORKSPACE_APPS
&& !app.is_empty()
&& app
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')))
.then_some(app)
}
#[must_use]
pub fn workspace_grant(address: &ActionAddress) -> Option<&str> {
let named = address
.resource
.strip_prefix(workspace_governance_resource("").as_str())?;
let (permissions, grant) = named.split_once('/')?.1.split_once('/')?;
(permissions == WORKSPACE_PERMISSIONS && !grant.is_empty()).then_some(grant)
}
pub mod settings_resources {
pub const PROVIDER: &str = "tilo.settings";
pub const SURFACE_APP: &str = "so.tilo.settings.sections";
#[must_use]
pub fn is_section(path: &str) -> bool {
let resource = path.split('#').next().unwrap_or_default();
let parts: Vec<&str> = resource.split('/').collect();
matches!(parts.as_slice(), ["settings", section] if !section.is_empty())
|| matches!(parts.as_slice(), ["devices", device, "settings", section]
if !device.is_empty() && !section.is_empty())
}
}
pub const CONFIRMED_ACTION_NEEDS_REVISION: &str =
"a confirmed action needs the revision it was shown at";
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum InvokeArgument {
#[default]
None,
Text(String),
Json(serde_json::Map<String, serde_json::Value>),
}
impl InvokeArgument {
#[must_use]
pub fn to_slot(&self) -> Option<String> {
match self {
Self::None => None,
Self::Text(text) => Some(text.clone()),
Self::Json(object) => Some(format!(
"{ARGUMENTS_JSON_PREFIX}{}",
serde_json::Value::Object(object.clone())
)),
}
}
#[must_use]
pub fn from_slot(slot: Option<&str>) -> Self {
match slot {
None => Self::None,
Some(text) => match text
.strip_prefix(ARGUMENTS_JSON_PREFIX)
.and_then(|json| serde_json::from_str(json).ok())
{
Some(object) => Self::Json(object),
None => Self::Text(text.to_owned()),
},
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvokeRequest {
pub invocation: InvocationId,
pub target: RemoteActionTarget,
#[serde(default)]
pub argument: InvokeArgument,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub context: Option<ActionContext>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confirmation: Option<Confirmation>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revision: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<InvocationId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub appearance: Option<crate::Appearance>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signed: Option<Box<SignedInvocation>>,
}
impl InvokeRequest {
#[must_use]
pub fn made_from(&self) -> Option<crate::params::MadeFrom> {
let InvokeArgument::Json(arguments) = &self.argument else {
return None;
};
crate::params::MadeFrom::from_json(arguments.get(crate::params::FROM_ARGUMENT)?)
}
#[must_use]
pub fn approval(&self) -> Option<&asked::Approval> {
match &self.confirmation {
Some(Confirmation::Asked(approval)) => Some(approval),
_ => None,
}
}
#[must_use]
pub fn said_session_name(&self) -> Option<String> {
let group = self
.context
.as_ref()?
.group
.as_ref()
.filter(|group| group.kind == crate::context::AGENT_SESSION_GROUP)?;
crate::context::one_line(group.session.as_deref()?, crate::context::MAX_LABEL_CHARS)
}
#[must_use]
pub fn same_invocation(&self, other: &Self) -> bool {
let Self {
invocation,
target,
argument,
context,
confirmation,
revision,
on_behalf_of,
wait_ms: _,
appearance,
signed: _,
} = self;
*invocation == other.invocation
&& *target == other.target
&& *argument == other.argument
&& *context == other.context
&& *confirmation == other.confirmation
&& *revision == other.revision
&& *on_behalf_of == other.on_behalf_of
&& *appearance == other.appearance
}
#[must_use]
pub fn plain(
target: RemoteActionTarget,
arguments: serde_json::Map<String, serde_json::Value>,
) -> Self {
Self {
invocation: InvocationId::new(),
target,
argument: if arguments.is_empty() {
InvokeArgument::None
} else {
InvokeArgument::Json(arguments)
},
context: None,
confirmation: None,
revision: None,
on_behalf_of: None,
wait_ms: None,
appearance: None,
signed: None,
}
}
}
pub const APPLICATION_CLOSE_ACTION: &str = "close";
#[must_use]
pub fn workspace_provider(workspace: &str) -> String {
format!("{WORKSPACE_PROVIDER}:{workspace}")
}
pub const ACTIONS_PROVIDER: &str = "tilo.actions";
#[must_use]
pub fn provider_workspace(provider: &str) -> Option<&str> {
provider
.strip_prefix(WORKSPACE_PROVIDER)
.and_then(|rest| rest.strip_prefix(':'))
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ReceiptStatus {
Accepted,
Completed { output: ActionOutput },
Failed { error: ActionFailure },
Rejected { error: ActionCallError },
Cancelled { message: Option<String> },
}
impl ReceiptStatus {
#[must_use]
pub const fn is_terminal(&self) -> bool {
!matches!(self, Self::Accepted)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationReceipt {
pub invocation: InvocationId,
pub status: ReceiptStatus,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct InvocationState {
pub update: InvocationUpdate,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub untrusted: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub left_at: Option<ActorPlace>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub link: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub read_answered: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActorPlace {
pub anchor: String,
pub head: String,
}
impl InvocationState {
#[must_use]
pub fn new(invocation: InvocationId, update: InvocationUpdate) -> Self {
Self {
update: update.with_invocation(invocation),
untrusted: false,
left_at: None,
link: None,
read_answered: false,
}
}
#[must_use]
pub fn of_read(mut self) -> Self {
self.read_answered = matches!(
&self.update,
InvocationUpdate::Item { value, .. }
if value.get("pending") != Some(&serde_json::Value::Bool(true))
);
self
}
#[must_use]
pub fn left_at(mut self, place: Option<ActorPlace>) -> Self {
self.left_at = place;
self
}
#[must_use]
pub fn linked(mut self, link: Option<String>) -> Self {
self.link = link;
self
}
#[must_use]
pub fn with_untrusted(mut self, untrusted: bool) -> Self {
self.untrusted = untrusted;
self
}
#[must_use]
pub fn invocation(&self) -> InvocationId {
self.update.invocation()
}
#[must_use]
pub fn is_terminal(&self) -> bool {
self.update.is_terminal()
}
#[must_use]
pub fn receipt(&self) -> InvocationReceipt {
let status = match &self.update {
InvocationUpdate::Accepted { .. }
| InvocationUpdate::Progress { .. }
| InvocationUpdate::Item { .. } => ReceiptStatus::Accepted,
InvocationUpdate::Succeeded { output, .. } => ReceiptStatus::Completed {
output: output.clone(),
},
InvocationUpdate::Failed { error, .. } if error.code == CONFIRMATION_REQUIRED_CODE => {
ReceiptStatus::Rejected {
error: ActionCallError::asks(asked::AskedFacts::from_details(
error.details.as_ref(),
)),
}
}
InvocationUpdate::Failed { error, .. } => ReceiptStatus::Failed {
error: error.clone(),
},
InvocationUpdate::Cancelled { message, .. } => ReceiptStatus::Cancelled {
message: message.clone(),
},
};
InvocationReceipt {
invocation: self.invocation(),
status,
}
}
}
pub const CONFIRMATION_REQUIRED_CODE: &str = "action_confirmation_required";
pub const AWAITING_APPROVAL: &str = "awaiting_approval";
pub const NOT_ON_THIS_SERVER: &str = "not_on_this_server";
pub const HOSTS_NONE_FOR_PEOPLE: &str = "hosts_none_for_people";
pub const KEY_REVOKED: &str = "key_revoked";
pub const APPROVE_AGAIN: &str = "approve a new key: the person types `tilo do account/keys#create name=\"<name>\"` \
and approves it in their Tilo tab (on their own computer, `tilo login` again)";
#[must_use]
pub fn not_on_this_server(person: &[u8; 32]) -> ActionCallError {
let key = hex::encode(person);
ActionCallError::Refused {
reason: format!(
"{NOT_ON_THIS_SERVER}: This server doesn't know you yet: its operator hasn't made you \
an owner, and no invitation brought you into a workspace here. Ask the operator to \
declare your key {key} an owner (on a local stack: `stack.sh owner {key}`), or join \
with an invitation link someone here sends you."
),
}
}
pub const AWAITING_APPROVAL_REASON: &str = "awaiting_approval: it waits for its person to approve it on a device that holds their identity";
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(from = "WireActionCallError", into = "WireActionCallError")]
pub enum ActionCallError {
#[error("remote actions are unavailable: {reason}")]
Unavailable { reason: String },
#[error("no such action is offered")]
UnknownAction,
#[error("the caller may not invoke this action")]
NotPermitted,
#[error("the action requires confirmation")]
ConfirmationRequired(Box<asked::AskedFacts>),
#[error("invalid request: {reason}")]
InvalidRequest { reason: String },
#[error("invalid request: {}", STALE_REVISION_REASON)]
StaleRevision,
#[error("no such invocation")]
UnknownInvocation,
#[error("the invocation id was already used for a different request")]
InvocationConflict,
#[error("the invocation cannot be cancelled: {reason}")]
NotCancellable { reason: String },
#[error("refused: {reason}")]
Refused { reason: String },
#[error("the workspace is not ready for this call yet")]
NotReady,
#[error("the action's provider did not answer in time")]
Unanswered,
}
impl ActionCallError {
#[must_use]
pub fn from_api(error: &crate::ApiError) -> Self {
use crate::ApiError;
match error {
ApiError::Unknown(_) | ApiError::UnregisteredType(_) => Self::UnknownAction,
ApiError::MissingArgument(_)
| ApiError::UnexpectedArgument(_)
| ApiError::InvalidArguments(_)
| ApiError::ArgumentOutOfRange { .. } => Self::InvalidRequest {
reason: error.to_string(),
},
ApiError::ConfirmationRequired => Self::confirmation_required(),
ApiError::Unavailable { .. } | ApiError::Refused { .. } | ApiError::Failed(_) => {
Self::Refused {
reason: error.to_string(),
}
}
}
}
#[must_use]
pub fn confirmation_required() -> Self {
Self::asks(asked::AskedFacts::default())
}
#[must_use]
pub fn asks(facts: asked::AskedFacts) -> Self {
Self::ConfirmationRequired(Box::new(facts))
}
#[must_use]
pub fn refused(reason: impl Into<String>) -> Self {
Self::Refused {
reason: reason.into(),
}
}
#[must_use]
pub fn own_words(&self) -> String {
match self {
Self::Refused { reason } => reason.clone(),
other => other.to_string(),
}
}
#[must_use]
pub fn invalid_request(reason: impl Into<String>) -> Self {
Self::InvalidRequest {
reason: reason.into(),
}
}
#[must_use]
pub fn unavailable(reason: impl Into<String>) -> Self {
Self::Unavailable {
reason: reason.into(),
}
}
#[must_use]
pub fn awaits_person(&self) -> bool {
matches!(self, Self::Refused { reason } if reason == AWAITING_APPROVAL_REASON)
}
#[must_use]
pub const fn code(&self) -> &'static str {
match self {
Self::Unavailable { .. } => "remote_actions_unavailable",
Self::UnknownAction => "unknown_action",
Self::NotPermitted => "not_permitted",
Self::ConfirmationRequired(_) => "action_confirmation_required",
Self::InvalidRequest { .. } => "invalid_arguments",
Self::StaleRevision => "stale_revision",
Self::UnknownInvocation => "unknown_invocation",
Self::InvocationConflict => "invocation_conflict",
Self::NotCancellable { .. } => "not_cancellable",
Self::Refused { .. } => "refused",
Self::NotReady => "not_ready",
Self::Unanswered => "unanswered",
}
}
#[must_use]
pub fn said(&self) -> String {
match self {
Self::StaleRevision => "stale_revision: the resource changed since you read it. \
Call the action again with tilo_do, which runs it against the resource as it \
is now, or tilo_read the resource first to see what changed"
.to_owned(),
Self::NotPermitted => {
format!("not_permitted: {}", crate::Availability::NOT_ALLOWED_HERE)
}
Self::Unavailable { reason } => format!("unavailable: {reason}"),
Self::Unanswered => "unanswered: the workspace did not answer in time; it may \
still be opening its documents after it started, so ask again"
.to_owned(),
Self::InvalidRequest { reason } | Self::Refused { reason } => {
format!("{}: {reason}", self.code())
}
other => format!("{}: {other}", other.code()),
}
}
#[must_use]
pub const fn ask_again(&self) -> bool {
matches!(self, Self::NotReady | Self::Unanswered)
}
#[must_use]
pub fn ask_again_code(code: &str) -> bool {
code == Self::NotReady.code() || code == Self::Unanswered.code()
}
#[must_use]
pub fn needs_revision(&self) -> bool {
matches!(self, Self::InvalidRequest { reason } if reason == CONFIRMED_ACTION_NEEDS_REVISION)
}
}
pub const STALE_REVISION_REASON: &str = "the target changed since that revision; list it again";
#[derive(Serialize, Deserialize)]
#[serde(rename = "ActionCallError")]
enum WireActionCallError {
Unavailable { reason: String },
UnknownAction,
NotPermitted,
ConfirmationRequired(Box<asked::AskedFacts>),
InvalidRequest { reason: String },
UnknownInvocation,
InvocationConflict,
NotCancellable { reason: String },
Refused { reason: String },
NotReady,
Unanswered,
}
impl From<ActionCallError> for WireActionCallError {
fn from(error: ActionCallError) -> Self {
match error {
ActionCallError::Unavailable { reason } => Self::Unavailable { reason },
ActionCallError::UnknownAction => Self::UnknownAction,
ActionCallError::NotPermitted => Self::NotPermitted,
ActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
ActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
ActionCallError::StaleRevision => Self::InvalidRequest {
reason: STALE_REVISION_REASON.to_owned(),
},
ActionCallError::UnknownInvocation => Self::UnknownInvocation,
ActionCallError::InvocationConflict => Self::InvocationConflict,
ActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
ActionCallError::Refused { reason } => Self::Refused { reason },
ActionCallError::NotReady => Self::NotReady,
ActionCallError::Unanswered => Self::Unanswered,
}
}
}
impl From<WireActionCallError> for ActionCallError {
fn from(error: WireActionCallError) -> Self {
match error {
WireActionCallError::InvalidRequest { reason } if reason == STALE_REVISION_REASON => {
Self::StaleRevision
}
WireActionCallError::Unavailable { reason } => Self::Unavailable { reason },
WireActionCallError::UnknownAction => Self::UnknownAction,
WireActionCallError::NotPermitted => Self::NotPermitted,
WireActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
WireActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
WireActionCallError::UnknownInvocation => Self::UnknownInvocation,
WireActionCallError::InvocationConflict => Self::InvocationConflict,
WireActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
WireActionCallError::Refused { reason } => Self::Refused { reason },
WireActionCallError::NotReady => Self::NotReady,
WireActionCallError::Unanswered => Self::Unanswered,
}
}
}
#[cfg_attr(
any(target_arch = "wasm32", not(feature = "off-worker")),
expect(
clippy::unused_async,
reason = "only a host with `off-worker` runs a runtime whose worker there is to leave"
)
)]
pub async fn observed_off_the_worker<P>(
provider: P,
caller: Caller,
invocation: InvocationId,
) -> Option<InvocationState>
where
P: ActionProvider + Send + 'static,
{
#[cfg(all(not(target_arch = "wasm32"), feature = "off-worker"))]
if tokio::runtime::Handle::try_current().is_ok() {
return tokio::task::spawn_blocking(move || provider.observe(&caller, &invocation))
.await
.ok()
.flatten();
}
provider.observe(&caller, &invocation)
}
pub struct RunningTool {
pub stopped: Pending<Result<(), ActionCallError>>,
stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
end: Option<Box<dyn FnOnce(bool) + Send + Sync>>,
}
impl RunningTool {
#[must_use]
pub fn new(
stopped: Pending<Result<(), ActionCallError>>,
stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
end: impl FnOnce(bool) + Send + Sync + 'static,
) -> Self {
Self {
stopped,
stop_noted,
end: Some(Box::new(end)),
}
}
#[must_use]
pub fn was_stopped(&self) -> bool {
self.stop_noted.load(std::sync::atomic::Ordering::Acquire)
}
pub fn ended(mut self, stopped: bool) {
if let Some(end) = self.end.take() {
end(stopped);
}
}
}
impl Drop for RunningTool {
fn drop(&mut self) {
if let Some(end) = self.end.take() {
end(false);
}
}
}
pub trait ActionProvider {
fn retire_execution(&self, caller: &Caller) {
caller.retire_execution();
}
fn serves(&self, provider: &str) -> bool {
let _ = provider;
false
}
fn published(&self) -> Vec<crate::ResourceSpec> {
Vec::new()
}
fn query(
&self,
caller: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>>;
fn invoke(
&self,
caller: &Caller,
request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>>;
fn tool_started(&self, caller: &Caller, id: &InvocationId, tool: &str) -> Option<RunningTool> {
let _ = (caller, id, tool);
None
}
fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState>;
fn observed(&self, caller: &Caller, id: &InvocationId, state: Option<&InvocationState>) {
let _ = (caller, id, state);
}
fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
let _ = (caller, id);
None
}
fn session_state(&self, caller: &Caller) -> Option<SessionState> {
let _ = caller;
None
}
fn session_state_changed(&self, caller: &Caller) -> Option<Pending<()>> {
let _ = caller;
None
}
fn changed(
&self,
caller: &Caller,
scope: WatchScope,
) -> Option<Pending<Result<(), ActionCallError>>> {
let _ = (caller, scope);
None
}
fn cancel(&self, caller: &Caller, id: &InvocationId) -> Pending<Result<(), ActionCallError>>;
fn content_puts(&self) -> Option<std::sync::Arc<dyn ContentPuts>> {
None
}
fn content_puts_for(
&self,
target: Option<&RemoteActionTarget>,
) -> Option<std::sync::Arc<dyn ContentPuts>> {
let _ = target;
self.content_puts()
}
fn content_gets(&self) -> Option<std::sync::Arc<dyn ContentGets>> {
None
}
fn introduced(&self, caller: &Caller, client: &str) {
let _ = (caller, client);
}
fn here(&self, caller: &Caller) -> Option<Vec<Here>> {
let _ = caller;
None
}
fn resource_reads(&self) -> Option<std::sync::Arc<dyn ResourceReads>> {
None
}
fn store_commands(&self) -> Option<std::sync::Arc<dyn StoreCommands>> {
None
}
fn change_feed(&self) -> Option<std::sync::Arc<dyn ChangeFeed>> {
None
}
fn installed_surface(&self, app_id: &str) -> Pending<Option<Vec<u8>>> {
let _ = app_id;
Pending::ready(None)
}
fn invocation(
&self,
address: &crate::ActionAddress,
argument: Option<&str>,
) -> Option<crate::api::ActionDescriptor> {
let _ = (address, argument);
None
}
fn run(
&self,
caller: &Caller,
request: InvokeRequest,
admitted: Admitted,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
let _ = admitted;
self.invoke(caller, request)
}
fn asks_first(
&self,
caller: &Caller,
request: &InvokeRequest,
admitted: &Admitted,
) -> Option<Pending<Result<(), ActionCallError>>> {
let _ = (caller, request, admitted);
None
}
fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
let _ = (caller, request);
Err("this action has no live result".into())
}
}
#[allow(
clippy::trivially_copy_pass_by_ref,
reason = "serde hands a skipped field to it by reference"
)]
const fn is_zero(value: &u64) -> bool {
*value == 0
}
fn updated(
correlation: u64,
invocation: InvocationId,
state: Option<InvocationState>,
) -> RemoteActionMessage {
RemoteActionMessage::Update {
invocation,
state,
correlation: Some(correlation),
}
}
#[allow(
clippy::large_enum_variant,
reason = "a message is built, encoded once and dropped; boxing would only add noise to every constructor and match"
)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum RemoteActionMessage {
RetiredFeedbackRequest { correlation: u64 },
RetiredFeedbackResponse { correlation: u64 },
CatalogueRequest {
correlation: u64,
#[serde(default)]
query: CatalogueQuery,
},
CatalogueResponse {
correlation: u64,
result: Result<CataloguePage, ActionCallError>,
},
Invoke(InvokeRequest),
Receipt(InvocationReceipt),
Observe {
#[serde(default, skip_serializing_if = "is_zero")]
correlation: u64,
invocation: InvocationId,
#[serde(default, skip_serializing_if = "Option::is_none")]
wait_ms: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
seen: Option<UpdateMark>,
},
Update {
invocation: InvocationId,
state: Option<InvocationState>,
#[serde(default, skip_serializing_if = "Option::is_none")]
correlation: Option<u64>,
},
Cancel { invocation: InvocationId },
CancelResponse {
invocation: InvocationId,
result: Result<(), ActionCallError>,
},
ConfirmationRequest {
correlation: u64,
question: ConfirmationQuestion,
},
ConfirmationResponse {
correlation: u64,
result: Result<ConfirmationReply, ActionCallError>,
},
CatalogueChanged { page: CataloguePage },
ContentPutRequest {
correlation: u64,
step: ContentPutStep,
},
ContentPutResponse {
correlation: u64,
result: Result<ContentPutAnswer, ActionCallError>,
},
ContentGetRequest {
correlation: u64,
content: String,
offset: u64,
length: u64,
},
ContentGetResponse {
correlation: u64,
result: Result<ContentGetAnswer, ActionCallError>,
},
ResourceRead {
correlation: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
on_behalf_of: Option<InvocationId>,
read: ResourceReadRequest,
},
ResourceReading {
correlation: u64,
result: Result<String, ActionCallError>,
},
ChangesRequest {
correlation: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
after: Option<String>,
},
ChangesResponse {
correlation: u64,
result: Result<ChangePage, ActionCallError>,
},
SurfaceRequest { correlation: u64, app: String },
SurfaceResponse {
correlation: u64,
result: Result<Option<String>, ActionCallError>,
},
ContentLinkRequest {
correlation: u64,
link: ContentLinkAsk,
},
ContentLinkResponse {
correlation: u64,
result: Result<ContentLink, ActionCallError>,
},
ChangedRequest { correlation: u64, scope: WatchScope },
ChangedResponse {
correlation: u64,
result: Result<(), ActionCallError>,
},
CallCarryRequest {
correlation: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pair: Option<call::BridgedCall>,
},
CallCarryResponse {
correlation: u64,
result: Result<(), ActionCallError>,
},
CallReport {
correlation: u64,
report: call::CallReport,
},
CallReportResponse {
correlation: u64,
result: Result<(), ActionCallError>,
},
CallHeard(call::CallAudio),
CallSaid(call::CallAudio),
CallStatus(call::CallStatus),
AudioOutputRequest {
correlation: u64,
command: audio_output::Request,
},
AudioOutputResponse {
correlation: u64,
result: Result<audio_output::Snapshot, ActionCallError>,
},
StoreRequest {
correlation: u64,
command: serde_json::Value,
#[serde(default, skip_serializing_if = "Option::is_none")]
kind: Option<String>,
},
StoreResponse {
correlation: u64,
result: Result<serde_json::Value, ActionCallError>,
},
CallMediaRequest {
correlation: u64,
request: native_media::Request,
},
CallMediaResult {
correlation: u64,
result: Result<native_media::Snapshot, ActionCallError>,
},
PresenceSaid { correlation: u64, said: String },
PresenceSaidResult {
correlation: u64,
result: Result<(), ActionCallError>,
},
PresenceHeard { heard: String },
ShellOpenRequest {
correlation: u64,
open: shell::ShellOpen,
},
ShellOpenResponse {
correlation: u64,
result: Result<shell::ShellOpened, ActionCallError>,
},
ShellInput(shell::ShellBytes),
ShellResize { shell: u64, cols: u16, rows: u16 },
ShellClose { shell: u64 },
ShellOutput(shell::ShellBytes),
ShellEnded(shell::ShellEnded),
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceReadRequest {
pub workspace: String,
pub app: String,
pub record: String,
#[serde(default)]
pub joined: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub after: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub wait_ms: Option<u32>,
#[serde(default, skip_serializing_if = "ReadAnswer::is_reading")]
pub answer: ReadAnswer,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReadAnswer {
#[default]
Reading,
Document,
Listing,
Decision,
WriteDecision,
}
impl ReadAnswer {
#[must_use]
pub const fn is_reading(&self) -> bool {
matches!(self, Self::Reading)
}
}
impl RemoteActionMessage {
#[must_use]
pub const fn observe(invocation: InvocationId) -> Self {
Self::Observe {
correlation: 0,
invocation,
wait_ms: None,
seen: None,
}
}
#[must_use]
pub const fn waits(&self) -> bool {
matches!(
self,
Self::Observe {
wait_ms: Some(_),
..
} | Self::Invoke(InvokeRequest {
wait_ms: Some(_),
..
}) | Self::ChangedRequest { .. }
| Self::ResourceRead {
read: ResourceReadRequest {
wait_ms: Some(_),
..
},
..
}
)
}
#[must_use]
pub const fn is_request(&self) -> bool {
matches!(
self,
Self::CatalogueRequest { .. }
| Self::Invoke(_)
| Self::Observe { .. }
| Self::Cancel { .. }
| Self::ResourceRead { .. }
| Self::RetiredFeedbackRequest { .. }
| Self::ConfirmationRequest { .. }
| Self::ContentPutRequest { .. }
| Self::ContentGetRequest { .. }
| Self::ContentLinkRequest { .. }
| Self::ChangesRequest { .. }
| Self::ChangedRequest { .. }
| Self::SurfaceRequest { .. }
| Self::AudioOutputRequest { .. }
| Self::StoreRequest { .. }
| Self::CallMediaRequest { .. }
| Self::PresenceSaid { .. }
)
}
}
fn not_kept(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
let reason = match message {
RemoteActionMessage::RetiredFeedbackRequest { .. } => "feedback receipts are retired",
RemoteActionMessage::ContentPutRequest { .. } => CONTENT_PUTS_UNAVAILABLE,
RemoteActionMessage::ContentGetRequest { .. } => CONTENT_GETS_UNAVAILABLE,
RemoteActionMessage::ContentLinkRequest { .. } => CONTENT_LINKS_UNAVAILABLE,
_ => return None,
};
refuse(
message,
ActionCallError::Unavailable {
reason: reason.into(),
},
)
}
fn store_answered<H: ActionProvider>(
provider: &H,
caller: &Caller,
correlation: u64,
(command, kind): (serde_json::Value, Option<String>),
) -> Pending<RemoteActionMessage> {
let result = match provider.store_commands() {
Some(store) => store.command(caller, command, kind),
None => Pending::ready(Err(ActionCallError::Unavailable {
reason: STORE_COMMANDS_UNAVAILABLE.into(),
})),
};
result.map(move |result| RemoteActionMessage::StoreResponse {
correlation,
result,
})
}
fn changed<H: ActionProvider>(
provider: &H,
caller: &Caller,
correlation: u64,
after: Option<&str>,
) -> Pending<RemoteActionMessage> {
let result = match provider.change_feed() {
Some(feed) => feed.since(caller, after),
None => Pending::ready(Err(ActionCallError::Unavailable {
reason: CHANGE_FEED_UNAVAILABLE.into(),
})),
};
result.map(move |result| RemoteActionMessage::ChangesResponse {
correlation,
result,
})
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct RemoteActionFrame {
pub version: u16,
pub message: RemoteActionMessage,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub workspace: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub press: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub press_at: Option<asked::PressPoint>,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum RemoteFrameError {
#[error("remote action frame of {len} bytes exceeds the limit")]
TooLarge { len: usize },
#[error("remote action frame version {version} is not supported")]
UnsupportedVersion { version: u16 },
#[error("malformed remote action frame: {0}")]
Malformed(String),
}
impl RemoteActionFrame {
#[must_use]
pub const fn new(message: RemoteActionMessage) -> Self {
Self {
version: REMOTE_ACTIONS_VERSION,
message,
workspace: None,
press: None,
press_at: None,
}
}
#[must_use]
pub fn pressed(mut self, press: Option<u32>) -> Self {
self.press = press;
self.press_at = press.and_then(press_points::of);
self
}
#[must_use]
pub fn in_workspace(mut self, workspace: Option<String>) -> Self {
self.workspace = workspace;
self
}
#[must_use]
pub fn workspace(&self) -> Option<&str> {
match &self.message {
RemoteActionMessage::ResourceRead { read, .. } => Some(&read.workspace),
_ => self.workspace.as_deref(),
}
}
pub fn encode(&self) -> Result<Vec<u8>, RemoteFrameError> {
let bytes = serde_json::to_vec(self)
.map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
return Err(RemoteFrameError::TooLarge { len: bytes.len() });
}
Ok(bytes)
}
pub fn decode(bytes: &[u8]) -> Result<Self, RemoteFrameError> {
#[derive(Deserialize)]
struct Version {
version: u16,
}
if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
return Err(RemoteFrameError::TooLarge { len: bytes.len() });
}
let Version { version } = serde_json::from_slice(bytes)
.map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
if version != REMOTE_ACTIONS_VERSION {
return Err(RemoteFrameError::UnsupportedVersion { version });
}
serde_json::from_slice(bytes)
.map_err(|error| RemoteFrameError::Malformed(error.to_string()))
}
}
#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
fn read_answered<H: ActionProvider>(
provider: &H,
caller: &Caller,
correlation: u64,
read: ResourceReadRequest,
) -> Pending<RemoteActionMessage> {
provider.resource_reads().map_or_else(
|| resource_read::unanswered(correlation),
|reads| resource_read::answered_where_it_ends(reads.answer_read(caller, correlation, read)),
)
}
#[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
fn read_answered<H: ActionProvider>(
_provider: &H,
_caller: &Caller,
correlation: u64,
_read: ResourceReadRequest,
) -> Pending<RemoteActionMessage> {
resource_read::unanswered(correlation)
}
fn no_call_media_lane() -> ActionCallError {
ActionCallError::Unavailable {
reason: "this connection carries no call media lane".into(),
}
}
fn no_shell(correlation: u64) -> RemoteActionMessage {
RemoteActionMessage::ShellOpenResponse {
correlation,
result: Err(ActionCallError::Unavailable {
reason: "this connection carries no shell".into(),
}),
}
}
fn no_presence_lane() -> ActionCallError {
ActionCallError::Unavailable {
reason: "this connection carries no presence lane".into(),
}
}
fn no_audio_output_lane() -> ActionCallError {
ActionCallError::Unavailable {
reason: "this connection carries no sound output lane".into(),
}
}
fn no_call_lane() -> ActionCallError {
ActionCallError::Unavailable {
reason: "this connection carries no call lane".into(),
}
}
pub fn serve<H: ActionProvider + Clone + Send + 'static>(
provider: &H,
caller: &Caller,
message: RemoteActionMessage,
) -> Option<Pending<RemoteActionMessage>> {
let abandoned = refuse(
&message,
ActionCallError::Unavailable {
reason: "the provider dropped the request".into(),
},
)?;
let answer = match message {
RemoteActionMessage::RetiredFeedbackRequest { .. }
| RemoteActionMessage::ContentPutRequest { .. }
| RemoteActionMessage::ContentGetRequest { .. }
| RemoteActionMessage::ContentLinkRequest { .. } => Pending::ready(not_kept(&message)?),
RemoteActionMessage::CatalogueRequest { correlation, query } => provider
.query(caller, query)
.map(move |result| RemoteActionMessage::CatalogueResponse {
correlation,
result,
}),
RemoteActionMessage::Invoke(request) => {
invoked(provider, caller, request).map(RemoteActionMessage::Receipt)
}
RemoteActionMessage::Observe {
correlation,
invocation,
wait_ms: Some(wait_ms),
seen,
} => settle_with(provider, caller, invocation, seen, wait::deadline(wait_ms))
.map(move |state| updated(correlation, invocation, state)),
RemoteActionMessage::Observe {
correlation,
invocation,
..
} => Pending::ready(updated(
correlation,
invocation,
provider.observe(caller, &invocation),
)),
RemoteActionMessage::Cancel { invocation } => provider
.cancel(caller, &invocation)
.map(move |result| RemoteActionMessage::CancelResponse { invocation, result }),
RemoteActionMessage::ResourceRead {
correlation, read, ..
} => read_answered(provider, caller, correlation, read),
RemoteActionMessage::ConfirmationRequest { correlation, .. } => Pending::ready(
confirmation::unanswered(correlation, ActionCallError::confirmation_required()),
),
RemoteActionMessage::ChangesRequest { correlation, after } => {
changed(provider, caller, correlation, after.as_deref())
}
RemoteActionMessage::ChangedRequest { correlation, scope } => {
watch::noticed(provider, caller, correlation, scope)
}
RemoteActionMessage::SurfaceRequest { correlation, app } => {
surfaces::surfaced(provider, correlation, &app)
}
RemoteActionMessage::CallCarryRequest { correlation, .. } => {
Pending::ready(RemoteActionMessage::CallCarryResponse {
correlation,
result: Err(no_call_lane()),
})
}
RemoteActionMessage::CallReport { correlation, .. } => {
Pending::ready(RemoteActionMessage::CallReportResponse {
correlation,
result: Err(no_call_lane()),
})
}
RemoteActionMessage::AudioOutputRequest { correlation, .. } => {
Pending::ready(RemoteActionMessage::AudioOutputResponse {
correlation,
result: Err(no_audio_output_lane()),
})
}
RemoteActionMessage::StoreRequest {
correlation,
command,
kind,
} => store_answered(provider, caller, correlation, (command, kind)),
RemoteActionMessage::CallMediaRequest { correlation, .. } => {
Pending::ready(RemoteActionMessage::CallMediaResult {
correlation,
result: Err(no_call_media_lane()),
})
}
RemoteActionMessage::PresenceSaid { correlation, .. } => {
Pending::ready(RemoteActionMessage::PresenceSaidResult {
correlation,
result: Err(no_presence_lane()),
})
}
RemoteActionMessage::ShellOpenRequest { correlation, .. } => {
Pending::ready(no_shell(correlation))
}
_ => return None,
};
let (completer, answered) = pending();
answer.then(move |answer| completer.complete(answer.unwrap_or(abandoned)));
Some(answered)
}
fn invoked<H: ActionProvider + Clone + Send + 'static>(
provider: &H,
caller: &Caller,
mut request: InvokeRequest,
) -> Pending<InvocationReceipt> {
let until = request.wait_ms.take().map(wait::deadline);
let invocation = request.invocation;
let receipt = provider.invoke(caller, request).map(move |result| {
result.unwrap_or_else(|error| InvocationReceipt {
invocation,
status: ReceiptStatus::Rejected { error },
})
});
match until {
Some(until) => wait::settle_receipt(provider, caller, receipt, until),
None => receipt,
}
}
#[must_use]
pub fn refuse(
message: &RemoteActionMessage,
error: ActionCallError,
) -> Option<RemoteActionMessage> {
Some(match message {
RemoteActionMessage::RetiredFeedbackRequest { correlation } => {
RemoteActionMessage::RetiredFeedbackResponse {
correlation: *correlation,
}
}
RemoteActionMessage::CatalogueRequest { correlation, .. } => {
RemoteActionMessage::CatalogueResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::Invoke(request) => RemoteActionMessage::Receipt(InvocationReceipt {
invocation: request.invocation,
status: ReceiptStatus::Rejected { error },
}),
RemoteActionMessage::Observe {
correlation,
invocation,
..
} => updated(*correlation, *invocation, None),
RemoteActionMessage::Cancel { invocation } => RemoteActionMessage::CancelResponse {
invocation: *invocation,
result: Err(error),
},
RemoteActionMessage::ResourceRead { correlation, .. } => {
RemoteActionMessage::ResourceReading {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
confirmation::unanswered(*correlation, error)
}
RemoteActionMessage::ContentPutRequest { correlation, .. } => {
RemoteActionMessage::ContentPutResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ContentGetRequest { correlation, .. } => {
RemoteActionMessage::ContentGetResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ContentLinkRequest { correlation, .. } => {
RemoteActionMessage::ContentLinkResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ChangesRequest { correlation, .. } => {
RemoteActionMessage::ChangesResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ChangedRequest { correlation, .. } => {
RemoteActionMessage::ChangedResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::SurfaceRequest { correlation, .. } => {
RemoteActionMessage::SurfaceResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::StoreRequest { correlation, .. } => {
RemoteActionMessage::StoreResponse {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::PresenceSaid { correlation, .. } => {
RemoteActionMessage::PresenceSaidResult {
correlation: *correlation,
result: Err(error),
}
}
RemoteActionMessage::ShellOpenRequest { correlation, .. } => {
RemoteActionMessage::ShellOpenResponse {
correlation: *correlation,
result: Err(error),
}
}
_ => return None,
})
}
struct LogEntry<T> {
caller: Caller,
request: InvokeRequest,
handle: Option<T>,
}
pub struct InvocationLog<T> {
entries: HashMap<InvocationId, LogEntry<T>>,
order: VecDeque<InvocationId>,
capacity: usize,
}
impl<T> Default for InvocationLog<T> {
fn default() -> Self {
Self::with_capacity(DEFAULT_LOG_CAPACITY)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reservation {
Reserved,
Admitted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Admission {
Started,
Retried,
}
impl<T> InvocationLog<T> {
#[must_use]
pub fn with_capacity(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
order: VecDeque::new(),
capacity: capacity.max(1),
}
}
pub fn admit(
&mut self,
caller: &Caller,
request: &InvokeRequest,
start: impl FnOnce() -> Result<T, ActionCallError>,
) -> Result<(&T, Admission), ActionCallError> {
let id = request.invocation;
let admission = match self.reserve(caller, request)? {
Reservation::Admitted => Admission::Retried,
Reservation::Reserved => match start() {
Ok(handle) => {
self.complete(&id, handle);
Admission::Started
}
Err(error) => {
self.abandon(&id);
return Err(error);
}
},
};
self.entries
.get(&id)
.and_then(|entry| entry.handle.as_ref())
.map(|handle| (handle, admission))
.ok_or(ActionCallError::UnknownInvocation)
}
pub fn reserve(
&mut self,
caller: &Caller,
request: &InvokeRequest,
) -> Result<Reservation, ActionCallError> {
let id = request.invocation;
if let Some(entry) = self.entries.get_mut(&id) {
if !caller.continues(&entry.caller) || !entry.request.same_invocation(request) {
return Err(ActionCallError::InvocationConflict);
}
entry.caller.clone_from(caller);
return if entry.handle.is_some() {
Ok(Reservation::Admitted)
} else {
Err(ActionCallError::Unanswered)
};
}
while self.order.len() >= self.capacity {
let oldest_completed = self.order.iter().position(|candidate| {
self.entries
.get(candidate)
.is_some_and(|entry| entry.handle.is_some())
});
let Some(index) = oldest_completed else {
return Err(ActionCallError::Unavailable {
reason: "all invocation slots are still being admitted; retry".into(),
});
};
if let Some(oldest) = self.order.remove(index) {
self.entries.remove(&oldest);
}
}
self.order.push_back(id);
self.entries.insert(
id,
LogEntry {
caller: caller.clone(),
request: InvokeRequest {
wait_ms: None,
appearance: None,
..request.clone()
},
handle: None,
},
);
Ok(Reservation::Reserved)
}
pub fn readmit(
&mut self,
caller: &Caller,
request: &InvokeRequest,
waits: impl FnOnce(Option<&T>) -> bool,
) -> bool {
let Some(entry) = self.entries.get_mut(&request.invocation) else {
return false;
};
let again = request.approval().is_some()
&& caller.continues(&entry.caller)
&& asked::same_call(&entry.request, request)
&& waits(entry.handle.as_ref());
if again {
entry.request = InvokeRequest {
wait_ms: None,
appearance: None,
..request.clone()
};
entry.handle = None;
}
again
}
pub fn complete(&mut self, id: &InvocationId, handle: T) {
if let Some(entry) = self.entries.get_mut(id) {
entry.handle = Some(handle);
}
}
pub fn abandon(&mut self, id: &InvocationId) {
if self
.entries
.get(id)
.is_some_and(|entry| entry.handle.is_none())
{
self.entries.remove(id);
self.order.retain(|candidate| candidate != id);
}
}
#[must_use]
pub fn request_of(&self, id: &InvocationId) -> Option<&InvokeRequest> {
self.entries.get(id).map(|entry| &entry.request)
}
#[must_use]
pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<&T> {
self.entries
.get(id)
.filter(|entry| caller.follows(&entry.caller))
.and_then(|entry| entry.handle.as_ref())
}
#[must_use]
pub fn admitted(&self, caller: &Caller, id: &InvocationId) -> Option<Option<&T>> {
self.entries
.get(id)
.filter(|entry| caller.follows(&entry.caller))
.map(|entry| entry.handle.as_ref())
}
pub fn get_mut(&mut self, caller: &Caller, id: &InvocationId) -> Option<&mut T> {
self.entries
.get_mut(id)
.filter(|entry| caller.follows(&entry.caller))
.and_then(|entry| entry.handle.as_mut())
}
}
pub const ACCOUNT_SECRET_ANSWERS: [&str; 3] =
["cloud-credential", "begin-sign-in", "begin-cloud-sign-in"];
#[must_use]
pub fn answers_a_secret(action: &str) -> bool {
VAULT_SECRET_ANSWERS.contains(&action) || ACCOUNT_SECRET_ANSWERS.contains(&action)
}
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use super::*;
use crate::{ActionContract, ActionDescriptor, ExecutionLocus, InputSpec, OperationKind};
tilo_test_env::scenario! {
fn a_caller_keeps_its_identity_and_authority;
phase a_bot_is_its_own_member_acting_for_its_installer;
{
let installer = [7u8; 32];
let caller = Caller::bot("6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6", installer, [9u8; 32]);
assert_eq!(
caller.acting().member_id(),
Some(&tilo_action_policy::MemberId::bot(
"6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6"
))
);
assert_eq!(
caller.acting().acted_for_person(),
Some(hex::encode(installer).as_str())
);
assert!(caller.acting().is_bot());
assert!(caller.acting().delegated());
}
phase an_app_caller_acts_as_the_person_whose_session_runs_it;
{
let caller = Caller::local_app("so.tilo.example").acting_for("ada");
assert_eq!(caller.acting().person_id(), Some("ada"));
assert_eq!(
caller.acting().app().map(ToString::to_string).as_deref(),
Some("so.tilo.example")
);
assert_eq!(caller.acting_for_person(), Some("ada"));
}
phase execution_lifetime_is_shared_without_changing_caller_identity;
{
let first = Caller::local_person("owner").in_new_execution();
let retained = first.clone();
let second = first.clone().in_new_execution();
let hash = |caller: &Caller| {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
std::hash::Hash::hash(caller, &mut hasher);
std::hash::Hasher::finish(&hasher)
};
let before = hash(&first);
first.retire_execution();
assert!(!retained.execution_is_live());
assert!(second.execution_is_live());
assert_eq!(first, retained);
assert_eq!(hash(&first), before);
let reconnected = retained.in_new_execution();
assert!(reconnected.execution_is_live());
assert_ne!(reconnected.execution_id(), first.execution_id());
}
phase projected_execution_retains_transport_retirement_without_changing_authority;
{
let original = Caller::local_person("projected-person").in_new_execution();
let projected = Caller::authenticated([1; 32], [2; 32])
.in_execution(original.execution_lease().unwrap());
assert_eq!(projected.execution_id(), original.execution_id());
assert_eq!(projected.user_public_key(), Some(&[1; 32]));
assert_eq!(original.user_public_key(), None);
original.retire_execution();
assert!(!projected.execution_is_live());
}
}
fn alice() -> Caller {
Caller::authenticated([1; 32], [2; 32])
}
fn mallory() -> Caller {
Caller::authenticated([9; 32], [8; 32])
}
tilo_test_env::scenario! {
fn an_application_action_names_its_destination;
phase opening_an_app_needs_no_workspace_consent;
{
for spec in [
ApplicationLaunch::app("so.tilo.photos").spec("open-photos", "Open Photos", ""),
ApplicationLaunch::content_spec("so.tilo.photos", "open-capture", "Open", ""),
] {
assert!(spec.contract.is_own_device(), "{}", spec.id);
assert_eq!(
spec.contract.need().kind,
crate::ActionKind::Read,
"{}",
spec.id
);
}
}
phase application_launch_action_preserves_destination_and_never_falls_back_to_open;
{
let launch = ApplicationLaunch::with_action(
"so.tilo.file-explorer",
"files.remote-account:616461",
"open-remote-account",
);
let spec = launch.spec("open-files", "Browse files", "Open this account in Files");
let encoded = spec.build_args([]).unwrap();
assert_eq!(encoded.type_id, ApplicationLaunch::TYPE);
let decoded: ApplicationLaunch = serde_json::from_slice(&encoded.payload).unwrap();
assert!(decoded.valid());
for workspace in ["workspace-a", "workspace-b"] {
assert_eq!(
decoded.target(workspace),
application_action_target(
workspace,
"so.tilo.file-explorer",
"files.remote-account:616461",
"open-remote-account",
)
);
}
assert!(matches!(decoded.argument(), InvokeArgument::None));
let legacy: ApplicationLaunch = serde_json::from_value(serde_json::json!({
"app_id": "so.tilo.photos"
}))
.unwrap();
assert!(legacy.valid());
assert_eq!(
legacy.target("workspace-a"),
application_open_target("workspace-a", "so.tilo.photos")
);
let mut invalid = decoded;
invalid.content_hash = Some("a".repeat(64));
assert!(
!invalid.valid(),
"a handoff must not mix content staging and an app action"
);
invalid.content_hash = None;
invalid.action.as_mut().unwrap().resource.clear();
assert!(
!invalid.valid(),
"an invalid destination must fail, not open an empty app"
);
}
phase an_application_action_target_names_its_workspace_and_app;
{
let target =
application_action_target("workspace-1", "so.tilo.chat", "chat.workspace", "call");
assert_eq!(
application_provider(&target.provider),
Some(("workspace-1", "so.tilo.chat"))
);
assert_eq!(target.address, ActionAddress::new("chat.workspace", "call"));
for other in [
"7",
"workspace:workspace-1",
"application:workspace-1",
"application::so.tilo.chat",
"application:workspace-1:",
"application:workspace-1:a:",
] {
assert_eq!(application_provider(other), None, "{other}");
}
assert_eq!(application_provider_resource(&target.provider), None);
let target = application_resource_target(
"workspace-1",
"so.tilo.notes",
"uuid:7",
"notes.page:1",
"open",
);
assert_eq!(
application_provider(&target.provider),
Some(("workspace-1", "so.tilo.notes"))
);
assert_eq!(
application_provider_resource(&target.provider),
Some("uuid:7")
);
assert_eq!(target.address, ActionAddress::new("notes.page:1", "open"));
}
}
fn descriptor(resource: &str, action: &str) -> ActionDescriptor {
ActionDescriptor {
did: None,
state: crate::ActionState::default(),
semantic_identity: None,
address: ActionAddress::new(resource, action),
resource_kind: "notes.note".into(),
resource_label: "Groceries".into(),
action_label: "Archive".into(),
keywords: Vec::new(),
icon: None,
description: Some("Move the note to the archive".into()),
locus: ExecutionLocus::ClientLocal,
kind: OperationKind::Document,
contract: ActionContract::default(),
input: InputSpec::None,
params: Vec::new(),
view: None,
}
}
struct CountingHost {
runs: AtomicU32,
log: Mutex<InvocationLog<Mutex<InvocationUpdate>>>,
}
impl CountingHost {
fn new() -> Self {
Self {
runs: AtomicU32::new(0),
log: Mutex::new(InvocationLog::default()),
}
}
fn runs(&self) -> u32 {
self.runs.load(Ordering::SeqCst)
}
fn finish(&self, caller: &Caller, id: &InvocationId) {
if let Some(update) = self.log.lock().unwrap().get(caller, id) {
*update.lock().unwrap() = InvocationUpdate::Succeeded {
invocation: *id,
output: ActionOutput::default(),
};
}
}
}
impl CountingHost {
fn cancel_now(&self, caller: &Caller, id: &InvocationId) -> Result<(), ActionCallError> {
let log = self.log.lock().unwrap();
let mut update = log
.get(caller, id)
.ok_or(ActionCallError::UnknownInvocation)?
.lock()
.unwrap();
if update.is_terminal() {
return Err(ActionCallError::NotCancellable {
reason: "finished".into(),
});
}
*update = InvocationUpdate::Cancelled {
invocation: *id,
message: None,
};
drop(update);
drop(log);
Ok(())
}
}
impl ActionProvider for CountingHost {
fn query(
&self,
_caller: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
Pending::ready(Ok(CataloguePage::from_rows(
"1".into(),
vec![catalogue_row("note:1", "archive")],
&query,
)))
}
fn invoke(
&self,
caller: &Caller,
request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
Pending::ready((|| {
if request.target.address != ActionAddress::new("note:1", "archive") {
return Err(ActionCallError::UnknownAction);
}
let update = {
let mut log = self.log.lock().unwrap();
let (update, _) = log.admit(caller, &request, || {
self.runs.fetch_add(1, Ordering::SeqCst);
Ok(Mutex::new(InvocationUpdate::Accepted {
invocation: request.invocation,
}))
})?;
let update = update.lock().unwrap().clone();
drop(log);
update
};
Ok(InvocationState::new(request.invocation, update).receipt())
})())
}
fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
self.log
.lock()
.unwrap()
.get(caller, id)
.map(|update| InvocationState::new(*id, update.lock().unwrap().clone()))
}
fn cancel(
&self,
caller: &Caller,
id: &InvocationId,
) -> Pending<Result<(), ActionCallError>> {
Pending::ready(self.cancel_now(caller, id))
}
}
fn catalogue_row(resource: &str, action: &str) -> CatalogueRow {
CatalogueRow {
offered: None,
provider: "7".into(),
app_id: "notes".into(),
parent_resource: String::new(),
resource: CatalogueResource {
id: resource.into(),
kind: "notes.note".into(),
label: "Groceries".into(),
presentation: None,
},
action: Some(descriptor(resource, action)),
has_children: false,
visibility: None,
surface: None,
}
}
fn now<T>(mut answer: Pending<T>) -> T {
match answer.poll_ready() {
PendingPoll::Ready(value) => value,
PendingPoll::Waiting | PendingPoll::Abandoned => panic!("the provider answers at once"),
}
}
#[derive(Clone)]
struct HugeCatalogue;
const HUGE_CATALOGUE: usize = 12_000;
impl ActionProvider for HugeCatalogue {
fn query(
&self,
_caller: &Caller,
query: CatalogueQuery,
) -> Pending<Result<CataloguePage, ActionCallError>> {
let rows = (0..HUGE_CATALOGUE)
.map(|n| {
let mut row = catalogue_row(&format!("note:{n}"), &format!("archive-{n}"));
if let Some(action) = row.action.as_mut() {
action.description = Some("Moves the note out of the list. ".repeat(8));
}
row
})
.collect();
Pending::ready(Ok(CataloguePage::from_rows("1".into(), rows, &query)))
}
fn invoke(
&self,
_caller: &Caller,
_request: InvokeRequest,
) -> Pending<Result<InvocationReceipt, ActionCallError>> {
Pending::ready(Err(ActionCallError::UnknownAction))
}
fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
None
}
fn cancel(
&self,
_caller: &Caller,
_id: &InvocationId,
) -> Pending<Result<(), ActionCallError>> {
Pending::ready(Err(ActionCallError::UnknownInvocation))
}
}
#[test]
fn a_catalogue_larger_than_a_frame_travels_in_pages_that_each_fit_one() {
for by_resource in [false, true] {
let mut query = CatalogueQuery {
max_results: u32::MAX,
by_resource,
..CatalogueQuery::default()
};
let mut listed = Vec::new();
let mut pages = 0usize;
loop {
let asked = RemoteActionMessage::CatalogueRequest {
correlation: 1,
query: query.clone(),
};
let answer =
now(serve(&HugeCatalogue, &alice(), asked).expect("a request is answered"));
let bytes = RemoteActionFrame::new(answer)
.encode()
.expect("every page fits one frame");
assert!(bytes.len() <= MAX_REMOTE_ACTION_FRAME_BYTES);
let RemoteActionMessage::CatalogueResponse {
result: Ok(page), ..
} = RemoteActionFrame::decode(&bytes).unwrap().message
else {
panic!("a catalogue request is answered with its page");
};
pages += 1;
listed.extend(
expand(page.rows)
.into_iter()
.filter_map(|row| row.action.map(|action| action.address.action)),
);
if page.exhausted {
break;
}
query.cursor = page.next_cursor;
query.revision = Some(page.revision);
}
assert!(pages > 1, "the catalogue is larger than one frame");
let expected: Vec<String> = (0..HUGE_CATALOGUE)
.map(|n| format!("archive-{n}"))
.collect();
assert_eq!(listed, expected, "every action is listed once, in order");
}
}
fn archive(invocation: InvocationId) -> InvokeRequest {
InvokeRequest {
on_behalf_of: None,
invocation,
target: RemoteActionTarget {
provider: "7".into(),
address: ActionAddress::new("note:1", "archive"),
},
argument: InvokeArgument::None,
context: None,
confirmation: None,
revision: None,
wait_ms: None,
appearance: None,
signed: None,
}
}
fn round_trip(message: RemoteActionMessage) -> RemoteActionMessage {
let bytes = RemoteActionFrame::new(message).encode().unwrap();
RemoteActionFrame::decode(&bytes).unwrap().message
}
fn request_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
let mut arguments = serde_json::Map::new();
arguments.insert("title".into(), serde_json::json!("Weekly"));
vec![
RemoteActionMessage::CatalogueRequest {
correlation: 3,
query: CatalogueQuery::default(),
},
RemoteActionMessage::CatalogueRequest {
correlation: 5,
query: CatalogueQuery {
provider: Some("7".into()),
parent_resource: Some("folder:a".into()),
needle: "gro".into(),
cursor: vec![1, 2],
revision: Some("r1".into()),
max_results: 8,
limits: Some(CatalogueLimits {
max_bytes: Some(4096),
max_work: None,
max_depth: Some(1),
}),
..CatalogueQuery::default()
},
},
RemoteActionMessage::CatalogueResponse {
correlation: 3,
result: now(CountingHost::new().query(&alice(), CatalogueQuery::default())),
},
RemoteActionMessage::CatalogueResponse {
correlation: 4,
result: Err(ActionCallError::Unavailable {
reason: "no apps".into(),
}),
},
RemoteActionMessage::Invoke(InvokeRequest {
on_behalf_of: None,
argument: InvokeArgument::Json(arguments),
context: Some(ActionContext::for_resource(
"note:1",
"notes.note",
"Groceries",
)),
..archive(invocation)
}),
RemoteActionMessage::Invoke(InvokeRequest {
on_behalf_of: None,
argument: InvokeArgument::Text("hello".into()),
..archive(invocation)
}),
RemoteActionMessage::Invoke(InvokeRequest {
on_behalf_of: None,
confirmation: Some(Confirmation::Phrase("delete it".into())),
..archive(invocation)
}),
RemoteActionMessage::Invoke(InvokeRequest {
wait_ms: Some(2_000),
appearance: None,
..archive(invocation)
}),
]
}
fn outcome_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
vec![
RemoteActionMessage::Receipt(InvocationReceipt {
invocation,
status: ReceiptStatus::Completed {
output: ActionOutput {
value: Some(serde_json::json!({"archived": true})),
resources: vec!["notes.note:1".into()],
},
},
}),
RemoteActionMessage::Receipt(InvocationReceipt {
invocation,
status: ReceiptStatus::Failed {
error: ActionFailure {
code: "disk_full".into(),
message: "no space".into(),
details: None,
retryable: true,
},
},
}),
RemoteActionMessage::Receipt(InvocationReceipt {
invocation,
status: ReceiptStatus::Rejected {
error: ActionCallError::InvocationConflict,
},
}),
RemoteActionMessage::Receipt(InvocationReceipt {
invocation,
status: ReceiptStatus::Cancelled {
message: Some("stopped".into()),
},
}),
RemoteActionMessage::observe(invocation),
RemoteActionMessage::Observe {
correlation: 7,
invocation,
wait_ms: Some(10_000),
seen: Some(UpdateMark::Progress { sequence: 2 }),
},
RemoteActionMessage::Update {
invocation,
state: Some(InvocationState::new(
invocation,
InvocationUpdate::Progress {
invocation,
sequence: 2,
phase: "copying".into(),
completed: Some(1),
total: Some(4),
message: None,
},
)),
correlation: Some(7),
},
RemoteActionMessage::Update {
invocation,
state: None,
correlation: Some(7),
},
RemoteActionMessage::Cancel { invocation },
RemoteActionMessage::CancelResponse {
invocation,
result: Err(ActionCallError::NotCancellable {
reason: "finished".into(),
}),
},
]
}
tilo_test_env::scenario! {
fn remote_messages_and_failures_read_back_typed;
phase a_stale_revision_is_typed_and_travels_as_older_peers_read_it;
{
let encoded = serde_json::to_value(ActionCallError::StaleRevision).unwrap();
assert_eq!(
encoded,
serde_json::json!({"InvalidRequest": {"reason": STALE_REVISION_REASON}})
);
assert_eq!(
serde_json::from_value::<ActionCallError>(encoded).unwrap(),
ActionCallError::StaleRevision
);
assert_eq!(ActionCallError::StaleRevision.code(), "stale_revision");
let other = ActionCallError::Refused {
reason: "the call changed since that revision, honestly".into(),
};
let round_trip: ActionCallError =
serde_json::from_value(serde_json::to_value(&other).unwrap()).unwrap();
assert_eq!(round_trip, other);
let needs = ActionCallError::InvalidRequest {
reason: CONFIRMED_ACTION_NEEDS_REVISION.into(),
};
assert!(needs.needs_revision());
assert!(!ActionCallError::StaleRevision.needs_revision());
}
phase a_failure_with_details_round_trips;
{
let update = InvocationUpdate::Failed {
invocation: InvocationId::new(),
error: ActionFailure {
code: "invalid_arguments".into(),
message: "argument `pageSize` must be at most 64".into(),
details: Some(serde_json::json!({
"param": "pageSize",
"violation": {"kind": "maximum", "bound": 64}
})),
retryable: false,
},
};
let encoded = serde_json::to_string(&update).unwrap();
assert_eq!(
serde_json::from_str::<InvocationUpdate>(&encoded).unwrap(),
update
);
}
phase a_refusal_for_want_of_the_person_carries_what_they_are_shown;
{
let facts = asked::AskedFacts::default()
.with_fact("kind", "submit")
.with_fact("destination", "https://visa.example")
.with_fact("picture", "tilo.content:5f2b");
let invocation = InvocationId::new();
let state = InvocationState::new(
invocation,
InvocationUpdate::Failed {
invocation,
error: ActionFailure {
code: CONFIRMATION_REQUIRED_CODE.into(),
message: "the person has to allow this".into(),
details: Some(facts.to_details()),
retryable: false,
},
},
);
let receipt = state.receipt();
let ReceiptStatus::Rejected {
error: ActionCallError::ConfirmationRequired(stated),
} = &receipt.status
else {
panic!("a run waiting on the person is a refusal: {receipt:?}");
};
assert_eq!(**stated, facts);
let error = ActionCallError::asks(facts);
let wire = serde_json::to_value(&error).unwrap();
assert_eq!(
serde_json::from_value::<ActionCallError>(wire).unwrap(),
error
);
let wire = postcard::to_allocvec(&error).unwrap();
assert_eq!(postcard::from_bytes::<ActionCallError>(&wire).unwrap(), error);
}
phase the_remote_wire_is_versioned_and_explicit;
{
every_message_round_trips_through_a_frame();
frames_from_another_version_are_refused_not_misread();
the_wire_names_versions_and_messages_explicitly();
}
}
fn every_message_round_trips_through_a_frame() {
let invocation = InvocationId(uuid::Uuid::from_u128(7));
let messages = request_messages(invocation)
.into_iter()
.chain(outcome_messages(invocation));
for message in messages {
assert_eq!(round_trip(message.clone()), message);
}
}
fn frames_from_another_version_are_refused_not_misread() {
let mut frame = serde_json::to_value(RemoteActionFrame::new(
RemoteActionMessage::CatalogueRequest {
correlation: 1,
query: CatalogueQuery::default(),
},
))
.unwrap();
frame["version"] = serde_json::json!(REMOTE_ACTIONS_VERSION + 1);
frame["message"] = serde_json::json!({"Subscribe": {"topic": 1}});
let bytes = serde_json::to_vec(&frame).unwrap();
assert_eq!(
RemoteActionFrame::decode(&bytes),
Err(RemoteFrameError::UnsupportedVersion {
version: REMOTE_ACTIONS_VERSION + 1
})
);
assert!(matches!(
RemoteActionFrame::decode(
format!(r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Subscribe":{{}}}}}}"#)
.as_bytes()
),
Err(RemoteFrameError::Malformed(_))
));
assert!(matches!(
RemoteActionFrame::decode(&vec![b' '; MAX_REMOTE_ACTION_FRAME_BYTES + 1]),
Err(RemoteFrameError::TooLarge { .. })
));
}
fn the_wire_names_versions_and_messages_explicitly() {
let bytes = RemoteActionFrame::new(RemoteActionMessage::Cancel {
invocation: InvocationId(uuid::Uuid::nil()),
})
.encode()
.unwrap();
assert_eq!(
String::from_utf8(bytes).unwrap(),
format!(
r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Cancel":{{"invocation":"00000000-0000-0000-0000-000000000000"}}}}}}"#
)
);
}
fn a_retried_invocation_reports_the_original_and_runs_once() {
let provider = CountingHost::new();
let id = InvocationId::new();
let first = now(provider.invoke(&alice(), archive(id))).unwrap();
assert_eq!(first.status, ReceiptStatus::Accepted);
let retry = now(provider.invoke(&alice(), archive(id))).unwrap();
assert_eq!(retry, first);
assert_eq!(provider.runs(), 1, "a retry never starts a second run");
provider.finish(&alice(), &id);
let after = now(provider.invoke(&alice(), archive(id))).unwrap();
assert!(matches!(after.status, ReceiptStatus::Completed { .. }));
assert_eq!(provider.runs(), 1, "a retry after completion reports it");
}
fn an_invocation_id_cannot_be_reused_or_borrowed() {
let provider = CountingHost::new();
let id = InvocationId::new();
now(provider.invoke(&alice(), archive(id))).unwrap();
let mut different = archive(id);
different.argument = InvokeArgument::Text("other".into());
assert_eq!(
now(provider.invoke(&alice(), different)),
Err(ActionCallError::InvocationConflict)
);
assert_eq!(
now(provider.invoke(&mallory(), archive(id))),
Err(ActionCallError::InvocationConflict),
"another actor cannot attach to someone else's invocation"
);
assert_eq!(provider.observe(&mallory(), &id), None);
assert_eq!(
now(provider.cancel(&mallory(), &id)),
Err(ActionCallError::UnknownInvocation)
);
assert_eq!(provider.runs(), 1);
}
fn a_refused_invocation_is_not_remembered() {
let mut log = InvocationLog::<u32>::default();
let request = archive(InvocationId::new());
assert_eq!(
log.admit(&alice(), &request, || Err(ActionCallError::NotPermitted)),
Err(ActionCallError::NotPermitted)
);
let (handle, admission) = log.admit(&alice(), &request, || Ok(5)).unwrap();
assert_eq!((*handle, admission), (5, Admission::Started));
}
fn the_log_forgets_oldest_invocations_past_capacity() {
let mut log = InvocationLog::<u32>::with_capacity(2);
let requests: Vec<_> = (0..3).map(|_| archive(InvocationId::new())).collect();
for (n, request) in (0u32..).zip(&requests) {
log.admit(&alice(), request, || Ok(n)).unwrap();
}
assert_eq!(log.get(&alice(), &requests[0].invocation), None);
assert_eq!(log.get(&alice(), &requests[2].invocation), Some(&2));
}
fn serve_answers_requests_and_ignores_responses() {
let provider = std::sync::Arc::new(CountingHost::new());
let id = InvocationId::new();
let Some(RemoteActionMessage::Receipt(receipt)) = serve(
&provider,
&alice(),
RemoteActionMessage::Invoke(archive(id)),
)
.map(now) else {
panic!("an invoke is answered with a receipt");
};
assert_eq!(receipt.status, ReceiptStatus::Accepted);
let mut unknown = archive(InvocationId::new());
unknown.target.address = ActionAddress::new("note:2", "delete");
assert_eq!(
serve(
&provider,
&alice(),
RemoteActionMessage::Invoke(unknown.clone())
)
.map(now),
Some(RemoteActionMessage::Receipt(InvocationReceipt {
invocation: unknown.invocation,
status: ReceiptStatus::Rejected {
error: ActionCallError::UnknownAction
},
}))
);
assert_eq!(
serve(
&provider,
&alice(),
RemoteActionMessage::Cancel { invocation: id }
)
.map(now),
Some(RemoteActionMessage::CancelResponse {
invocation: id,
result: Ok(()),
})
);
let Some(RemoteActionMessage::Update {
state: Some(state), ..
}) = serve(&provider, &alice(), RemoteActionMessage::observe(id)).map(now)
else {
panic!("an observe is answered with the invocation state");
};
assert!(matches!(
state.receipt().status,
ReceiptStatus::Cancelled { .. }
));
assert!(serve(&provider, &alice(), RemoteActionMessage::Receipt(receipt)).is_none());
}
fn typed_arguments_use_the_local_invocation_slot() {
let mut object = serde_json::Map::new();
object.insert("n".into(), serde_json::json!(2));
assert_eq!(InvokeArgument::None.to_slot(), None);
assert_eq!(
InvokeArgument::Text("hi".into()).to_slot().as_deref(),
Some("hi")
);
assert_eq!(
InvokeArgument::Json(object.clone()).to_slot(),
Some(format!("{ARGUMENTS_JSON_PREFIX}{{\"n\":2}}"))
);
for argument in [
InvokeArgument::None,
InvokeArgument::Text("hi".into()),
InvokeArgument::Json(object),
] {
assert_eq!(
InvokeArgument::from_slot(argument.to_slot().as_deref()),
argument
);
}
}
fn a_remote_device_is_the_person_its_root_names() {
let caller = Caller::authenticated([0xAB; 32], [1; 32]);
assert_eq!(
caller.acting().member_id(),
Some(&tilo_action_policy::MemberId::person("ab".repeat(32))),
"every device of one person is the same member"
);
assert_eq!(caller.workspace(), None);
let agent = Caller::local_agent("helper", "ada").in_workspace("workspace-1");
assert_eq!(
agent.acting().member_id(),
Some(&tilo_action_policy::MemberId::agent("helper", "ada"))
);
assert_eq!(agent.workspace(), Some("workspace-1"));
assert_eq!(agent.device_public_key(), None);
}
fn a_refusal_answers_every_request_and_nothing_else() {
let error = ActionCallError::Unavailable {
reason: "down".into(),
};
let id = InvocationId::new();
assert_eq!(
refuse(&invoke_message(id), error.clone()),
Some(RemoteActionMessage::Receipt(InvocationReceipt {
invocation: id,
status: ReceiptStatus::Rejected {
error: error.clone()
},
}))
);
assert_eq!(
refuse(&RemoteActionMessage::observe(id), error.clone()),
Some(RemoteActionMessage::Update {
invocation: id,
state: None,
correlation: Some(0),
})
);
assert_eq!(
refuse(
&RemoteActionMessage::Update {
invocation: id,
state: None,
correlation: None,
},
error
),
None
);
}
fn invoke_message(id: InvocationId) -> RemoteActionMessage {
RemoteActionMessage::Invoke(archive(id))
}
mod change_wire;
tilo_test_env::scenario! {
fn a_host_serves_each_invocation_once_as_its_caller;
phase a_retry_with_another_appearance_is_another_invocation;
{
let request = archive(InvocationId(uuid::Uuid::from_u128(9)));
let appearing = InvokeRequest {
appearance: Some(crate::Appearance::new("alice", None, None).unwrap()),
..request.clone()
};
assert!(!request.same_invocation(&appearing));
assert!(appearing.same_invocation(&InvokeRequest {
wait_ms: Some(10),
..appearing.clone()
}));
let json = serde_json::to_string(&request).unwrap();
assert!(!json.contains("appearance"), "{json}");
}
phase remote_invocations_run_at_most_once_per_owned_id;
{
a_retried_invocation_reports_the_original_and_runs_once();
an_invocation_id_cannot_be_reused_or_borrowed();
a_refused_invocation_is_not_remembered();
the_log_forgets_oldest_invocations_past_capacity();
a_reservation_holds_the_id_until_the_start_completes();
}
phase admitted_executions_share_authority_but_cannot_borrow_invocations;
{
let first = alice().in_new_execution();
let second = alice().in_new_execution();
assert_eq!(first.acting(), second.acting());
assert_eq!(first.workspace(), second.workspace());
assert_ne!(first.execution_id(), second.execution_id());
let provider = CountingHost::new();
let id = InvocationId::new();
let admitted = now(provider.invoke(&first, archive(id))).unwrap();
assert_eq!(now(provider.invoke(&first, archive(id))).unwrap(), admitted);
assert_eq!(
now(provider.invoke(&second, archive(id))),
Err(ActionCallError::InvocationConflict)
);
assert_eq!(provider.observe(&second, &id), None);
assert_eq!(
now(provider.cancel(&second, &id)),
Err(ActionCallError::UnknownInvocation)
);
let retained = first.clone();
let hash = |caller: &Caller| {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
std::hash::Hash::hash(caller, &mut hasher);
std::hash::Hasher::finish(&hasher)
};
let before = hash(&first);
provider.retire_execution(&first);
assert!(!retained.execution_is_live());
assert!(second.execution_is_live());
assert_eq!(first, retained);
assert_eq!(hash(&first), before);
let reconnected = retained.in_new_execution();
assert!(reconnected.execution_is_live());
assert_ne!(reconnected.execution_id(), first.execution_id());
provider.finish(&first, &id);
assert!(matches!(
now(provider.invoke(&first, archive(id))).unwrap().status,
ReceiptStatus::Completed { .. }
));
assert!(provider.observe(&first, &id).is_some());
assert!(provider.observe(&second, &id).is_none());
assert!(reconnected.continues(&first));
assert!(!second.continues(&first));
assert!(provider.observe(&reconnected, &id).is_some());
assert!(matches!(
now(provider.invoke(&reconnected, archive(id))).unwrap().status,
ReceiptStatus::Completed { .. }
));
assert_eq!(provider.runs(), 1);
let someone_else = Caller::authenticated([3; 32], [4; 32]).in_new_execution();
assert!(!someone_else.continues(&first), "another device continues nothing");
}
phase serving_answers_each_request_as_the_person_the_device_belongs_to;
{
serve_answers_requests_and_ignores_responses();
typed_arguments_use_the_local_invocation_slot();
a_remote_device_is_the_person_its_root_names();
a_refusal_answers_every_request_and_nothing_else();
}
phase capacity_churn_preserves_in_flight_deduplication;
{
let caller = alice();
let mut log = InvocationLog::<u32>::with_capacity(3);
let pending = archive(InvocationId::new());
assert_eq!(log.reserve(&caller, &pending), Ok(Reservation::Reserved));
let mut completed = VecDeque::new();
for n in 0..8 {
let request = archive(InvocationId::new());
assert_eq!(
log.admit(&caller, &request, || Ok(n)),
Ok((&n, Admission::Started))
);
completed.push_back(request.invocation);
if completed.len() > 2 {
let evicted = completed.pop_front().unwrap();
assert_eq!(log.get(&caller, &evicted), None);
}
for id in &completed {
assert!(log.get(&caller, id).is_some());
}
assert!(matches!(
log.admit(&caller, &pending, || panic!("duplicate dispatch")),
Err(ActionCallError::Unanswered)
));
assert_eq!(
log.reserve(&mallory(), &pending),
Err(ActionCallError::InvocationConflict)
);
}
log.complete(&pending.invocation, 99);
assert_eq!(
log.admit(&caller, &pending, || panic!("duplicate dispatch")),
Ok((&99, Admission::Retried))
);
let next = archive(InvocationId::new());
assert_eq!(log.reserve(&caller, &next), Ok(Reservation::Reserved));
assert_eq!(log.get(&caller, &pending.invocation), None);
}
phase capacity_churn_refuses_new_ids_when_every_slot_is_reserved;
{
let caller = alice();
for capacity in 0..=2 {
let mut log = InvocationLog::<u32>::with_capacity(capacity);
let pending: Vec<_> = (0..capacity.max(1))
.map(|_| archive(InvocationId::new()))
.collect();
for request in &pending {
assert_eq!(log.reserve(&caller, request), Ok(Reservation::Reserved));
}
let refused = archive(InvocationId::new());
for _ in 0..4 {
assert!(matches!(
log.admit(&caller, &refused, || panic!("dispatch at capacity")),
Err(ActionCallError::Unavailable { .. })
));
for request in &pending {
assert!(matches!(
log.admit(&caller, request, || panic!("duplicate dispatch")),
Err(ActionCallError::Unanswered)
));
}
}
for (n, request) in pending.iter().enumerate() {
let n = u32::try_from(n).unwrap();
log.complete(&request.invocation, n);
assert_eq!(
log.admit(&caller, request, || panic!("duplicate dispatch")),
Ok((&n, Admission::Retried))
);
}
assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
log.abandon(&refused.invocation);
assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
}
}
}
fn a_reservation_holds_the_id_until_the_start_completes() {
let mut log = InvocationLog::<u32>::default();
let request = archive(InvocationId::new());
assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Reserved));
assert!(
matches!(
log.reserve(&alice(), &request),
Err(ActionCallError::Unanswered)
),
"a retry during the start neither runs twice nor pretends to be admitted: it is \
asked again, as an answer lost on its way is"
);
assert_eq!(log.get(&alice(), &request.invocation), None);
log.complete(&request.invocation, 9);
assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Admitted));
assert_eq!(log.get(&alice(), &request.invocation), Some(&9));
let failed = archive(InvocationId::new());
assert_eq!(log.reserve(&alice(), &failed), Ok(Reservation::Reserved));
log.abandon(&failed.invocation);
assert_eq!(
log.reserve(&alice(), &failed),
Ok(Reservation::Reserved),
"an abandoned start ran nothing and may be admitted again"
);
}
#[test]
fn action_call_error_constructors_build_the_exact_variants() {
let refused = ActionCallError::refused("not allowed now");
assert_eq!(
refused,
ActionCallError::Refused {
reason: "not allowed now".to_owned(),
}
);
assert_eq!(refused.code(), "refused");
assert_eq!(refused.said(), "refused: not allowed now");
let owned_refusal = String::from("not allowed now");
assert_eq!(ActionCallError::refused(owned_refusal), refused);
let invalid = ActionCallError::invalid_request("missing field");
assert_eq!(
invalid,
ActionCallError::InvalidRequest {
reason: "missing field".to_owned(),
}
);
assert_eq!(invalid.code(), "invalid_arguments");
assert_eq!(invalid.said(), "invalid_arguments: missing field");
let owned_invalid = String::from("missing field");
assert_eq!(ActionCallError::invalid_request(owned_invalid), invalid);
let unavailable = ActionCallError::unavailable("service off");
assert_eq!(
unavailable,
ActionCallError::Unavailable {
reason: "service off".to_owned(),
}
);
assert_eq!(unavailable.code(), "remote_actions_unavailable");
assert_eq!(unavailable.said(), "unavailable: service off");
let owned_unavailable = String::from("service off");
assert_eq!(ActionCallError::unavailable(owned_unavailable), unavailable);
}
}