Skip to main content

Writer

Struct Writer 

Source
pub struct Writer { /* private fields */ }
Available on crate feature write only.
Expand description

Handle to the writer thread. Every fallible hand-off reports the writer’s stored error, in the required order: send-failure → join → report.

Implementations§

Source§

impl Writer

Source

pub fn create( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, ) -> Result<Self>

Create the archive at path and spawn its writer thread.

The file is a valid, openable archive from the moment this returns: there is no .partial, no rename at the end, and nothing to move aside at the start (Archive::create refuses an existing file atomically). No staging file is needed: an early-killed source is a source whose complete is 0.

The archive holds no sources yet; add each with add_source.

Source

pub fn create_checkpointing_every( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, checkpoint_every: Duration, ) -> Result<Self>

create with the WAL checkpoint cadence chosen by the caller.

Exists so the staleness bound is testable: asserting it through create would mean a test that sleeps CHECKPOINT_INTERVAL. Production takes the constant.

Source

pub fn create_beating_every( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, heartbeat_every: Duration, ) -> Result<Self>

Available on crate features test-support only.

create with the heartbeat cadence chosen by the caller, so a reader’s liveness rule is testable without waiting HEARTBEAT_INTERVALs.

Source

pub fn open( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, ) -> Result<Self>

Reopen an existing archive to append to it.

Opening changes nothing; a source is changed only by resume_source, which is what a caller that wants to continue one calls next. Segment numbering continues from what the file holds. A second writer of this file is refused as Error::InUse.

Source

pub fn open_checkpointing_every( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, checkpoint_every: Duration, ) -> Result<Self>

open with the WAL checkpoint cadence chosen by the caller.

Source

pub fn create_with_busy_timeout( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, checkpoint_every: Duration, busy_timeout: Duration, ) -> Result<Self>

Available on crate features test-support only.

create_checkpointing_every with the writer connection’s busy_timeout chosen by the caller.

Exists so the writer’s retry path is testable: with rusqlite’s 5 s default, a test that holds the write lock from a second connection would wait five seconds per attempt to see the writer notice.

Source

pub fn encoder_version(&self) -> Option<&str>

The version the archive’s encoder reports, which the writer records under keys::ENCODER for each source it adds.

Source

pub fn add_source(&mut self, seed: SourceMeta) -> Result<SourceWriter>

Open one source in this archive and return its writer handle.

Several may be open at once — that is the point of the container’s label-tagged sources list — and they are independent: each has its own segment sequences, its own clock-offset series, and its own complete flag.

Source

pub fn add_source_with_uuid( &mut self, seed: SourceMeta, uuid: Option<&str>, ) -> Result<SourceWriter>

add_source, for a source whose identity was minted somewhere else.

add_source mints a fresh uuid, which is right for a source this process is starting. This one carries an existing identity across, so that the row here is that source rather than another one with the same labels — the property SourceRow::uuid exists for, and what makes “do these two archives hold the same source” a comparison instead of a guess (FORMAT.md §3.1).

None mints a fresh one, exactly as add_source does. That is the right answer for a source from an archive written before the column existed: a fresh id claims only that two copies are not known to differ, where reusing a NULL would claim they are the same.

A uuid the archive already holds is refused as Error::DuplicateSource (FORMAT.md §3.1). Nothing checks that it is a UUID at all; it is the caller’s identity to assign, and the archive stores it the way it stores labels.

Source

pub fn resume_source( &mut self, source_id: i64, clock_anchor_wall_ns: i64, ) -> Result<(SourceWriter, Option<i64>)>

Continue an existing source in a reopened archive, as a new writer session.

The source’s complete flag is cleared, the session is recorded (keys::WRITER_SESSIONS, plus a writer_session event under keys::EVENTS at the new anchor), and the handle refuses any row stamped at or before the newest row the source has held, the returned last_ts. That is the newest row it holds, or a newer one that retention or a discard removed, since a stream’s timestamps strictly increase for the life of its source. So a clock that went backwards across the restart is Error::TimelineBackwards, not a silent collision or a timeline that runs backwards. The anchor itself is checked the same way.

clock_anchor_wall_ns is this session’s anchor: the resuming process has a fresh monotonic clock, so its rows are anchor + elapsed from a new wall reading, not from the source’s original anchor; rows keep timestamp + wall_offset = wall either way, and the gap between sessions is real time during which nothing was recorded.

Source

pub fn path(&self) -> &Path

The archive being written — valid and readable while it is written.

Source

pub fn put_document( &mut self, kind: &str, name: &str, schema: &str, body: &str, ) -> Result<RevisionId>

Write a new revision of document (kind, name) through the writer thread, and return its id and uuid once it is committed.

ArchiveMut::put_document, for an archive this writer is recording: an ArchiveMut cannot open a file a writer holds, and there is one writing connection, so a document written during a recording goes through this thread like every other write. It is ordered after everything queued before it and committed on its own. A refusal (a reserved kind, a body that is not JSON, a v4 archive reopened with Writer::open, which takes no documents) is returned and does not stop the writer.

Source

pub fn put_document_if_current( &mut self, kind: &str, name: &str, schema: &str, body: &str, expected: Option<&str>, ) -> Result<RevisionId>

ArchiveMut::put_document_if_current through the writer thread: refused with Error::DocumentConflict unless the current document’s uuid is expected.

Source

pub fn delete_document( &mut self, kind: &str, name: &str, ) -> Result<Option<RevisionId>>

ArchiveMut::delete_document through the writer thread.

Source

pub fn join(&mut self) -> Result<()>

Close the channel and join the writer, returning its stored result. Idempotent: a second call is a no-op Ok.

Drop every handle first — but not because this would otherwise block. Shutdown is sent below before our own sender is released, and the writer honors it whoever else still holds a clone, so a wrong order is an error (work queued after the stop is dropped), not a hang. The guarantee comes from Msg::Shutdown, not from the drop order, and removing it would turn every “must drop first” note in this file into a real deadlock.

Source

pub fn wal_tick(&mut self, ticks: Vec<(i64, Vec<WalRow>)>) -> Result<()>

Commit one tick’s staged rows for every source in one transaction.

The multi-source counterpart to SourceWriter::wal. Each source’s rows come from the caller’s staging; this hands them over together so the archive pays one commit — one fsync at synchronous=FULL — per tick rather than one per endpoint.

The hand-off is a blocking send on a bound-1 channel from inside the append, so a per-source commit put a linear-in-endpoint-count fsync bill on the loop that has to keep up with the sampling interval. seal_batch already refused exactly this trade within one source; this is the same argument across them.

An empty batch does not send: it still checks the writer is alive, so a tick where nothing advanced cannot mask a dead writer.

Source

pub fn commits_for_test(&mut self) -> u64

Available on crate features test-support only.

How many transactions the writer has committed, as a barrier: the answer arrives only after everything queued ahead of it is handled.

Exists so “one commit per tick, whatever the endpoint count” is a property a test asserts rather than a comment claims — an fsync is not observable from inside the process, but the commit that causes it is.

Source

pub fn finalize_single( self, writer: SourceWriter, clock_offset: (i64, i64), ) -> Result<()>

Available on crate features test-support only.

Finalize the one source and join the writer, so the file is fully committed when this returns.

The synchronous shape callers had before finalize was split: the handle can only queue completion now, since the archive owns the thread, so anything that reads the file straight afterwards has to join too.

Source

pub fn single( path: &Path, encoder: Box<dyn SegmentEncoder + Send>, seed: SourceMeta, ) -> Result<(Self, SourceWriter)>

Available on crate features test-support only.

Create an archive holding exactly one source.

The shape every caller had before archives could hold several, and still what a rolling buffer and a single-producer source want. Returns both halves because the archive owns the writer thread and must outlive the handle — Shutdown means a wrong order is an error rather than a hang, but the right order is still: finish with the handle, then join.

Trait Implementations§

Source§

impl Debug for Writer

Source§

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

Formats the value using the given formatter. Read more
Source§

impl Drop for Writer

Source§

fn drop(&mut self)

The writer must be joined on every path out — including the ones that skip an explicit join — so a dropped archive never leaves a detached thread still writing to the database.

Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more

Auto Trait Implementations§

§

impl !RefUnwindSafe for Writer

§

impl !UnwindSafe for Writer

§

impl Forget for Writer

§

impl Freeze for Writer

§

impl Move for Writer

§

impl Send for Writer

§

impl Sync for Writer

§

impl Unpin for Writer

§

impl UnsafeUnpin for Writer

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more