docs/generated/contracts.mdgenerated from code
Reference · 24 min read
doc-sync
Contracts: doc-sync.
Read as
Source: crates/lvcs-doc/src/sync/mod.rs.
1/// A node device, by its Ed25519 public key (the bytes of2/// `lvcs_net::transport::Node`), which keys the document actor's per-node3/// sync state (discussion:owner/30). Never a peer key.4#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]5pub struct DeviceKey(#[serde(with = "crate::cbor::fixed")] pub [u8; 32]);67/// Start syncing with `node` (the sync actor's `Join`): the actor sends it8/// what the document holds, its refusals, and its evidence ([`SyncOut`]),9/// and stores `tag` with it. `tag` is the sync actor's (discussion:owner/110): the10/// next value of a counter rising through one daemon run. The actor keeps11/// the last tag it had for each node, from this or a later [`SyncIn`], and12/// stamps it on every [`SyncOut`] and [`SyncSettled`] for the node. A13/// sync node keeps the actor from idling (discussion:owner/584).14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]15pub struct NodeJoined {16 pub node: DeviceKey,17 pub tag: u64,18}1920/// Stop syncing with `node`: the changes it sent that wait are dropped.21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]22pub struct NodeLeft {23 pub node: DeviceKey,24}2526/// A sync message from `node`: `payload` is a [`crate::SyncPayload`]27/// (history rows 457 and 459). The actor checks each signed change it28/// carries on its own before Loro sees it: imported when its signer's29/// grants authorize it at its own time; refused, remembered, and30/// advertised when they don't, when it depends on a refused change, or31/// when its signer equivocated (each a `PeerRefused`); dropped as the32/// sender's fault when it is unsigned, its signature doesn't verify, or33/// its peer id isn't its record's (one [`SyncRejected`] each); held while34/// a dep, its grant, or its path isn't known yet, within the node's35/// `DEFER_MAX_MESSAGES` and `DEFER_MAX_BYTES` (past them dropped, and sent36/// again, discussion:owner/571).37/// A payload that doesn't decode, or a change that isn't exactly the span38/// its record names, breaks the protocol (`Malformed`). `tag` is the sync39/// actor's (discussion:owner/110), stored with the node as the message arrives.40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]41pub struct SyncIn {42 pub node: DeviceKey,43 pub tag: u64,44 #[serde(with = "crate::cbor::bytes")]45 pub payload: Vec<u8>,46}4748/// The sync messages a document is stepped through at once, oldest first49/// (ApplyMore, discussion:owner/404's first default): the shell coalesces the50/// messages that arrive while the document has an event queued or running.51/// Its machine takes each as it would a lone [`SyncIn`] (checked, held,52/// rejected with its node, or applied and answered), and renders once,53/// after the last, when any of them changed the document.54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]55pub struct SyncBatch {56 pub messages: Vec<SyncIn>,57}5859/// The `.lvcs/caps` document settled with `node` (its [`SyncSettled`];60/// discussion:owner/108): the shell sends it to every document actor right after61/// the [`GrantsKnown`] of the caps render before it, and every change held62/// back is checked again. Sent by `M3.daemon`.63#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]64pub struct CapsSettled {65 pub node: DeviceKey,66}6768/// The daemon's signature for a change the actor asked about69/// ([`SignRequest`]): taken only when it is one of the document's own70/// unsigned changes, unchanged, and its signature verifies; the actor then71/// persists the signed change and sends it to every node (discussion:owner/459).72/// `incarnation` is the [`SignRequest`]'s, echoed: a document takes only an73/// outcome of a request its own incarnation made (f-perf/2).74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]75pub struct Signed {76 pub change: crate::change::SignedChange,77 pub incarnation: u64,78}7980/// The grants every change is authorized against (`kinds::caps::authorize`):81/// `project`, the project id this daemon runs; `root`, the owner and82/// project name, once this daemon's `.lvcs/caps` holds a seed whose root's83/// project id equals `project`, `None` before; and every signed grant the84/// caps document holds, by id. While `root` is unknown, or a change's grant85/// isn't among `grants`, the change waits, never refused (history row 459);86/// the caps document authorizes its seed against the root the seed itself87/// writes. `revoked` holds each revoked grant's revocation time `t` in Unix88/// seconds (discussion:owner/148): such a grant authorizes only changes whose own89/// time is before `t`. Sent by the shell on spawn and whenever the caps90/// document renders ([`CapsRendered`]); each one checks the changes held91/// back again.92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]93pub struct GrantsKnown {94 #[serde(with = "crate::cbor::fixed")]95 pub project: [u8; 32],96 pub root: Option<ProjectRoot>,97 pub grants: BTreeMap<GrantId, SignedGrant>,98 pub revoked: BTreeMap<GrantId, i64>,99 /// The installed plugins, by name (discussion:owner/514), whose rules the100 /// entry ledgers under `.lvcs/x/<name>/` are judged by.101 #[serde(default)]102 pub plugins: BTreeMap<String, PluginRecord>,103 /// The documents the owner purged, by address (a deleted file's104 /// `.lvcs/files/<id>`, or a plugin's entry ledger), each with its purge105 /// time in Unix seconds (discussion:owner/614): a document named here106 /// stops for good, its ledger deleted, and never loads again.107 #[serde(default)]108 pub purged: BTreeMap<String, i64>,109}110111/// Add a signed grant to the `.lvcs/caps` document (discussion:owner/148: `grant`112/// issues every grant, a renewal included), committed by113/// `origin.author`. Answered like an edit: `Changed` with `req`, or114/// `Rejected` (a document of another kind answers `Failed`).115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]116pub struct IssueGrant {117 pub req: RequestId,118 pub origin: Origin,119 pub grant: SignedGrant,120}121122/// Put, replace, or delete (`record` `None`) the installed plugin `name`'s123/// record in the `.lvcs/caps` document (discussion:owner/514: `lvcs plugin124/// install`, `upgrade`, and `remove`), committed by `origin`. Answered like125/// an edit: `Changed` with `req`, at the current heads and committing126/// nothing when the document holds that already, or `Rejected` (a127/// document of another kind, or a closed one, answers `Failed`). Every128/// node's verifier takes it only under a grant naming `Delegate`, the129/// owner always.130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]131pub struct PluginPut {132 pub req: RequestId,133 pub origin: Origin,134 pub name: String,135 pub record: Option<PluginRecord>,136}137138/// The `HASH` (SHA-256) of a string the secret scan flagged and its139/// author confirmed is no secret: the key of its signed allowlist entry in the140/// caps document (discussion:owner/108 and discussion:owner/128), which every scanner built from141/// the caps render honors.142#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]143pub struct SecretHash(#[serde(with = "crate::cbor::fixed")] pub [u8; 32]);144145/// Add `hash` to the `.lvcs/caps` document's signed allowlist (146/// discussion:owner/108, 109, and 128): the key `/allowlist/<hash>` in `ID_ENCODING`,147/// holding `true`, written once and committed by `origin`. Answered like148/// an edit: `Changed` with `req`, at the current heads and committing149/// nothing when the entry is already there, or `Rejected` (a document of150/// another kind, or a closed one, answers `Failed`). Every node's verifier151/// takes it from any signer whose grant chain and window hold (`Write` on152/// `ALLOWLIST_ADDRESS`, discussion:owner/147), the owner always. `reason` is the153/// author's why, from `lvcs add --force --reason` (discussion:owner/513).154#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]155pub struct AllowSecret {156 pub req: RequestId,157 pub origin: Origin,158 pub hash: SecretHash,159 pub reason: String,160}161162/// Revoke `grants` in the `.lvcs/caps` document (discussion:owner/148): for each163/// one not revoked yet, the key `/revoked/<grant id>` in `ID_ENCODING`,164/// holding `ScalarValue::Int(t)`, where `t` is the change's own commit165/// time, written once and committed by `origin` in one change. Answered166/// like an edit: `Changed` with `req`, at the current heads and committing167/// nothing when every one is revoked already, or `Rejected` `Failed` when168/// one is not in `/grants` or `t` is before its `not_before_s`, which every169/// node's verifier would refuse (a document of another kind, or a closed170/// one, answers `Failed` too). Every node's verifier takes it from a171/// signer `authorize` lets write `CAPS_ADDRESS` (a grant naming172/// `Delegate`, or the owner) that is the grant's issuer or the owner, or173/// that also holds `Delegate` on each path probe of the grant174/// (`paths::probe`).175#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]176pub struct RevokeGrant {177 pub req: RequestId,178 pub origin: Origin,179 pub grants: BTreeSet<GrantId>,180}181182/// Purge the documents at `addresses` in the `.lvcs/caps` document183/// (discussion:owner/614): for each one not purged yet, the key184/// `/purged/<file id>` for a deleted file's document, or185/// `/purged/<address>` for a plugin's entry ledger, holding186/// `ScalarValue::Int(t)`, where `t` is the change's own commit time,187/// written once and never removed, committed by `origin` in one change.188/// Answered like an edit: `Changed` with `req`, at the current heads and189/// committing nothing when every one is purged already (a document of190/// another kind, or a closed one, answers `Rejected` `Failed`). Every191/// node's verifier takes it only from the project owner's signature.192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]193pub struct PurgeDocs {194 pub req: RequestId,195 pub origin: Origin,196 pub addresses: BTreeSet<String>,197}198199/// Resolve cursor pairs against this document's current heads (discussion:owner/438:200/// the coord actor decides overlap between notifications on resolved201/// spans). Answered with exactly one [`Resolved`].202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]203pub struct ResolveAnchors {204 pub req: RequestId,205 pub anchors: Vec<RangeAnchor>,206}207208/// Anchor a notification's range (discussion:owner/156; `M3.coord`, `M3.daemon`):209/// `start..end` are code points of `/content` at `at`, the heads the210/// notifier last read (a write event's `about.base`), holding at least one211/// character, or `0..0` when the text there is empty. Answered with exactly212/// one [`Anchored`]: the cursor pair on the range's first and last213/// characters at `at` (discussion:owner/76), which the214/// daemon encodes as `Notification.range`; or `Whole` for an empty text,215/// which the daemon sends as an empty `range`, a whole-document216/// notification. It changes nothing in the document.217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]218pub struct AnchorRange {219 pub req: RequestId,220 #[serde(with = "crate::cbor::heads")]221 pub at: Vec<ChangeId>,222 pub start: usize,223 pub end: usize,224}225226/// A sync message for `node` (discussion:owner/30): `payload` is a227/// [`crate::SyncPayload`] in canonical CBOR, holding what the document228/// holds, its refusals, the signed changes the node's last `have` lacks,229/// and evidence it hasn't sent the node. `tag` is the one stored with the230/// node ([`NodeJoined`], [`SyncIn`]; discussion:owner/110).231///232/// When the answer names stored changes its document keeps no bytes of,233/// `payload` is empty and `fill` holds it: the document's effect executor234/// reads those changes from the ledger file and encodes the payload before235/// the output goes on (discussion:owner/792 step 3). Never journaled.236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]237pub struct SyncOut {238 pub node: DeviceKey,239 pub tag: u64,240 #[serde(with = "crate::cbor::bytes")]241 pub payload: Vec<u8>,242 #[serde(skip)]243 pub fill: Option<Box<SyncFill>>,244}245246/// A sync answer's payload before its stored changes are read247/// (discussion:owner/792 step 3): every part but the changes its document248/// keeps no bytes of, and each of those with its place among the payload's249/// changes, its record's first byte in the ledger file, and what it must be.250#[derive(Debug, Clone, PartialEq, Eq)]251pub struct SyncFill {252 /// The payload, holding every change it carries whole, in order.253 pub payload: crate::change::SyncPayload,254 /// Each change to read: its place in the filled payload's changes255 /// (ascending), its offset, and its metadata and signature.256 pub reads: Vec<(u32, u64, crate::change::HeldChange)>,257}258259impl SyncFill {260 /// What to read: each change's offset and what it must be, in order.261 #[must_use]262 pub fn wanted(&self) -> Vec<(u64, &crate::change::HeldChange)> {263 self.reads.iter().map(|(_, at, held)| (*at, held)).collect()264 }265266 /// The payload's canonical CBOR with `read`, the changes [`Self::wanted`]267 /// names in its order, each at its place; `None` when `read` isn't one268 /// change for each wanted or the payload doesn't encode.269 #[must_use]270 pub fn fill(self, read: Vec<crate::change::SignedChange>) -> Option<Vec<u8>> {271 let Self { mut payload, reads } = self;272 if read.len() != reads.len() {273 return None;274 }275 let mut whole = std::mem::take(&mut payload.changes).into_iter();276 let mut read = read.into_iter();277 let mut places = reads.iter().map(|(place, _, _)| *place).peekable();278 let total = whole.len() + read.len();279 let mut changes = Vec::with_capacity(total);280 for place in 0..total {281 let place = u32::try_from(place).ok()?;282 if places.peek() == Some(&place) {283 places.next();284 changes.push(read.next()?);285 } else {286 changes.push(whole.next()?);287 }288 }289 payload.changes = changes;290 crate::cbor::encode(&payload).ok()291 }292}293294/// The document's executor couldn't read the stored changes its answer295/// to `node` (tagged `tag`) named (discussion:owner/792 step 3): neither296/// that answer nor its settle went. While `node` is joined, the document297/// undoes the answer, so its next answer to the node carries every change298/// it is owed; it sends nothing for this event itself.299#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]300pub struct AnswerUnread {301 pub node: DeviceKey,302 pub tag: u64,303}304305/// The most changes one re-check read names (discussion:owner/792 step306/// 4): with `SYNC_ANSWER_BYTES` of their bytes, what one chunk of a307/// re-check holds.308pub const REJUDGE_READ_CHANGES: usize = 1_024;309310/// What a re-check chunk's step holds at its peak, in times the chunk's311/// bytes ([`rejudge_peak_bytes`], discussion:owner/811 rule 3): measured,312/// about 5.25 times a full chunk of large changes, its changes held in the313/// event and the fold's import of them.314pub const REJUDGE_PEAK_FACTOR: u64 = 6;315316/// What a re-check chunk's step holds at its peak whatever its bytes317/// ([`rejudge_peak_bytes`]): the fold's own start, and each change's318/// metadata, about 3 MiB for a chunk of [`REJUDGE_READ_CHANGES`] small319/// changes measured.320pub const REJUDGE_PEAK_BASE_BYTES: u64 = 4 * 1024 * 1024;321322/// The most a re-check chunk of `bytes` holds at its step's peak, the323/// read's changes and the fold's import of them, which the daemon charges324/// to its memory budget until the document stepped the chunk325/// (discussion:owner/811 rule 3). The tests `rejudge_large_changes_memory`326/// and `rejudge_small_changes_memory` measure each chunk's own peak327/// against it.328#[must_use]329pub const fn rejudge_peak_bytes(bytes: u64) -> u64 {330 bytes331 .saturating_mul(REJUDGE_PEAK_FACTOR)332 .saturating_add(REJUDGE_PEAK_BASE_BYTES)333}334335/// A re-check's ask for its next chunk of held changes336/// (discussion:owner/792 step 4): `ids`, the held changes from the fold's337/// next one on, in store order; `reads`, those of them that keep no bytes,338/// each with its record's first byte in the ledger file, for the339/// document's effect executor to read ([`RejudgeChanges`], or340/// [`RejudgeUnread`] when it can't). At most [`REJUDGE_READ_CHANGES`]341/// changes and `SYNC_ANSWER_BYTES` of their bytes, but always one;342/// `bytes`, all of them, read or kept, which the fold steps343/// ([`rejudge_peak_bytes`]).344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]345pub struct RejudgeRead {346 pub tag: u64,347 pub ids: Vec<ChangeId>,348 /// For its executor alone: an output is never journaled.349 #[serde(skip)]350 pub reads: Vec<(u64, crate::change::HeldChange)>,351 /// For its executor alone, as `reads`.352 #[serde(skip)]353 pub bytes: u64,354}355356/// The executor's reply to [`RejudgeRead`] `tag` (discussion:owner/792357/// step 4): the chunk's `ids`, `read`, the ids of the ones it read, and358/// `changes`, each read change whole in `read`'s order. The journal keeps359/// the ids and `digest` ([`Self::digest_of`] of `changes`), never the360/// bytes: replay fills `changes` back from the ledger file by id and361/// checks the digest.362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]363pub struct RejudgeChanges {364 pub tag: u64,365 pub ids: Vec<ChangeId>,366 pub read: Vec<ChangeId>,367 #[serde(with = "crate::cbor::fixed")]368 pub digest: [u8; 32],369 #[serde(skip)]370 pub changes: Vec<crate::change::SignedChange>,371}372373impl RejudgeChanges {374 /// The SHA-256 over each change's bytes digest and signature, in375 /// order: what the journal keeps of the changes a reply carried.376 #[must_use]377 pub fn digest_of(changes: &[crate::change::SignedChange]) -> [u8; 32] {378 use sha2::{Digest as _, Sha256};379 let mut hash = Sha256::new();380 for signed in changes {381 hash.update(signed.change.bytes_digest());382 hash.update(signed.sig);383 }384 hash.finalize().into()385 }386}387388/// The executor couldn't read [`RejudgeRead`] `tag`'s changes389/// (discussion:owner/792 step 4): the re-check judges nothing, and the390/// next report asks again.391#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]392pub struct RejudgeUnread {393 pub tag: u64,394}395396/// An equivocation's ask for the held change its refused change overlaps397/// (discussion:owner/792 step 5): `held`, that change's id, which keeps no398/// bytes; `at`, its record's first byte in the ledger file, and `meta`, it399/// as held, for the document's effect executor to read and check400/// ([`EvidenceHeld`], or [`EvidenceUnread`] when it can't). Until the reply401/// the pair is pending, never evidence and never sent.402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]403pub struct EvidenceRead {404 pub tag: u64,405 pub held: ChangeId,406 /// For its executor alone: an output is never journaled.407 #[serde(skip)]408 pub at: u64,409 #[serde(skip)]410 pub meta: Option<crate::change::HeldChange>,411}412413/// The executor's reply to [`EvidenceRead`] `tag` (discussion:owner/792414/// step 5): `id`, the change it read, and `held`, it whole. The journal415/// keeps the id and `digest` ([`RejudgeChanges::digest_of`] of it), never416/// its bytes: replay fills `held` back from the ledger file by id and417/// checks the digest.418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]419pub struct EvidenceHeld {420 pub tag: u64,421 pub id: ChangeId,422 #[serde(with = "crate::cbor::fixed")]423 pub digest: [u8; 32],424 #[serde(skip)]425 pub held: Option<crate::change::SignedChange>,426}427428/// The executor couldn't read [`EvidenceRead`] `tag`'s held change429/// (discussion:owner/792 step 5). `moved`: the ledger file's record at its430/// offset isn't that change, so it never will be read there, and the pair431/// is dropped; else the pair stays pending, and the next step that would432/// send evidence asks again.433#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]434pub struct EvidenceUnread {435 pub tag: u64,436 pub moved: bool,437}438439/// The document is settled with `node` (discussion:owner/110 and discussion:owner/112): the node's440/// `have` and refusals cover every signed change it holds, so it has441/// nothing more to send it until it hears from it. `tag` is as for442/// [`SyncOut`]; the sync actor ends a node's caps round (discussion:owner/68) only443/// on a caps `Settled` whose tag is its latest caps input's.444/// `held_back` says it still holds back changes or evidence the node sent445/// (their deps or grants not known yet, discussion:owner/762): a held-back446/// change never holds the round open, but the frames that carried it447/// aren't done with until it imports, is dropped, or the node leaves.448#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]449pub struct SyncSettled {450 pub node: DeviceKey,451 pub tag: u64,452 pub held_back: bool,453}454455/// The document took the [`SyncIn`] tagged `tag` from `node`456/// (session-29a3231b/2), whatever came of it: applied, held back, refused,457/// rejected, or left when an earlier message of its batch failed. One for458/// each message of a [`SyncBatch`] its machine steps, so the sync actor459/// knows that message's payload is in flight no more. `held_bytes` is how460/// many bytes of changes and evidence from the node the document holds461/// back once the step ran (discussion:owner/762 rule 7 as amended), `None`462/// when the step failed: the frame's transient charge shrinks to them, or463/// returns when none are held.464#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]465pub struct SyncTook {466 pub node: DeviceKey,467 pub tag: u64,468 pub held_bytes: Option<u64>,469}470471/// The rested document answered `node`'s message or join tagged `tag`472/// from its stored ledger, without loading (channel-judge/5), and runs no473/// more: the node's sync actor rests it there alone, after the answer, as474/// it rests a document that stopped. Every other node's link is left as475/// it was.476#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]477pub struct SyncRested {478 pub node: DeviceKey,479 pub tag: u64,480}481482/// The revocations a node holds (discussion:owner/326): the grant ids, in483/// `ID_ENCODING`, revoked in the caps document at the version the node484/// last reported holding (its `have`, as far as this document holds it),485/// sorted. The caps document emits it after a message from the node,486/// while it holds at least one revocation.487#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]488pub struct NodeRevocations {489 pub node: DeviceKey,490 pub grants: Vec<String>,491}492493/// A sender's fault in one sync message, or a protocol break (history row494/// 459): each maps to a `rejection` value. A refusal (unauthorized,495/// orphaned, equivocation) never produces one: the sender may be an496/// honest relayer.497#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]498pub enum SyncRejection {499 /// The payload doesn't decode, or a change's bytes aren't exactly the500 /// one span of its peer that it names (`malformed`): the node is501 /// disconnected at once.502 Malformed,503 /// A change carries no signature (`unsigned`).504 Unsigned,505 /// A change's signature doesn't verify for its record's signer, or a506 /// piece of evidence doesn't verify (`bad_signature`).507 BadSignature,508 /// A change's peer id isn't `peer_of` its record (`wrong_peer`).509 WrongPeer,510 /// A change or a piece of evidence whose signer the project doesn't511 /// name (discussion:owner/554: the owner's grant cited by another key,512 /// or a grant whose grantee is another key): nothing of it is kept,513 /// and it counts one sender fault (`no_capability`).514 NoStanding,515 /// A refusal or a piece of evidence this document would keep past516 /// `LEDGER_REFUSED_MAX`, `LEDGER_EVIDENCE_MAX`, or517 /// `LEDGER_EVIDENCE_MAX_BYTES` (discussion:owner/554): not kept, the518 /// change still not imported; never a sender fault (`over_limit`).519 LedgerFull,520 /// The document can't take sync now (closed, or a kind that doesn't521 /// sync yet); the shell drops the message and keeps the node.522 Unavailable,523}524525/// Node `node` said it refused the ops of `record`'s peer from counter526/// `from` on, and this document's own checks admit them up to `admitted`527/// (exclusive). Judging by the same rules (`rules`, `VERIFIER_RULES`) and528/// the same grants (`theirs`, `ours`: each side's grants digest), the529/// checks being deterministic, one of the two nodes has a bug (530/// discussion:owner/549); judging by other rules or other grants531/// (`expected`), the difference is expected. Either way the document keeps532/// the changes, and they are on no main of that node's: the daemon tells533/// the changes' signer when it is one of its own (r3-join/17), and reports534/// only a disputed one.535#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]536pub struct VerdictDisputed {537 pub node: DeviceKey,538 pub record: Record,539 pub from: i32,540 pub admitted: i32,541 pub rules: u32,542 pub theirs: Option<[u8; 32]>,543 pub ours: Option<[u8; 32]>,544 /// The two nodes judged by other rules or other grants: no dispute.545 #[serde(default)]546 pub expected: bool,547}548549/// A sender's fault or a protocol break in a sync message from `node`:550/// `change` is the change at fault, when one was named.551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]552pub struct SyncRejected {553 pub node: DeviceKey,554 #[serde(with = "crate::cbor::opt_hash")]555 pub change: Option<ChangeId>,556 pub reason: SyncRejection,557}558559/// A change was committed and awaits its signature (discussion:owner/459): the actor560/// sends it to no node until [`Signed`] returns it signed. A reload asks561/// again, on its first `Render`, for every own change still unsigned.562/// `req` is the request that caused it, when one did; `change` the change563/// to sign, whose record names the signer, grant, and device.564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]565pub struct SignRequest {566 pub req: Option<RequestId>,567 pub change: crate::change::Change,568 /// The change's index among its peer's signed changes: the quota569 /// count (discussion:owner/70, history row 459).570 pub seq: u64,571 /// The asking document's incarnation, as its load named it572 /// (`LoadDoc::incarnation`). Whoever answers echoes it in the outcome573 /// ([`Signed`], `SignFailed`, `RetrySigning`), and the document ignores574 /// an outcome that names another: after a stop and a reload a575 /// different change can hold the same id (f-perf/2).576 pub incarnation: u64,577 /// The file's path as the asking document names it, when it is a578 /// file's and names one: the stop gate keys a signed change by it, so579 /// it never asks the router per change (o-decouple/8).580 #[serde(default, skip_serializing_if = "Option::is_none")]581 pub path: Option<String>,582}583584impl SignRequest {585 /// The request to sign `change`, which `req` caused when one did, the586 /// `seq`-th of its peer's signed changes, asked by `incarnation`.587 #[must_use]588 pub fn new(589 req: Option<RequestId>,590 change: crate::change::Change,591 seq: u64,592 incarnation: u64,593 ) -> Self {594 Self {595 req,596 change,597 seq,598 incarnation,599 path: None,600 }601 }602}603604/// `output`, a [`SignRequest`] made by [`SignRequest::new`], naming the605/// asking file document's `path`; any other output as it is.606#[must_use]607pub(crate) fn sign_request_at(output: crate::DocOutput, path: Option<String>) -> crate::DocOutput {608 match output {609 crate::DocOutput::SignRequest(request) => {610 crate::DocOutput::SignRequest(SignRequest { path, ..request })611 }612 other => other,613 }614}615616/// The answer to an [`AnchorRange`].617#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]618pub struct Anchored {619 pub req: RequestId,620 pub outcome: AnchorOutcome,621}622623/// What an [`AnchorRange`] found.624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]625pub enum AnchorOutcome {626 /// The range's cursor pair, anchored at `at`.627 Anchor(RangeAnchor),628 /// The text is empty at `at` and the range is `0..0`: the whole629 /// document.630 Whole,631 /// `UnknownBase` when the document lacks `at` (the `announce` error632 /// `UNKNOWN_BASE`), `OutOfBounds` when `start..end` is past the text633 /// there or empty in a text that isn't (`OUT_OF_BOUNDS`), `Failed`634 /// for a kind with no text, or a closed actor.635 Refused(RejectReason),636}637638/// What a committed tree save changed, as the render after it reports639/// it (`DocOutput::Rendered.touched`, discussion:owner/165): one range per save.640///641/// `start..end` are code points of the text at the render's heads. For a642/// text save they are the hull of the code points its splices changed there,643/// from the first to the last, snapped to whole lines by discussion:owner/160's rule644/// (a pure deletion names the line that holds its gap, and a save that645/// leaves the text empty names `0..0`); a save that creates the file, or646/// turns a binary file into text, names the whole text. `lines` names that647/// range there. `anchor` is the range anchored at the render's heads, as648/// `DocEvent::Anchor` anchors one, and is `None` for an empty range. A649/// removal and a binary save carry no anchor and name `0..0`, line 1 of an650/// empty text.651#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]652pub struct Touched {653 /// The range anchored at the render's heads; `None` for an empty one.654 pub anchor: Option<RangeAnchor>,655 /// The range's first code point.656 pub start: usize,657 /// The code point after its last.658 pub end: usize,659 /// The range's lines, as a reader is shown them.660 pub lines: LineName,661 /// What the save did there.662 pub op: TouchOp,663}664665/// What a render of a derived document hid (row 180).666///667/// The document has two or more heads, and the state at the greatest of668/// them by `ChangeId` bytes has `/meta/derived` true, so every reader is669/// shown the text at that head alone. Every node computes the same value670/// from the document.671#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]672pub struct Superseded {673 /// The head whose text is shown.674 #[serde(with = "crate::cbor::hash")]675 pub shown: ChangeId,676 /// Each other head whose text differs from the shown text, in head677 /// order, with its change's signer (discussion:owner/125's records).678 pub hidden: Vec<HiddenHead>,679}680681/// One head a derived document's render hid ([`Superseded`]).682#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]683pub struct HiddenHead {684 /// The hidden head.685 #[serde(with = "crate::cbor::hash")]686 pub head: ChangeId,687 /// The signer its change's record names.688 pub author: PeerKey,689}690691/// How a save changed its file (discussion:owner/165).692#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]693pub enum TouchOp {694 /// Every splice only inserted, or the save created the file.695 Adding,696 /// The splices inserted and deleted, a binary file became text, or a697 /// binary save.698 Changing,699 /// Every splice only deleted, or the file was removed.700 Removing,701}702703/// The answer to a [`ResolveAnchors`].704#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]705pub struct Resolved {706 pub req: RequestId,707 pub outcome: ResolvedOutcome,708}709710/// What a [`ResolveAnchors`] found.711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]712pub enum ResolvedOutcome {713 /// Each anchor's span at `heads`, in order; `None` while the document714 /// lacks an anchor's heads or the anchor names characters not visible715 /// at them. `lines` names each span, in the same order, as a reader is716 /// shown it, from the text at `heads` (`lines::name`; a collapsed span717 /// names the line its gap is in), and is `None` where the span is718 /// (discussion:owner/165). A read: `heads` are the live heads, which719 /// may name a change not yet stored; only an answer's heads720 /// ([`crate::DocOutput::Changed`]'s `stored`) are a durable base721 /// (discussion:owner/720).722 Spans {723 #[serde(with = "crate::cbor::heads")]724 heads: Vec<ChangeId>,725 spans: Vec<Option<AnchorSpan>>,726 /// Each span's name, in order.727 lines: Vec<Option<LineName>>,728 },729 /// `Failed` when the document has no text to resolve against, or is730 /// closed.731 Refused(RejectReason),732}733734/// The record behind each writer's Loro peer of the signed changes this735/// document holds: its signer, grant, device, and epoch (history row 457;736/// a peer id is `peer_of` its record, so each names one). Emitted after a737/// step that adds a writer, and on `Render`. The daemon gathers every738/// document's pairs into one map for attribution, and the protected-path739/// gate reads it (discussion:owner/122).740#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]741pub struct Signers {742 pub signers: BTreeMap<u64, crate::change::Record>,743}744745/// One stored document as `lvcs audit` checks it (discussion:owner/463, teardown746/// invariant 3): its spec, its stored signed changes in the order stored,747/// the peers it refused (each one's first refused counter), and its748/// equivocation evidence, as [`crate::LoadDoc`] takes them.749#[derive(Debug, Clone, Copy)]750pub struct StoredDoc<'a> {751 pub spec: &'a DocSpec,752 pub changes: &'a [crate::change::SignedChange],753 pub refused: &'a BTreeMap<u64, i32>,754 pub evidence: &'a [crate::change::Evidence],755}756757/// A ledger's held changes as [`HistoryAudit::follow_held`] reads them:758/// their metadata, with the stored refusals and evidence.759pub(crate) struct HeldDoc<'a> {760 pub(crate) spec: &'a DocSpec,761 pub(crate) held: &'a [crate::ledger::Held],762 pub(crate) refused: &'a BTreeMap<u64, i32>,763 pub(crate) evidence: &'a [crate::change::Evidence],764}765766/// What [`verify_history`] found in a document that passed: how many767/// changes it checked.768#[derive(Debug, Clone, Copy, PartialEq, Eq)]769pub struct Audited {770 pub changes: u64,771}772773/// A stored change of a document that fails774/// the audit, and why.775#[derive(Debug, Clone, PartialEq, Eq)]776pub struct AuditViolation {777 pub change: Option<ChangeId>,778 pub reason: AuditReason,779 /// For a change its kind refused, what it needed and whose it was.780 pub detail: Option<String>,781}782783/// Why a stored change fails the audit.784#[derive(Debug, Clone, PartialEq, Eq)]785pub enum AuditReason {786 /// It is a sender's fault or malformed ([`SyncRejection`]), or the787 /// audit can't run on its kind (`Unavailable`).788 Fault(SyncRejection),789 /// Sync would refuse it (history row 459).790 Refused(crate::change::Refusal),791 /// A dep, its grant, or its path isn't known where it is stored: the792 /// store's order isn't causal, or its grant is unknown.793 Waiting,794 /// The store's refusals drop it, yet the audit's own checks admit it:795 /// it was dropped on no proof (discussion:owner/549, teardown invariant 8).796 DroppedUnproven,797}798799/// One change of a `file` document's history, as `lvcs audit`'s secret800/// scan reads it: the change, and the text the document801/// renders at it (its heads being that change alone).802#[derive(Debug, Clone, PartialEq, Eq)]803pub struct ChangeText {804 pub change: ChangeId,805 pub text: String,806}807808/// The `.lvcs/caps` document's render, after every applied change and on809/// `Render`: the root its seed holds (`None` while it holds only genesis),810/// every signed grant whose signature verifies, by id, the signed811/// allowlist, every `/allowlist` key that is a hash in `ID_ENCODING`812/// (discussion:owner/128), and the revocations, every `/revoked` key that is a813/// grant id in `ID_ENCODING` with its revocation time (discussion:owner/148), the814/// smallest `Int` among concurrent values when revocations of one grant815/// conflict, so the earliest one counts on every node, and the installed816/// plugins, every `/plugins/<name>` value that decodes to a bounded817/// `PluginRecord` (discussion:owner/514). The shell feeds it818/// to every document actor ([`GrantsKnown`], `root` only when its project819/// id is this daemon's), summarized per signer, to the gossip actor, and820/// its allowlist to the secret scan, as `lvcs audit` does.821#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]822pub struct CapsRendered {823 #[serde(with = "crate::cbor::heads")]824 pub heads: Vec<ChangeId>,825 pub root: Option<ProjectRoot>,826 pub grants: BTreeMap<GrantId, SignedGrant>,827 pub allowlist: BTreeSet<SecretHash>,828 pub revoked: BTreeMap<GrantId, i64>,829 pub plugins: BTreeMap<String, PluginRecord>,830 /// The purged documents by address, each with its purge time831 /// (discussion:owner/614): every `/purged` key that is a bare file id832 /// (its document's `.lvcs/files/<id>`) or a plugin's entry ledger's833 /// address, holding an `Int`.834 pub purged: BTreeMap<String, i64>,835 /// The name the owner is shown by (discussion:owner/682): the root's836 /// `owner_name`, which the seed writes, when it is an owner name837 /// (`owner_name_valid`); `None` shows the owner as `owner`.838 #[serde(default)]839 pub owner_name: Option<String>,840}