1use std::collections::{HashMap, VecDeque};
30
31use serde::{Deserialize, Serialize};
32
33pub use window_actions::{activation_requested, link_scheme, render_anchor};
34
35pub mod admitted;
36pub use admitted::{Admits, Admitted, LiveRead, LiveView, Outcome, ReportsProgress, Serving};
37mod application;
38pub mod asked;
39pub mod audio_output;
41pub mod call;
43mod caller;
44pub mod native_media;
46pub mod shell;
48pub use caller::{Caller, Invited, KeptCaller, KeyCall, PlacedCaller, device_agent_id};
49pub mod signed_invocation;
50pub use signed_invocation::{CallAllowed, SignedCall, SignedInvocation};
51mod catalogue;
52mod changes;
53mod confirmation;
54mod content_get;
55mod content_link;
56mod content_put;
57pub mod device_tickets;
60mod pending;
61pub mod session_actions;
62mod vault;
63pub use vault::{
64 ItemRef, KEEP_SEALED, KEEP_USES, REMOVE_SEALED, VAULT_DEVICE_KEY, VAULT_FIND,
65 VAULT_FORGET_PAGE_LOGIN, VAULT_ITEM_KIND, VAULT_KEEP, VAULT_KEEP_PAGE_LOGIN, VAULT_KIND,
66 VAULT_LIST, VAULT_PAGE_FILL, VAULT_PAGE_LOGINS, VAULT_PROVIDER, VAULT_RECORD, VAULT_RELEASE,
67 VAULT_RESOURCE, VAULT_SECRET_ANSWERS, answers_secret, calls_answering_a_secret,
68 calls_by_address, item_param, takes_item, vault_target,
69};
70pub mod press_points;
71mod providers;
72mod resource_read;
73pub mod secret_arguments;
74mod session_state;
75mod shared_provider;
76mod store_commands;
77mod surfaces;
78#[cfg(any(test, feature = "test-support"))]
79mod test_provider;
80pub use session_state::{SessionState, SyncState, WorkspaceState};
81mod wait;
82mod watch;
83pub use watch::{CHANGED_UNAVAILABLE, Here, HereWindow, KEY_GRANTS, PRESENCE, WatchScope};
84mod window_actions;
85mod within;
86pub mod workspace_activity;
87
88pub use application::{
89 APPLICATION_PROVIDER, application_action_target, application_open_target, application_provider,
90 application_provider_resource, application_provider_token, application_resource_target,
91 valid_file_name,
92};
93pub use confirmation::{
94 ASK, ASK_PROVIDER, ASK_RESOURCE, ASK_WITH_CHOICES, Confirmation, ConfirmationQuestion,
95 ConfirmationReply, MAX_ASK_CHARS, MAX_ASK_CHOICES, MAX_CHOICE_CHARS, PersonAnswer, PersonAsk,
96 argument_digest, ask_target, is_ask,
97};
98pub use providers::{
99 APPLICATION_OPEN_ACTION, APPLICATION_RESOURCE_KIND, APPLICATION_RESOURCE_PREFIX,
100 APPLICATION_START_ACTION, DEVICE_FILES_FOLDER, DEVICE_FILES_PROVIDER, OWN_PROVIDER,
101 RESOURCE_PROVIDER, SHARE_LINK_ACTION, WORKSPACE_PROVIDER, is_resource_provider, resource_parts,
102};
103
104pub use catalogue::{
105 CanonicalActionRoute, CatalogueLimits, CataloguePage, CatalogueProvider, CatalogueQuery,
106 CatalogueResource, CatalogueRow, MAX_BY_RESOURCE_PAGE, MAX_CATALOGUE_PAGE,
107 MAX_CATALOGUE_PAGE_BYTES, Offered, ProvidedPackage, ProvidedResource, ResourceViewLocator,
108 RowVisibility, ViewResourceQuery, compact, expand, rows_weight, stem_word, truncate_bytes,
109 truncate_resources, truncate_rows,
110};
111pub use changes::{CHANGE_FEED_UNAVAILABLE, ChangeFeed, ChangePage, ResourceChanged, What};
112pub use content_get::{CONTENT_GETS_UNAVAILABLE, ContentGetAnswer, ContentGets, ContentPiece};
113pub use content_link::{
114 CONTENT_LINK_TTL_SECS, CONTENT_LINKS_UNAVAILABLE, ContentLink, ContentLinkAsk, ContentLinkFile,
115 MAX_CONTENT_LINK_FILES, viewable,
116};
117pub use content_put::{
118 CONTENT_PUTS_UNAVAILABLE, CONTENT_REFERENCE, ContentPut, ContentPutAnswer, ContentPutStep,
119 ContentPuts, HostedContentPuts, MAX_CONTENT_PUT_AHEAD, MAX_CONTENT_PUT_CHUNK, MAX_HAVE_HASHES,
120 MAX_HOSTED_CONTENT_PUTS, MAX_OPEN_CONTENT_PUTS, MAX_PUT_MANY_BYTES, MAX_PUT_MANY_FILES,
121 content_hash,
122};
123pub use store_commands::{STORE_COMMANDS_UNAVAILABLE, StoreCommands};
124mod execution_lease;
125pub use execution_lease::ExecutionLease;
126pub use pending::{Abandoned, Completer, Pending, PendingPoll, pending};
127pub use resource_read::{
128 DEVICE_JOBS, DEVICE_SETTINGS, DEVICE_SETTINGS_REFUSED, Decided, HeldCopies, ListedResource,
129 RESOURCE_READ_REFUSED, RESOURCE_READS_FOR_AGENTS, RESOURCE_READS_UNAVAILABLE,
130 RESOURCE_WRITE_REFUSED, ReadingAnswer, ReadsAnswer, ResourceAddress, ResourceAsk, ResourceCopy,
131 ResourceReadings, ResourceReads, ResourceWake, answer_read, answered, device_job_address,
132 device_job_path, device_record_address, device_record_space, parse_device_record_space,
133 parse_job_path, read_resources, readings_from, readings_of, reads_answer,
134};
135#[cfg(any(test, feature = "test-support"))]
136pub use test_provider::TestProvider;
137pub use wait::{MAX_REMOTE_WAIT, MAX_REMOTE_WAIT_MS, UpdateMark, settle_with};
138
139use crate::api::ActionAddress;
140use crate::context::ActionContext;
141use crate::outcome::{ActionFailure, ActionOutput, InvocationId, InvocationUpdate};
142use crate::params::ARGUMENTS_JSON_PREFIX;
143
144pub const REMOTE_ACTIONS_VERSION: u16 = 5;
149
150pub const MAX_REMOTE_ACTION_FRAME_BYTES: usize = 1024 * 1024;
152
153pub const MAX_CONTENT_FRAME_BYTES: usize = 384 * 1024;
157
158pub const DEFAULT_LOG_CAPACITY: usize = 1024;
160
161#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
168pub struct RemoteActionTarget {
169 pub provider: String,
170 pub address: ActionAddress,
171}
172
173pub const WORKSPACE_GOVERNANCE_PROVIDER: &str = tilo_action_policy::agent_answers::WORKSPACE_APP;
177pub const WORKSPACE_GOVERNANCE_KIND: &str = "workspace.permissions";
179
180impl RemoteActionTarget {
181 #[must_use]
186 pub fn workspace_governance(workspace: &str, verb: &str) -> Self {
187 Self {
188 provider: WORKSPACE_GOVERNANCE_PROVIDER.to_owned(),
189 address: workspace_governance_address(workspace, verb),
190 }
191 }
192}
193
194#[must_use]
197pub fn workspace_governance_resource(workspace: &str) -> String {
198 format!("{WORKSPACE_GOVERNANCE_KIND}:{workspace}")
199}
200
201pub const WORKSPACE_SERVERS: &str = "servers";
204pub const WORKSPACE_APPS: &str = "apps";
207pub const WORKSPACE_TRUST: &str = "trust";
210pub const WORKSPACE_REGISTRIES: &str = "registries";
213pub const WORKSPACE_CONTENT: &str = "content";
218pub const WORKSPACE_APP: &str = "apps/*";
221pub const WORKSPACE_MAIL_ACCOUNTS: &str = "mail-accounts";
224pub const WORKSPACE_VAULT: &str = "vault";
227pub const WORKSPACE_MODELS: &str = "models";
230pub const WORKSPACE_MEMBERS: &str = "members";
232pub const WORKSPACE_MEMBER: &str = "members/*";
235pub const WORKSPACE_INVITE: &str = "invite";
239pub const WORKSPACE_MEMBER_ADMITTED: &str = "admit";
243pub const WORKSPACE_MEMBER_PLACED: &str = "role";
247pub const WORKSPACE_MEMBER_REMOVED: &str = "remove";
250pub const WORKSPACE_INVITATIONS: &str = "invitations";
253pub const WORKSPACE_WAITING: &str = "waiting";
256pub const WORKSPACE_PERMISSIONS: &str = "permissions";
258pub const WORKSPACE_PERMISSION: &str = "permissions/*";
261pub const WORKSPACE_GRANT_REVOKE: &str = "grant.revoke";
265pub const WORKSPACE_READ_GRANT: &str = "reading.grant";
270pub const WORKSPACE_READ_REVOKE: &str = "reading.revoke";
273pub const WORKSPACE_AGENTS: &str = "agents";
276pub const WORKSPACE_AGENT_CREATE: &str = "agent.create";
279pub const WORKSPACE_AGENT_UPDATE: &str = "agent.update";
282pub const WORKSPACE_AGENT_DELETE: &str = "agent.delete";
285pub const WORKSPACE_AGENTS_APP: &str = "tilo.workspace";
287pub const WORKSPACE_AGENTS_KIND: &str = "tilo.workspace.agent";
290pub const WORKSPACE_AGENT_CHANGES: [&str; 15] = [
293 "set-agent-spend-limit",
294 "record-agent-spend",
295 "rename-agent",
296 "set-agent-avatar",
297 "set-agent-model",
298 "set-agent-instruction",
299 "pause-agent",
300 "resume-agent",
301 "start-sub-agent",
302 "note-sub-agent",
303 "stop-sub-agent",
304 "sub-agent-stands",
305 "sub-agent-produced",
306 "sub-agent-coding",
307 "set-sub-agent-limits",
308];
309
310#[must_use]
315pub fn workspace_agent_effects(operation: &str) -> Vec<crate::ActionEffect> {
316 let step =
317 |verb: &str| crate::ActionEffect::new(WORKSPACE_AGENTS_APP, WORKSPACE_AGENTS_KIND, verb);
318 match operation {
319 WORKSPACE_AGENT_CREATE => vec![step("create-agent")],
320 WORKSPACE_AGENT_UPDATE => WORKSPACE_AGENT_CHANGES
321 .iter()
322 .map(|verb| step(verb))
323 .collect(),
324 WORKSPACE_AGENT_DELETE => vec![step("retire-agent")],
325 _ => Vec::new(),
326 }
327}
328pub const WORKSPACE_MEMBER_LIST_PUBLISHED: [(&str, Option<&str>, &str); 47] = [
337 ("member.list", Some(WORKSPACE_MEMBERS), "list"),
338 (
339 "member.add",
340 Some(WORKSPACE_MEMBERS),
341 WORKSPACE_MEMBER_ADMITTED,
342 ),
343 (
344 "member.add",
345 Some(WORKSPACE_MEMBER),
346 WORKSPACE_MEMBER_PLACED,
347 ),
348 (
349 "remove-member",
350 Some(WORKSPACE_MEMBER),
351 WORKSPACE_MEMBER_REMOVED,
352 ),
353 ("member.name", Some(WORKSPACE_MEMBERS), "name"),
354 ("ban", Some(WORKSPACE_MEMBERS), "ban"),
357 ("unban", Some(WORKSPACE_MEMBERS), "unban"),
358 ("invite", Some(WORKSPACE_INVITATIONS), "invite"),
359 ("invitation.list", Some(WORKSPACE_INVITATIONS), "list"),
360 ("invitation.cancel", Some(WORKSPACE_INVITATIONS), "cancel"),
361 ("wait-list.list", Some(WORKSPACE_WAITING), "list"),
362 ("wait-list.remove", Some(WORKSPACE_WAITING), "unlist"),
363 ("wait-list.mail", Some(WORKSPACE_WAITING), "mail"),
364 ("server.list", Some(WORKSPACE_SERVERS), "list"),
365 ("server.add", Some(WORKSPACE_SERVERS), "add"),
366 ("server.remove", Some(WORKSPACE_SERVERS), "remove"),
367 ("server.move", Some(WORKSPACE_SERVERS), "move"),
368 ("copies.set", Some(WORKSPACE_SERVERS), "copies"),
369 ("copies.read", Some(WORKSPACE_SERVERS), "keeps"),
370 ("content.held", Some(WORKSPACE_SERVERS), "content"),
371 ("content.policy", Some(WORKSPACE_CONTENT), "policy"),
372 ("content.set-policy", Some(WORKSPACE_CONTENT), "set-policy"),
373 ("trust.list", Some(WORKSPACE_TRUST), "list"),
374 ("trust.revoked", Some(WORKSPACE_TRUST), "revoked"),
375 ("trust.add", Some(WORKSPACE_TRUST), "add"),
376 ("trust.remove", Some(WORKSPACE_TRUST), "remove"),
377 ("trust.revoke", Some(WORKSPACE_TRUST), "revoke"),
378 ("registry.list", Some(WORKSPACE_REGISTRIES), "list"),
379 ("registry.add", Some(WORKSPACE_REGISTRIES), "add"),
380 ("registry.remove", Some(WORKSPACE_REGISTRIES), "remove"),
381 ("registry.enable", Some(WORKSPACE_REGISTRIES), "enable"),
382 ("registry.disable", Some(WORKSPACE_REGISTRIES), "disable"),
383 ("registry.channel", Some(WORKSPACE_REGISTRIES), "channel"),
384 ("install-app", Some(WORKSPACE_APPS), "install"),
385 ("upload-app-file", Some(WORKSPACE_APPS), "upload"),
386 ("app.offers", Some(WORKSPACE_APPS), "offers"),
387 ("install-app", Some(WORKSPACE_APP), "update"),
388 ("app.pin", Some(WORKSPACE_APP), "pin"),
389 ("app.unpin", Some(WORKSPACE_APP), "unpin"),
390 ("uninstall-app", Some(WORKSPACE_APP), "uninstall"),
391 ("app.earlier", Some(WORKSPACE_APP), "earlier"),
392 (WORKSPACE_GRANT_REVOKE, Some(WORKSPACE_PERMISSION), "revoke"),
393 (WORKSPACE_READ_GRANT, Some(WORKSPACE_MEMBERS), "grant-read"),
394 (
395 WORKSPACE_READ_REVOKE,
396 Some(WORKSPACE_MEMBERS),
397 "revoke-read",
398 ),
399 (WORKSPACE_AGENT_CREATE, Some(WORKSPACE_AGENTS), "create"),
400 (WORKSPACE_AGENT_UPDATE, Some(WORKSPACE_AGENTS), "update"),
401 (WORKSPACE_AGENT_DELETE, Some(WORKSPACE_AGENTS), "delete"),
402];
403
404pub const WORKSPACE_INVOCATIONS_PROVIDER: &str = "tilo.invocations";
407
408pub const MACHINES_PROVIDER: &str = "tilo.machines";
410
411pub const SERVER_ACCOUNT_PROVIDER: &str = "tilo.server";
413
414pub const WORKSPACE_EVENTS_PROVIDER: &str = "tilo.events";
416
417pub const MODERATION_PROVIDER: &str = "tilo.moderation";
419pub const MODERATION_HISTORY: &str = "moderation.history";
421pub const MODERATION_UNDO: &str = "undo";
423pub const MODERATED_APP: &str = "so.tilo.chat";
425
426pub const MODELS_PROVIDER: &str = "tilo.models";
431
432pub const TELLING_PROVIDER: &str = "tilo.telling";
436
437pub const ACCOUNTS_PROVIDER: &str = "tilo.accounts";
443
444pub const CONNECTIONS_PROVIDER: &str = "tilo.connections";
450
451#[must_use]
453pub fn workspace_governance_child(workspace: &str, child: Option<&str>) -> String {
454 let root = workspace_governance_resource(workspace);
455 match child {
456 Some(child) => format!("{root}/{child}"),
457 None => root,
458 }
459}
460
461#[must_use]
463pub fn workspace_permission(workspace: &str, grant: &str) -> String {
464 format!(
465 "{}/{grant}",
466 workspace_governance_child(workspace, Some(WORKSPACE_PERMISSIONS))
467 )
468}
469
470#[must_use]
472pub fn workspace_member(workspace: &str, person: &str) -> String {
473 format!(
474 "{}/{person}",
475 workspace_governance_child(workspace, Some(WORKSPACE_MEMBERS))
476 )
477}
478
479#[must_use]
481pub fn workspace_app(workspace: &str, app: &str) -> String {
482 format!(
483 "{}/{app}",
484 workspace_governance_child(workspace, Some(WORKSPACE_APPS))
485 )
486}
487
488#[must_use]
491pub fn workspace_governance_address(workspace: &str, operation: &str) -> ActionAddress {
492 match WORKSPACE_MEMBER_LIST_PUBLISHED
493 .iter()
494 .find(|(granted, child, _)| {
495 *granted == operation
496 && *child != Some(WORKSPACE_MEMBER)
497 && *child != Some(WORKSPACE_APP)
498 && *child != Some(WORKSPACE_PERMISSION)
499 }) {
500 Some((_, child, action)) => {
501 ActionAddress::new(workspace_governance_child(workspace, *child), *action)
502 }
503 None => ActionAddress::new(workspace_governance_resource(workspace), operation),
504 }
505}
506
507#[must_use]
512pub fn workspace_governance_operation(address: &ActionAddress) -> Option<(&str, &str)> {
513 let named = address
514 .resource
515 .strip_prefix(workspace_governance_resource("").as_str())?;
516 let (workspace, child) = match named.split_once('/') {
517 Some((workspace, child)) => (workspace, Some(child)),
518 None => (named, None),
519 };
520 if workspace.is_empty() {
521 return None;
522 }
523 let action = address.action.as_str();
524 let child = if workspace_person(address).is_some() {
525 Some(WORKSPACE_MEMBER)
526 } else if workspace_app_named(address).is_some() {
527 Some(WORKSPACE_APP)
528 } else if workspace_grant(address).is_some() {
529 Some(WORKSPACE_PERMISSION)
530 } else {
531 child
532 };
533 let published = WORKSPACE_MEMBER_LIST_PUBLISHED
534 .iter()
535 .find(|(_, at, published)| *at == child && *published == action);
536 match published {
537 Some((granted, _, _)) => Some((workspace, granted)),
538 None if child.is_none()
539 && !WORKSPACE_MEMBER_LIST_PUBLISHED
540 .iter()
541 .any(|(granted, _, _)| *granted == action) =>
542 {
543 Some((workspace, action))
544 }
545 None => None,
546 }
547}
548
549#[must_use]
552pub fn workspace_person(address: &ActionAddress) -> Option<&str> {
553 let named = address
554 .resource
555 .strip_prefix(workspace_governance_resource("").as_str())?;
556 let (members, person) = named.split_once('/')?.1.split_once('/')?;
557 (members == WORKSPACE_MEMBERS
558 && person.len() == 64
559 && person.bytes().all(|byte| byte.is_ascii_hexdigit()))
560 .then_some(person)
561}
562
563#[must_use]
566pub fn workspace_app_named(address: &ActionAddress) -> Option<&str> {
567 let named = address
568 .resource
569 .strip_prefix(workspace_governance_resource("").as_str())?;
570 let (apps, app) = named.split_once('/')?.1.split_once('/')?;
571 (apps == WORKSPACE_APPS
572 && !app.is_empty()
573 && app
574 .bytes()
575 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_')))
576 .then_some(app)
577}
578
579#[must_use]
582pub fn workspace_grant(address: &ActionAddress) -> Option<&str> {
583 let named = address
584 .resource
585 .strip_prefix(workspace_governance_resource("").as_str())?;
586 let (permissions, grant) = named.split_once('/')?.1.split_once('/')?;
587 (permissions == WORKSPACE_PERMISSIONS && !grant.is_empty()).then_some(grant)
588}
589
590pub mod settings_resources {
595 pub const PROVIDER: &str = "tilo.settings";
597 pub const SURFACE_APP: &str = "so.tilo.settings.sections";
599
600 #[must_use]
603 pub fn is_section(path: &str) -> bool {
604 let resource = path.split('#').next().unwrap_or_default();
605 let parts: Vec<&str> = resource.split('/').collect();
606 matches!(parts.as_slice(), ["settings", section] if !section.is_empty())
607 || matches!(parts.as_slice(), ["devices", device, "settings", section]
608 if !device.is_empty() && !section.is_empty())
609 }
610}
611
612pub const CONFIRMED_ACTION_NEEDS_REVISION: &str =
618 "a confirmed action needs the revision it was shown at";
619
620#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
622pub enum InvokeArgument {
623 #[default]
625 None,
626 Text(String),
628 Json(serde_json::Map<String, serde_json::Value>),
630}
631
632impl InvokeArgument {
633 #[must_use]
636 pub fn to_slot(&self) -> Option<String> {
637 match self {
638 Self::None => None,
639 Self::Text(text) => Some(text.clone()),
640 Self::Json(object) => Some(format!(
641 "{ARGUMENTS_JSON_PREFIX}{}",
642 serde_json::Value::Object(object.clone())
643 )),
644 }
645 }
646
647 #[must_use]
651 pub fn from_slot(slot: Option<&str>) -> Self {
652 match slot {
653 None => Self::None,
654 Some(text) => match text
655 .strip_prefix(ARGUMENTS_JSON_PREFIX)
656 .and_then(|json| serde_json::from_str(json).ok())
657 {
658 Some(object) => Self::Json(object),
659 None => Self::Text(text.to_owned()),
660 },
661 }
662 }
663}
664
665#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
667pub struct InvokeRequest {
668 pub invocation: InvocationId,
671 pub target: RemoteActionTarget,
672 #[serde(default)]
673 pub argument: InvokeArgument,
674 #[serde(default, skip_serializing_if = "Option::is_none")]
676 pub context: Option<ActionContext>,
677 #[serde(default, skip_serializing_if = "Option::is_none")]
681 pub confirmation: Option<Confirmation>,
682 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub revision: Option<String>,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
698 pub on_behalf_of: Option<InvocationId>,
699 #[serde(default, skip_serializing_if = "Option::is_none")]
706 pub wait_ms: Option<u32>,
707 #[serde(default, skip_serializing_if = "Option::is_none")]
712 pub appearance: Option<crate::Appearance>,
713 #[serde(default, skip_serializing_if = "Option::is_none")]
724 pub signed: Option<Box<SignedInvocation>>,
725}
726
727impl InvokeRequest {
728 #[must_use]
733 pub fn made_from(&self) -> Option<crate::params::MadeFrom> {
734 let InvokeArgument::Json(arguments) = &self.argument else {
735 return None;
736 };
737 crate::params::MadeFrom::from_json(arguments.get(crate::params::FROM_ARGUMENT)?)
738 }
739
740 #[must_use]
744 pub fn approval(&self) -> Option<&asked::Approval> {
745 match &self.confirmation {
746 Some(Confirmation::Asked(approval)) => Some(approval),
747 _ => None,
748 }
749 }
750
751 #[must_use]
755 pub fn said_session_name(&self) -> Option<String> {
756 let group = self
757 .context
758 .as_ref()?
759 .group
760 .as_ref()
761 .filter(|group| group.kind == crate::context::AGENT_SESSION_GROUP)?;
762 crate::context::one_line(group.session.as_deref()?, crate::context::MAX_LABEL_CHARS)
763 }
764
765 #[must_use]
769 pub fn same_invocation(&self, other: &Self) -> bool {
770 let Self {
771 invocation,
772 target,
773 argument,
774 context,
775 confirmation,
776 revision,
777 on_behalf_of,
778 wait_ms: _,
779 appearance,
780 signed: _,
783 } = self;
784 *invocation == other.invocation
785 && *target == other.target
786 && *argument == other.argument
787 && *context == other.context
788 && *confirmation == other.confirmation
789 && *revision == other.revision
790 && *on_behalf_of == other.on_behalf_of
791 && *appearance == other.appearance
792 }
793
794 #[must_use]
797 pub fn plain(
798 target: RemoteActionTarget,
799 arguments: serde_json::Map<String, serde_json::Value>,
800 ) -> Self {
801 Self {
802 invocation: InvocationId::new(),
803 target,
804 argument: if arguments.is_empty() {
805 InvokeArgument::None
806 } else {
807 InvokeArgument::Json(arguments)
808 },
809 context: None,
810 confirmation: None,
811 revision: None,
812 on_behalf_of: None,
813 wait_ms: None,
814 appearance: None,
815 signed: None,
816 }
817 }
818}
819
820pub const APPLICATION_CLOSE_ACTION: &str = "close";
822
823#[must_use]
825pub fn workspace_provider(workspace: &str) -> String {
826 format!("{WORKSPACE_PROVIDER}:{workspace}")
827}
828
829pub const ACTIONS_PROVIDER: &str = "tilo.actions";
832
833#[must_use]
836pub fn provider_workspace(provider: &str) -> Option<&str> {
837 provider
838 .strip_prefix(WORKSPACE_PROVIDER)
839 .and_then(|rest| rest.strip_prefix(':'))
840}
841
842#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
844pub enum ReceiptStatus {
845 Accepted,
847 Completed { output: ActionOutput },
849 Failed { error: ActionFailure },
851 Rejected { error: ActionCallError },
853 Cancelled { message: Option<String> },
855}
856
857impl ReceiptStatus {
858 #[must_use]
860 pub const fn is_terminal(&self) -> bool {
861 !matches!(self, Self::Accepted)
862 }
863}
864
865#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
867pub struct InvocationReceipt {
868 pub invocation: InvocationId,
869 pub status: ReceiptStatus,
870}
871
872#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
875pub struct InvocationState {
876 pub update: InvocationUpdate,
877 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
881 pub untrusted: bool,
882 #[serde(default, skip_serializing_if = "Option::is_none")]
886 pub left_at: Option<ActorPlace>,
887 #[serde(default, skip_serializing_if = "Option::is_none")]
891 pub link: Option<String>,
892 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
896 pub read_answered: bool,
897}
898
899#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
902pub struct ActorPlace {
903 pub anchor: String,
904 pub head: String,
905}
906
907impl InvocationState {
908 #[must_use]
910 pub fn new(invocation: InvocationId, update: InvocationUpdate) -> Self {
911 Self {
912 update: update.with_invocation(invocation),
913 untrusted: false,
914 left_at: None,
915 link: None,
916 read_answered: false,
917 }
918 }
919
920 #[must_use]
924 pub fn of_read(mut self) -> Self {
925 self.read_answered = matches!(
926 &self.update,
927 InvocationUpdate::Item { value, .. }
928 if value.get("pending") != Some(&serde_json::Value::Bool(true))
929 );
930 self
931 }
932
933 #[must_use]
935 pub fn left_at(mut self, place: Option<ActorPlace>) -> Self {
936 self.left_at = place;
937 self
938 }
939
940 #[must_use]
942 pub fn linked(mut self, link: Option<String>) -> Self {
943 self.link = link;
944 self
945 }
946
947 #[must_use]
949 pub fn with_untrusted(mut self, untrusted: bool) -> Self {
950 self.untrusted = untrusted;
951 self
952 }
953
954 #[must_use]
955 pub fn invocation(&self) -> InvocationId {
956 self.update.invocation()
957 }
958
959 #[must_use]
960 pub fn is_terminal(&self) -> bool {
961 self.update.is_terminal()
962 }
963
964 #[must_use]
967 pub fn receipt(&self) -> InvocationReceipt {
968 let status = match &self.update {
969 InvocationUpdate::Accepted { .. }
970 | InvocationUpdate::Progress { .. }
971 | InvocationUpdate::Item { .. } => ReceiptStatus::Accepted,
972 InvocationUpdate::Succeeded { output, .. } => ReceiptStatus::Completed {
973 output: output.clone(),
974 },
975 InvocationUpdate::Failed { error, .. } if error.code == CONFIRMATION_REQUIRED_CODE => {
979 ReceiptStatus::Rejected {
980 error: ActionCallError::asks(asked::AskedFacts::from_details(
981 error.details.as_ref(),
982 )),
983 }
984 }
985 InvocationUpdate::Failed { error, .. } => ReceiptStatus::Failed {
986 error: error.clone(),
987 },
988 InvocationUpdate::Cancelled { message, .. } => ReceiptStatus::Cancelled {
989 message: message.clone(),
990 },
991 };
992 InvocationReceipt {
993 invocation: self.invocation(),
994 status,
995 }
996 }
997}
998
999pub const CONFIRMATION_REQUIRED_CODE: &str = "action_confirmation_required";
1006
1007pub const AWAITING_APPROVAL: &str = "awaiting_approval";
1011
1012pub const NOT_ON_THIS_SERVER: &str = "not_on_this_server";
1015
1016pub const HOSTS_NONE_FOR_PEOPLE: &str = "hosts_none_for_people";
1020
1021pub const KEY_REVOKED: &str = "key_revoked";
1024
1025pub const APPROVE_AGAIN: &str = "approve a new key: the person types `tilo do account/keys#create name=\"<name>\"` \
1028 and approves it in their Tilo tab (on their own computer, `tilo login` again)";
1029
1030#[must_use]
1033pub fn not_on_this_server(person: &[u8; 32]) -> ActionCallError {
1034 let key = hex::encode(person);
1035 ActionCallError::Refused {
1036 reason: format!(
1037 "{NOT_ON_THIS_SERVER}: This server doesn't know you yet: its operator hasn't made you \
1038 an owner, and no invitation brought you into a workspace here. Ask the operator to \
1039 declare your key {key} an owner (on a local stack: `stack.sh owner {key}`), or join \
1040 with an invitation link someone here sends you."
1041 ),
1042 }
1043}
1044
1045#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
1054#[serde(from = "WireActionCallError", into = "WireActionCallError")]
1055pub enum ActionCallError {
1056 #[error("remote actions are unavailable: {reason}")]
1058 Unavailable { reason: String },
1059 #[error("no such action is offered")]
1062 UnknownAction,
1063 #[error("the caller may not invoke this action")]
1065 NotPermitted,
1066 #[error("the action requires confirmation")]
1070 ConfirmationRequired(Box<asked::AskedFacts>),
1071 #[error("invalid request: {reason}")]
1073 InvalidRequest { reason: String },
1074 #[error("invalid request: {}", STALE_REVISION_REASON)]
1078 StaleRevision,
1079 #[error("no such invocation")]
1081 UnknownInvocation,
1082 #[error("the invocation id was already used for a different request")]
1084 InvocationConflict,
1085 #[error("the invocation cannot be cancelled: {reason}")]
1087 NotCancellable { reason: String },
1088 #[error("refused: {reason}")]
1090 Refused { reason: String },
1091 #[error("the workspace is not ready for this call yet")]
1094 NotReady,
1095 #[error("the action's provider did not answer in time")]
1100 Unanswered,
1101}
1102
1103impl ActionCallError {
1104 #[must_use]
1109 pub fn from_api(error: &crate::ApiError) -> Self {
1110 use crate::ApiError;
1111 match error {
1112 ApiError::Unknown(_) | ApiError::UnregisteredType(_) => Self::UnknownAction,
1113 ApiError::MissingArgument(_)
1114 | ApiError::UnexpectedArgument(_)
1115 | ApiError::InvalidArguments(_)
1116 | ApiError::ArgumentOutOfRange { .. } => Self::InvalidRequest {
1117 reason: error.to_string(),
1118 },
1119 ApiError::ConfirmationRequired => Self::confirmation_required(),
1120 ApiError::Unavailable { .. } | ApiError::Refused { .. } | ApiError::Failed(_) => {
1121 Self::Refused {
1122 reason: error.to_string(),
1123 }
1124 }
1125 }
1126 }
1127
1128 #[must_use]
1131 pub fn confirmation_required() -> Self {
1132 Self::asks(asked::AskedFacts::default())
1133 }
1134
1135 #[must_use]
1137 pub fn asks(facts: asked::AskedFacts) -> Self {
1138 Self::ConfirmationRequired(Box::new(facts))
1139 }
1140
1141 #[must_use]
1143 pub fn refused(reason: impl Into<String>) -> Self {
1144 Self::Refused {
1145 reason: reason.into(),
1146 }
1147 }
1148
1149 #[must_use]
1152 pub fn own_words(&self) -> String {
1153 match self {
1154 Self::Refused { reason } => reason.clone(),
1155 other => other.to_string(),
1156 }
1157 }
1158
1159 #[must_use]
1161 pub fn invalid_request(reason: impl Into<String>) -> Self {
1162 Self::InvalidRequest {
1163 reason: reason.into(),
1164 }
1165 }
1166
1167 #[must_use]
1169 pub fn unavailable(reason: impl Into<String>) -> Self {
1170 Self::Unavailable {
1171 reason: reason.into(),
1172 }
1173 }
1174
1175 #[must_use]
1177 pub const fn code(&self) -> &'static str {
1178 match self {
1179 Self::Unavailable { .. } => "remote_actions_unavailable",
1180 Self::UnknownAction => "unknown_action",
1181 Self::NotPermitted => "not_permitted",
1182 Self::ConfirmationRequired(_) => "action_confirmation_required",
1183 Self::InvalidRequest { .. } => "invalid_arguments",
1184 Self::StaleRevision => "stale_revision",
1185 Self::UnknownInvocation => "unknown_invocation",
1186 Self::InvocationConflict => "invocation_conflict",
1187 Self::NotCancellable { .. } => "not_cancellable",
1188 Self::Refused { .. } => "refused",
1189 Self::NotReady => "not_ready",
1190 Self::Unanswered => "unanswered",
1191 }
1192 }
1193
1194 #[must_use]
1199 pub fn said(&self) -> String {
1200 match self {
1201 Self::StaleRevision => "stale_revision: the resource changed since you read it. \
1204 Call the action again with tilo_do, which runs it against the resource as it \
1205 is now, or tilo_read the resource first to see what changed"
1206 .to_owned(),
1207 Self::NotPermitted => {
1210 format!("not_permitted: {}", crate::Availability::NOT_ALLOWED_HERE)
1211 }
1212 Self::Unavailable { reason } => format!("unavailable: {reason}"),
1215 Self::Unanswered => "unanswered: the workspace did not answer in time; it may \
1218 still be opening its documents after it started, so ask again"
1219 .to_owned(),
1220 Self::InvalidRequest { reason } | Self::Refused { reason } => {
1221 format!("{}: {reason}", self.code())
1222 }
1223 other => format!("{}: {other}", other.code()),
1224 }
1225 }
1226
1227 #[must_use]
1231 pub const fn ask_again(&self) -> bool {
1232 matches!(self, Self::NotReady | Self::Unanswered)
1233 }
1234
1235 #[must_use]
1238 pub fn ask_again_code(code: &str) -> bool {
1239 code == Self::NotReady.code() || code == Self::Unanswered.code()
1240 }
1241
1242 #[must_use]
1246 pub fn needs_revision(&self) -> bool {
1247 matches!(self, Self::InvalidRequest { reason } if reason == CONFIRMED_ACTION_NEEDS_REVISION)
1248 }
1249}
1250
1251pub const STALE_REVISION_REASON: &str = "the target changed since that revision; list it again";
1254
1255#[derive(Serialize, Deserialize)]
1257#[serde(rename = "ActionCallError")]
1258enum WireActionCallError {
1259 Unavailable { reason: String },
1260 UnknownAction,
1261 NotPermitted,
1262 ConfirmationRequired(Box<asked::AskedFacts>),
1263 InvalidRequest { reason: String },
1264 UnknownInvocation,
1265 InvocationConflict,
1266 NotCancellable { reason: String },
1267 Refused { reason: String },
1268 NotReady,
1269 Unanswered,
1270}
1271
1272impl From<ActionCallError> for WireActionCallError {
1273 fn from(error: ActionCallError) -> Self {
1274 match error {
1275 ActionCallError::Unavailable { reason } => Self::Unavailable { reason },
1276 ActionCallError::UnknownAction => Self::UnknownAction,
1277 ActionCallError::NotPermitted => Self::NotPermitted,
1278 ActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
1279 ActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
1280 ActionCallError::StaleRevision => Self::InvalidRequest {
1281 reason: STALE_REVISION_REASON.to_owned(),
1282 },
1283 ActionCallError::UnknownInvocation => Self::UnknownInvocation,
1284 ActionCallError::InvocationConflict => Self::InvocationConflict,
1285 ActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
1286 ActionCallError::Refused { reason } => Self::Refused { reason },
1287 ActionCallError::NotReady => Self::NotReady,
1288 ActionCallError::Unanswered => Self::Unanswered,
1289 }
1290 }
1291}
1292
1293impl From<WireActionCallError> for ActionCallError {
1294 fn from(error: WireActionCallError) -> Self {
1295 match error {
1296 WireActionCallError::InvalidRequest { reason } if reason == STALE_REVISION_REASON => {
1297 Self::StaleRevision
1298 }
1299 WireActionCallError::Unavailable { reason } => Self::Unavailable { reason },
1300 WireActionCallError::UnknownAction => Self::UnknownAction,
1301 WireActionCallError::NotPermitted => Self::NotPermitted,
1302 WireActionCallError::ConfirmationRequired(facts) => Self::ConfirmationRequired(facts),
1303 WireActionCallError::InvalidRequest { reason } => Self::InvalidRequest { reason },
1304 WireActionCallError::UnknownInvocation => Self::UnknownInvocation,
1305 WireActionCallError::InvocationConflict => Self::InvocationConflict,
1306 WireActionCallError::NotCancellable { reason } => Self::NotCancellable { reason },
1307 WireActionCallError::Refused { reason } => Self::Refused { reason },
1308 WireActionCallError::NotReady => Self::NotReady,
1309 WireActionCallError::Unanswered => Self::Unanswered,
1310 }
1311 }
1312}
1313
1314#[cfg_attr(
1318 any(target_arch = "wasm32", not(feature = "off-worker")),
1319 expect(
1320 clippy::unused_async,
1321 reason = "only a host with `off-worker` runs a runtime whose worker there is to leave"
1322 )
1323)]
1324pub async fn observed_off_the_worker<P>(
1325 provider: P,
1326 caller: Caller,
1327 invocation: InvocationId,
1328) -> Option<InvocationState>
1329where
1330 P: ActionProvider + Send + 'static,
1331{
1332 #[cfg(all(not(target_arch = "wasm32"), feature = "off-worker"))]
1333 if tokio::runtime::Handle::try_current().is_ok() {
1334 return tokio::task::spawn_blocking(move || provider.observe(&caller, &invocation))
1335 .await
1336 .ok()
1337 .flatten();
1338 }
1339 provider.observe(&caller, &invocation)
1340}
1341
1342pub struct RunningTool {
1347 pub stopped: Pending<Result<(), ActionCallError>>,
1349 stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1352 end: Option<Box<dyn FnOnce(bool) + Send + Sync>>,
1353}
1354
1355impl RunningTool {
1356 #[must_use]
1360 pub fn new(
1361 stopped: Pending<Result<(), ActionCallError>>,
1362 stop_noted: std::sync::Arc<std::sync::atomic::AtomicBool>,
1363 end: impl FnOnce(bool) + Send + Sync + 'static,
1364 ) -> Self {
1365 Self {
1366 stopped,
1367 stop_noted,
1368 end: Some(Box::new(end)),
1369 }
1370 }
1371
1372 #[must_use]
1374 pub fn was_stopped(&self) -> bool {
1375 self.stop_noted.load(std::sync::atomic::Ordering::Acquire)
1376 }
1377
1378 pub fn ended(mut self, stopped: bool) {
1380 if let Some(end) = self.end.take() {
1381 end(stopped);
1382 }
1383 }
1384}
1385
1386impl Drop for RunningTool {
1387 fn drop(&mut self) {
1390 if let Some(end) = self.end.take() {
1391 end(false);
1392 }
1393 }
1394}
1395
1396pub trait ActionProvider {
1404 fn retire_execution(&self, caller: &Caller) {
1406 caller.retire_execution();
1407 }
1408
1409 fn serves(&self, provider: &str) -> bool {
1414 let _ = provider;
1415 false
1416 }
1417
1418 fn published(&self) -> Vec<crate::ResourceSpec> {
1424 Vec::new()
1425 }
1426
1427 fn query(
1430 &self,
1431 caller: &Caller,
1432 query: CatalogueQuery,
1433 ) -> Pending<Result<CataloguePage, ActionCallError>>;
1434
1435 fn invoke(
1440 &self,
1441 caller: &Caller,
1442 request: InvokeRequest,
1443 ) -> Pending<Result<InvocationReceipt, ActionCallError>>;
1444
1445 fn tool_started(&self, caller: &Caller, id: &InvocationId, tool: &str) -> Option<RunningTool> {
1451 let _ = (caller, id, tool);
1452 None
1453 }
1454
1455 fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState>;
1458
1459 fn observed(&self, caller: &Caller, id: &InvocationId, state: Option<&InvocationState>) {
1462 let _ = (caller, id, state);
1463 }
1464
1465 fn next_change(&self, caller: &Caller, id: &InvocationId) -> Option<Pending<()>> {
1477 let _ = (caller, id);
1478 None
1479 }
1480
1481 fn session_state(&self, caller: &Caller) -> Option<SessionState> {
1484 let _ = caller;
1485 None
1486 }
1487
1488 fn session_state_changed(&self, caller: &Caller) -> Option<Pending<()>> {
1492 let _ = caller;
1493 None
1494 }
1495
1496 fn changed(
1506 &self,
1507 caller: &Caller,
1508 scope: WatchScope,
1509 ) -> Option<Pending<Result<(), ActionCallError>>> {
1510 let _ = (caller, scope);
1511 None
1512 }
1513
1514 fn cancel(&self, caller: &Caller, id: &InvocationId) -> Pending<Result<(), ActionCallError>>;
1522
1523 fn content_puts(&self) -> Option<std::sync::Arc<dyn ContentPuts>> {
1526 None
1527 }
1528
1529 fn content_puts_for(
1534 &self,
1535 target: Option<&RemoteActionTarget>,
1536 ) -> Option<std::sync::Arc<dyn ContentPuts>> {
1537 let _ = target;
1538 self.content_puts()
1539 }
1540
1541 fn content_gets(&self) -> Option<std::sync::Arc<dyn ContentGets>> {
1544 None
1545 }
1546
1547 fn introduced(&self, caller: &Caller, client: &str) {
1552 let _ = (caller, client);
1553 }
1554
1555 fn here(&self, caller: &Caller) -> Option<Vec<Here>> {
1559 let _ = caller;
1560 None
1561 }
1562
1563 fn resource_reads(&self) -> Option<std::sync::Arc<dyn ResourceReads>> {
1568 None
1569 }
1570
1571 fn store_commands(&self) -> Option<std::sync::Arc<dyn StoreCommands>> {
1575 None
1576 }
1577
1578 fn change_feed(&self) -> Option<std::sync::Arc<dyn ChangeFeed>> {
1582 None
1583 }
1584
1585 fn installed_surface(&self, app_id: &str) -> Pending<Option<Vec<u8>>> {
1589 let _ = app_id;
1590 Pending::ready(None)
1591 }
1592
1593 fn invocation(
1598 &self,
1599 address: &crate::ActionAddress,
1600 argument: Option<&str>,
1601 ) -> Option<crate::api::ActionDescriptor> {
1602 let _ = (address, argument);
1603 None
1604 }
1605
1606 fn run(
1609 &self,
1610 caller: &Caller,
1611 request: InvokeRequest,
1612 admitted: Admitted,
1613 ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
1614 let _ = admitted;
1615 self.invoke(caller, request)
1616 }
1617
1618 fn asks_first(
1625 &self,
1626 caller: &Caller,
1627 request: &InvokeRequest,
1628 admitted: &Admitted,
1629 ) -> Option<Pending<Result<(), ActionCallError>>> {
1630 let _ = (caller, request, admitted);
1631 None
1632 }
1633
1634 fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
1642 let _ = (caller, request);
1643 Err("this action has no live result".into())
1644 }
1645}
1646
1647#[allow(
1650 clippy::trivially_copy_pass_by_ref,
1651 reason = "serde hands a skipped field to it by reference"
1652)]
1653const fn is_zero(value: &u64) -> bool {
1654 *value == 0
1655}
1656
1657fn updated(
1659 correlation: u64,
1660 invocation: InvocationId,
1661 state: Option<InvocationState>,
1662) -> RemoteActionMessage {
1663 RemoteActionMessage::Update {
1664 invocation,
1665 state,
1666 correlation: Some(correlation),
1667 }
1668}
1669
1670#[allow(
1672 clippy::large_enum_variant,
1673 reason = "a message is built, encoded once and dropped; boxing would only add noise to every constructor and match"
1674)]
1675#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
1676pub enum RemoteActionMessage {
1677 RetiredFeedbackRequest { correlation: u64 },
1681 RetiredFeedbackResponse { correlation: u64 },
1683 CatalogueRequest {
1685 correlation: u64,
1686 #[serde(default)]
1687 query: CatalogueQuery,
1688 },
1689 CatalogueResponse {
1691 correlation: u64,
1692 result: Result<CataloguePage, ActionCallError>,
1693 },
1694 Invoke(InvokeRequest),
1696 Receipt(InvocationReceipt),
1698 Observe {
1700 #[serde(default, skip_serializing_if = "is_zero")]
1706 correlation: u64,
1707 invocation: InvocationId,
1708 #[serde(default, skip_serializing_if = "Option::is_none")]
1713 wait_ms: Option<u32>,
1714 #[serde(default, skip_serializing_if = "Option::is_none")]
1716 seen: Option<UpdateMark>,
1717 },
1718 Update {
1721 invocation: InvocationId,
1722 state: Option<InvocationState>,
1723 #[serde(default, skip_serializing_if = "Option::is_none")]
1726 correlation: Option<u64>,
1727 },
1728 Cancel { invocation: InvocationId },
1730 CancelResponse {
1732 invocation: InvocationId,
1733 result: Result<(), ActionCallError>,
1734 },
1735 ConfirmationRequest {
1737 correlation: u64,
1738 question: ConfirmationQuestion,
1739 },
1740 ConfirmationResponse {
1742 correlation: u64,
1743 result: Result<ConfirmationReply, ActionCallError>,
1744 },
1745 CatalogueChanged { page: CataloguePage },
1749 ContentPutRequest {
1754 correlation: u64,
1755 step: ContentPutStep,
1756 },
1757 ContentPutResponse {
1759 correlation: u64,
1760 result: Result<ContentPutAnswer, ActionCallError>,
1761 },
1762 ContentGetRequest {
1767 correlation: u64,
1768 content: String,
1770 offset: u64,
1772 length: u64,
1775 },
1776 ContentGetResponse {
1778 correlation: u64,
1779 result: Result<ContentGetAnswer, ActionCallError>,
1780 },
1781 ResourceRead {
1788 correlation: u64,
1789 #[serde(default, skip_serializing_if = "Option::is_none")]
1790 on_behalf_of: Option<InvocationId>,
1791 read: ResourceReadRequest,
1792 },
1793 ResourceReading {
1796 correlation: u64,
1797 result: Result<String, ActionCallError>,
1798 },
1799 ChangesRequest {
1802 correlation: u64,
1803 #[serde(default, skip_serializing_if = "Option::is_none")]
1804 after: Option<String>,
1805 },
1806 ChangesResponse {
1808 correlation: u64,
1809 result: Result<ChangePage, ActionCallError>,
1810 },
1811 SurfaceRequest { correlation: u64, app: String },
1813 SurfaceResponse {
1815 correlation: u64,
1816 result: Result<Option<String>, ActionCallError>,
1817 },
1818 ContentLinkRequest {
1822 correlation: u64,
1823 link: ContentLinkAsk,
1824 },
1825 ContentLinkResponse {
1827 correlation: u64,
1828 result: Result<ContentLink, ActionCallError>,
1829 },
1830 ChangedRequest { correlation: u64, scope: WatchScope },
1834 ChangedResponse {
1837 correlation: u64,
1838 result: Result<(), ActionCallError>,
1839 },
1840 CallCarryRequest {
1844 correlation: u64,
1845 #[serde(default, skip_serializing_if = "Option::is_none")]
1846 pair: Option<call::BridgedCall>,
1847 },
1848 CallCarryResponse {
1850 correlation: u64,
1851 result: Result<(), ActionCallError>,
1852 },
1853 CallReport {
1856 correlation: u64,
1857 report: call::CallReport,
1858 },
1859 CallReportResponse {
1861 correlation: u64,
1862 result: Result<(), ActionCallError>,
1863 },
1864 CallHeard(call::CallAudio),
1866 CallSaid(call::CallAudio),
1869 CallStatus(call::CallStatus),
1872 AudioOutputRequest {
1875 correlation: u64,
1876 command: audio_output::Request,
1877 },
1878 AudioOutputResponse {
1880 correlation: u64,
1881 result: Result<audio_output::Snapshot, ActionCallError>,
1882 },
1883 StoreRequest {
1889 correlation: u64,
1890 command: serde_json::Value,
1891 #[serde(default, skip_serializing_if = "Option::is_none")]
1894 kind: Option<String>,
1895 },
1896 StoreResponse {
1899 correlation: u64,
1900 result: Result<serde_json::Value, ActionCallError>,
1901 },
1902 CallMediaRequest {
1906 correlation: u64,
1907 request: native_media::Request,
1908 },
1909 CallMediaResult {
1911 correlation: u64,
1912 result: Result<native_media::Snapshot, ActionCallError>,
1913 },
1914 PresenceSaid { correlation: u64, said: String },
1919 PresenceSaidResult {
1922 correlation: u64,
1923 result: Result<(), ActionCallError>,
1924 },
1925 PresenceHeard { heard: String },
1928 ShellOpenRequest {
1932 correlation: u64,
1933 open: shell::ShellOpen,
1934 },
1935 ShellOpenResponse {
1937 correlation: u64,
1938 result: Result<shell::ShellOpened, ActionCallError>,
1939 },
1940 ShellInput(shell::ShellBytes),
1942 ShellResize { shell: u64, cols: u16, rows: u16 },
1944 ShellClose { shell: u64 },
1946 ShellOutput(shell::ShellBytes),
1948 ShellEnded(shell::ShellEnded),
1951}
1952
1953#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1957pub struct ResourceReadRequest {
1958 pub workspace: String,
1961 pub app: String,
1963 pub record: String,
1965 #[serde(default)]
1966 pub joined: bool,
1967 #[serde(default, skip_serializing_if = "Option::is_none")]
1968 pub after: Option<String>,
1969 #[serde(default, skip_serializing_if = "Option::is_none")]
1971 pub wait_ms: Option<u32>,
1972 #[serde(default, skip_serializing_if = "ReadAnswer::is_reading")]
1975 pub answer: ReadAnswer,
1976}
1977
1978#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
1980#[serde(rename_all = "snake_case")]
1981pub enum ReadAnswer {
1982 #[default]
1984 Reading,
1985 Document,
1988 Listing,
1991 Decision,
1994 WriteDecision,
1997}
1998
1999impl ReadAnswer {
2000 #[must_use]
2002 pub const fn is_reading(&self) -> bool {
2003 matches!(self, Self::Reading)
2004 }
2005}
2006
2007impl RemoteActionMessage {
2008 #[must_use]
2010 pub const fn observe(invocation: InvocationId) -> Self {
2011 Self::Observe {
2012 correlation: 0,
2013 invocation,
2014 wait_ms: None,
2015 seen: None,
2016 }
2017 }
2018
2019 #[must_use]
2024 pub const fn waits(&self) -> bool {
2025 matches!(
2026 self,
2027 Self::Observe {
2028 wait_ms: Some(_),
2029 ..
2030 } | Self::Invoke(InvokeRequest {
2031 wait_ms: Some(_),
2032 ..
2033 }) | Self::ChangedRequest { .. }
2034 | Self::ResourceRead {
2035 read: ResourceReadRequest {
2036 wait_ms: Some(_),
2037 ..
2038 },
2039 ..
2040 }
2041 )
2042 }
2043
2044 #[must_use]
2047 pub const fn is_request(&self) -> bool {
2048 matches!(
2049 self,
2050 Self::CatalogueRequest { .. }
2051 | Self::Invoke(_)
2052 | Self::Observe { .. }
2053 | Self::Cancel { .. }
2054 | Self::ResourceRead { .. }
2055 | Self::RetiredFeedbackRequest { .. }
2056 | Self::ConfirmationRequest { .. }
2057 | Self::ContentPutRequest { .. }
2058 | Self::ContentGetRequest { .. }
2059 | Self::ContentLinkRequest { .. }
2060 | Self::ChangesRequest { .. }
2061 | Self::ChangedRequest { .. }
2062 | Self::SurfaceRequest { .. }
2063 | Self::AudioOutputRequest { .. }
2064 | Self::StoreRequest { .. }
2065 | Self::CallMediaRequest { .. }
2066 | Self::PresenceSaid { .. }
2067 )
2068 }
2069}
2070
2071fn not_kept(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
2076 let reason = match message {
2077 RemoteActionMessage::RetiredFeedbackRequest { .. } => "feedback receipts are retired",
2078 RemoteActionMessage::ContentPutRequest { .. } => CONTENT_PUTS_UNAVAILABLE,
2079 RemoteActionMessage::ContentGetRequest { .. } => CONTENT_GETS_UNAVAILABLE,
2080 RemoteActionMessage::ContentLinkRequest { .. } => CONTENT_LINKS_UNAVAILABLE,
2081 _ => return None,
2082 };
2083 refuse(
2084 message,
2085 ActionCallError::Unavailable {
2086 reason: reason.into(),
2087 },
2088 )
2089}
2090
2091fn store_answered<H: ActionProvider>(
2094 provider: &H,
2095 caller: &Caller,
2096 correlation: u64,
2097 (command, kind): (serde_json::Value, Option<String>),
2098) -> Pending<RemoteActionMessage> {
2099 let result = match provider.store_commands() {
2100 Some(store) => store.command(caller, command, kind),
2101 None => Pending::ready(Err(ActionCallError::Unavailable {
2102 reason: STORE_COMMANDS_UNAVAILABLE.into(),
2103 })),
2104 };
2105 result.map(move |result| RemoteActionMessage::StoreResponse {
2106 correlation,
2107 result,
2108 })
2109}
2110
2111fn changed<H: ActionProvider>(
2114 provider: &H,
2115 caller: &Caller,
2116 correlation: u64,
2117 after: Option<&str>,
2118) -> Pending<RemoteActionMessage> {
2119 let result = match provider.change_feed() {
2120 Some(feed) => feed.since(caller, after),
2121 None => Pending::ready(Err(ActionCallError::Unavailable {
2122 reason: CHANGE_FEED_UNAVAILABLE.into(),
2123 })),
2124 };
2125 result.map(move |result| RemoteActionMessage::ChangesResponse {
2126 correlation,
2127 result,
2128 })
2129}
2130
2131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
2137pub struct RemoteActionFrame {
2138 pub version: u16,
2139 pub message: RemoteActionMessage,
2140 #[serde(default, skip_serializing_if = "Option::is_none")]
2145 pub workspace: Option<String>,
2146 #[serde(default, skip_serializing_if = "Option::is_none")]
2152 pub press: Option<u32>,
2153 #[serde(default, skip_serializing_if = "Option::is_none")]
2157 pub press_at: Option<asked::PressPoint>,
2158}
2159
2160#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
2162pub enum RemoteFrameError {
2163 #[error("remote action frame of {len} bytes exceeds the limit")]
2164 TooLarge { len: usize },
2165 #[error("remote action frame version {version} is not supported")]
2166 UnsupportedVersion { version: u16 },
2167 #[error("malformed remote action frame: {0}")]
2168 Malformed(String),
2169}
2170
2171impl RemoteActionFrame {
2172 #[must_use]
2174 pub const fn new(message: RemoteActionMessage) -> Self {
2175 Self {
2176 version: REMOTE_ACTIONS_VERSION,
2177 message,
2178 workspace: None,
2179 press: None,
2180 press_at: None,
2181 }
2182 }
2183
2184 #[must_use]
2187 pub fn pressed(mut self, press: Option<u32>) -> Self {
2188 self.press = press;
2189 self.press_at = press.and_then(press_points::of);
2190 self
2191 }
2192
2193 #[must_use]
2195 pub fn in_workspace(mut self, workspace: Option<String>) -> Self {
2196 self.workspace = workspace;
2197 self
2198 }
2199
2200 #[must_use]
2203 pub fn workspace(&self) -> Option<&str> {
2204 match &self.message {
2205 RemoteActionMessage::ResourceRead { read, .. } => Some(&read.workspace),
2206 _ => self.workspace.as_deref(),
2207 }
2208 }
2209
2210 pub fn encode(&self) -> Result<Vec<u8>, RemoteFrameError> {
2218 let bytes = serde_json::to_vec(self)
2219 .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
2220 if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
2221 return Err(RemoteFrameError::TooLarge { len: bytes.len() });
2222 }
2223 Ok(bytes)
2224 }
2225
2226 pub fn decode(bytes: &[u8]) -> Result<Self, RemoteFrameError> {
2230 #[derive(Deserialize)]
2231 struct Version {
2232 version: u16,
2233 }
2234 if bytes.len() > MAX_REMOTE_ACTION_FRAME_BYTES {
2235 return Err(RemoteFrameError::TooLarge { len: bytes.len() });
2236 }
2237 let Version { version } = serde_json::from_slice(bytes)
2238 .map_err(|error| RemoteFrameError::Malformed(error.to_string()))?;
2239 if version != REMOTE_ACTIONS_VERSION {
2240 return Err(RemoteFrameError::UnsupportedVersion { version });
2241 }
2242 serde_json::from_slice(bytes)
2243 .map_err(|error| RemoteFrameError::Malformed(error.to_string()))
2244 }
2245}
2246
2247#[cfg(all(feature = "answer-reads", not(tilo_no_js)))]
2250fn read_answered<H: ActionProvider>(
2251 provider: &H,
2252 caller: &Caller,
2253 correlation: u64,
2254 read: ResourceReadRequest,
2255) -> Pending<RemoteActionMessage> {
2256 provider.resource_reads().map_or_else(
2257 || resource_read::unanswered(correlation),
2258 |reads| resource_read::answered_where_it_ends(reads.answer_read(caller, correlation, read)),
2259 )
2260}
2261
2262#[cfg(not(all(feature = "answer-reads", not(tilo_no_js))))]
2265fn read_answered<H: ActionProvider>(
2266 _provider: &H,
2267 _caller: &Caller,
2268 correlation: u64,
2269 _read: ResourceReadRequest,
2270) -> Pending<RemoteActionMessage> {
2271 resource_read::unanswered(correlation)
2272}
2273
2274fn no_call_media_lane() -> ActionCallError {
2276 ActionCallError::Unavailable {
2277 reason: "this connection carries no call media lane".into(),
2278 }
2279}
2280
2281fn no_shell(correlation: u64) -> RemoteActionMessage {
2284 RemoteActionMessage::ShellOpenResponse {
2285 correlation,
2286 result: Err(ActionCallError::Unavailable {
2287 reason: "this connection carries no shell".into(),
2288 }),
2289 }
2290}
2291
2292fn no_presence_lane() -> ActionCallError {
2294 ActionCallError::Unavailable {
2295 reason: "this connection carries no presence lane".into(),
2296 }
2297}
2298
2299fn no_audio_output_lane() -> ActionCallError {
2301 ActionCallError::Unavailable {
2302 reason: "this connection carries no sound output lane".into(),
2303 }
2304}
2305
2306fn no_call_lane() -> ActionCallError {
2308 ActionCallError::Unavailable {
2309 reason: "this connection carries no call lane".into(),
2310 }
2311}
2312
2313pub fn serve<H: ActionProvider + Clone + Send + 'static>(
2325 provider: &H,
2326 caller: &Caller,
2327 message: RemoteActionMessage,
2328) -> Option<Pending<RemoteActionMessage>> {
2329 let abandoned = refuse(
2330 &message,
2331 ActionCallError::Unavailable {
2332 reason: "the provider dropped the request".into(),
2333 },
2334 )?;
2335 if let Some(answer) = unprovided(&message) {
2336 return Some(Pending::ready(answer));
2337 }
2338 let answer = match message {
2339 RemoteActionMessage::CatalogueRequest { correlation, query } => provider
2340 .query(caller, query)
2341 .map(move |result| RemoteActionMessage::CatalogueResponse {
2342 correlation,
2343 result,
2344 }),
2345 RemoteActionMessage::Invoke(request) => {
2346 invoked(provider, caller, request).map(RemoteActionMessage::Receipt)
2347 }
2348 RemoteActionMessage::Observe {
2349 correlation,
2350 invocation,
2351 wait_ms: Some(wait_ms),
2352 seen,
2353 } => settle_with(provider, caller, invocation, seen, wait::deadline(wait_ms))
2354 .map(move |state| updated(correlation, invocation, state)),
2355 RemoteActionMessage::Observe {
2356 correlation,
2357 invocation,
2358 ..
2359 } => Pending::ready(updated(
2360 correlation,
2361 invocation,
2362 provider.observe(caller, &invocation),
2363 )),
2364 RemoteActionMessage::Cancel { invocation } => provider
2365 .cancel(caller, &invocation)
2366 .map(move |result| RemoteActionMessage::CancelResponse { invocation, result }),
2367 RemoteActionMessage::ResourceRead {
2370 correlation, read, ..
2371 } => read_answered(provider, caller, correlation, read),
2372 RemoteActionMessage::ChangesRequest { correlation, after } => {
2373 changed(provider, caller, correlation, after.as_deref())
2374 }
2375 RemoteActionMessage::ChangedRequest { correlation, scope } => {
2376 watch::noticed(provider, caller, correlation, scope)
2377 }
2378 RemoteActionMessage::SurfaceRequest { correlation, app } => {
2379 surfaces::surfaced(provider, correlation, &app)
2380 }
2381 RemoteActionMessage::StoreRequest {
2382 correlation,
2383 command,
2384 kind,
2385 } => store_answered(provider, caller, correlation, (command, kind)),
2386 _ => return None,
2390 };
2391 let (completer, answered) = pending();
2393 answer.then(move |answer| completer.complete(answer.unwrap_or(abandoned)));
2394 Some(answered)
2395}
2396
2397fn unprovided(message: &RemoteActionMessage) -> Option<RemoteActionMessage> {
2402 Some(match *message {
2403 RemoteActionMessage::RetiredFeedbackRequest { .. }
2404 | RemoteActionMessage::ContentPutRequest { .. }
2405 | RemoteActionMessage::ContentGetRequest { .. }
2406 | RemoteActionMessage::ContentLinkRequest { .. } => not_kept(message)?,
2407 RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
2408 confirmation::unanswered(correlation, ActionCallError::confirmation_required())
2409 }
2410 RemoteActionMessage::CallCarryRequest { correlation, .. } => {
2411 RemoteActionMessage::CallCarryResponse {
2412 correlation,
2413 result: Err(no_call_lane()),
2414 }
2415 }
2416 RemoteActionMessage::CallReport { correlation, .. } => {
2417 RemoteActionMessage::CallReportResponse {
2418 correlation,
2419 result: Err(no_call_lane()),
2420 }
2421 }
2422 RemoteActionMessage::AudioOutputRequest { correlation, .. } => {
2423 RemoteActionMessage::AudioOutputResponse {
2424 correlation,
2425 result: Err(no_audio_output_lane()),
2426 }
2427 }
2428 RemoteActionMessage::CallMediaRequest { correlation, .. } => {
2429 RemoteActionMessage::CallMediaResult {
2430 correlation,
2431 result: Err(no_call_media_lane()),
2432 }
2433 }
2434 RemoteActionMessage::PresenceSaid { correlation, .. } => {
2435 RemoteActionMessage::PresenceSaidResult {
2436 correlation,
2437 result: Err(no_presence_lane()),
2438 }
2439 }
2440 RemoteActionMessage::ShellOpenRequest { correlation, .. } => no_shell(correlation),
2441 _ => return None,
2442 })
2443}
2444
2445fn invoked<H: ActionProvider + Clone + Send + 'static>(
2448 provider: &H,
2449 caller: &Caller,
2450 mut request: InvokeRequest,
2451) -> Pending<InvocationReceipt> {
2452 let until = request.wait_ms.take().map(wait::deadline);
2453 let invocation = request.invocation;
2454 let receipt = provider.invoke(caller, request).map(move |result| {
2455 result.unwrap_or_else(|error| InvocationReceipt {
2456 invocation,
2457 status: ReceiptStatus::Rejected { error },
2458 })
2459 });
2460 match until {
2461 Some(until) => wait::settle_receipt(provider, caller, receipt, until),
2462 None => receipt,
2463 }
2464}
2465
2466#[must_use]
2470pub fn refuse(
2471 message: &RemoteActionMessage,
2472 error: ActionCallError,
2473) -> Option<RemoteActionMessage> {
2474 Some(match message {
2475 RemoteActionMessage::RetiredFeedbackRequest { correlation } => {
2476 RemoteActionMessage::RetiredFeedbackResponse {
2477 correlation: *correlation,
2478 }
2479 }
2480 RemoteActionMessage::CatalogueRequest { correlation, .. } => {
2481 RemoteActionMessage::CatalogueResponse {
2482 correlation: *correlation,
2483 result: Err(error),
2484 }
2485 }
2486 RemoteActionMessage::Invoke(request) => RemoteActionMessage::Receipt(InvocationReceipt {
2487 invocation: request.invocation,
2488 status: ReceiptStatus::Rejected { error },
2489 }),
2490 RemoteActionMessage::Observe {
2491 correlation,
2492 invocation,
2493 ..
2494 } => updated(*correlation, *invocation, None),
2495 RemoteActionMessage::Cancel { invocation } => RemoteActionMessage::CancelResponse {
2496 invocation: *invocation,
2497 result: Err(error),
2498 },
2499 RemoteActionMessage::ResourceRead { correlation, .. } => {
2500 RemoteActionMessage::ResourceReading {
2501 correlation: *correlation,
2502 result: Err(error),
2503 }
2504 }
2505 RemoteActionMessage::ConfirmationRequest { correlation, .. } => {
2506 confirmation::unanswered(*correlation, error)
2507 }
2508 RemoteActionMessage::ContentPutRequest { correlation, .. } => {
2509 RemoteActionMessage::ContentPutResponse {
2510 correlation: *correlation,
2511 result: Err(error),
2512 }
2513 }
2514 RemoteActionMessage::ContentGetRequest { correlation, .. } => {
2515 RemoteActionMessage::ContentGetResponse {
2516 correlation: *correlation,
2517 result: Err(error),
2518 }
2519 }
2520 RemoteActionMessage::ContentLinkRequest { correlation, .. } => {
2521 RemoteActionMessage::ContentLinkResponse {
2522 correlation: *correlation,
2523 result: Err(error),
2524 }
2525 }
2526 RemoteActionMessage::ChangesRequest { correlation, .. } => {
2527 RemoteActionMessage::ChangesResponse {
2528 correlation: *correlation,
2529 result: Err(error),
2530 }
2531 }
2532 RemoteActionMessage::ChangedRequest { correlation, .. } => {
2533 RemoteActionMessage::ChangedResponse {
2534 correlation: *correlation,
2535 result: Err(error),
2536 }
2537 }
2538 RemoteActionMessage::SurfaceRequest { correlation, .. } => {
2539 RemoteActionMessage::SurfaceResponse {
2540 correlation: *correlation,
2541 result: Err(error),
2542 }
2543 }
2544 RemoteActionMessage::StoreRequest { correlation, .. } => {
2545 RemoteActionMessage::StoreResponse {
2546 correlation: *correlation,
2547 result: Err(error),
2548 }
2549 }
2550 RemoteActionMessage::PresenceSaid { correlation, .. } => {
2551 RemoteActionMessage::PresenceSaidResult {
2552 correlation: *correlation,
2553 result: Err(error),
2554 }
2555 }
2556 RemoteActionMessage::ShellOpenRequest { correlation, .. } => {
2557 RemoteActionMessage::ShellOpenResponse {
2558 correlation: *correlation,
2559 result: Err(error),
2560 }
2561 }
2562 _ => return None,
2564 })
2565}
2566
2567struct LogEntry<T> {
2568 caller: Caller,
2569 request: InvokeRequest,
2570 handle: Option<T>,
2573}
2574
2575pub struct InvocationLog<T> {
2585 entries: HashMap<InvocationId, LogEntry<T>>,
2586 order: VecDeque<InvocationId>,
2587 capacity: usize,
2588}
2589
2590impl<T> Default for InvocationLog<T> {
2591 fn default() -> Self {
2592 Self::with_capacity(DEFAULT_LOG_CAPACITY)
2593 }
2594}
2595
2596#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2598pub enum Reservation {
2599 Reserved,
2601 Admitted,
2603}
2604
2605#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2607pub enum Admission {
2608 Started,
2609 Retried,
2610}
2611
2612impl<T> InvocationLog<T> {
2613 #[must_use]
2615 pub fn with_capacity(capacity: usize) -> Self {
2616 Self {
2617 entries: HashMap::new(),
2618 order: VecDeque::new(),
2619 capacity: capacity.max(1),
2620 }
2621 }
2622
2623 pub fn admit(
2631 &mut self,
2632 caller: &Caller,
2633 request: &InvokeRequest,
2634 start: impl FnOnce() -> Result<T, ActionCallError>,
2635 ) -> Result<(&T, Admission), ActionCallError> {
2636 let id = request.invocation;
2637 let admission = match self.reserve(caller, request)? {
2638 Reservation::Admitted => Admission::Retried,
2639 Reservation::Reserved => match start() {
2640 Ok(handle) => {
2641 self.complete(&id, handle);
2642 Admission::Started
2643 }
2644 Err(error) => {
2645 self.abandon(&id);
2646 return Err(error);
2647 }
2648 },
2649 };
2650 self.entries
2651 .get(&id)
2652 .and_then(|entry| entry.handle.as_ref())
2653 .map(|handle| (handle, admission))
2654 .ok_or(ActionCallError::UnknownInvocation)
2655 }
2656
2657 pub fn reserve(
2670 &mut self,
2671 caller: &Caller,
2672 request: &InvokeRequest,
2673 ) -> Result<Reservation, ActionCallError> {
2674 let id = request.invocation;
2675 if let Some(entry) = self.entries.get_mut(&id) {
2676 if !caller.continues(&entry.caller) || !entry.request.same_invocation(request) {
2677 return Err(ActionCallError::InvocationConflict);
2678 }
2679 entry.caller.clone_from(caller);
2681 return if entry.handle.is_some() {
2686 Ok(Reservation::Admitted)
2687 } else {
2688 Err(ActionCallError::Unanswered)
2689 };
2690 }
2691 while self.order.len() >= self.capacity {
2692 let oldest_completed = self.order.iter().position(|candidate| {
2693 self.entries
2694 .get(candidate)
2695 .is_some_and(|entry| entry.handle.is_some())
2696 });
2697 let Some(index) = oldest_completed else {
2698 return Err(ActionCallError::Unavailable {
2699 reason: "all invocation slots are still being admitted; retry".into(),
2700 });
2701 };
2702 if let Some(oldest) = self.order.remove(index) {
2703 self.entries.remove(&oldest);
2704 }
2705 }
2706 self.order.push_back(id);
2707 self.entries.insert(
2708 id,
2709 LogEntry {
2710 caller: caller.clone(),
2711 request: InvokeRequest {
2712 wait_ms: None,
2713 appearance: None,
2714 ..request.clone()
2715 },
2716 handle: None,
2717 },
2718 );
2719 Ok(Reservation::Reserved)
2720 }
2721
2722 pub fn readmit(
2729 &mut self,
2730 caller: &Caller,
2731 request: &InvokeRequest,
2732 waits: impl FnOnce(Option<&T>) -> bool,
2733 ) -> bool {
2734 let Some(entry) = self.entries.get_mut(&request.invocation) else {
2735 return false;
2736 };
2737 let again = request.approval().is_some()
2738 && caller.continues(&entry.caller)
2739 && asked::same_call(&entry.request, request)
2740 && waits(entry.handle.as_ref());
2741 if again {
2742 entry.request = InvokeRequest {
2743 wait_ms: None,
2744 appearance: None,
2745 ..request.clone()
2746 };
2747 entry.handle = None;
2748 }
2749 again
2750 }
2751
2752 pub fn complete(&mut self, id: &InvocationId, handle: T) {
2754 if let Some(entry) = self.entries.get_mut(id) {
2755 entry.handle = Some(handle);
2756 }
2757 }
2758
2759 pub fn abandon(&mut self, id: &InvocationId) {
2762 if self
2763 .entries
2764 .get(id)
2765 .is_some_and(|entry| entry.handle.is_none())
2766 {
2767 self.entries.remove(id);
2768 self.order.retain(|candidate| candidate != id);
2769 }
2770 }
2771
2772 #[must_use]
2775 pub fn request_of(&self, id: &InvocationId) -> Option<&InvokeRequest> {
2776 self.entries.get(id).map(|entry| &entry.request)
2777 }
2778
2779 #[must_use]
2782 pub fn get(&self, caller: &Caller, id: &InvocationId) -> Option<&T> {
2783 self.entries
2784 .get(id)
2785 .filter(|entry| caller.follows(&entry.caller))
2786 .and_then(|entry| entry.handle.as_ref())
2787 }
2788
2789 #[must_use]
2792 pub fn admitted(&self, caller: &Caller, id: &InvocationId) -> Option<Option<&T>> {
2793 self.entries
2794 .get(id)
2795 .filter(|entry| caller.follows(&entry.caller))
2796 .map(|entry| entry.handle.as_ref())
2797 }
2798
2799 pub fn get_mut(&mut self, caller: &Caller, id: &InvocationId) -> Option<&mut T> {
2801 self.entries
2802 .get_mut(id)
2803 .filter(|entry| caller.follows(&entry.caller))
2804 .and_then(|entry| entry.handle.as_mut())
2805 }
2806}
2807
2808pub const ACCOUNT_SECRET_ANSWERS: [&str; 3] =
2811 ["cloud-credential", "begin-sign-in", "begin-cloud-sign-in"];
2812
2813#[must_use]
2818pub fn answers_a_secret(action: &str) -> bool {
2819 VAULT_SECRET_ANSWERS.contains(&action) || ACCOUNT_SECRET_ANSWERS.contains(&action)
2820}
2821
2822#[cfg(test)]
2823mod tests {
2824 use std::sync::Mutex;
2825 use std::sync::atomic::{AtomicU32, Ordering};
2826
2827 use super::*;
2828 use crate::{ActionContract, ActionDescriptor, ExecutionLocus, InputSpec, OperationKind};
2829
2830 tilo_test_env::scenario! {
2831 fn a_caller_keeps_its_identity_and_authority;
2832
2833 phase a_bot_is_its_own_member_acting_for_its_installer;
2834 {
2835 let installer = [7u8; 32];
2836 let caller = Caller::bot("6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6", installer, [9u8; 32]);
2837 assert_eq!(
2838 caller.acting().member_id(),
2839 Some(&tilo_action_policy::MemberId::bot(
2840 "6f1c2a8e-3b4d-4c5e-9f60-718293a4b5c6"
2841 ))
2842 );
2843 assert_eq!(
2844 caller.acting().acted_for_person(),
2845 Some(hex::encode(installer).as_str())
2846 );
2847 assert!(caller.acting().is_bot());
2848 assert!(caller.acting().delegated());
2849 }
2850
2851 phase an_app_caller_acts_as_the_person_whose_session_runs_it;
2852 {
2853 let caller = Caller::local_app("so.tilo.example").acting_for("ada");
2854 assert_eq!(caller.acting().person_id(), Some("ada"));
2855 assert_eq!(
2856 caller.acting().app().map(ToString::to_string).as_deref(),
2857 Some("so.tilo.example")
2858 );
2859 assert_eq!(caller.acting_for_person(), Some("ada"));
2860 }
2861
2862 phase execution_lifetime_is_shared_without_changing_caller_identity;
2863 {
2864 let first = Caller::local_person("owner").in_new_execution();
2865 let retained = first.clone();
2866 let second = first.clone().in_new_execution();
2867 let hash = |caller: &Caller| {
2868 let mut hasher = std::collections::hash_map::DefaultHasher::new();
2869 std::hash::Hash::hash(caller, &mut hasher);
2870 std::hash::Hasher::finish(&hasher)
2871 };
2872 let before = hash(&first);
2873 first.retire_execution();
2874 assert!(!retained.execution_is_live());
2875 assert!(second.execution_is_live());
2876 assert_eq!(first, retained);
2877 assert_eq!(hash(&first), before);
2878 let reconnected = retained.in_new_execution();
2879 assert!(reconnected.execution_is_live());
2880 assert_ne!(reconnected.execution_id(), first.execution_id());
2881 }
2882
2883 phase projected_execution_retains_transport_retirement_without_changing_authority;
2884 {
2885 let original = Caller::local_person("projected-person").in_new_execution();
2886 let projected = Caller::authenticated([1; 32], [2; 32])
2887 .in_execution(original.execution_lease().unwrap());
2888 assert_eq!(projected.execution_id(), original.execution_id());
2889 assert_eq!(projected.user_public_key(), Some(&[1; 32]));
2890 assert_eq!(original.user_public_key(), None);
2891 original.retire_execution();
2892 assert!(!projected.execution_is_live());
2893 }
2894 }
2895
2896 fn alice() -> Caller {
2897 Caller::authenticated([1; 32], [2; 32])
2898 }
2899
2900 fn mallory() -> Caller {
2901 Caller::authenticated([9; 32], [8; 32])
2902 }
2903
2904 tilo_test_env::scenario! {
2905 fn an_application_action_names_its_destination;
2906
2907 phase an_application_action_target_names_its_workspace_and_app;
2908 {
2909 let target =
2910 application_action_target("workspace-1", "so.tilo.chat", "chat.workspace", "call");
2911 assert_eq!(
2912 application_provider(&target.provider),
2913 Some(("workspace-1", "so.tilo.chat"))
2914 );
2915 assert_eq!(target.address, ActionAddress::new("chat.workspace", "call"));
2916 for other in [
2917 "7",
2918 "workspace:workspace-1",
2919 "application:workspace-1",
2920 "application::so.tilo.chat",
2921 "application:workspace-1:",
2922 "application:workspace-1:a:",
2923 ] {
2924 assert_eq!(application_provider(other), None, "{other}");
2925 }
2926 assert_eq!(application_provider_resource(&target.provider), None);
2927
2928 let target = application_resource_target(
2929 "workspace-1",
2930 "so.tilo.notes",
2931 "uuid:7",
2932 "notes.page:1",
2933 "open",
2934 );
2935 assert_eq!(
2936 application_provider(&target.provider),
2937 Some(("workspace-1", "so.tilo.notes"))
2938 );
2939 assert_eq!(
2940 application_provider_resource(&target.provider),
2941 Some("uuid:7")
2942 );
2943 assert_eq!(target.address, ActionAddress::new("notes.page:1", "open"));
2944 }
2945 }
2946
2947 fn descriptor(resource: &str, action: &str) -> ActionDescriptor {
2948 ActionDescriptor {
2949 did: None,
2950 state: crate::ActionState::default(),
2951 semantic_identity: None,
2952 address: ActionAddress::new(resource, action),
2953 resource_kind: "notes.note".into(),
2954 resource_label: "Groceries".into(),
2955 action_label: "Archive".into(),
2956 keywords: Vec::new(),
2957 icon: None,
2958 description: Some("Move the note to the archive".into()),
2959 locus: ExecutionLocus::ClientLocal,
2960 kind: OperationKind::Document,
2961 contract: ActionContract::default(),
2962 input: InputSpec::None,
2963 params: Vec::new(),
2964 view: None,
2965 }
2966 }
2967
2968 struct CountingHost {
2971 runs: AtomicU32,
2972 log: Mutex<InvocationLog<Mutex<InvocationUpdate>>>,
2973 }
2974
2975 impl CountingHost {
2976 fn new() -> Self {
2977 Self {
2978 runs: AtomicU32::new(0),
2979 log: Mutex::new(InvocationLog::default()),
2980 }
2981 }
2982
2983 fn runs(&self) -> u32 {
2984 self.runs.load(Ordering::SeqCst)
2985 }
2986
2987 fn finish(&self, caller: &Caller, id: &InvocationId) {
2988 if let Some(update) = self.log.lock().unwrap().get(caller, id) {
2989 *update.lock().unwrap() = InvocationUpdate::Succeeded {
2990 invocation: *id,
2991 output: ActionOutput::default(),
2992 };
2993 }
2994 }
2995 }
2996
2997 impl CountingHost {
2998 fn cancel_now(&self, caller: &Caller, id: &InvocationId) -> Result<(), ActionCallError> {
2999 let log = self.log.lock().unwrap();
3000 let mut update = log
3001 .get(caller, id)
3002 .ok_or(ActionCallError::UnknownInvocation)?
3003 .lock()
3004 .unwrap();
3005 if update.is_terminal() {
3006 return Err(ActionCallError::NotCancellable {
3007 reason: "finished".into(),
3008 });
3009 }
3010 *update = InvocationUpdate::Cancelled {
3011 invocation: *id,
3012 message: None,
3013 };
3014 drop(update);
3015 drop(log);
3016 Ok(())
3017 }
3018 }
3019
3020 impl ActionProvider for CountingHost {
3021 fn query(
3022 &self,
3023 _caller: &Caller,
3024 query: CatalogueQuery,
3025 ) -> Pending<Result<CataloguePage, ActionCallError>> {
3026 Pending::ready(Ok(CataloguePage::from_rows(
3027 "1".into(),
3028 vec![catalogue_row("note:1", "archive")],
3029 &query,
3030 )))
3031 }
3032
3033 fn invoke(
3034 &self,
3035 caller: &Caller,
3036 request: InvokeRequest,
3037 ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
3038 Pending::ready((|| {
3039 if request.target.address != ActionAddress::new("note:1", "archive") {
3040 return Err(ActionCallError::UnknownAction);
3041 }
3042 let update = {
3043 let mut log = self.log.lock().unwrap();
3044 let (update, _) = log.admit(caller, &request, || {
3045 self.runs.fetch_add(1, Ordering::SeqCst);
3046 Ok(Mutex::new(InvocationUpdate::Accepted {
3047 invocation: request.invocation,
3048 }))
3049 })?;
3050 let update = update.lock().unwrap().clone();
3051 drop(log);
3052 update
3053 };
3054 Ok(InvocationState::new(request.invocation, update).receipt())
3055 })())
3056 }
3057
3058 fn observe(&self, caller: &Caller, id: &InvocationId) -> Option<InvocationState> {
3059 self.log
3060 .lock()
3061 .unwrap()
3062 .get(caller, id)
3063 .map(|update| InvocationState::new(*id, update.lock().unwrap().clone()))
3064 }
3065
3066 fn cancel(
3067 &self,
3068 caller: &Caller,
3069 id: &InvocationId,
3070 ) -> Pending<Result<(), ActionCallError>> {
3071 Pending::ready(self.cancel_now(caller, id))
3072 }
3073 }
3074
3075 fn catalogue_row(resource: &str, action: &str) -> CatalogueRow {
3076 CatalogueRow {
3077 offered: None,
3078 provider: "7".into(),
3079 app_id: "notes".into(),
3080 parent_resource: String::new(),
3081 resource: CatalogueResource {
3082 id: resource.into(),
3083 kind: "notes.note".into(),
3084 label: "Groceries".into(),
3085 presentation: None,
3086 },
3087 action: Some(descriptor(resource, action)),
3088 has_children: false,
3089 visibility: None,
3090 surface: None,
3091 }
3092 }
3093
3094 fn now<T>(mut answer: Pending<T>) -> T {
3096 match answer.poll_ready() {
3097 PendingPoll::Ready(value) => value,
3098 PendingPoll::Waiting | PendingPoll::Abandoned => panic!("the provider answers at once"),
3099 }
3100 }
3101
3102 #[derive(Clone)]
3105 struct HugeCatalogue;
3106
3107 const HUGE_CATALOGUE: usize = 12_000;
3108
3109 impl ActionProvider for HugeCatalogue {
3110 fn query(
3111 &self,
3112 _caller: &Caller,
3113 query: CatalogueQuery,
3114 ) -> Pending<Result<CataloguePage, ActionCallError>> {
3115 let rows = (0..HUGE_CATALOGUE)
3116 .map(|n| {
3117 let mut row = catalogue_row(&format!("note:{n}"), &format!("archive-{n}"));
3118 if let Some(action) = row.action.as_mut() {
3119 action.description = Some("Moves the note out of the list. ".repeat(8));
3120 }
3121 row
3122 })
3123 .collect();
3124 Pending::ready(Ok(CataloguePage::from_rows("1".into(), rows, &query)))
3125 }
3126
3127 fn invoke(
3128 &self,
3129 _caller: &Caller,
3130 _request: InvokeRequest,
3131 ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
3132 Pending::ready(Err(ActionCallError::UnknownAction))
3133 }
3134
3135 fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
3136 None
3137 }
3138
3139 fn cancel(
3140 &self,
3141 _caller: &Caller,
3142 _id: &InvocationId,
3143 ) -> Pending<Result<(), ActionCallError>> {
3144 Pending::ready(Err(ActionCallError::UnknownInvocation))
3145 }
3146 }
3147
3148 #[test]
3152 fn the_workspaces_own_app_keeps_one_name() {
3153 assert_eq!(
3154 WORKSPACE_AGENTS_APP, WORKSPACE_GOVERNANCE_PROVIDER,
3155 "a workspace's agents are the workspace's own app's record"
3156 );
3157 assert_eq!(
3158 crate::tree::app_meant("workspace", &[(WORKSPACE_GOVERNANCE_PROVIDER, "Workspace")]),
3159 Ok(Some(WORKSPACE_GOVERNANCE_PROVIDER.to_owned())),
3160 "`workspace` names the workspace's own app"
3161 );
3162 }
3163
3164 #[test]
3169 fn a_catalogue_larger_than_a_frame_travels_in_pages_that_each_fit_one() {
3170 for by_resource in [false, true] {
3171 let mut query = CatalogueQuery {
3172 max_results: u32::MAX,
3173 by_resource,
3174 ..CatalogueQuery::default()
3175 };
3176 let mut listed = Vec::new();
3177 let mut pages = 0usize;
3178 loop {
3179 let asked = RemoteActionMessage::CatalogueRequest {
3180 correlation: 1,
3181 query: query.clone(),
3182 };
3183 let answer =
3184 now(serve(&HugeCatalogue, &alice(), asked).expect("a request is answered"));
3185 let bytes = RemoteActionFrame::new(answer)
3186 .encode()
3187 .expect("every page fits one frame");
3188 assert!(bytes.len() <= MAX_REMOTE_ACTION_FRAME_BYTES);
3189 let RemoteActionMessage::CatalogueResponse {
3190 result: Ok(page), ..
3191 } = RemoteActionFrame::decode(&bytes).unwrap().message
3192 else {
3193 panic!("a catalogue request is answered with its page");
3194 };
3195 pages += 1;
3196 listed.extend(
3197 expand(page.rows)
3198 .into_iter()
3199 .filter_map(|row| row.action.map(|action| action.address.action)),
3200 );
3201 if page.exhausted {
3202 break;
3203 }
3204 query.cursor = page.next_cursor;
3205 query.revision = Some(page.revision);
3206 }
3207 assert!(pages > 1, "the catalogue is larger than one frame");
3208 let expected: Vec<String> = (0..HUGE_CATALOGUE)
3209 .map(|n| format!("archive-{n}"))
3210 .collect();
3211 assert_eq!(listed, expected, "every action is listed once, in order");
3212 }
3213 }
3214
3215 fn archive(invocation: InvocationId) -> InvokeRequest {
3216 InvokeRequest {
3217 on_behalf_of: None,
3218 invocation,
3219 target: RemoteActionTarget {
3220 provider: "7".into(),
3221 address: ActionAddress::new("note:1", "archive"),
3222 },
3223 argument: InvokeArgument::None,
3224 context: None,
3225 confirmation: None,
3226 revision: None,
3227 wait_ms: None,
3228 appearance: None,
3229 signed: None,
3230 }
3231 }
3232
3233 fn round_trip(message: RemoteActionMessage) -> RemoteActionMessage {
3234 let bytes = RemoteActionFrame::new(message).encode().unwrap();
3235 RemoteActionFrame::decode(&bytes).unwrap().message
3236 }
3237
3238 fn request_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
3240 let mut arguments = serde_json::Map::new();
3241 arguments.insert("title".into(), serde_json::json!("Weekly"));
3242 vec![
3243 RemoteActionMessage::CatalogueRequest {
3244 correlation: 3,
3245 query: CatalogueQuery::default(),
3246 },
3247 RemoteActionMessage::CatalogueRequest {
3248 correlation: 5,
3249 query: CatalogueQuery {
3250 provider: Some("7".into()),
3251 parent_resource: Some("folder:a".into()),
3252 needle: "gro".into(),
3253 cursor: vec![1, 2],
3254 revision: Some("r1".into()),
3255 max_results: 8,
3256 limits: Some(CatalogueLimits {
3257 max_bytes: Some(4096),
3258 max_work: None,
3259 max_depth: Some(1),
3260 }),
3261 ..CatalogueQuery::default()
3262 },
3263 },
3264 RemoteActionMessage::CatalogueResponse {
3265 correlation: 3,
3266 result: now(CountingHost::new().query(&alice(), CatalogueQuery::default())),
3267 },
3268 RemoteActionMessage::CatalogueResponse {
3269 correlation: 4,
3270 result: Err(ActionCallError::Unavailable {
3271 reason: "no apps".into(),
3272 }),
3273 },
3274 RemoteActionMessage::Invoke(InvokeRequest {
3275 on_behalf_of: None,
3276 argument: InvokeArgument::Json(arguments),
3277 context: Some(ActionContext::for_resource(
3278 "note:1",
3279 "notes.note",
3280 "Groceries",
3281 )),
3282 ..archive(invocation)
3283 }),
3284 RemoteActionMessage::Invoke(InvokeRequest {
3285 on_behalf_of: None,
3286 argument: InvokeArgument::Text("hello".into()),
3287 ..archive(invocation)
3288 }),
3289 RemoteActionMessage::Invoke(InvokeRequest {
3290 on_behalf_of: None,
3291 confirmation: Some(Confirmation::Phrase("delete it".into())),
3292 ..archive(invocation)
3293 }),
3294 RemoteActionMessage::Invoke(InvokeRequest {
3295 wait_ms: Some(2_000),
3296 appearance: None,
3297 ..archive(invocation)
3298 }),
3299 ]
3300 }
3301
3302 fn outcome_messages(invocation: InvocationId) -> Vec<RemoteActionMessage> {
3304 vec![
3305 RemoteActionMessage::Receipt(InvocationReceipt {
3306 invocation,
3307 status: ReceiptStatus::Completed {
3308 output: ActionOutput {
3309 value: Some(serde_json::json!({"archived": true})),
3310 resources: vec!["notes.note:1".into()],
3311 },
3312 },
3313 }),
3314 RemoteActionMessage::Receipt(InvocationReceipt {
3315 invocation,
3316 status: ReceiptStatus::Failed {
3317 error: ActionFailure {
3318 code: "disk_full".into(),
3319 message: "no space".into(),
3320 details: None,
3321 retryable: true,
3322 },
3323 },
3324 }),
3325 RemoteActionMessage::Receipt(InvocationReceipt {
3326 invocation,
3327 status: ReceiptStatus::Rejected {
3328 error: ActionCallError::InvocationConflict,
3329 },
3330 }),
3331 RemoteActionMessage::Receipt(InvocationReceipt {
3332 invocation,
3333 status: ReceiptStatus::Cancelled {
3334 message: Some("stopped".into()),
3335 },
3336 }),
3337 RemoteActionMessage::observe(invocation),
3338 RemoteActionMessage::Observe {
3339 correlation: 7,
3340 invocation,
3341 wait_ms: Some(10_000),
3342 seen: Some(UpdateMark::Progress { sequence: 2 }),
3343 },
3344 RemoteActionMessage::Update {
3345 invocation,
3346 state: Some(InvocationState::new(
3347 invocation,
3348 InvocationUpdate::Progress {
3349 invocation,
3350 sequence: 2,
3351 phase: "copying".into(),
3352 completed: Some(1),
3353 total: Some(4),
3354 message: None,
3355 },
3356 )),
3357 correlation: Some(7),
3358 },
3359 RemoteActionMessage::Update {
3360 invocation,
3361 state: None,
3362 correlation: Some(7),
3363 },
3364 RemoteActionMessage::Cancel { invocation },
3365 RemoteActionMessage::CancelResponse {
3366 invocation,
3367 result: Err(ActionCallError::NotCancellable {
3368 reason: "finished".into(),
3369 }),
3370 },
3371 ]
3372 }
3373
3374 tilo_test_env::scenario! {
3375 fn remote_messages_and_failures_read_back_typed;
3376
3377 phase a_stale_revision_is_typed_and_travels_as_older_peers_read_it;
3378 {
3382 let encoded = serde_json::to_value(ActionCallError::StaleRevision).unwrap();
3383 assert_eq!(
3384 encoded,
3385 serde_json::json!({"InvalidRequest": {"reason": STALE_REVISION_REASON}})
3386 );
3387 assert_eq!(
3388 serde_json::from_value::<ActionCallError>(encoded).unwrap(),
3389 ActionCallError::StaleRevision
3390 );
3391 assert_eq!(ActionCallError::StaleRevision.code(), "stale_revision");
3392 let other = ActionCallError::Refused {
3395 reason: "the call changed since that revision, honestly".into(),
3396 };
3397 let round_trip: ActionCallError =
3398 serde_json::from_value(serde_json::to_value(&other).unwrap()).unwrap();
3399 assert_eq!(round_trip, other);
3400 let needs = ActionCallError::InvalidRequest {
3401 reason: CONFIRMED_ACTION_NEEDS_REVISION.into(),
3402 };
3403 assert!(needs.needs_revision());
3404 assert!(!ActionCallError::StaleRevision.needs_revision());
3405 }
3406
3407 phase a_failure_with_details_round_trips;
3408 {
3410 let update = InvocationUpdate::Failed {
3411 invocation: InvocationId::new(),
3412 error: ActionFailure {
3413 code: "invalid_arguments".into(),
3414 message: "argument `pageSize` must be at most 64".into(),
3415 details: Some(serde_json::json!({
3416 "param": "pageSize",
3417 "violation": {"kind": "maximum", "bound": 64}
3418 })),
3419 retryable: false,
3420 },
3421 };
3422 let encoded = serde_json::to_string(&update).unwrap();
3423 assert_eq!(
3424 serde_json::from_str::<InvocationUpdate>(&encoded).unwrap(),
3425 update
3426 );
3427 }
3428
3429 phase a_refusal_for_want_of_the_person_carries_what_they_are_shown;
3430 {
3434 let facts = asked::AskedFacts::default()
3435 .with_fact("kind", "submit")
3436 .with_fact("destination", "https://visa.example")
3437 .with_fact("picture", "tilo.content:5f2b");
3438 let invocation = InvocationId::new();
3439 let state = InvocationState::new(
3440 invocation,
3441 InvocationUpdate::Failed {
3442 invocation,
3443 error: ActionFailure {
3444 code: CONFIRMATION_REQUIRED_CODE.into(),
3445 message: "the person has to allow this".into(),
3446 details: Some(facts.to_details()),
3447 retryable: false,
3448 },
3449 },
3450 );
3451 let receipt = state.receipt();
3452 let ReceiptStatus::Rejected {
3453 error: ActionCallError::ConfirmationRequired(stated),
3454 } = &receipt.status
3455 else {
3456 panic!("a run waiting on the person is a refusal: {receipt:?}");
3457 };
3458 assert_eq!(**stated, facts);
3459 let error = ActionCallError::asks(facts);
3462 let wire = serde_json::to_value(&error).unwrap();
3463 assert_eq!(
3464 serde_json::from_value::<ActionCallError>(wire).unwrap(),
3465 error
3466 );
3467 let wire = postcard::to_allocvec(&error).unwrap();
3468 assert_eq!(postcard::from_bytes::<ActionCallError>(&wire).unwrap(), error);
3469 }
3470
3471 phase the_remote_wire_is_versioned_and_explicit;
3472 {
3476 every_message_round_trips_through_a_frame();
3477 frames_from_another_version_are_refused_not_misread();
3478 the_wire_names_versions_and_messages_explicitly();
3479 }
3480 }
3481
3482 fn every_message_round_trips_through_a_frame() {
3483 let invocation = InvocationId(uuid::Uuid::from_u128(7));
3484 let messages = request_messages(invocation)
3485 .into_iter()
3486 .chain(outcome_messages(invocation));
3487 for message in messages {
3488 assert_eq!(round_trip(message.clone()), message);
3489 }
3490 }
3491
3492 fn frames_from_another_version_are_refused_not_misread() {
3493 let mut frame = serde_json::to_value(RemoteActionFrame::new(
3494 RemoteActionMessage::CatalogueRequest {
3495 correlation: 1,
3496 query: CatalogueQuery::default(),
3497 },
3498 ))
3499 .unwrap();
3500 frame["version"] = serde_json::json!(REMOTE_ACTIONS_VERSION + 1);
3501 frame["message"] = serde_json::json!({"Subscribe": {"topic": 1}});
3503 let bytes = serde_json::to_vec(&frame).unwrap();
3504 assert_eq!(
3505 RemoteActionFrame::decode(&bytes),
3506 Err(RemoteFrameError::UnsupportedVersion {
3507 version: REMOTE_ACTIONS_VERSION + 1
3508 })
3509 );
3510 assert!(matches!(
3511 RemoteActionFrame::decode(
3512 format!(r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Subscribe":{{}}}}}}"#)
3513 .as_bytes()
3514 ),
3515 Err(RemoteFrameError::Malformed(_))
3516 ));
3517 assert!(matches!(
3518 RemoteActionFrame::decode(&vec![b' '; MAX_REMOTE_ACTION_FRAME_BYTES + 1]),
3519 Err(RemoteFrameError::TooLarge { .. })
3520 ));
3521 }
3522
3523 fn the_wire_names_versions_and_messages_explicitly() {
3524 let bytes = RemoteActionFrame::new(RemoteActionMessage::Cancel {
3525 invocation: InvocationId(uuid::Uuid::nil()),
3526 })
3527 .encode()
3528 .unwrap();
3529 assert_eq!(
3530 String::from_utf8(bytes).unwrap(),
3531 format!(
3532 r#"{{"version":{REMOTE_ACTIONS_VERSION},"message":{{"Cancel":{{"invocation":"00000000-0000-0000-0000-000000000000"}}}}}}"#
3533 )
3534 );
3535 }
3536
3537 fn a_retried_invocation_reports_the_original_and_runs_once() {
3538 let provider = CountingHost::new();
3539 let id = InvocationId::new();
3540 let first = now(provider.invoke(&alice(), archive(id))).unwrap();
3541 assert_eq!(first.status, ReceiptStatus::Accepted);
3542 let retry = now(provider.invoke(&alice(), archive(id))).unwrap();
3543 assert_eq!(retry, first);
3544 assert_eq!(provider.runs(), 1, "a retry never starts a second run");
3545
3546 provider.finish(&alice(), &id);
3547 let after = now(provider.invoke(&alice(), archive(id))).unwrap();
3548 assert!(matches!(after.status, ReceiptStatus::Completed { .. }));
3549 assert_eq!(provider.runs(), 1, "a retry after completion reports it");
3550 }
3551
3552 fn an_invocation_id_cannot_be_reused_or_borrowed() {
3553 let provider = CountingHost::new();
3554 let id = InvocationId::new();
3555 now(provider.invoke(&alice(), archive(id))).unwrap();
3556
3557 let mut different = archive(id);
3558 different.argument = InvokeArgument::Text("other".into());
3559 assert_eq!(
3560 now(provider.invoke(&alice(), different)),
3561 Err(ActionCallError::InvocationConflict)
3562 );
3563 assert_eq!(
3564 now(provider.invoke(&mallory(), archive(id))),
3565 Err(ActionCallError::InvocationConflict),
3566 "another actor cannot attach to someone else's invocation"
3567 );
3568 assert_eq!(provider.observe(&mallory(), &id), None);
3569 assert_eq!(
3570 now(provider.cancel(&mallory(), &id)),
3571 Err(ActionCallError::UnknownInvocation)
3572 );
3573 assert_eq!(provider.runs(), 1);
3574 }
3575
3576 fn a_refused_invocation_is_not_remembered() {
3577 let mut log = InvocationLog::<u32>::default();
3578 let request = archive(InvocationId::new());
3579 assert_eq!(
3580 log.admit(&alice(), &request, || Err(ActionCallError::NotPermitted)),
3581 Err(ActionCallError::NotPermitted)
3582 );
3583 let (handle, admission) = log.admit(&alice(), &request, || Ok(5)).unwrap();
3584 assert_eq!((*handle, admission), (5, Admission::Started));
3585 }
3586
3587 fn the_log_forgets_oldest_invocations_past_capacity() {
3588 let mut log = InvocationLog::<u32>::with_capacity(2);
3589 let requests: Vec<_> = (0..3).map(|_| archive(InvocationId::new())).collect();
3590 for (n, request) in (0u32..).zip(&requests) {
3591 log.admit(&alice(), request, || Ok(n)).unwrap();
3592 }
3593 assert_eq!(log.get(&alice(), &requests[0].invocation), None);
3594 assert_eq!(log.get(&alice(), &requests[2].invocation), Some(&2));
3595 }
3596
3597 fn serve_answers_requests_and_ignores_responses() {
3598 let provider = std::sync::Arc::new(CountingHost::new());
3599 let id = InvocationId::new();
3600 let Some(RemoteActionMessage::Receipt(receipt)) = serve(
3601 &provider,
3602 &alice(),
3603 RemoteActionMessage::Invoke(archive(id)),
3604 )
3605 .map(now) else {
3606 panic!("an invoke is answered with a receipt");
3607 };
3608 assert_eq!(receipt.status, ReceiptStatus::Accepted);
3609
3610 let mut unknown = archive(InvocationId::new());
3611 unknown.target.address = ActionAddress::new("note:2", "delete");
3612 assert_eq!(
3613 serve(
3614 &provider,
3615 &alice(),
3616 RemoteActionMessage::Invoke(unknown.clone())
3617 )
3618 .map(now),
3619 Some(RemoteActionMessage::Receipt(InvocationReceipt {
3620 invocation: unknown.invocation,
3621 status: ReceiptStatus::Rejected {
3622 error: ActionCallError::UnknownAction
3623 },
3624 }))
3625 );
3626 assert_eq!(
3627 serve(
3628 &provider,
3629 &alice(),
3630 RemoteActionMessage::Cancel { invocation: id }
3631 )
3632 .map(now),
3633 Some(RemoteActionMessage::CancelResponse {
3634 invocation: id,
3635 result: Ok(()),
3636 })
3637 );
3638 let Some(RemoteActionMessage::Update {
3639 state: Some(state), ..
3640 }) = serve(&provider, &alice(), RemoteActionMessage::observe(id)).map(now)
3641 else {
3642 panic!("an observe is answered with the invocation state");
3643 };
3644 assert!(matches!(
3645 state.receipt().status,
3646 ReceiptStatus::Cancelled { .. }
3647 ));
3648 assert!(serve(&provider, &alice(), RemoteActionMessage::Receipt(receipt)).is_none());
3649 }
3650
3651 fn typed_arguments_use_the_local_invocation_slot() {
3652 let mut object = serde_json::Map::new();
3653 object.insert("n".into(), serde_json::json!(2));
3654 assert_eq!(InvokeArgument::None.to_slot(), None);
3655 assert_eq!(
3656 InvokeArgument::Text("hi".into()).to_slot().as_deref(),
3657 Some("hi")
3658 );
3659 assert_eq!(
3660 InvokeArgument::Json(object.clone()).to_slot(),
3661 Some(format!("{ARGUMENTS_JSON_PREFIX}{{\"n\":2}}"))
3662 );
3663 for argument in [
3666 InvokeArgument::None,
3667 InvokeArgument::Text("hi".into()),
3668 InvokeArgument::Json(object),
3669 ] {
3670 assert_eq!(
3671 InvokeArgument::from_slot(argument.to_slot().as_deref()),
3672 argument
3673 );
3674 }
3675 }
3676
3677 fn a_remote_device_is_the_person_its_root_names() {
3678 let caller = Caller::authenticated([0xAB; 32], [1; 32]);
3679 assert_eq!(
3680 caller.acting().member_id(),
3681 Some(&tilo_action_policy::MemberId::person("ab".repeat(32))),
3682 "every device of one person is the same member"
3683 );
3684 assert_eq!(caller.workspace(), None);
3685 let agent = Caller::local_agent("helper", "ada").in_workspace("workspace-1");
3686 assert_eq!(
3687 agent.acting().member_id(),
3688 Some(&tilo_action_policy::MemberId::agent("helper", "ada"))
3689 );
3690 assert_eq!(agent.workspace(), Some("workspace-1"));
3691 assert_eq!(agent.device_public_key(), None);
3692 }
3693
3694 fn a_refusal_answers_every_request_and_nothing_else() {
3695 let error = ActionCallError::Unavailable {
3696 reason: "down".into(),
3697 };
3698 let id = InvocationId::new();
3699 assert_eq!(
3700 refuse(&invoke_message(id), error.clone()),
3701 Some(RemoteActionMessage::Receipt(InvocationReceipt {
3702 invocation: id,
3703 status: ReceiptStatus::Rejected {
3704 error: error.clone()
3705 },
3706 }))
3707 );
3708 assert_eq!(
3709 refuse(&RemoteActionMessage::observe(id), error.clone()),
3710 Some(RemoteActionMessage::Update {
3711 invocation: id,
3712 state: None,
3713 correlation: Some(0),
3714 })
3715 );
3716 assert_eq!(
3717 refuse(
3718 &RemoteActionMessage::Update {
3719 invocation: id,
3720 state: None,
3721 correlation: None,
3722 },
3723 error
3724 ),
3725 None
3726 );
3727 }
3728
3729 fn invoke_message(id: InvocationId) -> RemoteActionMessage {
3730 RemoteActionMessage::Invoke(archive(id))
3731 }
3732
3733 mod change_wire;
3735
3736 tilo_test_env::scenario! {
3737 fn a_host_serves_each_invocation_once_as_its_caller;
3738
3739 phase a_retry_with_another_appearance_is_another_invocation;
3740 {
3741 let request = archive(InvocationId(uuid::Uuid::from_u128(9)));
3742 let appearing = InvokeRequest {
3743 appearance: Some(crate::Appearance::new("alice", None, None).unwrap()),
3744 ..request.clone()
3745 };
3746 assert!(!request.same_invocation(&appearing));
3747 assert!(appearing.same_invocation(&InvokeRequest {
3748 wait_ms: Some(10),
3749 ..appearing.clone()
3750 }));
3751 let json = serde_json::to_string(&request).unwrap();
3752 assert!(!json.contains("appearance"), "{json}");
3753 }
3754
3755 phase remote_invocations_run_at_most_once_per_owned_id;
3756 {
3761 a_retried_invocation_reports_the_original_and_runs_once();
3762 an_invocation_id_cannot_be_reused_or_borrowed();
3763 a_refused_invocation_is_not_remembered();
3764 the_log_forgets_oldest_invocations_past_capacity();
3765 a_reservation_holds_the_id_until_the_start_completes();
3766 }
3767
3768 phase admitted_executions_share_authority_but_cannot_borrow_invocations;
3769 {
3770 let first = alice().in_new_execution();
3771 let second = alice().in_new_execution();
3772 assert_eq!(first.acting(), second.acting());
3773 assert_eq!(first.workspace(), second.workspace());
3774 assert_ne!(first.execution_id(), second.execution_id());
3775 let provider = CountingHost::new();
3776 let id = InvocationId::new();
3777 let admitted = now(provider.invoke(&first, archive(id))).unwrap();
3778 assert_eq!(now(provider.invoke(&first, archive(id))).unwrap(), admitted);
3779 assert_eq!(
3780 now(provider.invoke(&second, archive(id))),
3781 Err(ActionCallError::InvocationConflict)
3782 );
3783 assert_eq!(provider.observe(&second, &id), None);
3784 assert_eq!(
3785 now(provider.cancel(&second, &id)),
3786 Err(ActionCallError::UnknownInvocation)
3787 );
3788 let retained = first.clone();
3789 let hash = |caller: &Caller| {
3790 let mut hasher = std::collections::hash_map::DefaultHasher::new();
3791 std::hash::Hash::hash(caller, &mut hasher);
3792 std::hash::Hasher::finish(&hasher)
3793 };
3794 let before = hash(&first);
3795 provider.retire_execution(&first);
3796 assert!(!retained.execution_is_live());
3797 assert!(second.execution_is_live());
3798 assert_eq!(first, retained);
3799 assert_eq!(hash(&first), before);
3800 let reconnected = retained.in_new_execution();
3801 assert!(reconnected.execution_is_live());
3802 assert_ne!(reconnected.execution_id(), first.execution_id());
3803 provider.finish(&first, &id);
3804 assert!(matches!(
3805 now(provider.invoke(&first, archive(id))).unwrap().status,
3806 ReceiptStatus::Completed { .. }
3807 ));
3808 assert!(provider.observe(&first, &id).is_some());
3809 assert!(provider.observe(&second, &id).is_none());
3810 assert!(reconnected.continues(&first));
3814 assert!(!second.continues(&first));
3815 assert!(provider.observe(&reconnected, &id).is_some());
3816 assert!(matches!(
3817 now(provider.invoke(&reconnected, archive(id))).unwrap().status,
3818 ReceiptStatus::Completed { .. }
3819 ));
3820 assert_eq!(provider.runs(), 1);
3821 let someone_else = Caller::authenticated([3; 32], [4; 32]).in_new_execution();
3822 assert!(!someone_else.continues(&first), "another device continues nothing");
3823 }
3824
3825 phase serving_answers_each_request_as_the_person_the_device_belongs_to;
3826 {
3831 serve_answers_requests_and_ignores_responses();
3832 typed_arguments_use_the_local_invocation_slot();
3833 a_remote_device_is_the_person_its_root_names();
3834 a_refusal_answers_every_request_and_nothing_else();
3835 }
3836
3837 phase capacity_churn_preserves_in_flight_deduplication;
3838 {
3839 let caller = alice();
3840 let mut log = InvocationLog::<u32>::with_capacity(3);
3841 let pending = archive(InvocationId::new());
3842 assert_eq!(log.reserve(&caller, &pending), Ok(Reservation::Reserved));
3843 let mut completed = VecDeque::new();
3844 for n in 0..8 {
3845 let request = archive(InvocationId::new());
3846 assert_eq!(
3847 log.admit(&caller, &request, || Ok(n)),
3848 Ok((&n, Admission::Started))
3849 );
3850 completed.push_back(request.invocation);
3851 if completed.len() > 2 {
3852 let evicted = completed.pop_front().unwrap();
3853 assert_eq!(log.get(&caller, &evicted), None);
3854 }
3855 for id in &completed {
3856 assert!(log.get(&caller, id).is_some());
3857 }
3858 assert!(matches!(
3859 log.admit(&caller, &pending, || panic!("duplicate dispatch")),
3860 Err(ActionCallError::Unanswered)
3861 ));
3862 assert_eq!(
3863 log.reserve(&mallory(), &pending),
3864 Err(ActionCallError::InvocationConflict)
3865 );
3866 }
3867 log.complete(&pending.invocation, 99);
3868 assert_eq!(
3869 log.admit(&caller, &pending, || panic!("duplicate dispatch")),
3870 Ok((&99, Admission::Retried))
3871 );
3872 let next = archive(InvocationId::new());
3873 assert_eq!(log.reserve(&caller, &next), Ok(Reservation::Reserved));
3874 assert_eq!(log.get(&caller, &pending.invocation), None);
3875 }
3876
3877 phase capacity_churn_refuses_new_ids_when_every_slot_is_reserved;
3878 {
3879 let caller = alice();
3880 for capacity in 0..=2 {
3882 let mut log = InvocationLog::<u32>::with_capacity(capacity);
3883 let pending: Vec<_> = (0..capacity.max(1))
3884 .map(|_| archive(InvocationId::new()))
3885 .collect();
3886 for request in &pending {
3887 assert_eq!(log.reserve(&caller, request), Ok(Reservation::Reserved));
3888 }
3889 let refused = archive(InvocationId::new());
3890 for _ in 0..4 {
3891 assert!(matches!(
3892 log.admit(&caller, &refused, || panic!("dispatch at capacity")),
3893 Err(ActionCallError::Unavailable { .. })
3894 ));
3895 for request in &pending {
3896 assert!(matches!(
3897 log.admit(&caller, request, || panic!("duplicate dispatch")),
3898 Err(ActionCallError::Unanswered)
3899 ));
3900 }
3901 }
3902 for (n, request) in pending.iter().enumerate() {
3903 let n = u32::try_from(n).unwrap();
3904 log.complete(&request.invocation, n);
3905 assert_eq!(
3906 log.admit(&caller, request, || panic!("duplicate dispatch")),
3907 Ok((&n, Admission::Retried))
3908 );
3909 }
3910 assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
3912 log.abandon(&refused.invocation);
3913 assert_eq!(log.reserve(&caller, &refused), Ok(Reservation::Reserved));
3914 }
3915 }
3916 }
3917
3918 fn a_reservation_holds_the_id_until_the_start_completes() {
3919 let mut log = InvocationLog::<u32>::default();
3920 let request = archive(InvocationId::new());
3921 assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Reserved));
3922 assert!(
3923 matches!(
3924 log.reserve(&alice(), &request),
3925 Err(ActionCallError::Unanswered)
3926 ),
3927 "a retry during the start neither runs twice nor pretends to be admitted: it is \
3928 asked again, as an answer lost on its way is"
3929 );
3930 assert_eq!(log.get(&alice(), &request.invocation), None);
3931 log.complete(&request.invocation, 9);
3932 assert_eq!(log.reserve(&alice(), &request), Ok(Reservation::Admitted));
3933 assert_eq!(log.get(&alice(), &request.invocation), Some(&9));
3934
3935 let failed = archive(InvocationId::new());
3936 assert_eq!(log.reserve(&alice(), &failed), Ok(Reservation::Reserved));
3937 log.abandon(&failed.invocation);
3938 assert_eq!(
3939 log.reserve(&alice(), &failed),
3940 Ok(Reservation::Reserved),
3941 "an abandoned start ran nothing and may be admitted again"
3942 );
3943 }
3944
3945 #[test]
3946 fn action_call_error_constructors_build_the_exact_variants() {
3947 let refused = ActionCallError::refused("not allowed now");
3948 assert_eq!(
3949 refused,
3950 ActionCallError::Refused {
3951 reason: "not allowed now".to_owned(),
3952 }
3953 );
3954 assert_eq!(refused.code(), "refused");
3955 assert_eq!(refused.said(), "refused: not allowed now");
3956 let owned_refusal = String::from("not allowed now");
3957 assert_eq!(ActionCallError::refused(owned_refusal), refused);
3958
3959 let invalid = ActionCallError::invalid_request("missing field");
3960 assert_eq!(
3961 invalid,
3962 ActionCallError::InvalidRequest {
3963 reason: "missing field".to_owned(),
3964 }
3965 );
3966 assert_eq!(invalid.code(), "invalid_arguments");
3967 assert_eq!(invalid.said(), "invalid_arguments: missing field");
3968 let owned_invalid = String::from("missing field");
3969 assert_eq!(ActionCallError::invalid_request(owned_invalid), invalid);
3970
3971 let unavailable = ActionCallError::unavailable("service off");
3972 assert_eq!(
3973 unavailable,
3974 ActionCallError::Unavailable {
3975 reason: "service off".to_owned(),
3976 }
3977 );
3978 assert_eq!(unavailable.code(), "remote_actions_unavailable");
3979 assert_eq!(unavailable.said(), "unavailable: service off");
3980 let owned_unavailable = String::from("service off");
3981 assert_eq!(ActionCallError::unavailable(owned_unavailable), unavailable);
3982 }
3983}