Skip to main content

Edge

Struct Edge 

pub struct Edge<R, A = Accept> { /* private fields */ }
Expand description

One replication edge: the local side’s view of one peer relationship.

Generic over the far side’s resume token R rather than over the peer, so the struct carries no bound and the peer is borrowed per step rather than owned.

And over the merge rule A it applies to what it pulls, Accept unless with_adjudicator says otherwise. A type parameter rather than a per-step argument, because SY-7 assigns a rule to an edge for its life, and a rule handed to each step could change between two of them. Defaulted, so Edge<R> still names the edge that judges nothing.

§One edge, one peer, for its whole life

The token is the peer’s, and the watermark says what that peer acknowledged. Stepped against a different peer, the edge would hand the second peer a token it never minted and skip every local event the first one confirmed. Where the far side names its store on its answers (ADR-0104), the edge catches that: it stops at the first answer from another store (StopCause::Incarnation). Where it does not, nothing in the type stops it, so it is the caller’s to keep: build one edge per peer, and a new edge when a peer is replaced.

§Examples

A local store pushes what it holds to a hub and pulls what the hub holds, then reads its status without another round trip:

use happenstance_core::{Event, EventStore, StoreId};
use happenstance_sync::runner::{Edge, EdgeState, Pending};
use happenstance_sync::{MemoryIngestStore, MemorySyncPeer};

let hub = MemorySyncPeer::new(StoreId::from_bytes([2; 16]));
let tablet = MemoryIngestStore::new();
let taken = tablet
    .append(&[Event::new("ReadingTaken", &b"{\"celsius\":4}"[..])?], None)
    .await?;

let mut edge = Edge::new();
let stepped = edge.step(&hub, &tablet).await?;

assert_eq!(stepped.pushed, 1);
let status = edge.status();
assert_eq!(status.state, EdgeState::Running);
assert_eq!(status.confirmed, Some(taken));
assert_eq!(status.pending, Pending::Exactly(0));
assert!(status.is_synced());

Implementations§

§

impl<R, A: Adjudicate> Edge<R, A>

pub async fn run<P, S, Z>( &mut self, peer: &P, store: &S, backoff: &mut Backoff, sleep: &Z, ) -> Result<(), StepFailure<P, S, A>>
where P: SyncPeer<Resume = R>, S: WriteGroupStore + IngestStore, Z: Sleep,

Steps until the edge is synced, or quiet, or halts: a caller-owned loop, driven on whatever runtime the caller has. Nothing is spawned.

It returns Ok after a step that left the edge synced, or that left it quiet: the step pushed nothing, ingested nothing it lacked, and did not read through echoes toward something waiting. So a far side that cannot say Waiting::Nothing still lets the run end. Call it again to sync again; how often is the caller’s.

Echoes are this edge’s own events coming back, as they do on a pull from the start of the far side’s log. A page of them moves nothing, yet the run reads on while the far side’s Waiting::Events count falls, because what is waiting behind them may be new. A count that holds or rises is no progress, so a far side stuck on one page cannot hold the run.

After a Transient failure it waits the backoff’s next delay through sleep and steps again, and a successful step resets the backoff. After a Split the edge could halve, it steps again at once, with the smaller batch.

Every pass of the loop either moved an event, lowered the far side’s waiting count, halved the batch, or spent a backoff attempt, so the run ends; and it can be dropped between any two awaits without losing anything a later run does not redo.

§Errors

The step error that ended the run: one that parked or stopped the edge, including StepError::Incarnation, or the last transient failure once the backoff’s attempts are spent. In that last case the edge is still running, and a later run retries: the remedy for a far side that stays down is the caller’s.

§Examples

A run against a reachable hub ends synced, without waiting at all:

use core::time::Duration;

use happenstance_core::{Event, EventStore, StoreId};
use happenstance_sync::runner::{Backoff, Edge, Sleep};
use happenstance_sync::{MemoryIngestStore, MemorySyncPeer};

/// The caller's clock. A real one awaits its runtime's timer here —
/// `tokio::time::sleep`, a Durable Object alarm — which the library never
/// names; this run never fails, so it is never called.
struct Clock;

impl Sleep for Clock {
    async fn sleep(&self, _duration: Duration) {}
}

let hub = MemorySyncPeer::new(StoreId::from_bytes([2; 16]));
let tablet = MemoryIngestStore::new();
tablet
    .append(&[Event::new("ReadingTaken", &b"{\"celsius\":4}"[..])?], None)
    .await?;
let mut backoff = Backoff::new(Duration::from_millis(100), Duration::from_secs(30), 7)?;

let mut edge = Edge::new();
edge.run(&hub, &tablet, &mut backoff, &Clock).await?;

assert!(edge.status().is_synced());
§

impl<R> Edge<R>

pub const DEFAULT_BUFFER: NonZeroUsize

The most local events one push carries unless with_buffer says otherwise: eight times PeerLimits::minimum’s batch.

pub const fn new() -> Self

An edge that has never exchanged: it pulls from the start of the far side’s log and pushes the whole local log.

Examples found in repository?
examples/two-devices-one-seat/src/scenario.rs (line 142)
134    fn linked_to(central: &Central, rule: A) -> Self {
135        // Two handles onto one store: central's read half and ingest half
136        // must be the same store, and a `SqliteEventStore` clone is a second
137        // handle onto the same connection, not a copy of the log.
138        let far = StoreSyncPeer::new(central.clone(), central.clone()).with_adjudicator(rule);
139        let limits = far.limits();
140        Self {
141            peer: RemoteSyncPeer::new(Uplink::new(far), limits),
142            edge: Edge::new(),
143        }
144    }

pub const fn resuming( confirmed: Option<SequencePosition>, resume: Option<R>, ) -> Self

An edge resuming from a watermark and a token a caller kept.

confirmed is the first position of the last local write group the far side acknowledged, as SyncStatus::confirmed reported it; resume is the token resume_token reported. Both are about this link only, and where they are stored is SY-31’s. Pair it with with_responder, so the resumed edge still knows which store it synced with.

pub fn with_adjudicator<B>(self, rule: B) -> Edge<R, B>

The same edge, judging what it pulls by rule: each pulled group lands in one write with the compensation rule answers for it (SY-2, SY-7).

Only the pull: what the edge pushes is the far side’s to judge. Give an edge a rule when its local side is the adjudicator SY-7 assigns for the facts it pulls, such as a hub that drives its own edge to a spoke.

The edge holds rule by value, and no bound is placed on it here: the edge is Debug only when B is, and its step future is Send only for a SendAdjudicate rule that is Send + Sync.

§Examples
use happenstance_sync::runner::{Accept, Edge};

// `Accept` stands in for a rule of the caller's own; `u64` for the far
// side's resume token.
let edge: Edge<u64, Accept> = Edge::new().with_adjudicator(Accept);
assert!(edge.resume_token().is_none());

pub const fn restored(watermark: Watermark) -> Self

An edge resuming from a kept watermark: it pushes what the local log holds above it, pulls from the start of the far side’s log, and stops at the first answer from a store other than the watermark’s peer.

Edge::resuming with the watermark’s position and no token, then with_responder with its peer.

§

impl<R, A> Edge<R, A>

pub const fn with_responder(self, responder: StoreId) -> Self

The same edge, knowing the far side as responder: the SyncStatus::responder a caller kept. Its first answer from any other store stops it.

Without it, a resumed edge pins the first store that answers it, so a far side restored while the edge was down would go unnoticed.

pub const fn with_buffer(self, buffer: NonZeroUsize) -> Self

The same edge, carrying at most buffer local events per push, and holding at most one more than that in memory per step, whatever the peer’s limits declare. A single write group larger than buffer is still read and offered whole, alone: the store’s own write limits bound it.

pub const fn status(&self) -> &SyncStatus

The edge’s status as of its last step. No I/O.

Examples found in repository?
examples/two-devices-one-seat/src/scenario.rs (line 323)
303    pub async fn sync(&mut self, device: Device) -> Result<Synced, StoryError> {
304        // What landed is counted on central's log before and after: two whole
305        // reads, which a log of six events can afford and a real one would
306        // replace with a count query.
307        let before = self.central.log(Place::Central).await?.len();
308        let (site, handset) = match device {
309            Device::Tablet => (&self.tablet, &mut self.tablet_link),
310            Device::Phone => (&self.phone, &mut self.phone_link),
311        };
312        let mut synced = Synced::default();
313        for _ in 0..MAX_STEPS {
314            let stepped = handset
315                .edge
316                .step(&handset.peer, &site.events)
317                .await
318                .map_err(|source| StoryError::Sync {
319                    device,
320                    source: Box::new(source),
321                })?;
322            synced.pulled = synced.pulled.saturating_add(stepped.ingested.appended);
323            if handset.edge.status().is_synced() {
324                let after = self.central.log(Place::Central).await?.len();
325                synced.landed = after.saturating_sub(before);
326                return Ok(synced);
327            }
328        }
329        Err(StoryError::NotSynced {
330            device,
331            steps: MAX_STEPS,
332        })
333    }
334
335    /// A device's edge, as of its last step.
336    #[must_use]
337    pub const fn status(&self, device: Device) -> &SyncStatus {
338        self.handset(device).edge.status()
339    }

pub const fn resume_token(&self) -> Option<&R>

The token the next pull resumes from, for a caller that persists it.

pub const fn watermark(&self) -> Option<Watermark>

The edge’s confirmation watermark, to keep through the projection port (SY-31): the far side’s identity and SyncStatus::confirmed.

None until the edge knows both its peer and a confirmed position: before the far side has acknowledged a push, and for good with a far side that never names its store (ADR-0104), whose watermark has no id to be kept under. A caller who knows that peer’s identity another way builds one with Watermark::new.

§

impl<R, A: Adjudicate> Edge<R, A>

pub async fn step<P, S>( &mut self, peer: &P, store: &S, ) -> Result<Stepped, StepFailure<P, S, A>>
where P: SyncPeer<Resume = R>, S: WriteGroupStore + IngestStore,

One exchange: pull and ingest, then read and push.

The pull token, and SyncStatus::waiting, advance only once the pulled batch has been ingested, and the watermark only once the far side has acknowledged a push, so a failure anywhere re-offers the same events on the next step and loses none. The only local write is the ingest: a refused push leaves the local log as it was (SY-34).

Local events are read in their write groups above SyncStatus::confirmed, one event more than a batch may carry: the least of the peer’s limits, the edge’s buffer and any cap a split left. The groups that fit are pushed, one EventGroup each; the run stops at the first group that does not fit rather than skipping it, because the watermark is a prefix. If not even the first fits, it is offered alone, and the peer’s refusal states its class: the runner reads a class and never infers one (SY-36).

An answer naming a store other than SyncStatus::responder is not acted on: a pulled batch is not ingested, and an ack does not move the watermark.

Each pulled group is judged by the edge’s rule, with the groups before it in the batch, before any of them lands; each then lands in one write with the compensation the rule answered (SY-2). Under Accept that is none.

§Errors

A StepError naming the phase that failed and carrying the failure, StepError::Incarnation for an answer from another store, or StepError::Adjudicate for a rule that could not decide. Its class is recorded in SyncStatus::last_failure and acted on as the module describes. A parked or stopped edge returns StepError::Parked or StepError::Stopped without any I/O.

Examples found in repository?
examples/two-devices-one-seat/src/scenario.rs (line 316)
303    pub async fn sync(&mut self, device: Device) -> Result<Synced, StoryError> {
304        // What landed is counted on central's log before and after: two whole
305        // reads, which a log of six events can afford and a real one would
306        // replace with a count query.
307        let before = self.central.log(Place::Central).await?.len();
308        let (site, handset) = match device {
309            Device::Tablet => (&self.tablet, &mut self.tablet_link),
310            Device::Phone => (&self.phone, &mut self.phone_link),
311        };
312        let mut synced = Synced::default();
313        for _ in 0..MAX_STEPS {
314            let stepped = handset
315                .edge
316                .step(&handset.peer, &site.events)
317                .await
318                .map_err(|source| StoryError::Sync {
319                    device,
320                    source: Box::new(source),
321                })?;
322            synced.pulled = synced.pulled.saturating_add(stepped.ingested.appended);
323            if handset.edge.status().is_synced() {
324                let after = self.central.log(Place::Central).await?.len();
325                synced.landed = after.saturating_sub(before);
326                return Ok(synced);
327            }
328        }
329        Err(StoryError::NotSynced {
330            device,
331            steps: MAX_STEPS,
332        })
333    }

Trait Implementations§

§

impl<R: Debug, A: Debug> Debug for Edge<R, A>

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
§

impl<R> Default for Edge<R>

§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<R, A> Freeze for Edge<R, A>
where Option<R>: Freeze, A: Freeze,

§

impl<R, A> RefUnwindSafe for Edge<R, A>

§

impl<R, A> Send for Edge<R, A>
where Option<R>: Send, A: Send,

§

impl<R, A> Sync for Edge<R, A>
where Option<R>: Sync, A: Sync,

§

impl<R, A> Unpin for Edge<R, A>
where Option<R>: Unpin, A: Unpin,

§

impl<R, A> UnsafeUnpin for Edge<R, A>

§

impl<R, A> UnwindSafe for Edge<R, A>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.