1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! A resource type's actions with the type erased.
//!
//! What the framework publishes for a resource — its declared actions,
//! `apply`, `group`, field edits, item resources and their schemas — is the
//! same for every resource, apart from a few facts and functions of the
//! type: its kind and label, its declarations, how a JSON value or a field
//! edit becomes one of its actions. A [`Vocabulary`] gathers those once per
//! type and a [`Built`] carries one of its actions without its type, so the
//! publishing code is compiled once rather than once per resource of every
//! app.
use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use tilo_actions::{
ActionArgs, ActionError, ActionNeed, ActionParam, ActionSpec, EncodedAction, ResourceViewSpec,
RiskLevel,
};
use crate::action::ActionKind;
use crate::collection::Id;
use crate::path::Edit;
use crate::resource::Resource;
use crate::shape::Shape;
/// One action of some resource, built and not yet encoded.
pub struct Built(Box<dyn AnyAction>);
/// What the framework does with a built action, whatever its type.
trait AnyAction {
fn stamp(&mut self, now_ms: i64);
fn action_type(&self) -> &'static str;
fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error>;
fn need(&self) -> ActionNeed;
fn risk(&self) -> RiskLevel;
fn undoable(&self) -> bool;
fn by_app(&self) -> bool;
fn into_any(self: Box<Self>) -> Box<dyn Any>;
}
struct Typed<R: Resource>(R::Action);
impl<R: Resource> AnyAction for Typed<R> {
fn stamp(&mut self, now_ms: i64) {
R::stamp(&mut self.0, now_ms);
}
fn action_type(&self) -> &'static str {
R::ACTION_TYPE
}
fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
serde_json::to_writer(out, &self.0)
}
fn need(&self) -> ActionNeed {
crate::resource::need_of::<R>(&self.0)
}
fn risk(&self) -> RiskLevel {
tilo_actions::Action::risk(&self.0)
}
fn undoable(&self) -> bool {
tilo_actions::undo_takes_back(
tilo_actions::Action::action_kind(&self.0),
tilo_actions::Action::change_kind(&self.0),
tilo_actions::Action::irreversible(&self.0),
)
}
fn by_app(&self) -> bool {
R::by_app(&self.0)
}
fn into_any(self: Box<Self>) -> Box<dyn Any> {
Box::new(self.0)
}
}
impl Built {
#[must_use]
pub fn of<R: Resource>(action: R::Action) -> Self {
Self(Box::new(Typed::<R>(action)))
}
/// Stamp the origin's clock on it ([`Resource::stamp`]).
pub fn stamp(&mut self, now_ms: i64) {
self.0.stamp(now_ms);
}
/// What it is, for the grants deciding it ([`crate::need_of`]).
#[must_use]
pub fn need(&self) -> ActionNeed {
self.0.need()
}
/// Its consequence class.
#[must_use]
pub fn risk(&self) -> RiskLevel {
self.0.risk()
}
/// Whether Undo takes it back: a person's change of the document alone.
#[must_use]
pub fn undoable(&self) -> bool {
self.0.undoable()
}
/// Whether only the app's own code applies it
/// ([`Resource::by_app`]): no caller's value is one.
#[must_use]
pub fn by_app(&self) -> bool {
self.0.by_app()
}
/// Encoded under its resource's registry type id.
///
/// # Errors
/// Returns [`ActionError::Encode`] when the action does not serialize.
pub fn encode(&self) -> Result<EncodedAction, ActionError> {
let mut payload = Vec::with_capacity(128);
self.0
.write_json(&mut payload)
.map_err(ActionError::Encode)?;
Ok(EncodedAction {
type_id: self.0.action_type().to_owned(),
payload,
})
}
/// Its JSON form, appended to `out`.
pub(crate) fn write_json(&self, out: &mut Vec<u8>) -> Result<(), serde_json::Error> {
self.0.write_json(out)
}
/// The action as the type of the resource `R` it was built for; `None`
/// when it is another resource's.
#[must_use]
pub fn into_action<R: Resource>(self) -> Option<R::Action> {
self.0
.into_any()
.downcast::<R::Action>()
.ok()
.map(|action| *action)
}
}
/// Builds a resource's action from arguments already bound against the
/// declaration's parameters. `now_ms` is the origin's clock, captured once so
/// replay is deterministic.
pub type Builds = Arc<dyn Fn(&ActionArgs, i64) -> Result<Built, String> + Send + Sync>;
/// One mutation offered by name, of whichever resource: what
/// [`ActionDecl`](crate::ActionDecl) holds for its resource type.
#[derive(Clone)]
pub struct Declaration {
pub id: &'static str,
/// What a person reads it by, in the language it was declared in.
pub label: String,
/// The declared word [`Self::label`] is the source text of, read in the
/// person's language each time the action is published.
pub word: Option<crate::label::Word>,
/// The other words people use for the action
/// ([`tilo_actions::ActionSpec::keywords`]).
pub keywords: Vec<String>,
/// The action's own picture, by its Lucide name
/// ([`tilo_actions::ActionSpec::icon`]).
pub icon: Option<String>,
/// What the action did, in the app's own words
/// (`did = "renamed"`): the past-tense form a record of what was done
/// reads ([`tilo_actions::ActionSpec::did`]).
pub did: Option<String>,
pub description: Option<String>,
pub params: Vec<ActionParam>,
/// What the action is able to do. See [`tilo_actions::ActionContract::kind`].
pub kind: ActionKind,
/// Whether one invocation's kind is decided by its arguments, `kind`
/// being the least it is: every check asks the action built from them.
pub by_arguments: bool,
/// The one field it writes, if only one. See [`Resource::field_of`].
pub field: Option<&'static str>,
pub destructive: bool,
/// What the action answers its caller with, beside the change: the state
/// it left, as the declaring resource's surface reports it.
pub result: Option<tilo_actions::ResultSpec>,
/// Contract tags its callers read: a precondition on the invoker's view
/// (`ContextRequirement`), a text that may arrive in parts.
pub tags: Vec<String>,
/// The prompt of an action whose one input is content another action
/// produced (an image to place), carried by its callers rather than
/// typed: the build reads its content hash as the
/// [`PROMPTED_PARAM`](tilo_actions::PROMPTED_PARAM) argument.
pub content: Option<String>,
/// A bound edit that refines the resource's declared action of the same
/// id: it builds the same action from the same arguments, and also
/// places its invoker (the caret an append leaves its writer at).
/// See [`bind_declaration`](crate::bind_declaration).
pub refines: bool,
/// The kind of step it takes, as it declares it
/// ([`tilo_actions::StepKind`]), published with its contract.
pub step: Option<tilo_actions::StepKind>,
/// The collection of its resource it adds to, when it is a create whose
/// declaration names one (`writes = issues`): what the step makes, so a
/// surface says that collection's own noun ("Creating an issue in Issues").
pub creates: Option<&'static str>,
/// The collection whose item it acts on, when it is an item verb
/// (`#[action(item = issues)]`): published on the resource itself, it
/// says it needs an item ([`tilo_actions::ActionContract::item`]), and
/// each item offers it with the item bound.
pub item: Option<&'static str>,
/// The units the action writes ([`crate::footprint`]): `record`, an
/// item's unit, declared fields'.
pub writes: Vec<String>,
/// The kind of resource it is declared on ([`Resource::KIND`]).
pub resource: &'static str,
/// The registry type id the action it builds replays under
/// ([`Resource::ACTION_TYPE`]).
pub action_type: &'static str,
pub build: Builds,
/// The resource's own published action this one invokes, and the
/// arguments it fixes of it: a bound field edit is the resource's field
/// edit of that edit, a bound verb that verb with its bound values. What
/// another provider keeping the resource runs it as.
pub invokes: Option<(String, serde_json::Map<String, serde_json::Value>)>,
/// The type of each parameter the code declares by its Rust type
/// ([`JsonSchema::field_type`](crate::JsonSchema::field_type)), by name:
/// what the surface publishes of it. A parameter without one is
/// published as its schema says.
pub param_types: Vec<(&'static str, ParamFieldType)>,
/// For a flattened parameter, its record's fields and their types, by
/// name: the verb's own parameters even though the code declares one.
pub flat_types: Option<crate::surface::FlatTypes>,
/// The type of the value it answers with, when the code declares one
/// ([`JsonSchema::field_type`](crate::JsonSchema::field_type)): what the
/// surface publishes of its result.
pub result_type: Option<ParamFieldType>,
}
/// How a parameter's [`FieldType`](crate::FieldType) is worked out,
/// declaring the records and enums it names.
pub type ParamFieldType = crate::surface::FieldTypeOf;
impl AsRef<Self> for Declaration {
fn as_ref(&self) -> &Self {
self
}
}
impl Declaration {
/// What a person reads it by now, in their language.
#[must_use]
pub fn shown_label(&self) -> String {
self.word
.as_ref()
.map_or_else(|| self.label.clone(), crate::label::Word::read)
}
/// Its parameters, each called what the person reads it by where its
/// catalogue has a word for it ([`crate::label::titled`]).
#[must_use]
pub fn shown_params(&self) -> Vec<ActionParam> {
match &self.word {
Some(word) => crate::label::titled(word, self.resource, self.params.clone()),
None => self.params.clone(),
}
}
/// The declaration `id` of the resource `vocabulary`, labelled `label`,
/// taking `params`, built by `build`.
pub(crate) fn new(
vocabulary: &Vocabulary,
id: &'static str,
label: String,
params: Vec<ActionParam>,
build: Builds,
) -> Self {
Self {
id,
label,
word: None,
keywords: Vec::new(),
icon: None,
did: None,
description: None,
params,
kind: ActionKind::Undoable,
by_arguments: false,
field: None,
destructive: false,
result: None,
tags: Vec::new(),
content: None,
refines: false,
step: None,
creates: None,
item: None,
writes: vec![crate::footprint::RESOURCE_UNIT.to_owned()],
resource: vocabulary.kind,
action_type: vocabulary.action_type,
build,
invokes: None,
param_types: Vec::new(),
flat_types: None,
result_type: None,
}
}
}
/// What the framework's publishing code needs of one resource type, as
/// plain values and functions. See the [module docs](self).
pub struct Vocabulary {
/// [`Resource::KIND`].
pub kind: &'static str,
/// [`Resource::APP_ID`].
pub app: &'static str,
/// [`Resource::LABEL`].
pub label: &'static str,
/// [`Resource::CATALOGUE`].
pub catalogue: Option<&'static crate::label::Catalogue>,
/// [`Resource::ACTION_TYPE`].
pub action_type: &'static str,
/// [`Resource::EDITS`].
pub edits: bool,
/// [`Resource::READERS`].
pub readers: &'static str,
/// [`Resource::RESOURCE_TABLE`].
pub(crate) resource_table: Option<&'static crate::table::ModelTable>,
pub(crate) type_id: fn() -> TypeId,
pub(crate) shape: fn() -> Option<Shape>,
pub(crate) op_schemas: fn() -> Vec<(String, serde_json::Value)>,
pub(crate) action_schema: fn() -> Option<serde_json::Value>,
pub(crate) least_need: fn() -> ActionNeed,
/// Builds every declaration afresh; read them through
/// [`Vocabulary::declarations`], which keeps them.
pub(crate) declare: fn() -> Vec<Declaration>,
pub(crate) item_effects: fn(&str, &Id) -> Vec<ActionSpec>,
pub(crate) item_views: fn(&str, &Id) -> Vec<ResourceViewSpec>,
/// An action from its JSON form (serde's), unstamped.
pub(crate) read: fn(serde_json::Value) -> Result<Built, String>,
/// The action a field edit is ([`Resource::edit_action`]), unstamped.
pub(crate) edit: fn(Edit<()>) -> Option<Built>,
}
impl Vocabulary {
/// The field edit `edit` a caller sent, its path read from the record's
/// root ([`Edit::past_resource_name`]): the record answers to the last
/// part of its kind and to its label.
pub(crate) fn rooted_edit(&self, edit: Edit<()>) -> Result<Edit<()>, String> {
let Some(shape) = (self.shape)() else {
return Ok(edit);
};
let kind = self.kind.rsplit('.').next().unwrap_or(self.kind);
edit.past_resource_name(shape, &[kind, self.label])
}
/// Every declaration of the resource. They depend on its type alone, so
/// each thread builds them once per generation of app code
/// ([`reset_type_schemas`](crate::reset_type_schemas)) and answers the
/// same list after: publishing, binding a verb or reading an action no
/// longer rebuilds every verb's parameters and builder.
#[must_use]
pub fn declarations(&self) -> Rc<[Declaration]> {
type Kept = (u64, HashMap<TypeId, Rc<[Declaration]>>);
thread_local! {
static KEPT: RefCell<Kept> = RefCell::new((0, HashMap::new()));
}
let epoch = crate::resource::type_epoch();
let key = (self.type_id)();
let found = KEPT.with(|kept| {
let kept = kept.borrow();
if kept.0 == epoch {
kept.1.get(&key).cloned()
} else {
None
}
});
if let Some(found) = found {
return found;
}
// Built outside the borrow: a declaration may read another
// resource's vocabulary.
let built: Rc<[Declaration]> = (self.declare)().into();
KEPT.with(|kept| {
let mut kept = kept.borrow_mut();
if kept.0 != epoch {
*kept = (epoch, HashMap::new());
}
kept.1.insert(key, Rc::clone(&built));
});
built
}
}
fn declarations<R: Resource>() -> Vec<Declaration> {
let mut out = Vec::new();
for decl in R::declarations() {
out.push(decl.into_declaration());
}
out
}
fn read<R: Resource>(value: serde_json::Value) -> Result<Built, String> {
match serde_json::from_value::<R::Action>(value) {
Ok(action) => Ok(Built::of::<R>(action)),
Err(error) => Err(error.to_string()),
}
}
fn edit<R: Resource>(edit: Edit<()>) -> Option<Built> {
R::edit_action(edit.retyped()).map(Built::of::<R>)
}
struct VocabularyOf<R>(std::marker::PhantomData<R>);
/// The least permission any of the resource's actions needs, as publishing it
/// states it; a model build applies actions and publishes nothing.
#[cfg(tilo_model_guest)]
fn least_need_default() -> ActionNeed {
tilo_actions::ActionContract::default().need()
}
#[cfg(tilo_model_guest)]
fn empty_op_schemas() -> Vec<(String, serde_json::Value)> {
Vec::new()
}
#[cfg(tilo_model_guest)]
fn no_item_effects(_: &str, _: &Id) -> Vec<ActionSpec> {
Vec::new()
}
#[cfg(tilo_model_guest)]
fn no_item_views(_: &str, _: &Id) -> Vec<ResourceViewSpec> {
Vec::new()
}
impl<R: Resource> VocabularyOf<R> {
const VOCABULARY: Vocabulary = Vocabulary {
kind: R::KIND,
app: R::APP_ID,
label: R::LABEL,
// What a model build leaves out is what a device applying an action
// never reads: the words of the resource's catalogue, the effects its
// items offer and the views they open, the schemas of its operations,
// and the least permission its actions need. Publishing them is the
// app's own work, so those bytes stay in the app.
#[cfg(tilo_model_guest)]
catalogue: None,
#[cfg(not(tilo_model_guest))]
catalogue: R::CATALOGUE,
action_type: R::ACTION_TYPE,
edits: R::EDITS,
readers: R::READERS,
resource_table: R::RESOURCE_TABLE,
type_id: TypeId::of::<R>,
shape: R::shape,
#[cfg(tilo_model_guest)]
op_schemas: empty_op_schemas,
#[cfg(not(tilo_model_guest))]
op_schemas: R::op_schemas,
action_schema: R::action_schema,
#[cfg(tilo_model_guest)]
least_need: least_need_default,
#[cfg(not(tilo_model_guest))]
least_need: R::least_need,
declare: declarations::<R>,
#[cfg(tilo_model_guest)]
item_effects: no_item_effects,
#[cfg(not(tilo_model_guest))]
item_effects: R::item_effects,
#[cfg(tilo_model_guest)]
item_views: no_item_views,
#[cfg(not(tilo_model_guest))]
item_views: R::item_views,
read: read::<R>,
edit: edit::<R>,
};
}
#[must_use]
pub fn vocabulary<R: Resource>() -> &'static Vocabulary {
&VocabularyOf::<R>::VOCABULARY
}