Skip to main content

Crate tilo_resource

Crate tilo_resource 

Source
Expand description

§The Tilo resource layer

A Tilo app’s state is a set of resources: typed, versioned, shared values the system owns. This crate is the layer that turns a Rust type into one. It has no rendering, windowing or widget dependency. The UI toolkit uses only its document-generic parts (history, stamped commits, replay); tilo-app binds resources to views.

§The golden path

use tilo_resource::{ActionCx, Collection, Id, Model, resource};

#[derive(Model, Default)]
pub struct Todo {
    pub items: Collection<Item>,
}

#[derive(Model, Default)]
pub struct Item {
    pub title: String,
    pub done: bool,
}

#[resource(kind = "example.todo")]
impl Todo {
    /// Add an item.
    #[action]
    pub fn add(&mut self, cx: &mut ActionCx, title: String) {
        self.items.push(cx.id(), Item { title, done: false });
    }

    /// Mark an item done or not done.
    #[action]
    pub fn set_done(&mut self, item: Id, done: bool) -> Result<(), &'static str> {
        self.items.get_mut(&item).ok_or("no such item")?.done = done;
        Ok(())
    }
}

// Tests are replay: apply actions the way a control, the palette, an agent
// or a script would, and assert on state.
fn main() {
    // A replica names the app whose record it is before it applies anything: every device
    // decides its changes against that app's surface.
    let mut replica = tilo_resource::Replica::<Todo>::new().in_app("so.tilo.todo", "Todo");
    replica.apply(Todo::ADD.with("Buy milk")).unwrap();
    let id = replica.state().unwrap().items.ids().next().unwrap().clone();
    replica.apply(Todo::SET_DONE.with((id, true))).unwrap();
    assert!(replica.state().unwrap().items.values().all(|item| item.done));
}

That is the whole app-side state layer. From it the app gets, without writing any of it:

  • storage and sync — the resource is an Automerge document; every field write is a minimal diff, text is spliced, collections are keyed and fractionally ordered, so members’ concurrent edits merge;
  • replayable actions — each #[action] method is a serializable operation with typed parameters, applied deterministically (ids and time come from ActionCx) and replayed byte-identically on every replica;
  • exposure — the same declarations are what the palette, agents and scripts list and invoke (publish), with permissions per action, and the generic APPLY operation publishes a JSON Schema of the action vocabulary (Resource::action_schema, JsonSchema);
  • history — every action is a change attributed to its author with its label and time (history); any version can be read back (history::read_at) and restored, field by field and item by item, from the record’s stored Shape;
  • search — text fields are indexed by default (Resource::search);
  • reading — a record whose declaration names a document read answers the framework’s read with what it holds, as typed data (read::fields for a record whose fields are all it holds), so an agent, a script or the SDK with no window open reads any record through the same action, permissions and audit as everything else;
  • lookup by kind — a host that works with whatever a workspace holds reads, publishes and replays any registered type from the kind its record names (Kinds, ResourceKind);
  • document machinery — fractional order keys, stamped commits and positional replay (history), writing large content as a few changes (batch) and id-aligned structural diffs, shared by every resource type including the hand-written ones;
  • incremental reads — after a change only what it touched is read again (Resource::refresh, Delta); a record resource gets this field by field and item by item, and a resource too large to read whole reads what views look at (Resource::load, Demand).

§Custom resource types

A type with its own layout and merge semantics — a rich-text document, a sheet — implements Resource by hand: read its state from a document, name its replayable Action type, and optionally declarations for named, typed palette entries. The SDK ships those types (RichText, plain text, Grid); an app derives its record with #[derive(Model)] and #[resource] and holds them as fields, never implementing Resource itself (docs/architecture/resources.md §8). Such a type gets exactly the same services. Edits without a named declaration travel as the generic APPLY action, so nothing a custom surface does has to bypass permissions, history or undo. APPLY is for surfaces, agents and scripts, never a palette row; each value’s own risk decides whether it needs confirmation, so a destructive typed edit is treated exactly as a declared destructive action is: what Undo takes back runs at once and offers Undo, and only what it cannot is confirmed.

Re-exports§

pub use action::ActionCx;
pub use action::ActionRef;
pub use action::Binds;
pub use action::Invoke;
pub use action::Mapped;
pub use action::NoParams;
pub use action::Operation;
pub use action::Outcome;
pub use action::Params;
pub use action::Reverting;
pub use action::Stamped;
pub use action::TryMapped;
pub use action::Undoing;
pub use action::fresh_uuid;
pub use action::invoking_member;
pub use action::invoking_name;
pub use action::minted_entry;
pub use action::minted_ids;
pub use action::minted_keys;
pub use action::restore_minted;
pub use action::reverting_type;
pub use action::take_minted;
pub use child::child_resource_id;
pub use child::publish_child;
pub use children::ChildList;
pub use children::ChildRef;
pub use children::Children;
pub use children::Trashed;
pub use collection::Collection;
pub use collection::Id;
pub use collection::Membership;
pub use collection::Quarantined;
pub use collection::stored_entry;
pub use collection::stored_ids;
pub use collection::stored_item;
pub use delta::Delta;
pub use delta::ObjPath;
pub use delta::Touch;
pub use delta::Touched;
pub use delta::Tracker;
pub use derived::Bound;
pub use derived::Derived;
pub use effect::Answers;
pub use effect::Effect;
pub use effect::EffectDecl;
pub use effect::EffectDecodeError;
pub use effect::EffectOffload;
pub use effect::EffectTarget;
pub use effect::NoEffect;
pub use effect::decode;
pub use effect::offer;
pub use evolution::Unreadable;
pub use group::ActionGroup;
pub use group::GROUP;
pub use group::GROUP_PARAM;
pub use keyed::ById;
pub use keyed::Identified;
pub use keyed::ItemStorage;
pub use keyed::Items;
pub use keyed::Keyed;
pub use kind::Kinds;
pub use kind::ResourceKind;
pub use model::Atom;
pub use model::Doc;
pub use model::Fields;
pub use model::Fresh;
pub use model::LocatedAt;
pub use model::MapSlot;
pub use model::Model;
pub use model::ModelError;
pub use model::Slot;
pub use model::VARIANT_KEY;
pub use model::edit_whole;
pub use model::load_slot;
pub use model::read_key;
pub use model::read_slots;
pub use model::refresh_key;
pub use model::take_slot;
pub use model::write_key;
pub use model::write_key_changed;
pub use ordered::Arranged;
pub use ordered::Ordered;
pub use origin::Origin;
pub use path::At;
pub use path::Edit;
pub use path::EditOp;
pub use path::OP_ARGUMENTS;
pub use path::Operations;
pub use path::Path;
pub use path::Segment;
pub use path::Settable;
pub use path::op_argument_schema;
pub use path::op_arguments;
pub use path::op_usage;
pub use path::outbox_settle_arguments;
pub use reactions::Reaction;
pub use reactions::Reactions;
pub use reactions::reaction_emoji;
pub use reader::Demand;
pub use reader::Reader;
pub use reader::heads_of;
pub use replica::AppNamed;
pub use replica::NoApp;
pub use replica::Replica;
pub use resource::APPLY;
pub use resource::APPLY_PARAM;
pub use resource::ActionDecl;
pub use resource::BuildAction;
pub use resource::EDIT_PARAM;
pub use resource::FIELD_EDIT;
pub use resource::HeadInputs;
pub use resource::NamesItem;
pub use resource::NoAction;
pub use resource::Place;
pub use resource::Resource;
pub use resource::SearchBody;
pub use resource::SearchEntry;
pub use resource::SearchPiece;
pub use resource::SearchRow;
pub use resource::SearchRowShape;
pub use resource::SearchText;
pub use resource::SearchWeight;
pub use resource::SharedResource;
pub use resource::bind_declaration;
pub use resource::build_action;
pub use resource::by_app_refusal;
pub use resource::child_by_id;
pub use resource::declaration_spec;
pub use resource::encode;
pub use resource::head_inputs;
pub use resource::need_of;
pub use resource::origin_now_ms;
pub use resource::publish;
pub use resource::publish_head;
pub use resource::publish_head_of;
pub use resource::spec_kind;
pub use resource::state_from_reading;
pub use resource::with_origin_clock;
pub use row::Handle;
pub use row::LiveRow;
pub use row::RowBindings;
pub use row::typed_resource;
pub use schema::JsonSchema;
pub use shape::FieldShape;
pub use shape::Shape;
pub use shape::StoredText;
pub use shape::Trust;
pub use shape::absent_scalar;
pub use shape::stored_text;
pub use status::EffectStatus;
pub use storage::Bytes;
pub use storage::Counter;
pub use storage::Grid;
pub use storage::Outbox;
pub use storage::OutboxEntry;
pub use storage::Set;
pub use storage::Settled;
pub use text::PlainText;
pub use text::TextEdit;
pub use unreadable::withhold_document_actions;
pub use vocabulary::Built;
pub use vocabulary::Declaration;
pub use vocabulary::Vocabulary;
pub use vocabulary::vocabulary;

Modules§

action
Typed actions over a record resource: a method on the record becomes a replayable, attributable, undoable operation.
batch
Writing a large amount of new content — a whole imported document, a pasted book — as a few changes instead of one operation at a time.
child
Resources nested inside another: a note’s rich-text body, a draft’s message, a saved query’s SQL.
children
Resources that contain resources: a container lists its children, each a record of its own.
collection
Items with identity: Id and the ordered, keyed Collection.
content
The content store of the window whose code is running.
delta
What changed in a document since a resource was last read.
derived
Derived resources: things computed from a record’s state that people act on (the folders of a snippet library, its tags, a smart list), published as children whose actions are the record’s own verbs with some arguments bound.
diff
Structural diffs between two versions of the same resource.
effect
Effects: work an app does that changes no document — reloading a list, running a job, talking to a server, opening a system picker.
evolution
How a resource’s storage changes between versions of its app.
footprint
What an action may write, and which storage units a change wrote.
founding
The founding an app’s record is derived from: what every holder makes of it alike.
genesis
A resource’s genesis change: the one every device creates alike.
group
Several actions applied as one: one change, one version in history, one undo step, one permission decision.
history
Version history of any resource, derived from its document’s change graph: who changed it, when, through which action — and what it looked like then.
items
Actions on the items of a collection, offered on the items themselves.
keyed
Items keyed by an id they carry, with no stored order: Keyed.
kind
Resource types by kind, for a host that links no resource type’s code at the call site.
label
What a person calls a resource, in the language they read.
members
Who a workspace’s members are, as the host running a record’s code knows them: what an action binds a typed @Name to and what a reading of the record calls an author by.
model
How typed values live in a resource’s CRDT document.
order
Fractional order keys: a key strictly between any two distinct keys always exists, so an ordered collection survives concurrent inserts and moves without renumbering its neighbours.
ordered
A list someone arranges, of items that carry their own ids: Ordered.
origin
Where content came from, when it was written somewhere else first.
path
Typed paths into a model and the field edits made at them.
profiling
Bounded observations of named scopes in the real code on this thread.
reactions
Reactions: people answering something with an emoji.
read
read: what a readable resource holds, as typed data. With no item it answers the resource itself; with an item id, the nested resource of that id; with a version, frozen historical content. It is a view: it changes nothing, needs only read permission and is checked like every other action.
reader
Keeping a resource’s state current as its document changes, reading only what changed and what views look at.
recording
A stretch of a resource’s history as a document of its own: what a report carries so its reader can step through the states the reporter saw (docs/architecture/session-replay.md).
replica
An in-memory replica of one resource: the harness for replay-based tests, and a resource document held apart from any window — the contents of a file an app saves its resource to and opens it from (Replica::load, Replica::save).
resource
The resource contract: what any resource type provides so that it gets history, undo, collaboration, permissions, palette/agent/script exposure, search and replay without writing any of them.
row
A live row: one entity a surface publishes beneath its resource that lives outside the resource’s document — a process, a device, a container, a journal entry, a fetched catalogue row, a running job — for the palette, agents and scripts.
schema
JSON Schemas for the values actions carry, so a caller with no screen can read what an operation takes instead of guessing it.
schema_check
Whether a resource’s published actions say everything they need.
search_default
The search entries a record publishes without one of its own: one per item it lists, each anchored at that item, or else all of its text in one entry. Split out of [crate::resource] because it is one reading of a record’s fields, not part of what a resource publishes as actions.
search_index
An app’s search entries as the system’s persistent search index takes them.
shape
The stored layout of a model, as data.
share
share-link and share-invite-link: what a person, a bot or an agent asks for to get “a link to this”.
sort
Sorting compiled once for every item type.
status
What an effect, or one of the resource’s own actions, looks like to callers right now: unavailable while the engine is offline, labelled differently while recording, saying what it does on one row.
storage
Storage types whose concurrent edits merge per element: Counter, Set, Grid and Outbox, and Bytes for binary values.
stored_items
The items a resource’s collections hold, whatever their type, and what each takes stored: what a store bounding the resources it keeps by the items they hold counts and measures them by.
surface
A resource’s public surface as data (tilo_actions::surface), read from its declarations and stored shape. tilolang surface writes it to the app’s surface.toml and compiled surface.json, and tilolang check compares it with the code, so a rename or an incompatible storage change shows up in review, and it is what the OS knows about an app that is not running and what another language compiles its actions and types against.
table
A model type’s storage contract as data.
text
Collaborative plain text: a SQL buffer, a report note, a commit message, a source file.
unreadable
What a resource publishes when the document it should read from does not read: every action that would change it, and every action it declares, says why it does not apply, instead of the surface showing a hole or the last state that read as if it were what the record holds.
vocabulary
A resource type’s actions with the type erased.
words
What a resource is called, for the resources its type publishes.

Macros§

bindings
A provider’s actions as a Rust caller calls them, from the compiled surface its provider publishes: bindings!(provider = "tilo.environment", surface = "../ush/environment.json"), the surface’s path from the calling crate’s manifest. See bindings.rs.
committed_surface
The app’s compiled surface, the file tilolang surface --write writes beside its authored surface.toml: Option<&'static str>, Some when it has a surface.json at its root, else None.
declared_catalogue
The catalogue beside the crate being built, as a static: declared_catalogue!(CATALOGUE);, its source language embedded and its other languages read from the language packs as a declaration’s words are.
declared_names
What a resource of a kind this crate publishes from outside a document is called, in the person’s language: the kind’s entry in the catalogue beside this crate, read the way a declaration’s words are.
json_model
Implements Model (and Settable) for serde types stored whole as one JSON string, last writer wins: values with no meaningful concurrent merge (a tone curve, a keyframe track). The types need Serialize, Deserialize, Default (the value of an absent slot) and PartialEq holding only between values of equal JSON forms, as a derived one does: the edits between two copies compare each value in memory, and serialise only the ones that differ.
leaf_paths
Implements the path items of a type edited whole or through its own operations: its paths are the Path itself.
operations_model
Implements the Model items that route a record’s edits of an Operations type to it; call it inside the type’s impl Model.
value_model
Implements Model (and Settable) for serde types stored as their JSON form, the way a serde_json::Value is: an object as a map, an array as a list, everything else as a scalar. For a type #[derive(Model)] cannot describe: one defined in a crate below this one (an ActionKey), or one that holds itself (a condition made of conditions). A type the app shapes derives Model instead, so its fields have paths and edits of their own.
word
A word of the catalogue beside the crate that names it, word!("files-rename-here"): a label::Word read in the person’s language whenever what carries it is published. A key the crate’s locales/en-US.ftl does not hold does not build; word!("key", catalogue = "tests/locales") reads another catalogue.

Structs§

AbsolutePath
An absolute path on this device. It cannot be made from a relative one.
Acting
Who made a change, and who they acted for, as a tree: an automation a person set up, run by an agent, for two people, is Automation(1) for [Agent(1) for [Person(Q), Person(X)]].
ActionKey
The stored form of a reference to one published action: a Shortcut step, an agent’s plan, a palette entry, a history entry. It names the app, the resource kind that publishes the action and the action’s public id.
Blank
Why text is not a NonBlank: there is nothing in it but whitespace.
Frecency
What was chosen how often and when, by an id the caller picks (a package id, an action id). Time is passed in as seconds since the epoch, so the ranking is testable without a clock.
HybridClock
A writer’s clock over the times it has seen.
Map
A map from string keys, sorted by key, stored and merged as a BTreeMap<String, V> is: one document map, reconciled key by key.
NonBlank
Text with at least one character that is not whitespace, trimmed. See the module.
Patch
A change a document reports, as an answer hook reads what its action did. A change to the current state of the document
PersonId
A person’s id: the lowercase hex of their root public key, bare.
ReactionGroup
Everyone who reacted with one emoji, first reaction first.
Reactor
One person (or outside account) among those who reacted with an emoji.
Recents
What was used lately, newest first, each item once, at most KEEP.
Refusal
Why an action declined to run, in the user’s words, and, where a caller acts on the reason rather than reads it, a stable code naming it.
RelativePath
Why a path was refused: it was relative.
ScopeDecl
SearchPreview
What the palette’s preview band shows of a hit: a heading, short facts side by side, items one per line and the start of its text. Data only; the platform lays it out.
Surface
The public surface of one resource kind. See the module docs.
TypeSet
The named types a surface declares, gathered while its fields’ types are worked out: each declared once under one name, however often it is used.

Enums§

ActionKind
What an action is able to do, derived by the framework from the action’s code and never declared by an app.
Availability
Whether an action can be invoked in the resource’s current state.
FieldType
A field’s or value’s type. See the module docs.
MemberId
A person, agent or bot in a workspace.
Weaker
Which way a field’s value weakens the person’s security.

Constants§

DIRECT_CONVERSATION_PREFIX
The prefix of a direct conversation’s id: the members it is with follow it, sorted, as JSON.

Traits§

FlatFields
A record’s fields as an action’s own parameters, typed as the record declares them: what #[param(flatten)] publishes, so an argument that is an enum names that enum rather than “any”.

Functions§

custom_emoji_name
The name of the workspace emoji emoji writes as :name:, when it is one.
frecency
How strongly something chosen count times, the last at last, pulls at now (both seconds since the epoch): more choices pull harder, and the pull halves every two weeks after the last. Zero for something never chosen.
scope_contains
Whether anchor is scope or lies beneath it in the anchor path.
valid_custom_emoji_name
Whether name can name a workspace emoji: 2 to 32 ASCII letters, digits and underscores, as Discord names its custom emoji, so the same name works on both sides of the bridge.

Attribute Macros§

resource
Turn a record’s #[action] methods into its replayable, published action vocabulary, and implement Resource for it.

Derive Macros§

Effect
Derive Effect: an enum’s variants become the app’s published effects — work with no document delta, invoked by buttons, the palette, agents and scripts alike. See tilo_resource::effect.
JsonSchema
Derive JsonSchema: the JSON Schema of the type’s serde JSON form.
Model
Derive Model (and Fields for structs with named fields).
Row
Derive Row: a plain struct as the type of the entities a surface publishes that live outside any document — processes, devices, containers, journal entries, a fetched catalogue’s rows. See tilo_resource::words.