tilo_actions/remote/admitted.rs
1//! What a device's dispatch hands a provider registered on it for a call it already admitted,
2//! beyond the call itself ([`ActionProvider::run`](super::ActionProvider::run)), and the live
3//! result such a provider may serve ([`ActionProvider::watch`](super::ActionProvider::watch)).
4//!
5//! The dispatch decides the caller's grant, asks the person where the action's contract says so,
6//! and keeps the invocation's record; the provider only carries the call out. Most providers need
7//! nothing beyond the call. A provider whose call makes calls of its own (an agent session's
8//! programs) makes them through [`Admitted::through`], so its session admits each in turn; one
9//! whose contract says it may be cancelled stops when [`Admitted::stop`] is set. A call an app
10//! makes as the work of an invocation it was delivered names that invocation
11//! ([`Admitted::serving`]), as the connection the call arrived on was delivered it, and a call
12//! that runs a while says how far it got ([`Admitted::progress`]).
13
14use std::sync::Arc;
15use std::sync::atomic::AtomicBool;
16
17use super::{
18 ActionCallError, ActionProvider, Caller, CataloguePage, CatalogueQuery, CatalogueRow,
19 InvocationReceipt, InvocationState, InvokeRequest, Pending, ReceiptStatus,
20};
21use crate::api::{ActionDescriptor, PlacedAction};
22use crate::{
23 ActionAddress, ActionContract, ActionFailure, ActionOutput, InvocationId, OperationKind,
24 ResourceSemanticIdentity,
25};
26
27/// How a call a registered provider carried out ended: its output, or why it failed.
28pub type Outcome = Result<ActionOutput, Box<ActionFailure>>;
29
30/// Says how far a call got, for whoever follows it: a phase, and how much of how much is done.
31pub type ReportsProgress = Arc<dyn Fn(&str, Option<u64>, Option<u64>) + Send + Sync>;
32
33/// What the dispatch knows of a call it admitted for a provider registered on the device.
34#[derive(Clone)]
35pub struct Admitted {
36 /// The provider the call's own further calls go through: an agent session's, when the call is
37 /// one of its programs, so the session admits what the program does as it admits the agent.
38 pub through: Option<Arc<dyn ActionProvider + Send + Sync>>,
39 /// Set when the caller cancels a call whose contract says it may be
40 /// ([`crate::ExecutionMode::cancellable`]): the provider stops, and the call ends cancelled.
41 pub stop: Arc<AtomicBool>,
42 /// The invocation the call is the work of, when an app makes it for one it was delivered
43 /// on the connection the call arrived on: filled by the dispatch from that connection, never
44 /// from the request.
45 pub serving: Option<Arc<dyn Serving>>,
46 /// How far the call got, for whoever follows it: a phase, and how much of how much is done.
47 pub progress: ReportsProgress,
48}
49
50impl Default for Admitted {
51 fn default() -> Self {
52 Self {
53 through: None,
54 stop: Arc::new(AtomicBool::new(false)),
55 serving: None,
56 progress: Arc::new(|_, _, _| {}),
57 }
58 }
59}
60
61/// An invocation the dispatch delivered to an app's connection and still runs, as a call that
62/// connection makes for it reaches a provider: the app, record and resource it was asked of and
63/// what it was asked, all as the dispatch delivered it.
64pub trait Serving: Send + Sync {
65 /// Its id.
66 fn invocation(&self) -> InvocationId;
67 /// The app it was delivered to, by package id.
68 fn app(&self) -> &str;
69 /// The workspace of its record.
70 fn workspace(&self) -> &str;
71 /// The record whose resource it is an action of.
72 fn record(&self) -> &str;
73 /// The resource and action it was asked of.
74 fn address(&self) -> &ActionAddress;
75 /// What the action declared it is.
76 fn kind(&self) -> OperationKind;
77 /// The contract the action was published with.
78 fn contract(&self) -> &ActionContract;
79 /// What it was asked with, as delivered.
80 fn argument(&self) -> Option<&str>;
81 /// The identity the resource was published with.
82 ///
83 /// # Errors
84 ///
85 /// The resource was published with none.
86 fn resource_identity(&self) -> Result<&ResourceSemanticIdentity, String>;
87 /// Whether it still runs as delivered: its caller still may, its app still holds it, the
88 /// resource is still published as it was, and nobody cancelled it.
89 ///
90 /// # Errors
91 ///
92 /// What no longer holds.
93 fn recheck(&self) -> Result<(), String>;
94}
95
96/// A provider that only the device's dispatch calls, once it admitted the call: what it offers,
97/// and how it carries a call out. The rest of [`ActionProvider`] follows from these: a call ends in
98/// its receipt, so there is no invocation left to observe or cancel once it answers.
99pub trait Admits {
100 /// The provider id its rows name.
101 const PROVIDER: &'static str;
102 /// The application its rows are offered for, whose grants decide them.
103 const APP: &'static str;
104
105 /// The actions it offers.
106 fn rows(&self) -> Vec<PlacedAction>;
107
108 /// Start `request`, which the dispatch admitted for `caller`.
109 ///
110 /// # Errors
111 ///
112 /// Why the call is refused before it starts.
113 fn start(
114 &self,
115 caller: &Caller,
116 request: &InvokeRequest,
117 admitted: &Admitted,
118 ) -> Result<Pending<Outcome>, String>;
119
120 /// Whether a call nobody approved yet waits for its person's yes, found by looking at the
121 /// call itself ([`ActionProvider::asks_first`]).
122 fn asks_first(
123 &self,
124 caller: &Caller,
125 request: &InvokeRequest,
126 admitted: &Admitted,
127 ) -> Option<Pending<Result<(), ActionCallError>>> {
128 let _ = (caller, request, admitted);
129 None
130 }
131
132 /// The action `address` is with `argument`, where it differs from its row
133 /// ([`ActionProvider::invocation`]).
134 fn described(
135 &self,
136 address: &ActionAddress,
137 argument: Option<&str>,
138 ) -> Option<ActionDescriptor> {
139 let _ = (address, argument);
140 None
141 }
142
143 /// Follow an admitted call of a live action ([`ActionProvider::watch`]).
144 ///
145 /// # Errors
146 ///
147 /// The action has no live result here, or `caller` may not follow it.
148 fn live(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
149 let _ = (caller, request);
150 Err("this action has no live result".into())
151 }
152}
153
154impl<T: Admits> ActionProvider for T {
155 fn query(
156 &self,
157 _caller: &Caller,
158 query: CatalogueQuery,
159 ) -> Pending<Result<CataloguePage, ActionCallError>> {
160 offered(T::PROVIDER, T::APP, self.rows(), &query)
161 }
162
163 fn invoke(
164 &self,
165 caller: &Caller,
166 request: InvokeRequest,
167 ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
168 self.run(caller, request, Admitted::default())
169 }
170
171 fn observe(&self, _caller: &Caller, _id: &InvocationId) -> Option<InvocationState> {
172 None
173 }
174
175 fn cancel(&self, _caller: &Caller, _id: &InvocationId) -> Pending<Result<(), ActionCallError>> {
176 Pending::ready(Err(ActionCallError::UnknownInvocation))
177 }
178
179 fn invocation(
180 &self,
181 address: &ActionAddress,
182 argument: Option<&str>,
183 ) -> Option<ActionDescriptor> {
184 self.described(address, argument)
185 }
186
187 fn run(
188 &self,
189 caller: &Caller,
190 request: InvokeRequest,
191 admitted: Admitted,
192 ) -> Pending<Result<InvocationReceipt, ActionCallError>> {
193 settled(request.invocation, self.start(caller, &request, &admitted))
194 }
195
196 fn asks_first(
197 &self,
198 caller: &Caller,
199 request: &InvokeRequest,
200 admitted: &Admitted,
201 ) -> Option<Pending<Result<(), ActionCallError>>> {
202 Admits::asks_first(self, caller, request, admitted)
203 }
204
205 fn watch(&self, caller: &Caller, request: &InvokeRequest) -> Result<LiveView, String> {
206 self.live(caller, request)
207 }
208}
209
210/// A result that stays current ([`crate::ExecutionMode::Live`]), as a provider serves it.
211pub struct LiveView {
212 /// The whole result as it is now. A provider that reads it on a thread of its own answers
213 /// when it has; one that has it at hand answers at once ([`Pending::ready`]).
214 pub read: Box<dyn FnMut() -> Pending<LiveRead> + Send>,
215 /// Asked before each read: resolves once the result may have changed after it. A provider that
216 /// stopped serving the result drops it unanswered, which ends the view.
217 pub changes: Box<dyn FnMut() -> Pending<()> + Send>,
218}
219
220/// One read of a [`LiveView`]: the result now, or why it failed for good.
221pub type LiveRead = Result<serde_json::Value, Box<ActionFailure>>;
222
223/// The receipt of `invocation` once `started` ends: the call's outcome, or the refusal that kept it
224/// from starting.
225#[must_use]
226pub fn settled(
227 invocation: InvocationId,
228 started: Result<Pending<Outcome>, String>,
229) -> Pending<Result<InvocationReceipt, ActionCallError>> {
230 match started {
231 Err(reason) => Pending::ready(Err(ActionCallError::Refused { reason })),
232 Ok(started) => started.map(move |outcome| {
233 Ok(InvocationReceipt {
234 invocation,
235 status: match outcome {
236 Ok(output) => ReceiptStatus::Completed { output },
237 Err(error) => ReceiptStatus::Failed { error: *error },
238 },
239 })
240 }),
241 }
242}
243
244/// The page `query` asks of `rows`, the actions `provider` offers for the application `app_id`.
245#[must_use]
246pub fn offered(
247 provider: &str,
248 app_id: &str,
249 rows: Vec<PlacedAction>,
250 query: &CatalogueQuery,
251) -> Pending<Result<CataloguePage, ActionCallError>> {
252 let rows: Vec<CatalogueRow> = rows
253 .into_iter()
254 .map(|placed| CatalogueRow::for_placed_action(provider, app_id, placed))
255 .collect();
256 let revision = rows.len().to_string();
257 Pending::ready(Ok(CataloguePage::from_rows(revision, rows, query)))
258}
259
260/// Every action of `actions` as a top-level row.
261#[must_use]
262pub fn top_level(actions: Vec<ActionDescriptor>) -> Vec<PlacedAction> {
263 actions
264 .into_iter()
265 .map(|action| PlacedAction {
266 parent: String::new(),
267 has_children: false,
268 action,
269 })
270 .collect()
271}