tilo_resource/effect.rs
1//! Effects: work an app does that changes no document — reloading a list,
2//! running a job, talking to a server, opening a system picker.
3//!
4//! An app names its effects as one typed enum and derives [`Effect`]:
5//!
6//! ```
7//! use tilo_resource::Effect;
8//!
9//! #[derive(Clone, Debug, PartialEq, Eq, Effect)]
10//! #[effect(operation = "example.backups")]
11//! pub enum Backups {
12//! /// Back up now.
13//! #[effect(kind = "outside")]
14//! #[effect(job, cancellable)]
15//! BackUp,
16//! /// Restore a snapshot.
17//! #[effect(kind = "outside")]
18//! #[effect(job, destructive)]
19//! Restore {
20//! #[param("Id of the snapshot")]
21//! snapshot: String,
22//! },
23//! }
24//!
25//! let restore = Backups::Restore { snapshot: "monday".into() };
26//! assert_eq!(restore.id(), "restore");
27//! let decoded = Backups::decode("restore", &restore.arguments()).unwrap();
28//! assert!(matches!(decoded, Backups::Restore { snapshot } if snapshot == "monday"));
29//! ```
30//!
31//! Each variant is one published action of kind `Effect`, with typed
32//! parameters, so the palette, agents and scripts invoke it like the app's
33//! buttons do. Unlike a resource's `Action`, an effect is never replayed: it
34//! runs where it was invoked, and what it changes in the document it changes
35//! through ordinary actions. `tilo-app` runs the handler.
36//!
37//! A parameter naming a file or folder on this device is an
38//! [`AbsolutePath`](crate::AbsolutePath): a relative one is refused as the
39//! arguments are decoded, so no effect writes where its process happens to
40//! run.
41//!
42//! A variant that only changes what this presence sees — open a snippet,
43//! reveal a tag, show a result — is a `view`: published as a `View`
44//! operation (any reader may invoke it, a member may not move someone
45//! else's view, repeating it is harmless), answered by the same handler.
46//!
47//! Who may run an effect is decided by its kind alone, like any action: an
48//! effect that reaches the files, hardware or services of the device it
49//! runs on — set this computer up, kill a process here, read a local
50//! folder — reaches outside the record, so the person's Allow, Ask first or
51//! Deny for outside effects decides it.
52//!
53//! An effect whose whole scope is the invoking person's own device —
54//! copy to their clipboard, apply their own appearance, measure their own
55//! connection — and that touches nothing shared and no one else is
56//! `own_device`: a workspace's grants have nothing to consent to, so a
57//! guest invokes it as the workspace's owner does, and it runs only for the
58//! person at the device it acts on ([`tilo_actions::OWN_DEVICE_SCOPE`]). An
59//! effect that reaches other people (a direct message, a call) is not.
60//!
61//! An effect that needs its person attending — it opens a chooser for
62//! them, asks them for a credential or a sign-in, or shows something only
63//! they may see — is `attended`: whoever acts for the person (an agent, a
64//! bot) is always asked first, and no answer allows it unasked
65//! ([`tilo_actions::ATTENDED_TAG`]).
66//!
67//! An effect that acts on one item — open *this* snippet, connect *this*
68//! connection — is offered on the item itself with its arguments bound
69//! ([`Effect::bound`]): a published child or a live row carries it, and
70//! invoking it there reaches the handler as that value. Such an effect is
71//! often `row`: offered only bound, never on the resource with an id for
72//! the caller to type.
73//!
74//! An effect's label is a key of the catalogue beside its crate
75//! (`locales/en-US.ftl`): `<operation>-<id>` with the operation's separators
76//! as dashes (`notes-effect-export` for `export` of `notes.effect`), or the
77//! key `label = "…"` names where the crate already says the same thing. Its
78//! doc comment is for developers and describes it to agents; it is never the
79//! label.
80//!
81//! Variant options: `label = "key"`, `view` (changes
82//! only what is shown; answers at once), `document` (a document operation the
83//! app's own registry applies, as the history verbs are: its operation type is
84//! the action's, never an operation the surface answers), `prompted` (asks its
85//! first parameter in the palette even where every parameter may be left out:
86//! a named verb whose optional argument a person still says), `row` (offered
87//! only bound to the items it acts on), `job` (runs in the background and reports
88//! progress, then its result), `cancellable` (a job the caller may cancel),
89//! `returns` (answers with a JSON value), `content` (answers with content
90//! another app's operation takes: bytes in this device's content store, named
91//! by their hash as a `tilo.content` resource; an operation that takes content
92//! collects it with `ActionSpec::prompted_content`, so a caller chains the
93//! two by type), `destructive` (asks for confirmation),
94//! `risk = "path"` (a `fn(&Self) -> RiskLevel` classifying one invocation:
95//! one it finds destructive asks for confirmation, so formatting the system
96//! disk can, and another disk need not), `phrase = "path"` (a
97//! `fn(&Self) -> String` naming what one bound invocation of a `destructive`
98//! `row` effect loses, such as the drive it erases: its caller types it to
99//! confirm, [`Effect::bound`] asks for it), `privileged` (hands out or shows a
100//! credential, such as copying a one-time
101//! code: asks for confirmation too), `sensitive` (discloses a copy of private
102//! data, such as exporting an address book: asks for confirmation too), `idempotent` (safe to repeat after an
103//! uncertain outcome), `own_device` (its scope is the invoker's own device),
104//! `attended` (needs its person attending: anyone acting for them asks),
105//! `audience = "agents"` (listed for agents and programs, never in the
106//! palette; `"people"` lists it for people only),
107//! `untrusted` (answers with content from outside the user's data, such as a
108//! web page's text: the caller reasons about it and never follows it),
109//! `opens_path` (opens the file its `path` names in this instance, which is
110//! how an app launched with a file opens it; `opens_path = "csv,tsv"` only
111//! those types),
112//! `presence` (a view that moves only the invoking presence's own
113//! view, such as an agent's caret, so a remote presence may invoke it),
114//! `member` (any member of a workspace may ask the workspace's host to run it
115//! for themselves on the workspace's record, as linking their own account
116//! elsewhere),
117//! `host_render` (a host answers it in a render service of its own, never in
118//! the record's confined app worker: [`tilo_actions::HOST_RENDER_TAG`]),
119//! `tag = EXPR` (repeatable: a further contract tag, a `&'static str`
120//! constant, for how a host treats the effect),
121//! `outside_with = "path"` (an effect of `kind = "read"` that reaches outside
122//! the record only when that parameter is given: an export that writes the
123//! file it names, else keeps what it made as content; each invocation is
124//! admitted as what it does),
125//! `item = field` (offered on each item of the collection, its first
126//! parameter bound to the item's id, beside the item's own verbs) or
127//! `on = RowType` (offered on each row of a `#[derive(Row)]` type, its first
128//! parameter bound to the row's id; `LiveRow::typed` publishes them; write it
129//! more than once to offer the effect on several types, and leave the effect
130//! without parameters to offer it on the type as it is)
131//! and
132//! `kind = "read"` (an effect that only reads, which whoever may read may
133//! invoke), `kind = "undoable"` (an undoable change) or `kind = "outside"`
134//! (a change checked against the caller's grants: every effect states its
135//! kind, while a `view` reads and an `edit` is undoable),
136//! and `offload(cpu_ms = N, memory_mb = N,
137//! output_mb = N, gpu)` (a `content`, `kind = "read"` transform of content
138//! inputs whose outputs depend on the inputs alone: the system may dispatch it
139//! to the invoker's best-placed device, where the action runs through that
140//! device's provider, and the handler is its local run; [`tilo_actions::Offload`]). Field
141//! `#[param("…")]` describes a parameter; `#[param(secret, "…")]` makes it a
142//! secret the host keeps out of logs, history and confirmations;
143//! `#[param(decimal, "…")]` makes it an identity that travels as canonical
144//! decimal text and is refused otherwise; and `#[param("…", choices = EXPR)]`
145//! names the values it takes when they are a fixed list (`EXPR` yields
146//! strings: a constant table, an array of names). `#[param(label = "key")]`
147//! takes the description from the vocabulary's catalogue instead, read in the
148//! person's language where the action is published.
149//!
150//! A parameter's Rust type describes its JSON form — it derives
151//! [`JsonSchema`](crate::JsonSchema) — because the surface publishes the
152//! parameter's type, its schema and the records and enums it names, which
153//! other languages compile against. A type that describes none is refused
154//! where the effect is declared, naming the parameter and the type:
155//!
156//! ```compile_fail
157//! use serde::{Deserialize, Serialize};
158//! use tilo_resource::Effect;
159//!
160//! /// A value that says nothing about its JSON form.
161//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
162//! pub struct Snapshot;
163//!
164//! #[derive(Clone, Debug, PartialEq, Effect)]
165//! #[effect(operation = "example.backups")]
166//! pub enum Backups {
167//! /// Restore a snapshot.
168//! #[effect(kind = "outside")]
169//! Restore { snapshot: Snapshot },
170//! }
171//! # fn main() {}
172//! ```
173//!
174//! The value a wrapper carries must describe itself too: a list, an option or
175//! a box of a type with no schema is refused as well, so a parameter can never
176//! be published with no type to say what it holds.
177//!
178//! ```compile_fail
179//! use serde::{Deserialize, Serialize};
180//! use tilo_resource::Effect;
181//!
182//! /// A value that says nothing about its JSON form.
183//! #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
184//! pub struct Snapshot;
185//!
186//! #[derive(Clone, Debug, PartialEq, Effect)]
187//! #[effect(operation = "example.backups")]
188//! pub enum Backups {
189//! /// Restore snapshots.
190//! #[effect(kind = "outside")]
191//! Restore { snapshots: Vec<Snapshot> },
192//! }
193//! # fn main() {}
194//! ```
195
196use std::sync::Arc;
197
198use tilo_actions::{
199 ActionAddress, ActionContract, ActionKind, ActionParam, ActionSpec, ActionType, ApiError,
200 ConfirmationPolicy, EncodedAction, ExecutionMode, OperationKind, ResourceSpec, ResultSpec,
201 RetryPolicy, RiskLevel, Target,
202};
203
204/// `resource` offering every action of the vocabulary `E`: a device's
205/// readings and the desktop's verbs are published this way.
206///
207/// It sits beside [`Effect::specs`] so that a crate publishing a vocabulary
208/// needs only the vocabulary, not the service host that runs one.
209#[must_use]
210pub fn offer<E: Effect>(mut resource: ResourceSpec) -> ResourceSpec {
211 resource.actions.extend(E::specs());
212 resource
213}
214
215/// The effect of `E` that invoking `action` of `resource` with `arguments`
216/// names, once the spec `published` offers for it checked the arguments
217/// and that it is available now. A spec offered bound to an item (a
218/// network, an accessory) adds the item's arguments.
219///
220/// It sits beside [`offer`] for the same reason: whatever answers a
221/// vocabulary's actions decodes them without the service host.
222///
223/// # Errors
224/// [`ApiError::Unknown`] when nothing published names it,
225/// [`ApiError::Unavailable`], or the arguments' refusal.
226pub fn decode<E: Effect>(
227 published: &[ResourceSpec],
228 resource: &str,
229 action: &str,
230 arguments: &serde_json::Map<String, serde_json::Value>,
231) -> Result<E, ApiError> {
232 let address = ActionAddress::new(resource, action);
233 let (_, spec) = tilo_actions::api::locate(published, &address)
234 .ok_or_else(|| ApiError::Unknown(address.clone()))?;
235 tilo_actions::api::encode_json(published, &address, arguments)?;
236 let mut all = arguments.clone();
237 for (name, value) in spec.bound() {
238 all.insert(name.clone(), value.clone());
239 }
240 E::decode(&spec.id, &all).map_err(|error| ApiError::InvalidArguments(error.to_string()))
241}
242
243/// Why a caller's invocation does not name an effect of a vocabulary.
244#[derive(Debug, thiserror::Error)]
245pub enum EffectDecodeError {
246 /// The vocabulary offers no effect of that id.
247 #[error("there is no effect `{0}`")]
248 Unknown(String),
249 /// The payload the invocation travels in does not decode.
250 #[error("the effect's payload does not decode: {0}")]
251 Payload(#[source] serde_json::Error),
252 /// One argument does not have its field's type, as the field's own type
253 /// says (`AbsolutePath`'s refusal of a relative path, say). `name` is
254 /// its path in the invocation: a flattened struct's field by its own
255 /// name (`path`), a field of one with its parent's (`adjust.grayscale`).
256 #[error("the effect's `{name}` argument does not decode: {source}")]
257 Argument {
258 name: String,
259 #[source]
260 source: serde_json::Error,
261 },
262 /// One argument names no identity: it is not canonical decimal text.
263 #[error(
264 "the effect's `{name}` argument is `{value}`, which names no id: ids travel as decimal text"
265 )]
266 Identity { name: String, value: String },
267}
268
269/// A typed vocabulary of effects. Derive it (`#[derive(Effect)]`); see the
270/// [module docs](self).
271pub trait Effect: Sized + 'static {
272 /// The operation type every effect of the vocabulary travels under:
273 /// unique per vocabulary, like a resource's kind.
274 const OPERATION: &'static str;
275
276 /// The app whose resource offers the vocabulary's effects, which an
277 /// effect's typed reference names its action by: defaults to none of its
278 /// own, for a vocabulary that is not an app's (a test's, a host's).
279 const APP_ID: &'static str = crate::kind::DEFAULT_APP;
280
281 /// The vocabulary's name, as its effects are labelled when they are
282 /// offered on their own.
283 const LABEL: &'static str = Self::OPERATION;
284
285 /// One declaration per effect, in order.
286 fn declarations() -> Vec<EffectDecl>;
287
288 /// The vocabulary's declarations where they are kept, for a surface that
289 /// publishes an app without running it: every area's, for a vocabulary
290 /// that gathers several.
291 fn rows() -> Vec<EffectRow>;
292
293 /// The declaration of the effect `id`, built alone: what binding one
294 /// effect to an item reads, so offering it on many items costs one
295 /// declaration each, not the whole vocabulary.
296 fn declaration(id: &str) -> Option<EffectDecl> {
297 first_declaration(Self::declarations(), id)
298 }
299
300 /// This effect's id among the declarations.
301 fn id(&self) -> &'static str;
302
303 /// What its caller types to confirm this invocation, when its effect
304 /// declares `phrase`: the name of what it erases.
305 fn confirmation_phrase(&self) -> Option<String> {
306 None
307 }
308
309 /// The kind the vocabulary's effects are published under, which a typed
310 /// reference to one names: the operation they travel as, the vocabulary's
311 /// name, and the app that offers it.
312 fn kind() -> crate::kind::ResourceKind {
313 crate::kind::ResourceKind::of_effect::<Self>(Self::OPERATION, Self::LABEL, Self::APP_ID)
314 }
315
316 /// The key this effect is offered under: the app that offers the
317 /// vocabulary, the operation its effects travel as, and this effect's id.
318 fn key(&self) -> tilo_actions::ActionKey {
319 tilo_actions::ActionKey::new(Self::APP_ID, Self::OPERATION, self.id())
320 }
321
322 /// The spec `id` declares: what a control binding it reads, so binding one
323 /// effect costs one declaration rather than the vocabulary's.
324 fn spec(id: &str) -> Option<tilo_actions::ActionSpec> {
325 Self::declaration(id).map(|decl| decl.spec_checked(Self::OPERATION, check::<Self>))
326 }
327
328 /// This effect's arguments, named as its declaration's parameters.
329 fn arguments(&self) -> serde_json::Map<String, serde_json::Value>;
330
331 /// The effect `id` with `arguments`, as a caller invoked it.
332 fn decode(
333 id: &str,
334 arguments: &serde_json::Map<String, serde_json::Value>,
335 ) -> Result<Self, EffectDecodeError>;
336
337 /// The published action of every effect offered on the resource: all
338 /// but the `row` ones, which are offered only [bound](Self::bound).
339 fn specs() -> Vec<ActionSpec> {
340 kept_specs(
341 check::<Self>,
342 std::any::TypeId::of::<Self>(),
343 Self::OPERATION,
344 Self::declarations,
345 )
346 }
347
348 /// This effect with its arguments as one action that takes none: what a
349 /// published child or a live row offers (open *this* snippet, stop
350 /// *this* process), answered by the vocabulary's handler like any other
351 /// invocation of the effect, under the same contract as its
352 /// declaration.
353 fn bound(&self) -> ActionSpec {
354 let id = self.id();
355 let arguments = self.arguments();
356 let spec = kept_type((std::any::TypeId::of::<Self>(), id, None), || {
357 bound_type(check::<Self>, Self::OPERATION, id, Self::declaration(id))
358 })
359 .bind(Target::new(arguments.clone()))
360 .with_bound(arguments.into_iter().collect());
361 asking_phrase(spec, self.confirmation_phrase())
362 }
363
364 /// This effect bound to the item it acts on, as [`bound`](Self::bound),
365 /// still asking its caller for the arguments named in `asking`: rename
366 /// *this* file, to a name the caller gives. The bound arguments are this
367 /// effect's own; an asked one the caller supplies replaces it.
368 fn bound_asking(&self, asking: &[&str]) -> ActionSpec {
369 let params = Self::declaration(self.id())
370 .map(|decl| {
371 decl.params
372 .into_iter()
373 .filter(|param| asking.contains(&&*param.name))
374 .collect()
375 })
376 .unwrap_or_default();
377 self.bound_asking_params(params)
378 }
379
380 /// [`bound_asking`](Self::bound_asking) with the asked parameters given
381 /// whole, narrowed for this item: the applications that can open *this*
382 /// file as the choices of `app`.
383 fn bound_asking_params(&self, params: Vec<ActionParam>) -> ActionSpec {
384 let id = self.id();
385 match Self::declaration(id) {
386 Some(decl) => asking_phrase(
387 asking_spec(
388 check::<Self>,
389 Self::OPERATION,
390 &decl,
391 params,
392 self.arguments(),
393 ),
394 self.confirmation_phrase(),
395 ),
396 None => self.bound(),
397 }
398 }
399
400 /// The effects offered on the item `item` of the collection `field`
401 /// (`#[effect(item = field)]`), each with its first parameter bound to
402 /// the item and the rest still asked.
403 fn item_specs(field: &str, item: &crate::Id) -> Vec<ActionSpec> {
404 target_specs(
405 check::<Self>,
406 std::any::TypeId::of::<Self>(),
407 Self::OPERATION,
408 Self::declarations,
409 &|target| target.is_field(field),
410 item,
411 )
412 }
413
414 /// The effects offered on the row `row` of the
415 /// [`RowType`](crate::words::RowType) `kind` (`#[effect(on = Row)]`),
416 /// each with its first parameter bound to the row and the rest still
417 /// asked. [`RowType::effects`](crate::words::RowType::effects) calls it.
418 fn row_specs(kind: &'static str, row: &crate::Id) -> Vec<ActionSpec> {
419 target_specs(
420 check::<Self>,
421 std::any::TypeId::of::<Self>(),
422 Self::OPERATION,
423 Self::declarations,
424 &|target| target.is_row(kind),
425 row,
426 )
427 }
428
429 /// The effects offered on the row `row` of the
430 /// [`RowType`](crate::words::RowType) `kind`, those `bindings` names
431 /// among them, each with exactly the arguments they give bound and the
432 /// rest still asked. [`RowType::effects_with`](crate::words::RowType::effects_with)
433 /// calls it.
434 fn row_specs_with(
435 kind: &'static str,
436 _row: &crate::Id,
437 bindings: &crate::row::RowBindings,
438 ) -> Vec<ActionSpec> {
439 target_specs_with(
440 check::<Self>,
441 std::any::TypeId::of::<Self>(),
442 Self::OPERATION,
443 Self::declarations,
444 &|target| target.is_row(kind),
445 bindings,
446 )
447 }
448
449 /// This effect as the published resource `resource` offers it (the
450 /// record, or a child or live row it is bound on, by its published id):
451 /// what a search hit invokes or a caller addresses through the host's
452 /// API. Its id comes from the effect itself.
453 fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
454 tilo_actions::ActionAddress::new(resource, self.id())
455 }
456
457 /// Decode one invocation's payload, as the operation's specs encode it.
458 ///
459 /// Read where the effect runs, as an action's arguments are read where
460 /// it is invoked: an effect is never replayed, so content its arguments
461 /// name — a reference, or the data inline — is read from this window's
462 /// store and kept, sealed, in it ([`crate::content::invoking`]).
463 fn from_payload(payload: &[u8]) -> Result<Self, EffectDecodeError> {
464 crate::content::invoking(|| {
465 let Payload { effect, args } = decode_payload(payload)?;
466 Self::decode(&effect, &args)
467 })
468 }
469}
470
471/// `spec`, asking its caller to type `phrase` when there is one. Not
472/// generic, so every vocabulary shares it.
473#[inline(never)]
474fn asking_phrase(mut spec: ActionSpec, phrase: Option<String>) -> ActionSpec {
475 if let Some(phrase) = phrase {
476 spec.type_mut().contract.confirmation = ConfirmationPolicy::Phrase { phrase };
477 }
478 spec
479}
480
481/// How the effect's specs carry an invocation: its id and its arguments.
482#[derive(serde::Serialize, serde::Deserialize)]
483struct Payload {
484 effect: String,
485 #[serde(default)]
486 args: serde_json::Map<String, serde_json::Value>,
487}
488
489/// The [`Payload`] in `payload`. Not generic over the effect, so its decoder
490/// is compiled once rather than in every app's `from_payload`.
491#[inline(never)]
492fn decode_payload(payload: &[u8]) -> Result<Payload, EffectDecodeError> {
493 tilo_actions::decode_json(payload).map_err(EffectDecodeError::Payload)
494}
495
496/// How an encoded invocation's arguments are made of the caller's and the
497/// ones bound to the item the effect was offered on.
498#[derive(Clone, Copy)]
499enum Bound {
500 /// The caller's alone.
501 None,
502 /// The bound ones alone: the spec asks for nothing.
503 Only,
504 /// The bound ones, any the caller gives replacing them.
505 UnderCaller,
506 /// The caller's, the bound ones replacing them.
507 OverCaller,
508}
509
510/// The arguments an effect spec's [`Target`] binds: the ones of the item it
511/// was offered on.
512type BoundArguments = serde_json::Map<String, serde_json::Value>;
513
514/// Why the effect `id` of a vocabulary does not take `arguments`, as the
515/// vocabulary reads them back; `None` when it does.
516type Check = fn(&str, &BoundArguments) -> Option<String>;
517
518/// [`Check`] of the vocabulary `E`: the only part of its specs compiled for it.
519fn check<E: Effect>(id: &str, arguments: &BoundArguments) -> Option<String> {
520 E::decode(id, arguments)
521 .err()
522 .map(|problem| problem.to_string())
523}
524
525/// The one encoder of every effect spec of a vocabulary, which `check`s: the invocation
526/// of effect `effect` under `operation`, with its arguments made as `mode`
527/// says of the ones its target binds ([`BoundArguments`]) and the caller's.
528///
529/// The arguments are read back as `E` before they are encoded, so a client
530/// that names an id or a value the effect does not take is refused at the
531/// API, [`INVALID_ARGUMENTS_TYPE`](tilo_actions::resource::INVALID_ARGUMENTS_TYPE)
532/// with why, rather than handed to a host that cannot run it.
533fn encoder(
534 check: Check,
535 operation: &'static str,
536 effect: &'static str,
537 mode: Bound,
538) -> impl Fn(&Target, &tilo_actions::ActionArgs) -> EncodedAction + Send + Sync + 'static {
539 move |target, args| {
540 let args = effect_arguments(mode, target, args);
541 if let Some(problem) = check(effect, &args) {
542 return EncodedAction {
543 type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
544 payload: problem.into_bytes(),
545 };
546 }
547 EncodedAction::encode_operation(
548 operation,
549 &Payload {
550 effect: effect.to_owned(),
551 args,
552 },
553 )
554 .unwrap_or_else(|_| EncodedAction {
555 type_id: operation.to_owned(),
556 payload: Vec::new(),
557 })
558 }
559}
560
561/// The arguments an invocation of an effect offered with `mode` carries: the
562/// ones its target binds, the caller's, or both, as [`Bound`] says.
563fn effect_arguments(
564 mode: Bound,
565 target: &Target,
566 args: &tilo_actions::ActionArgs,
567) -> BoundArguments {
568 let empty = BoundArguments::new();
569 let bound = target.get::<BoundArguments>().unwrap_or(&empty);
570 match mode {
571 Bound::None => args.to_json(),
572 Bound::Only => bound.clone(),
573 Bound::UnderCaller => {
574 let mut merged = bound.clone();
575 merged.extend(args.to_json());
576 merged
577 }
578 Bound::OverCaller => {
579 let mut merged = args.to_json();
580 merged.extend(
581 bound
582 .iter()
583 .map(|(name, value)| (name.clone(), value.clone())),
584 );
585 merged
586 }
587 }
588}
589
590/// [`Effect::specs`] of the vocabulary `key`. They depend on its type alone
591/// and are published on every refresh of a view's actions, so each thread
592/// builds them once per generation of app code
593/// ([`reset_type_schemas`](crate::reset_type_schemas)) and hands out copies.
594fn kept_specs(
595 check: Check,
596 key: std::any::TypeId,
597 operation: &'static str,
598 declarations: fn() -> Vec<EffectDecl>,
599) -> Vec<ActionSpec> {
600 type Kept = (
601 u64,
602 std::collections::HashMap<std::any::TypeId, std::rc::Rc<[ActionSpec]>>,
603 );
604 thread_local! {
605 static KEPT: std::cell::RefCell<Kept> =
606 std::cell::RefCell::new((0, std::collections::HashMap::new()));
607 }
608 let epoch = crate::resource::words_epoch();
609 let found = KEPT.with(|kept| {
610 let kept = kept.borrow();
611 if kept.0 == epoch {
612 kept.1.get(&key).cloned()
613 } else {
614 None
615 }
616 });
617 let specs = found.unwrap_or_else(|| {
618 let built: std::rc::Rc<[ActionSpec]> =
619 offered_specs(check, declarations(), operation).into();
620 KEPT.with(|kept| {
621 let mut kept = kept.borrow_mut();
622 if kept.0 != epoch {
623 *kept = (epoch, std::collections::HashMap::new());
624 }
625 kept.1.insert(key, std::rc::Rc::clone(&built));
626 });
627 built
628 });
629 specs.to_vec()
630}
631
632/// The declaration `id` of `declarations`, as [`Effect::declaration`] reads
633/// one. Not generic over the vocabulary, so the search is compiled once rather
634/// than in every app that declares effects.
635#[inline(never)]
636fn first_declaration(declarations: Vec<EffectDecl>, id: &str) -> Option<EffectDecl> {
637 declarations.into_iter().find(|decl| decl.id == id)
638}
639
640fn offered_specs(check: Check, decls: Vec<EffectDecl>, operation: &'static str) -> Vec<ActionSpec> {
641 // Offered on an item or a row (`item = field`, `on = Row`) as well as
642 // here, where it acts on the item a caller names: its audience is the
643 // declaration's, and it says it needs an item, so a listing holding none
644 // leaves it to the items that offer it bound.
645 decls
646 .into_iter()
647 .filter(|decl| !decl.row)
648 .map(|decl| {
649 let mut spec = decl.spec_checked(operation, check);
650 if let Some(target) = decl.items.first() {
651 spec.type_mut().contract.item = Some(target.key().to_owned());
652 }
653 spec
654 })
655 .collect()
656}
657
658/// The type of [`Effect::bound`] of the effect `id`, declared as `decl`: its
659/// target binds every argument.
660fn bound_type(
661 check: Check,
662 operation: &'static str,
663 id: &'static str,
664 decl: Option<EffectDecl>,
665) -> Arc<ActionType> {
666 let build = encoder(check, operation, id, Bound::Only);
667 let spec = match decl {
668 Some(decl) => decl.spec_with_boxed(operation, Vec::new(), Arc::new(build)),
669 None => ActionSpec::typed_operation_on(
670 id,
671 id,
672 id,
673 OperationKind::Effect,
674 operation,
675 Vec::new(),
676 Arc::new(build),
677 ),
678 };
679 Arc::clone(spec.action_type())
680}
681
682/// [`Effect::bound_asking_params`] of the effect `decl` declares, bound to
683/// `args`, asking `params`.
684fn asking_spec(
685 check: Check,
686 operation: &'static str,
687 decl: &EffectDecl,
688 params: Vec<ActionParam>,
689 args: BoundArguments,
690) -> ActionSpec {
691 let fixed = args
692 .iter()
693 .filter(|(name, _)| !params.iter().any(|param| param.name == name.as_str()))
694 .map(|(name, value)| (name.clone(), value.clone()))
695 .collect();
696 let build = encoder(check, operation, decl.id, Bound::UnderCaller);
697 decl.spec_with_boxed(operation, params, Arc::new(build))
698 .action_type()
699 .bind(Target::new(args))
700 .with_bound(fixed)
701}
702
703/// A copy of `params`, made by one function for every effect vocabulary.
704#[inline(never)]
705fn params_from(params: &[ActionParam]) -> Vec<ActionParam> {
706 params.to_vec()
707}
708
709/// [`Effect::item_specs`] and [`Effect::row_specs`] of the vocabulary `key`,
710/// whose declarations `declarations` are: every effect `matches` offers on an
711/// entity, its first parameter bound here to `entity` — or, for an effect
712/// with no parameters, offered as it is, since the entity changes nothing
713/// about it. Each type is kept per target, so offering the same effect on
714/// many items costs one type.
715fn target_specs(
716 check: Check,
717 key: std::any::TypeId,
718 operation: &'static str,
719 declarations: fn() -> Vec<EffectDecl>,
720 matches: &dyn Fn(&EffectTarget) -> bool,
721 entity: &crate::Id,
722) -> Vec<ActionSpec> {
723 declared(key, declarations)
724 .iter()
725 .filter_map(|decl| {
726 let target = *decl.items.iter().find(|target| matches(target))?;
727 let mut refused = None;
728 let bound = match decl.params.first() {
729 Some(first) => BoundArguments::from_iter([(
730 first.name.to_string(),
731 match (target, decl.row_id) {
732 (EffectTarget::Row(_), Some(parse)) => match parse(entity.as_str()) {
733 Ok(value) => value,
734 // The row's id is not what the effect acts on: it
735 // is published, refused with the reason, so an
736 // agent sees why rather than a broken call.
737 Err(reason) => {
738 refused = Some(reason);
739 serde_json::Value::String(entity.as_str().to_owned())
740 }
741 },
742 _ => serde_json::Value::String(entity.as_str().to_owned()),
743 },
744 )]),
745 None => BoundArguments::new(),
746 };
747 let ty = kept_type((key, decl.id, Some(target.key())), || {
748 let rest = params_from(decl.params.get(1..).unwrap_or_default());
749 let build = encoder(check, operation, decl.id, Bound::OverCaller);
750 Arc::clone(
751 decl.spec_with_boxed(operation, rest, Arc::new(build))
752 .action_type(),
753 )
754 });
755 let fixed: Vec<(String, serde_json::Value)> = bound.clone().into_iter().collect();
756 let arguments: serde_json::Map<String, serde_json::Value> =
757 fixed.iter().cloned().collect();
758 let mut spec = ty.bind(Target::new(bound)).with_bound(fixed);
759 if let Some(phrase) = decl.phrase {
760 spec = asking_phrase(spec, phrase(&arguments));
761 }
762 if let Some(reason) = refused {
763 spec.type_mut().contract.availability = tilo_actions::Availability::Unavailable {
764 code: "row_id".to_owned(),
765 reason,
766 };
767 }
768 Some(spec)
769 })
770 .collect()
771}
772
773/// [`Effect::row_specs_with`] of the vocabulary `key`, whose declarations
774/// `declarations` are: every effect `matches` offers on an entity that
775/// `bindings` names among them, with exactly the arguments it gives bound and
776/// the rest asked.
777fn target_specs_with(
778 check: Check,
779 key: std::any::TypeId,
780 operation: &'static str,
781 declarations: fn() -> Vec<EffectDecl>,
782 matches: &dyn Fn(&EffectTarget) -> bool,
783 bindings: &crate::row::RowBindings,
784) -> Vec<ActionSpec> {
785 declared(key, declarations)
786 .iter()
787 .filter(|decl| decl.items.iter().any(matches))
788 .flat_map(|decl| {
789 bindings
790 .arguments(decl.id)
791 .unwrap_or_default()
792 .iter()
793 .map(|given| {
794 // A parameter the row offers with its own value as the
795 // default is asked, not taken: the caller may give
796 // another, and leaving it out takes the row's value.
797 let asking = bindings.asks(decl.id);
798 let asks = |name: &str| asking.contains(&name);
799 // An argument the row binds to null is the argument left
800 // unset, as a declaration's own binding leaves an optional
801 // one: it is taken, not asked, and travels as absent.
802 let mut bound = BoundArguments::new();
803 let mut defaults: Vec<(&str, serde_json::Value)> = Vec::new();
804 let mut taken: Vec<&str> = Vec::new();
805 for (name, value) in given {
806 if !decl
807 .params
808 .iter()
809 .any(|param| param.name.as_ref() == name.as_str())
810 {
811 continue;
812 }
813 if asks(name.as_str()) {
814 defaults.push((name.as_str(), value.clone()));
815 continue;
816 }
817 taken.push(name.as_str());
818 if !value.is_null() {
819 bound.insert(name.clone(), value.clone());
820 }
821 }
822 let mut asked = decl
823 .params
824 .iter()
825 .filter(|param| !taken.contains(¶m.name.as_ref()))
826 .cloned()
827 .collect::<Vec<_>>();
828 for param in &mut asked {
829 if let Some((_, value)) = defaults
830 .iter()
831 .find(|(name, _)| *name == param.name.as_ref())
832 && !value.is_null()
833 {
834 *param = param.clone().with_default(value.clone());
835 }
836 // The values the row's own state says this parameter
837 // takes (a display's modes) stand where the
838 // declaration's do.
839 if let Some(choices) = bindings.chosen(decl.id, param.name.as_ref()) {
840 param.choices = choices.iter().cloned().map(Into::into).collect();
841 }
842 }
843 let asked = params_from(&asked);
844 let mode = if asking.is_empty() {
845 Bound::OverCaller
846 } else {
847 Bound::UnderCaller
848 };
849 let build = encoder(check, operation, decl.id, mode);
850 let fixed: Vec<(String, serde_json::Value)> =
851 bound.clone().into_iter().collect();
852 // The row's own values travel in the target too, so an
853 // argument the caller leaves out takes them.
854 let mut target = bound.clone();
855 for (name, value) in &defaults {
856 target.insert((*name).to_owned(), value.clone());
857 }
858 let arguments: serde_json::Map<String, serde_json::Value> =
859 target.clone().into_iter().collect();
860 let mut spec = decl.spec_with_boxed(operation, asked, Arc::new(build));
861 if let Some(phrase) = decl.phrase {
862 spec = asking_phrase(spec, phrase(&arguments));
863 }
864 spec.action_type()
865 .bind(Target::new(target))
866 .with_bound(fixed)
867 })
868 .collect::<Vec<_>>()
869 })
870 .collect()
871}
872
873/// Where a kept effect type is offered: the vocabulary, the effect, and for
874/// an offered effect the field or row kind whose entities offer it.
875type TypeKey = (std::any::TypeId, &'static str, Option<&'static str>);
876
877/// The declarations of the vocabulary `key`, built once on each thread: its rows are published
878/// far more often than what it declares changes.
879fn declared(
880 key: std::any::TypeId,
881 declarations: fn() -> Vec<EffectDecl>,
882) -> std::rc::Rc<[EffectDecl]> {
883 thread_local! {
884 static KEPT: std::cell::RefCell<crate::kept::KeptTypes<std::any::TypeId, std::rc::Rc<[EffectDecl]>>> =
885 std::cell::RefCell::default();
886 }
887 crate::kept::kept_type(&KEPT, key, || declarations().into())
888}
889
890/// The action type `key` names, kept once per thread and generation of app
891/// code, as [`kept_specs`] keeps a vocabulary's specs: what every item
892/// offering the effect shares.
893fn kept_type(key: TypeKey, build: impl FnOnce() -> Arc<ActionType>) -> Arc<ActionType> {
894 thread_local! {
895 static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeKey>> =
896 std::cell::RefCell::default();
897 }
898 crate::kept::kept_type(&KEPT, key, build)
899}
900
901/// What an effect is offered on, bound to it: a collection's items, or a
902/// declared row type's rows. The two are one thing — an effect offered on an
903/// entity of a declared type, with the entity's id bound — declared either
904/// beside the document that holds the items, or on the type of rows that live
905/// outside any document.
906#[derive(Clone, Copy, Debug, PartialEq, Eq)]
907pub enum EffectTarget {
908 /// The collection field whose items the effect is offered on
909 /// (`#[effect(item = connections)]`).
910 Field(&'static str),
911 /// The kind of the [`RowType`](crate::words::RowType) whose rows the
912 /// effect is offered on (`#[effect(on = Process)]`).
913 Row(&'static str),
914}
915
916impl EffectTarget {
917 /// The key the offered type is kept under: the field or the row kind.
918 fn key(self) -> &'static str {
919 match self {
920 Self::Field(field) | Self::Row(field) => field,
921 }
922 }
923
924 /// Whether this is the collection `field`.
925 fn is_field(self, field: &str) -> bool {
926 matches!(self, Self::Field(named) if named == field)
927 }
928
929 /// Whether this is the row type of kind `kind`.
930 fn is_row(self, kind: &str) -> bool {
931 matches!(self, Self::Row(named) if named == kind)
932 }
933}
934
935/// One effect of a derived vocabulary, as a constant: its declaration but for
936/// the parameters, which [`Self::params`] builds. `#[derive(Effect)]` writes
937/// one per variant; [`EffectDecl::of_rows`] and [`EffectDecl::of_row`] read
938/// them, the same code for every vocabulary.
939#[doc(hidden)]
940#[derive(Clone)]
941#[allow(
942 clippy::struct_excessive_bools,
943 reason = "each flag is an independent property a declaration states, as the derive's options do"
944)]
945pub struct EffectRow {
946 pub id: &'static str,
947 /// What a person reads it by: a key of its crate's catalogue.
948 pub label: crate::label::Word,
949 /// The other words people use for it (`keywords = "…"`), comma
950 /// separated: search finds it by them as by its label.
951 pub keywords: &'static [&'static str],
952 /// Its own picture (`icon = "…"`), by its Lucide name.
953 pub icon: Option<&'static str>,
954 pub description: &'static str,
955 pub params: fn() -> Vec<ActionParam>,
956 /// The surface types of the parameters whose types describe one, by name.
957 pub param_types: fn() -> Vec<(&'static str, crate::surface::FieldTypeOf)>,
958 /// The value it answers with, when the code declares one
959 /// (`returns = Type`): its JSON Schema and its type.
960 pub result: Option<EffectResult>,
961 pub kind: OperationKind,
962 /// Offered with its first parameter's prompt even where every parameter
963 /// may be left out: a named verb whose optional argument a person still
964 /// says (how many steps to undo).
965 pub prompted: bool,
966 pub row: bool,
967 pub answers: Answers,
968 pub risk: RiskLevel,
969 pub idempotent: bool,
970 pub action_kind: ActionKind,
971 pub own_device: bool,
972 pub attended: bool,
973 pub risk_of: Option<fn(&tilo_actions::ActionArgs) -> RiskLevel>,
974 pub audience: tilo_actions::Audience,
975 pub untrusted: bool,
976 pub opens: Option<&'static [&'static str]>,
977 pub presence: bool,
978 pub edits: bool,
979 pub member: bool,
980 /// The kinds of entity its rows are offered on
981 /// ([`EffectTarget`]): none for an effect offered on the resource alone.
982 pub items: &'static [EffectTarget],
983 /// How the row id becomes the first parameter's value when the effect is
984 /// offered on a row (`#[effect(on = Row)]`): the row id parsed as that
985 /// field's own type (`u64` counts, an identity parses), so a row whose id
986 /// is not one is offered unavailable with the reason. Absent for an
987 /// effect offered on a collection's items, whose id is bound as it is.
988 pub row_id: Option<RowIdOf>,
989 /// The phrase its caller types for a bound invocation (offered on a row
990 /// or an item), from the arguments it is bound with, when the effect
991 /// declares `phrase`: `#[effect(phrase = "Self::data_name")]` names what
992 /// one invocation loses wherever the effect is offered.
993 pub phrase: Option<PhraseOf>,
994 pub offload: Option<EffectOffload>,
995 pub tags: &'static [&'static str],
996 pub outside_with: Option<&'static str>,
997}
998
999/// The phrase a bound invocation's caller types, from the arguments it is
1000/// bound with: what one invocation loses.
1001pub type PhraseOf = fn(&serde_json::Map<String, serde_json::Value>) -> Option<String>;
1002
1003/// An effect's row id read as the field it acts with: the value bound, or
1004/// why this row's id is not one.
1005pub type RowIdOf = fn(&str) -> Result<serde_json::Value, String>;
1006
1007/// An effect's `#[effect(offload(...))]`: what the transform needs of a
1008/// device, so the system may dispatch it to the invoker's best-placed one
1009/// ([`tilo_actions::Offload`]).
1010#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1011pub struct EffectOffload {
1012 /// Whether it needs a GPU.
1013 pub gpu: bool,
1014 /// CPU time ceiling, in milliseconds.
1015 pub cpu_time_ms: u64,
1016 /// Memory ceiling, in bytes.
1017 pub memory_bytes: u64,
1018 /// Ceiling on all outputs together, in bytes.
1019 pub output_bytes: u64,
1020}
1021
1022impl EffectOffload {
1023 /// The declaration as the action contract carries it.
1024 #[must_use]
1025 pub fn contract(&self) -> tilo_actions::Offload {
1026 tilo_actions::Offload {
1027 gpu: self.gpu,
1028 cpu_time_ms: self.cpu_time_ms,
1029 memory_bytes: self.memory_bytes,
1030 output_bytes: self.output_bytes,
1031 }
1032 }
1033}
1034
1035/// The parameters of an effect that takes none.
1036#[doc(hidden)]
1037#[must_use]
1038pub fn no_params() -> Vec<ActionParam> {
1039 Vec::new()
1040}
1041
1042/// The parameter types of an effect whose parameters describe none.
1043#[doc(hidden)]
1044#[must_use]
1045pub fn no_param_types() -> Vec<(&'static str, crate::surface::FieldTypeOf)> {
1046 Vec::new()
1047}
1048
1049/// The value an effect answers with, as its code declares it
1050/// (`#[effect(returns = Type)]`): its JSON Schema, and its type with the
1051/// records and enums it names.
1052#[derive(Clone, Copy, Debug)]
1053pub struct EffectResult {
1054 /// Its schema, from [`JsonSchema`](crate::JsonSchema).
1055 pub schema: fn() -> serde_json::Value,
1056 /// Its surface type, declaring the records and enums it names.
1057 pub ty: Option<crate::surface::FieldTypeOf>,
1058}
1059
1060/// The declaration of one effect: what callers see of it.
1061#[derive(Clone, Debug)]
1062#[allow(
1063 clippy::struct_excessive_bools,
1064 reason = "each flag is an independent property a declaration states, as the derive's options do"
1065)]
1066pub struct EffectDecl {
1067 pub id: &'static str,
1068 /// What a person reads it by, read in their language when it is
1069 /// published.
1070 pub label: crate::label::Word,
1071 /// The other words people use for it (`keywords = "…"`), comma
1072 /// separated: search finds it by them as by its label.
1073 pub keywords: &'static [&'static str],
1074 /// Its own picture (`icon = "…"`), by its Lucide name.
1075 pub icon: Option<&'static str>,
1076 pub description: &'static str,
1077 pub params: Vec<ActionParam>,
1078 /// The surface type of each parameter whose Rust type describes one
1079 /// ([`JsonSchema`](crate::JsonSchema)), by name: a record or enum a
1080 /// parameter's wire type ([`ParamType::Object`](tilo_actions::ParamType))
1081 /// says nothing of, which a package of another language names.
1082 pub param_types: Vec<(&'static str, crate::surface::FieldTypeOf)>,
1083 /// The value it answers with, when the code declares one
1084 /// (`returns = Type`); see [`EffectResult`].
1085 pub result: Option<EffectResult>,
1086 /// `View` for an effect that only changes what its caller sees, `Document`
1087 /// for one published as a document operation the app's own registry
1088 /// applies, else `Effect`.
1089 pub kind: OperationKind,
1090 /// Offered with its first parameter's prompt even where every parameter
1091 /// may be left out (`prompted`).
1092 pub prompted: bool,
1093 /// Offered only bound to the items it acts on, not on the resource.
1094 pub row: bool,
1095 pub answers: Answers,
1096 /// How much harm invoking it can do: `Destructive` (deletes,
1097 /// overwrites, sends) and `Privileged` (hands out or shows a credential)
1098 /// ask for confirmation; a view is `None`.
1099 pub risk: RiskLevel,
1100 /// Safe to repeat after an uncertain outcome.
1101 pub idempotent: bool,
1102 /// What it is able to do: reach outside the record by default, read for
1103 /// a view or an effect declared `kind = "read"`.
1104 pub action_kind: ActionKind,
1105 /// Its whole scope is the invoking person's own device: it touches
1106 /// nothing shared and no one else, so a workspace's grants have nothing to
1107 /// consent to ([`tilo_actions::OWN_DEVICE_SCOPE`]).
1108 pub own_device: bool,
1109 /// Needs its person attending: it opens a chooser, asks for a credential
1110 /// or a sign-in, or shows what only they may see, so whoever acts for
1111 /// them is always asked first ([`tilo_actions::ATTENDED_TAG`]).
1112 pub attended: bool,
1113 /// How much harm one invocation can do, classified from its arguments
1114 /// (formatting the system disk, against any other): an invocation the
1115 /// classifier finds destructive asks for the confirmation a declared
1116 /// destructive effect does.
1117 pub risk_of: Option<fn(&tilo_actions::ActionArgs) -> RiskLevel>,
1118 /// Who listings offer it to (`#[effect(audience = "agents")]`): an agent
1119 /// reading a page's structure is never a person's palette row.
1120 pub audience: tilo_actions::Audience,
1121 /// Answers with content from outside the user's own data (a web page's
1122 /// text and logs): data to reason about, never instructions to follow.
1123 pub untrusted: bool,
1124 /// Opens the file its `path` names in this instance (`#[effect(opens_path)]`),
1125 /// of any type when empty, else of these extensions: how a caller that
1126 /// launched the app with a file opens it ([`tilo_actions::OPENS_PATH_TAG`]).
1127 pub opens: Option<&'static [&'static str]>,
1128 /// A view that changes only the invoking presence's own view (an
1129 /// agent's caret, its Find), so a remote presence may invoke it
1130 /// without moving anybody else's.
1131 pub presence: bool,
1132 /// A view of the invoker that submits only edits of this record (typing
1133 /// at the invoker's caret): its kind is Undoable, offered to whoever may
1134 /// edit, and the edits it submits are checked like any other.
1135 pub edits: bool,
1136 /// Any member of a workspace may ask the workspace's host to run it for
1137 /// themselves on the workspace's record (`#[effect(member)]`,
1138 /// [`tilo_actions::MEMBER_OWN_TAG`]): it runs there as that member.
1139 pub member: bool,
1140 /// What the effect is offered on, its first parameter bound to it: the
1141 /// collection field whose items offer it (`#[effect(item = connections)]`,
1142 /// published on each item resource as an item verb is), or the kind of a
1143 /// [`RowType`](crate::words::RowType) whose rows offer it
1144 /// (`#[effect(on = Process)]`, published on each of the type's rows). An
1145 /// effect declared on several of them (`#[effect(on = QueueItem, on =
1146 /// HistoryItem)]`) is offered on each, bound to the row it was offered on;
1147 /// one with no parameters is offered on them as it is.
1148 pub items: &'static [EffectTarget],
1149 /// How a row id becomes the first parameter's value, when the effect is
1150 /// offered on rows ([`EffectRow::row_id`]).
1151 pub row_id: Option<RowIdOf>,
1152 /// The phrase its caller types for a bound invocation
1153 /// ([`EffectRow::phrase`]).
1154 pub phrase: Option<PhraseOf>,
1155 /// A content transform the system may run on the invoker's best-placed
1156 /// device (`#[effect(offload(...))]`); the handler is its local run.
1157 pub offload: Option<EffectOffload>,
1158 /// Further contract tags, each naming how a host treats the effect
1159 /// (`#[effect(host_render)]`, `#[effect(tag = ...)]`): an agent's host
1160 /// routes a [`tilo_actions::HOST_RENDER_TAG`] effect to its render
1161 /// service rather than the app's worker.
1162 pub tags: &'static [&'static str],
1163 /// The parameter that, given, makes an invocation reach outside the
1164 /// record (`#[effect(kind = "read", outside_with = "path")]`): an export
1165 /// writing the file it names. Without it the invocation only reads and
1166 /// keeps what it made as content, and is admitted as a read.
1167 pub outside_with: Option<&'static str>,
1168}
1169
1170/// The contract tag of an effect that submits only edits of its record
1171/// ([`EffectDecl::edits`]): its kind is Undoable.
1172pub const EDITS_TAG: &str = "submits-edits";
1173
1174/// How an effect answers its caller.
1175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1176pub enum Answers {
1177 /// At once, with nothing to report.
1178 Nothing,
1179 /// At once, with a JSON value.
1180 Value,
1181 /// At once, with content: one `tilo.content` resource another app's
1182 /// content-collecting operation takes.
1183 Content,
1184 /// Later: a job that reports progress, then its result.
1185 Later {
1186 cancellable: bool,
1187 /// The completed job returns a JSON value, independently of its job id.
1188 returns: bool,
1189 },
1190}
1191
1192impl EffectDecl {
1193 /// The published action of this effect under `operation`, of the
1194 /// vocabulary `E` it is declared in.
1195 ///
1196 /// An effect whose fields are all optional runs when a person chooses
1197 /// it, asked nothing: a field left out is `None`, which the effect gives
1198 /// a meaning ("About"'s `open` left out switches the sheet). Asking
1199 /// instead put the first field's help text in the search field. One
1200 /// that takes an entry or content still asks for it.
1201 pub fn spec<E: Effect>(&self, operation: &'static str) -> ActionSpec {
1202 self.spec_checked(operation, check::<E>)
1203 }
1204
1205 /// [`Self::spec`] of a vocabulary that reads arguments back with `check`.
1206 fn spec_checked(&self, operation: &'static str, check: Check) -> ActionSpec {
1207 let build = encoder(check, operation, self.id, Bound::None);
1208 let spec = self.spec_with_boxed(operation, params_from(&self.params), Arc::new(build));
1209 let asks_words = matches!(
1210 spec.input(),
1211 tilo_actions::ActionInput::Prompted {
1212 collects: tilo_actions::Collects::Words,
1213 ..
1214 }
1215 );
1216 if asks_words && !self.prompted && !self.params.iter().any(|param| param.entry) {
1217 spec.with_immediate_per_target()
1218 } else {
1219 spec
1220 }
1221 }
1222
1223 /// The published action of this effect, as the vocabulary `E` that
1224 /// declares it publishes it: [`Self::spec`] under `E`'s own operation.
1225 pub fn spec_of<E: Effect>(&self) -> ActionSpec {
1226 self.spec::<E>(E::OPERATION)
1227 }
1228
1229 /// Every effect of a derived vocabulary, declared as `rows` say.
1230 #[doc(hidden)]
1231 #[must_use]
1232 pub fn of_rows(rows: &'static [EffectRow]) -> Vec<Self> {
1233 rows.iter().map(Self::of_row).collect()
1234 }
1235
1236 /// The effect `id` of a derived vocabulary declared as `rows` say.
1237 #[doc(hidden)]
1238 #[must_use]
1239 pub fn find_row(rows: &'static [EffectRow], id: &str) -> Option<Self> {
1240 rows.iter().find(|row| row.id == id).map(Self::of_row)
1241 }
1242
1243 pub fn of_row(row: &EffectRow) -> Self {
1244 Self {
1245 id: row.id,
1246 label: row.label.clone(),
1247 keywords: row.keywords,
1248 icon: row.icon,
1249 description: row.description,
1250 params: (row.params)(),
1251 param_types: (row.param_types)(),
1252 result: row.result,
1253 kind: row.kind,
1254 prompted: row.prompted,
1255 row: row.row,
1256 answers: row.answers,
1257 risk: row.risk,
1258 idempotent: row.idempotent,
1259 action_kind: row.action_kind,
1260 own_device: row.own_device,
1261 attended: row.attended,
1262 risk_of: row.risk_of,
1263 audience: row.audience,
1264 untrusted: row.untrusted,
1265 opens: row.opens,
1266 presence: row.presence,
1267 edits: row.edits,
1268 member: row.member,
1269 items: row.items,
1270 row_id: row.row_id,
1271 phrase: row.phrase,
1272 offload: row.offload,
1273 tags: row.tags,
1274 outside_with: row.outside_with,
1275 }
1276 }
1277
1278 /// What an invocation of this effect answers with: the value its type
1279 /// describes, the content it made, or a job's result.
1280 fn result_contract(&self) -> ResultSpec {
1281 match self.answers {
1282 Answers::Later { returns: false, .. } => ResultSpec::Job,
1283 Answers::Value | Answers::Later { returns: true, .. } => ResultSpec::Json {
1284 schema: self
1285 .result
1286 .map_or_else(|| serde_json::json!({}), |result| (result.schema)()),
1287 },
1288 Answers::Content => ResultSpec::Resource {
1289 resource_kind: tilo_actions::CONTENT_RESOURCE_KIND.to_owned(),
1290 },
1291 Answers::Nothing => ResultSpec::None,
1292 }
1293 }
1294
1295 /// The published action of this effect, taking `params` and encoding
1296 /// an invocation with `build`.
1297 /// What kind of action the effect is: a view reads, anything else
1298 /// reaches outside the document.
1299 #[must_use]
1300 pub fn action_kind(&self) -> crate::ActionKind {
1301 if self.edits {
1302 crate::ActionKind::Undoable
1303 } else if self.kind == OperationKind::View {
1304 crate::ActionKind::Read
1305 } else {
1306 crate::ActionKind::Outside
1307 }
1308 }
1309
1310 /// The tags the published contract carries: `base`'s, then what this effect declares of
1311 /// itself (its device, its audience, what it opens and who may call it).
1312 fn contract_tags(&self, base: &[String]) -> Vec<String> {
1313 let mut tags = base.to_vec();
1314 if self.own_device {
1315 tags.push(tilo_actions::OWN_DEVICE_SCOPE.to_owned());
1316 }
1317 if self.attended {
1318 tags.push(tilo_actions::ATTENDED_TAG.to_owned());
1319 }
1320 if let Some(tag) = self.audience.tag() {
1321 tags.push(tag.to_owned());
1322 }
1323 if self.untrusted {
1324 tags.push(tilo_actions::UNTRUSTED_CONTENT_TAG.to_owned());
1325 }
1326 if let Some(extensions) = self.opens {
1327 tags.push(tilo_actions::OPENS_PATH_TAG.to_owned());
1328 tags.extend(extensions.iter().map(|extension| {
1329 format!("{}{extension}", tilo_actions::OPENS_PATH_EXTENSION_PREFIX)
1330 }));
1331 }
1332 if self.presence {
1333 tags.push(tilo_actions::PRESENCE_VIEW_TAG.to_owned());
1334 }
1335 if self.edits {
1336 tags.push(EDITS_TAG.to_owned());
1337 }
1338 if self.member {
1339 tags.push(tilo_actions::MEMBER_OWN_TAG.to_owned());
1340 }
1341 tags.extend(self.tags.iter().map(|tag| (*tag).to_owned()));
1342 tags
1343 }
1344
1345 /// The published action of this effect, taking `params` and encoding an
1346 /// invocation with `build`. The builder is passed boxed: boxing at the
1347 /// call site keeps this out of every app's vocabulary instance.
1348 fn spec_with_boxed(
1349 &self,
1350 operation: &'static str,
1351 params: Vec<ActionParam>,
1352 build: tilo_actions::resource::ArgsBuilder,
1353 ) -> ActionSpec {
1354 let view = self.kind == OperationKind::View;
1355 let label = self.label.read();
1356 let params = crate::label::titled(&self.label, operation, params);
1357 let mut spec = if self.kind == OperationKind::Document {
1358 // A document operation belongs to the app's own registry, which
1359 // decodes the action and applies it as the record's change: its
1360 // type is the action's, not an operation the surface answers.
1361 ActionSpec::typed_on(
1362 self.id,
1363 label.clone(),
1364 label,
1365 tilo_actions::ExecutionLocus::ClientLocal,
1366 params,
1367 move |target: &Target, args: &tilo_actions::ActionArgs| build(target, args),
1368 )
1369 } else {
1370 ActionSpec::typed_operation_on(
1371 self.id,
1372 label.clone(),
1373 label,
1374 if view {
1375 OperationKind::View
1376 } else {
1377 OperationKind::Effect
1378 },
1379 operation,
1380 params,
1381 build,
1382 )
1383 };
1384 if !self.description.is_empty() {
1385 spec = spec.with_description(self.description);
1386 }
1387 if !self.keywords.is_empty() {
1388 spec = spec.with_keywords(self.keywords.iter().copied());
1389 }
1390 spec.type_mut().icon = self.icon.map(str::to_owned);
1391 let base = match self.kind {
1392 OperationKind::View => ActionContract::view(),
1393 OperationKind::Document => ActionContract::for_operation(OperationKind::Document),
1394 OperationKind::Effect => ActionContract::default(),
1395 };
1396 spec.type_mut().contract = ActionContract {
1397 kind: self.action_kind,
1398 risk: self.risk,
1399 confirmation: if matches!(
1400 self.risk,
1401 RiskLevel::Destructive | RiskLevel::Privileged | RiskLevel::Sensitive
1402 ) {
1403 ConfirmationPolicy::Confirm
1404 } else {
1405 ConfirmationPolicy::None
1406 },
1407 execution: match self.answers {
1408 Answers::Later { cancellable, .. } => ExecutionMode::Background { cancellable },
1409 Answers::Nothing | Answers::Value | Answers::Content => ExecutionMode::Immediate,
1410 },
1411 result: self.result_contract(),
1412 retry: if view || self.idempotent {
1413 RetryPolicy::Idempotent
1414 } else {
1415 base.retry
1416 },
1417 tags: self.contract_tags(&base.tags),
1418 offload: self.offload.as_ref().map(EffectOffload::contract),
1419 ..base
1420 };
1421 let spec = match self.outside_with {
1422 Some(param) => spec.with_need_of(outside_with(param, self.action_kind)),
1423 None => spec,
1424 };
1425 match self.risk_of {
1426 Some(classify) => spec.with_risk(classify),
1427 None => spec,
1428 }
1429 }
1430
1431 /// Whether the effect runs in the background, reporting its result later.
1432 pub fn is_job(&self) -> bool {
1433 matches!(self.answers, Answers::Later { .. })
1434 }
1435}
1436
1437/// What one invocation of an effect declared `outside_with = param` is:
1438/// reaching outside when `param` is given (the file an export writes), else
1439/// the `least` it was declared as.
1440fn outside_with(
1441 param: &'static str,
1442 least: ActionKind,
1443) -> impl Fn(&tilo_actions::ActionArgs) -> tilo_actions::ActionNeed + Send + Sync + 'static {
1444 move |args| {
1445 let given = args
1446 .to_json()
1447 .get(param)
1448 .is_some_and(|value| !value.is_null());
1449 tilo_actions::ActionNeed::of(if given { ActionKind::Outside } else { least })
1450 }
1451}
1452
1453/// The vocabulary of a surface that has no effects.
1454#[derive(Clone, Copy, Debug)]
1455pub enum NoEffect {}
1456
1457impl Effect for NoEffect {
1458 const OPERATION: &'static str = "tilo.no-effect";
1459
1460 fn declarations() -> Vec<EffectDecl> {
1461 Vec::new()
1462 }
1463
1464 fn rows() -> Vec<EffectRow> {
1465 Vec::new()
1466 }
1467
1468 // No value of the type exists to ask.
1469 fn id(&self) -> &'static str {
1470 ""
1471 }
1472
1473 fn arguments(&self) -> serde_json::Map<String, serde_json::Value> {
1474 serde_json::Map::new()
1475 }
1476
1477 fn decode(
1478 id: &str,
1479 _: &serde_json::Map<String, serde_json::Value>,
1480 ) -> Result<Self, EffectDecodeError> {
1481 Err(EffectDecodeError::Unknown(id.to_owned()))
1482 }
1483}
1484
1485/// Read one argument of an effect being decoded. An absent argument reads
1486/// as `null`, which an `Option` field takes as `None`.
1487#[doc(hidden)]
1488pub fn argument<T: serde::de::DeserializeOwned>(
1489 arguments: &serde_json::Map<String, serde_json::Value>,
1490 name: &str,
1491) -> Result<T, EffectDecodeError> {
1492 // Only the decode is per type: the lookup and the message are compiled
1493 // once for every argument of every effect.
1494 T::deserialize(argument_value(arguments, name)).map_err(|error| EffectDecodeError::Argument {
1495 name: name.to_owned(),
1496 source: error,
1497 })
1498}
1499
1500/// The effect's `#[param(flatten)]` struct, decoded from the invocation's
1501/// whole object. A field that does not decode is named by its path within
1502/// that object (`path`, or `adjust.grayscale` for one of a struct's
1503/// fields), so the caller hears the argument to fix rather than the struct
1504/// that carries it; `struct_name` names the field itself for a failure that
1505/// is not one field's, such as an unknown one.
1506#[doc(hidden)]
1507pub fn flattened_argument<T: serde::de::DeserializeOwned>(
1508 arguments: &serde_json::Map<String, serde_json::Value>,
1509 struct_name: &str,
1510) -> Result<T, EffectDecodeError> {
1511 // The path and the message live here, not in every effect's generated
1512 // decode.
1513 serde_path_to_error::deserialize(serde_json::Value::Object(arguments.clone())).map_err(
1514 |error| {
1515 let path = error.path().to_string();
1516 EffectDecodeError::Argument {
1517 name: if path.is_empty() {
1518 struct_name.to_owned()
1519 } else {
1520 path
1521 },
1522 source: error.into_inner(),
1523 }
1524 },
1525 )
1526}
1527
1528/// The identity argument `name`: canonical decimal text, as a record and a
1529/// surface name their windows, strips, groups and workspaces by. A salted id
1530/// outgrows what a JSON number carries exactly, so it travels as text; any
1531/// other text names no id, and is refused here rather than taken for one.
1532pub fn identity_argument(
1533 arguments: &serde_json::Map<String, serde_json::Value>,
1534 name: &str,
1535) -> Result<String, EffectDecodeError> {
1536 match argument_value(arguments, name) {
1537 serde_json::Value::String(text) => identity(name, &text),
1538 serde_json::Value::Null => Err(EffectDecodeError::Argument {
1539 name: name.to_owned(),
1540 source: serde::de::Error::custom("is required"),
1541 }),
1542 other => Err(not_an_identity(name, other.to_string())),
1543 }
1544}
1545
1546/// [`identity_argument`] for an identity that need not be given.
1547pub fn optional_identity_argument(
1548 arguments: &serde_json::Map<String, serde_json::Value>,
1549 name: &str,
1550) -> Result<Option<String>, EffectDecodeError> {
1551 match argument_value(arguments, name) {
1552 serde_json::Value::Null => Ok(None),
1553 serde_json::Value::String(text) => identity(name, &text).map(Some),
1554 other => Err(not_an_identity(name, other.to_string())),
1555 }
1556}
1557
1558/// `text` as an identity of `name`, its decimal form being its own.
1559fn identity(name: &str, text: &str) -> Result<String, EffectDecodeError> {
1560 let canonical = text.parse::<u64>().is_ok_and(|id| id.to_string() == text);
1561 if canonical {
1562 return Ok(text.to_owned());
1563 }
1564 Err(not_an_identity(name, text.to_owned()))
1565}
1566
1567/// Why `value`, given for the identity `name`, names no id.
1568fn not_an_identity(name: &str, value: String) -> EffectDecodeError {
1569 EffectDecodeError::Identity {
1570 name: name.to_owned(),
1571 value,
1572 }
1573}
1574
1575/// The argument `name`, or `null` when it is absent.
1576#[inline(never)]
1577fn argument_value(
1578 arguments: &serde_json::Map<String, serde_json::Value>,
1579 name: &str,
1580) -> serde_json::Value {
1581 arguments
1582 .get(name)
1583 .cloned()
1584 .unwrap_or(serde_json::Value::Null)
1585}
1586
1587/// Put one argument of an effect being encoded; an absent optional one
1588/// (`null`) is left out, as a caller leaves it out.
1589#[doc(hidden)]
1590pub fn put<T: serde::Serialize>(
1591 arguments: &mut serde_json::Map<String, serde_json::Value>,
1592 name: &str,
1593 value: &T,
1594) {
1595 match crate::__private::json_via_bytes(value) {
1596 Ok(serde_json::Value::Null) | Err(_) => {}
1597 Ok(value) => {
1598 arguments.insert(name.to_owned(), value);
1599 }
1600 }
1601}
1602
1603#[cfg(test)]
1604mod tests {
1605 use super::*;
1606 use crate::Effect;
1607
1608 /// What the derive must produce, checked through the spec a caller sees.
1609 #[derive(Clone, Debug, PartialEq, Effect)]
1610 #[effect(operation = "test.effects", catalogue = "tests/locales")]
1611 enum Sample {
1612 /// Reload everything.
1613 #[effect(kind = "outside")]
1614 Reload,
1615 /// Rename a thing.
1616 ///
1617 /// It keeps its id.
1618 #[effect(returns, kind = "read")]
1619 RenameThing {
1620 #[param("The thing")]
1621 thing: String,
1622 label: Option<String>,
1623 },
1624 #[effect(kind = "outside")]
1625 #[effect(job, cancellable, destructive)]
1626 Wipe { passes: u32 },
1627 /// Copy a thing's key.
1628 #[effect(privileged, kind = "read")]
1629 CopyKey { thing: String },
1630 /// Paint a thing.
1631 #[effect(kind = "outside")]
1632 Paint {
1633 #[param("The colour", choices = ["red", "green"])]
1634 colour: String,
1635 // `Self` in an attribute reaches the rows' static as the enum.
1636 #[param(choices = Self::SHADES)]
1637 shade: Option<String>,
1638 },
1639 /// Widen a column.
1640 #[effect(kind = "outside")]
1641 Widen {
1642 #[param(decimal, "The column")]
1643 column: String,
1644 #[param(decimal, "The table")]
1645 table: Option<String>,
1646 #[param("The width")]
1647 width: u32,
1648 },
1649 }
1650
1651 impl Sample {
1652 const SHADES: [&str; 2] = ["light", "dark"];
1653 }
1654
1655 /// A content transform declared offloadable.
1656 #[derive(Clone, Debug, PartialEq, Effect)]
1657 #[effect(operation = "test.transforms", catalogue = "tests/locales")]
1658 enum Transforms {
1659 /// Shrink images.
1660 #[effect(
1661 content,
1662 idempotent,
1663 kind = "read",
1664 offload(cpu_ms = 60000, memory_mb = 512, output_mb = 8)
1665 )]
1666 Shrink {
1667 #[param(content, "The images")]
1668 images: Vec<String>,
1669 },
1670 /// Copy an image.
1671 #[effect(content, kind = "read")]
1672 Copy {
1673 #[param(content, "The image")]
1674 image: String,
1675 },
1676 }
1677
1678 tilo_test_env::scenario! {
1679 fn an_effect_declares_publishes_and_binds_what_its_type_says;
1680
1681 phase an_offload_option_declares_a_valid_offloadable_contract;
1682 {
1683 let specs = Transforms::specs();
1684 let shrink = &specs[0];
1685 assert_eq!(
1686 shrink.contract.offload,
1687 Some(tilo_actions::Offload {
1688 gpu: false,
1689 cpu_time_ms: 60_000,
1690 memory_bytes: 512 * 1024 * 1024,
1691 output_bytes: 8 * 1024 * 1024,
1692 })
1693 );
1694 assert_eq!(shrink.contract.kind, ActionKind::Read);
1695 assert!(
1696 shrink.contract.validate_declaration().is_empty(),
1697 "{:?}",
1698 shrink.contract.validate_declaration()
1699 );
1700 assert_eq!(specs[1].contract.offload, None, "only where declared");
1701 assert!(shrink.params()[0].is_content_list());
1702 assert!(specs[1].params()[0].is_content());
1703 }
1704
1705 phase a_derived_vocabulary_publishes_each_variant_and_round_trips_through_its_spec;
1706 {
1707 let specs = Sample::specs();
1708 let ids: Vec<&str> = specs.iter().map(|spec| spec.id.as_str()).collect();
1709 assert_eq!(
1710 ids,
1711 [
1712 "reload",
1713 "rename-thing",
1714 "wipe",
1715 "copy-key",
1716 "paint",
1717 "widen"
1718 ]
1719 );
1720
1721 let rename = &specs[1];
1722 assert_eq!(rename.label, "Rename a thing");
1723 assert_eq!(
1724 rename.description.as_deref(),
1725 Some("Rename a thing. It keeps its id.")
1726 );
1727 assert_eq!(rename.kind, OperationKind::Effect);
1728 assert_eq!(rename.contract.kind, ActionKind::Read);
1729 assert!(matches!(rename.contract.result, ResultSpec::Json { .. }));
1730 assert_eq!(rename.contract.execution, ExecutionMode::Immediate);
1731
1732 // A parameter carries its type's schema, as a verb's does: it is
1733 // what a caller of another language reads of the argument.
1734 let schema_type = |param: &tilo_actions::ActionParam| {
1735 param
1736 .schema
1737 .as_deref()
1738 .and_then(|schema| schema.get("type"))
1739 .cloned()
1740 };
1741 assert_eq!(
1742 schema_type(&rename.params()[0]),
1743 Some(serde_json::json!("string"))
1744 );
1745 assert_eq!(
1746 schema_type(&specs[2].params()[0]),
1747 Some(serde_json::json!("integer"))
1748 );
1749
1750 let paint = &specs[4];
1751 assert_eq!(paint.params()[0].description, "The colour");
1752 let choices = |index: usize| -> Vec<&str> {
1753 paint.params()[index]
1754 .choices
1755 .iter()
1756 .map(std::convert::AsRef::as_ref)
1757 .collect()
1758 };
1759 assert_eq!(choices(0), ["red", "green"]);
1760 assert_eq!(choices(1), ["light", "dark"]);
1761 assert!(!paint.params()[1].required);
1762
1763 let wipe = &specs[2];
1764 assert_eq!(wipe.label, "Wipe");
1765 assert_eq!(wipe.contract.risk, RiskLevel::Destructive);
1766 assert_eq!(wipe.contract.confirmation, ConfirmationPolicy::Confirm);
1767 assert_eq!(
1768 wipe.contract.execution,
1769 ExecutionMode::Background { cancellable: true }
1770 );
1771
1772 // A caller's arguments, encoded by the published spec, decode to the
1773 // value the handler receives.
1774 let value = Sample::RenameThing {
1775 thing: "a".into(),
1776 label: None,
1777 };
1778 let encoded = rename.build_json(&value.arguments()).unwrap();
1779 assert_eq!(encoded.type_id, "test.effects");
1780 assert_eq!(Sample::from_payload(&encoded.payload).unwrap(), value);
1781 assert_eq!(
1782 Sample::from_payload(
1783 &specs[0]
1784 .build_json(&serde_json::Map::new())
1785 .unwrap()
1786 .payload
1787 )
1788 .unwrap(),
1789 Sample::Reload
1790 );
1791 assert!(Sample::decode("wipe", &serde_json::Map::new()).is_err());
1792
1793 let bound = Sample::Wipe { passes: 3 }.bound();
1794 assert_eq!(bound.id, "wipe");
1795 assert_eq!(bound.label, "Wipe");
1796 assert!(bound.params().is_empty());
1797 assert_eq!(bound.contract.confirmation, ConfirmationPolicy::Confirm);
1798 let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
1799 assert_eq!(
1800 Sample::from_payload(&encoded.payload).unwrap(),
1801 Sample::Wipe { passes: 3 }
1802 );
1803 assert!(Sample::decode("format", &serde_json::Map::new()).is_err());
1804
1805 let asking = Sample::RenameThing {
1806 thing: "a".into(),
1807 label: None,
1808 }
1809 .bound_asking(&["label"]);
1810 assert_eq!(asking.id, "rename-thing");
1811 let asked: Vec<&str> = asking.params().iter().map(|param| &*param.name).collect();
1812 assert_eq!(asked, ["label"]);
1813 let mut label = serde_json::Map::new();
1814 label.insert("label".into(), "b".into());
1815 let encoded = asking.build_json(&label).unwrap();
1816 assert_eq!(
1817 Sample::from_payload(&encoded.payload).unwrap(),
1818 Sample::RenameThing {
1819 thing: "a".into(),
1820 label: Some("b".into()),
1821 }
1822 );
1823 }
1824
1825 phase an_identity_argument_is_decimal_text_and_is_refused_otherwise;
1826 // An identity travels as decimal text, and one that names no id is
1827 // refused when the invocation is encoded: the API answers a caller that
1828 // names something the effect cannot act on, rather than a host failing
1829 // to read it.
1830 {
1831 let widen = Sample::spec("widen").unwrap();
1832 let encoded = |arguments: serde_json::Value| -> Result<String, String> {
1833 let arguments: serde_json::Map<String, serde_json::Value> =
1834 serde_json::from_value(arguments).expect("a test's call is an object");
1835 widen
1836 .build_json(&arguments)
1837 .map(|built| built.type_id)
1838 .map_err(|error| error.to_string())
1839 };
1840 assert_eq!(
1841 encoded(serde_json::json!({"column": "9007199254740993", "width": 80})),
1842 Ok("test.effects".to_owned()),
1843 "a salted id outgrows a JSON number, and travels as text"
1844 );
1845 for refused in [
1846 serde_json::json!({"column": "left", "width": 80}),
1847 serde_json::json!({"column": "07", "width": 80}),
1848 serde_json::json!({"column": "1", "table": "wide", "width": 80}),
1849 ] {
1850 assert_eq!(
1851 encoded(refused.clone()),
1852 Ok(tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned()),
1853 "{refused}"
1854 );
1855 }
1856 let not_text = encoded(serde_json::json!({"column": 7, "width": 80}));
1857 assert!(
1858 not_text.is_err(),
1859 "an id is text, never a number: {not_text:?}"
1860 );
1861 }
1862
1863 phase views_publish_as_views_and_row_effects_only_bound_to_their_item;
1864 {
1865 let specs = Rows::specs();
1866 let ids: Vec<&str> = specs.iter().map(|spec| spec.id.as_str()).collect();
1867 assert_eq!(
1868 ids,
1869 ["search"],
1870 "a row effect is not offered on the resource"
1871 );
1872 let search = &specs[0];
1873 assert_eq!(search.kind, OperationKind::View);
1874 assert_eq!(search.contract.kind, ActionKind::Read);
1875 assert_eq!(search.contract.risk, RiskLevel::None);
1876 assert_eq!(search.contract.retry, RetryPolicy::Idempotent);
1877
1878 let open = Rows::Open { item: "a".into() };
1879 let bound = open.bound();
1880 assert_eq!(
1881 (bound.id.as_str(), bound.kind),
1882 ("open", OperationKind::View)
1883 );
1884 assert!(bound.params().is_empty());
1885 let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
1886 assert_eq!(encoded.type_id, "test.rows");
1887 assert_eq!(Rows::from_payload(&encoded.payload).unwrap(), open);
1888
1889 let connect = Rows::Connect { item: "b".into() }.bound();
1890 assert_eq!(connect.kind, OperationKind::Effect);
1891 assert_eq!(connect.contract.kind, ActionKind::Outside);
1892 assert_eq!(connect.contract.retry, RetryPolicy::Idempotent);
1893 assert_eq!(
1894 connect.contract.execution,
1895 ExecutionMode::Background { cancellable: false }
1896 );
1897 assert_eq!(
1898 Sample::specs()[0].contract.retry,
1899 RetryPolicy::AtMostOnce,
1900 "an effect is not repeated unless it says it may be"
1901 );
1902 }
1903
1904 phase a_privileged_effect_asks_first_and_binds_to_the_entity_it_names;
1905 {
1906 let copy = Sample::CopyKey { thing: "a".into() };
1907 let bound = copy.bound();
1908 assert_eq!(bound.id, "copy-key");
1909 assert_eq!(bound.label, "Copy a thing's key");
1910 assert_eq!(bound.kind, OperationKind::Effect);
1911 assert!(bound.params().is_empty(), "the row names the thing already");
1912 assert_eq!(bound.contract.risk, RiskLevel::Privileged);
1913 assert_eq!(bound.contract.confirmation, ConfirmationPolicy::Confirm);
1914 assert_eq!(bound.contract.kind, ActionKind::Read);
1915 let encoded = bound.build_json(&serde_json::Map::new()).unwrap();
1916 assert_eq!(encoded.type_id, "test.effects");
1917 assert_eq!(Sample::from_payload(&encoded.payload).unwrap(), copy);
1918 }
1919
1920 phase a_sensitive_effect_asks_first;
1921 {
1922 let spec = Exports::ExportBook.bound();
1923 assert_eq!(spec.contract.risk, RiskLevel::Sensitive);
1924 assert_eq!(spec.contract.confirmation, ConfirmationPolicy::Confirm);
1925 }
1926
1927 phase a_secret_parameter_is_published_as_a_secret;
1928 {
1929 let specs = Pairing::specs();
1930 let params = specs[0].params();
1931 assert_eq!(params[0].ty, tilo_actions::ParamType::Secret);
1932 assert_eq!(&*params[0].description, "The invite the other device shows");
1933 assert_eq!(params[1].ty, tilo_actions::ParamType::Secret);
1934 assert!(!params[1].required);
1935 let value = Pairing::Pair {
1936 invite: "grayjay://invite".into(),
1937 pin: None,
1938 };
1939 let encoded = specs[0].build_json(&value.arguments()).unwrap();
1940 assert_eq!(Pairing::from_payload(&encoded.payload).unwrap(), value);
1941 }
1942
1943 phase a_path_parameter_refuses_a_relative_path;
1944 {
1945 let specs = Files::specs();
1946 let params = specs[0].params();
1947 assert_eq!(params[0].ty, tilo_actions::ParamType::Text);
1948 assert!(params[0].required);
1949 assert_eq!(params[1].ty, tilo_actions::ParamType::Text);
1950 assert!(!params[1].required);
1951 let arguments = |path: &str, folder: Option<&str>| {
1952 let mut arguments = serde_json::Map::new();
1953 arguments.insert("path".into(), path.into());
1954 if let Some(folder) = folder {
1955 arguments.insert("folder".into(), folder.into());
1956 }
1957 arguments
1958 };
1959 let error = Files::decode("save-copy", &arguments("copy.txt", None)).unwrap_err();
1960 assert!(
1961 matches!(
1962 &error,
1963 EffectDecodeError::Argument { name, source }
1964 if name == "path" && source.to_string().contains("absolute")
1965 ),
1966 "{error}"
1967 );
1968 assert!(Files::decode("save-copy", &arguments("/a/copy.txt", Some("b"))).is_err());
1969 let value = Files::decode("save-copy", &arguments("/a/copy.txt", Some("/b"))).unwrap();
1970 let encoded = specs[0].build_json(&value.arguments()).unwrap();
1971 assert_eq!(Files::from_payload(&encoded.payload).unwrap(), value);
1972 }
1973
1974 phase variant_refs_bind_controls_by_id;
1975 {
1976 assert_eq!(Sample::RENAME_THING.id, "rename-thing");
1977 assert_eq!(
1978 Sample::RENAME_THING
1979 .arguments(&("b".to_owned(), Some("B".to_owned())))
1980 .unwrap(),
1981 Sample::RenameThing {
1982 thing: "b".into(),
1983 label: Some("B".into())
1984 }
1985 .arguments()
1986 );
1987 }
1988 }
1989
1990 /// A vocabulary with presentation-only effects and effects offered only
1991 /// on the items they act on.
1992 #[derive(Clone, Debug, PartialEq, Effect)]
1993 #[effect(operation = "test.rows", catalogue = "tests/locales")]
1994 enum Rows {
1995 /// Open an item.
1996 #[effect(view, row)]
1997 Open { item: String },
1998 /// Connect to an item.
1999 #[effect(kind = "outside")]
2000 #[effect(row, job, idempotent)]
2001 Connect { item: String },
2002 /// Search.
2003 #[effect(view)]
2004 Search,
2005 }
2006
2007 /// A copy of private data leaving the app asks first, without being a
2008 /// credential or a deletion.
2009 #[derive(Clone, Debug, PartialEq, Effect)]
2010 #[effect(operation = "test.exports", catalogue = "tests/locales")]
2011 enum Exports {
2012 /// Export the address book.
2013 #[effect(kind = "outside")]
2014 #[effect(job, sensitive)]
2015 ExportBook,
2016 }
2017
2018 /// A secret argument is published as one, and still reaches the handler.
2019 #[derive(Clone, Debug, PartialEq, Effect)]
2020 #[effect(operation = "test.secrets", catalogue = "tests/locales")]
2021 enum Pairing {
2022 /// Pair a device.
2023 #[effect(kind = "outside")]
2024 Pair {
2025 #[param(secret, "The invite the other device shows")]
2026 invite: String,
2027 #[param(secret)]
2028 pin: Option<String>,
2029 },
2030 }
2031
2032 #[derive(Clone, Debug, PartialEq, Effect)]
2033 #[effect(operation = "test.files", catalogue = "tests/locales")]
2034 enum Files {
2035 /// Save a copy.
2036 #[effect(kind = "outside")]
2037 SaveCopy {
2038 #[param("Where to write it")]
2039 path: crate::AbsolutePath,
2040 folder: Option<crate::AbsolutePath>,
2041 },
2042 }
2043
2044 /// The ids a device mints: a desktop id carries its salt in the high 16
2045 /// bits, so more than half of them outgrow an `i64`.
2046 #[derive(Clone, Debug, PartialEq, Effect)]
2047 #[effect(operation = "test.ids", catalogue = "tests/locales")]
2048 enum Ids {
2049 /// Stand a resource in a strip.
2050 #[effect(kind = "undoable")]
2051 Place {
2052 #[param("The strip it stands in")]
2053 strip: u64,
2054 #[param("The place's own id; a new one when left out")]
2055 place: Option<u64>,
2056 #[param(resource = "", "The resource it shows")]
2057 resource: String,
2058 },
2059 }
2060
2061 /// A caller encodes an invocation through the published spec and its
2062 /// handler decodes it there: one declaration writes both sides, so what a
2063 /// caller gives — an id past `i64::MAX` included — is what the effect reads.
2064 #[test]
2065 fn an_effects_named_arguments_round_trip_through_its_spec() {
2066 let spec = Ids::specs().remove(0);
2067 let salted = 0xB3A1_0000_0000_0001_u64;
2068 let arguments = serde_json::json!({
2069 "strip": salted,
2070 "place": salted,
2071 "resource": "notes:1",
2072 })
2073 .as_object()
2074 .expect("arguments")
2075 .clone();
2076 let encoded = spec.build_json(&arguments).expect("the place encodes");
2077 assert_eq!(
2078 encoded.type_id,
2079 Ids::OPERATION,
2080 "the place is encoded as its own operation, not a refusal: {:?}",
2081 String::from_utf8_lossy(&encoded.payload)
2082 );
2083 assert_eq!(
2084 Ids::from_payload(&encoded.payload).expect("the place decodes"),
2085 Ids::Place {
2086 strip: salted,
2087 place: Some(salted),
2088 resource: "notes:1".into(),
2089 }
2090 );
2091 }
2092
2093 /// A content transform whose inputs are the bytes themselves.
2094 #[derive(Clone, Debug, PartialEq, Effect)]
2095 #[effect(operation = "test.readers", catalogue = "tests/locales")]
2096 enum Readers {
2097 /// Open documents.
2098 #[effect(kind = "read")]
2099 Open {
2100 #[param(content, "The documents")]
2101 documents: Vec<crate::Bytes>,
2102 },
2103 }
2104
2105 /// An effect is never replayed: the content its arguments name is read
2106 /// where the effect runs. A caller's address — a `tilo.content:<hash>`
2107 /// an operation collecting content answers, or the reference alone, as
2108 /// requests named it before content was sealed — decodes into the
2109 /// reference that opens exactly those bytes.
2110 #[test]
2111 fn an_effects_content_argument_is_read_where_the_effect_runs() {
2112 let window = tilo_wake::WakeScope::new();
2113 let workspace = tilo_content::ContentStore::memory_in_workspace().sealing();
2114 crate::content::register(&window.handle(), workspace.clone());
2115 let _entered = window.enter();
2116 let documents: Vec<Vec<u8>> = [7_u8, 8].into_iter().map(|byte| vec![byte; 4096]).collect();
2117 let references: Vec<String> = documents
2118 .iter()
2119 .map(|bytes| workspace.put(bytes).expect("kept"))
2120 .collect();
2121 let arguments = serde_json::Map::from_iter([(
2122 "documents".to_owned(),
2123 serde_json::json!([
2124 tilo_actions::content_resource(&references[0]).expect("an address"),
2125 references[1].clone(),
2126 ]),
2127 )]);
2128 let spec = Readers::specs().remove(0);
2129 assert!(spec.params()[0].is_content_list());
2130 let encoded = crate::content::invoking(|| spec.build_json(&arguments).unwrap());
2131
2132 let Readers::Open { documents: read } =
2133 Readers::from_payload(&encoded.payload).expect("read where it runs");
2134 assert_eq!(read.len(), 2);
2135 for (read, kept) in read.iter().zip(&references) {
2136 assert_eq!(
2137 read.reference().as_deref(),
2138 Some(kept.as_str()),
2139 "the reference that opens exactly those bytes"
2140 );
2141 assert!(read.read(&workspace).is_some(), "and the bytes themselves");
2142 }
2143 }
2144}