Skip to main content

Pipeline

Struct Pipeline 

Source
pub struct Pipeline<T, B = (), P = Batch<'static>> { /* private fields */ }
Expand description

Streaming multithreaded hasher with bounded memory and pull-based Event delivery.

In a pool of one thread (initialize_multithreaded asked for one, or a machine with one CPU) there is no worker, and the calling thread hashes: in the calls that hand work over (commit, end, owned, lent and batch), and in the waits (ready, room and message). Short messages are gathered into groups, and a group that is not yet full is hashed by a later call or by a wait: so a short message’s event may come only after ready has been awaited, there as with workers, and its Lent guard is held until its event.

Pipelines, and the other multithreaded calls made beside them, share the pool’s workers. A worker looks for work among them in one order, and after every 16 takings it takes once from the next of them that has any, going round (a taking is one action, or a run of a call’s pieces): a Pipeline that streams without a pause slows another’s messages, and does not keep them waiting while it streams. The thread kept for SME2, where there is one, takes in the one order only.

§Memory

A Pipeline allocates its per-pipeline storage (Rooms — 64 KiB each, using a 1-byte-aligned zeroed byte buffer whose layout allows OS lazy demand-zero paging under standard allocators such as System/calloc, though custom allocators that eagerly zero on allocation will fault those pages — plus its groups, piece nodes, slots, and completion buffers) at construction and frees all of it back to the allocator once the Pipeline and any surviving Rooms have dropped. Completed Lent guards do not pin per-pipeline storage. Because freeing per-pipeline storage on drop makes repeated create/drop of equal limits slower than reusing one Pipeline, keep a Pipeline alive across requests (as # Giving up a message recommends) rather than creating and dropping one per short message.

Only the worker-facing action ring (on pools with workers), waker slot, and monotonic completion lines (PipeSlot) are retained for reuse by later Pipelines:

  • Multi-worker pools (threads > 1): 24 bytes per action (at least 1,024 actions = 24 KiB) plus 128-byte completion lines sized to the rounded power-of-two tier (cap / 64 slot lines and clamp(cap / 64, 4, 256) group lines), where cap rounds up actions (messages * 64 when rooms == 0, else messages * 64 + rooms + messages + 1 + clamp(messages, 4, 256)).
  • One-thread pools (threads == 1): zero ticket slots are allocated or retained (actions_len() == 0), while waker and completion lines size to the power-of-two tier of (messages * 64).max(1024) (independent of rooms).

Because slots round to powers of two and match exact-tier first then best-fit (loan_completed.len() * 64 >= need), ascending Limits keep retained power-of-two tier units (action-ring tickets on worker pools and loan_completed lines on all pools) below twice the largest tier per peak overlapping slot acquisition (counting concurrent constructors/destructors from cache lookup through return to the free list; group_completed caps at 256 lines per slot and fixed per-slot headers scale linearly with the number of distinct retained tiers), and varying Limits.rooms within a power-of-two tier reuses the same slot. As before, no call of this crate wipes freed memory or keys.

§Giving up a message

The contract is the caller’s, and a server’s peers must not be able to break it for the server:

  • A message whose bytes will not all come (its client went away) goes to abort. The Pipeline forgets it, gives its Event::Aborted, and goes on with the others. A Message that is dropped instead panics.
  • A Pipeline is dropped only when it has nothing left to hash: every message ended or aborted, and every message’s event taken with next_event. Dropped while a worker may still be reading its buffers, it stops the whole process. (Dropped earlier than this rule allows at a moment when nothing it has handed to the pool is unfinished, it drops what it holds, and what it had not handed over is never hashed.)

So keep a Pipeline in a task that outlives its clients (one for a thread’s connections, not one a connection), and do not let a time-out or a cancelled task drop it mid-message.

§Panics

Each call says what it refuses. When owned, lent, or batch panics on a Message of this Pipeline (bytes given two ways, a batch of the wrong shape, or an owner’s as_ref panicking), the rejected message’s slot is aborted cleanly (releasing any Room credit, dropping any unwritten owner, and queuing Event::Aborted) so the Pipeline stays usable and later message calls do not hang. A Message given by value to another Pipeline is refused before that Pipeline touches its own slots (so the refusing Pipeline goes on as it was, while the other Pipeline’s slot remains open with no Message left to name it, and that other Pipeline is good only for dropping). (commit borrows its Message: after its panic the Message is still the program’s, and its drop panics as any open Message’s does, unless the thread is unwinding already.) A Waker that panics when it is cloned or dropped may leave the Pipeline usable only for dropping; a waker that panics when it is woken ends the process, on whichever thread it is woken: the wake comes in the middle of other work, which a panic would leave half done.

use blake3_servil::{Mode, convenience, throughput::{Event, Limits, Pipeline, block_on}};
// A client's next bytes, or the error of one that went away.
async fn read(client: u32, into: &mut [u8]) -> std::io::Result<usize> {
    if client == 1 {
        return Err(std::io::ErrorKind::ConnectionReset.into());
    }
    into[..5].copy_from_slice(b"hello");
    Ok(5)
}

let mut pipeline = Pipeline::new(Mode::Plain, Limits { messages: 2, rooms: 2 });
block_on(async {
    for client in [0u32, 1, 2] {
        let mut message = pipeline.message(client, None).await;
        let mut room = pipeline.room().await;
        match read(client, room.bytes_mut()).await {
            Ok(n) => {
                pipeline.commit(&mut message, &mut room, n);
                pipeline.end(message);
            }
            // Not `?`: the message goes back first.
            Err(_) => pipeline.abort(message),
        }
    }
    // Every event taken: the Pipeline may then be dropped.
    let mut seen = Vec::new();
    while seen.len() < 3 {
        match pipeline.next_event() {
            Some(Event::Hashed { tag, hash, .. }) => seen.push((tag, Some(hash))),
            Some(Event::Aborted { tag, .. }) => seen.push((tag, None)),
            Some(_) => unreachable!(),
            None => pipeline.ready().await,
        }
    }
    let hello = Some(convenience::hash(b"hello"));
    assert_eq!(seen, [(0, hello), (1, None), (2, hello)]);
});

§Trait implementations

  • Drop stops the process (an abort) if work it has handed to the pool is unfinished, whether a worker is hashing it or it still waits for one; otherwise it drops quietly, with the messages not yet handed over, the events not taken and their owners, frees its per-pipeline storage (once any surviving Rooms also drop), and returns its worker-facing slot for reuse.
  • Send lets a pipeline move between threads when its tags, owners, and batches are Send, keeping the same messages and tokens.

Implementations§

Source§

impl<T> Pipeline<T, (), Batch<'static>>

Source

pub fn new(mode: Mode<'_>, limits: Limits) -> Self

Create a pipeline in mode with fixed memory limits.

§Panics

If limits.messages is zero, or if limits.messages and limits.rooms together reach 2^29 - 1 (the Pipeline numbers its work in 29 bits). Before initialize_multithreaded, and in a child process forked after that call started the pool’s threads.

Source§

impl<T, P: Prepared + 'static> Pipeline<T, (), P>

Source

pub fn with_batches(mode: Mode<'_>, limits: Limits) -> Self

Create a pipeline whose Pipeline::batch accepts owned prepared batches of type P, such as Packed<16>, Packed<32>, Packed<48>, Vec<[u8; 32]>, Box<[[u8; 32]]>, or Batch<'static>.

§Panics

As new.

Source§

impl<T, B: AsRef<[u8]> + 'static> Pipeline<T, B, Batch<'static>>

Source

pub fn with_owners(mode: Mode<'_>, limits: Limits) -> Self

Create a pipeline that also accepts owned message buffers of type B (Pipeline::owned): a type that owns its bytes, such as Vec<u8> or Box<[u8]>.

use blake3_servil::{Mode, throughput::{Limits, Pipeline}};
fn pipeline_of<B: AsRef<[u8]> + 'static>(_first: B) -> Pipeline<(), B> {
    Pipeline::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 })
}
let _ = pipeline_of(vec![0u8; 64]);

A borrowed slice is no owner (the same code but for the borrow, so this fails for that reason):

ⓘ
use blake3_servil::{Mode, throughput::{Limits, Pipeline}};
fn pipeline_of<'a>(_first: &'a [u8]) -> Pipeline<(), &'a [u8]> {
    Pipeline::with_owners(Mode::Plain, Limits { messages: 1, rooms: 0 })
}
§Panics

As new.

Source§

impl<T, B: AsRef<[u8]> + 'static, P: Prepared + 'static> Pipeline<T, B, P>

Source

pub fn with_owners_and_batches(mode: Mode<'_>, limits: Limits) -> Self

Create a pipeline that accepts both owned message buffers of type B (Pipeline::owned) and owned prepared batches of type P (Pipeline::batch).

§Panics

As new.

Source§

impl<T, B: AsRef<[u8]> + 'static, P> Pipeline<T, B, P>

Source

pub fn owned(&mut self, message: Message, owner: B)

Hash owner’s bytes in place and return owner in the message’s Event::Hashed.

§Panics

If message is another Pipeline’s, or has had a commit from a Room already, even one of no bytes: a message’s bytes come one way.

Source§

impl<T, B, P: Prepared + 'static> Pipeline<T, B, P>

Source

pub fn batch(&mut self, message: Message, batch: P, digests: Box<[[u8; 32]]>)

Hash batch into digests and return both in Event::Batch.

Accepts any owned Prepared batch type P chosen when the pipeline was constructed (Batch<'static> by default, or Packed<N> / Vec<[u8; N]> / Box<[[u8; N]]> via Pipeline::with_batches or Pipeline::with_owners_and_batches).

§Panics

If message is another Pipeline’s, or has had a commit from a Room already (even one of no bytes); or if digests has not one place for each message of batch.

Source§

impl<T, B, P> Pipeline<T, B, P>

Source

pub fn message( &mut self, tag: T, length_hint: Option<u64>, ) -> impl Future<Output = Message> + '_

Wait for a free message slot and open a Message in this pipeline’s default Mode.

length_hint is currently ignored (None suffices); actual message lengths are determined by the bytes submitted via commit + end, lent, owned, or batch.

§Panics

If no slot is free and waiting cannot free one: as many messages as Limits.messages are open, or as many events wait to be taken (next_event). Only this task could end one or take one, and it is here.

Source

pub fn message_with<'p>( &'p mut self, mode: Mode<'_>, tag: T, length_hint: Option<u64>, ) -> impl Future<Output = Message> + use<'p, T, B, P>

Wait for a free message slot and open a Message hashed in mode, overriding this pipeline’s default Mode for that message alone.

length_hint is currently ignored (None suffices); actual message lengths are determined by the bytes submitted via commit + end, lent, owned, or batch.

mode is prepared immediately, so the returned future does not borrow mode’s key or context string. Short messages opened with Pipeline::message or message_with(Mode::Plain, ..) batch by public provenance; keyed and derived per-message modes are never grouped across messages so dispatch never depends on secret key bytes.

§Panics

Same as Pipeline::message.

Source

pub fn room(&mut self) -> impl Future<Output = Room> + '_

Wait for a Room of ROOM_LEN bytes.

A Room is free again when it has been dropped, on any thread, and the bytes committed from it have been hashed. (A message’s last commit of less than a whole Room may keep its Room until the message is ended or aborted, or until a wait here sends it on.) A program that keeps every Room alive waits here for ever.

§Panics

If the Pipeline has no Rooms (Limits.rooms is 0).

Source

pub fn commit(&mut self, message: &mut Message, room: &mut Room, written: usize)

Commit the first written bytes of room as message’s next bytes.

room advances to the next 64-byte boundary. Every commit to a message except its last must be a whole room (ROOM_LEN bytes).

§Panics

If message or room is another Pipeline’s; if written is more than room has left (Room::len); if an earlier commit to message was of less than a whole Room.

Source

pub fn end(&mut self, message: Message)

Finish message and queue its Event::Hashed in end order.

§Panics

If message is another Pipeline’s.

Source

pub fn abort(&mut self, message: Message)

Abort message and queue its Event::Aborted in end order.

§Panics

If message is another Pipeline’s.

Source

pub unsafe fn lent<'a>(&mut self, message: Message, bytes: &'a [u8]) -> Lent<'a>

Hash bytes in place on loan, returning a Lent guard.

§Safety

The returned Lent guard must be dropped and never leaked (core::mem::forget, Box::leak, a reference cycle, or a leaked task holding it).

§Panics

If message is another Pipeline’s, or has had a commit from a Room already, even one of no bytes: a message’s bytes come one way.

Source

pub fn next_event(&mut self) -> Option<Event<T, B, P>>

Pull the next finished Event, if one is ready.

This takes what is finished and starts nothing. A message’s work may wait for ready (or another wait of this Pipeline) to hand it to the workers, so a loop that calls only this may never be given an event: where this gives None, await ready.

Source

pub fn ready(&mut self) -> impl Future<Output = ()> + '_

Wait until Pipeline::next_event has an Event ready.

§Panics

If no message has been ended (or aborted, or handed over whole) whose event is still to come: nothing would end the wait.

Trait Implementations§

Source§

impl<T, B, P> Drop for Pipeline<T, B, P>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
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
Source§

impl<T: Send, B: Send, P: Send> Send for Pipeline<T, B, P>

Auto Trait Implementations§

§

impl<T, B = (), P = Batch<'static>> !RefUnwindSafe for Pipeline<T, B, P>

§

impl<T, B = (), P = Batch<'static>> !Sync for Pipeline<T, B, P>

§

impl<T, B = (), P = Batch<'static>> !UnwindSafe for Pipeline<T, B, P>

§

impl<T, B, P> Freeze for Pipeline<T, B, P>

§

impl<T, B, P> Unpin for Pipeline<T, B, P>

§

impl<T, B, P> UnsafeUnpin for Pipeline<T, B, P>

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.