Skip to content

Streams

Stream[T] — a shared bounded channel with backpressure in both directions.

Stream[T] is a shared handle to a bounded FIFO ring buffer. Every copy of the handle — passed as an argument, stored in a field, captured by a spawned block — refers to the same control block, which is what makes it a channel rather than a value.

The type is the task module’s: a file that names it or makes one says import task and writes task.Stream[int] and task.Stream.new[int](8). send, recv and the rest are methods on the handle and need no import of their own.

import task

fn round_trip() int {
    events: task.Stream[int] = task.Stream.new(4)
    events.send(1)
    events.send(2)
    events.close()

    mut total := 0
    for Some(v) := events.recv() {
        total = total + v
    }
    return total
}

for Some(v) := events.recv() is the drain idiom: it loops as long as the pattern matches and stops on the first None. Because recv waits, that None means the stream is over — not merely empty at this instant.

The naming rule

A bare name may suspend. A try_ name never does. It holds across the whole channel surface and is the only thing you have to remember:

Bare — may suspend try_ — never suspends
send(v) waits for a free slot try_send(v) answers false on a full ring
recv() waits for an element try_recv() answers None on an empty ring

The two Nones are different facts, and the rule is what tells them apart. try_recv()’s means nothing right now — a producer may be about to send. recv()’s means closed and drained — there will be no more.

Reaching for a try_ form is a decision to do something else with the time. If there is nothing else to do, the bare form is both simpler and cheaper: it parks the task at the reactor’s idle point instead of spinning through the scheduler.

Constructing

task.Stream.new takes a capacity, defaulting to 16. The element type comes from an explicit type argument or from the annotation.

import task

fn shapes() int {
    from_annotation: task.Stream[int] = task.Stream.new(4)
    from_type_arg := task.Stream.new[string](2)
    with_default_capacity := task.Stream.new[int]()
    return from_annotation.len() + from_type_arg.len() + with_default_capacity.len()
}

Capacity is fixed for the stream’s lifetime and bounds live buffered elements, not the total number that pass through. A capacity of zero or less is normalized to 1.

Choose it from the largest burst you intend to absorb and the size of T:

  • a small capacity couples producer progress tightly to consumer progress;
  • a larger capacity smooths bursts but keeps more values live;
  • capacity does not limit how many handles or producers share the channel.

Sending

Method Ring full Stream closed Effect
send(v) suspends until a slot frees or the stream closes returns false Suspend
try_send(v) returns false immediately returns false none
import task

fn publish(events task.Stream[int], value int) bool {
    return events.send(value)
}

fn publish_or_drop(events task.Stream[int], value int) bool {
    return events.try_send(value)
}

Use send when every accepted value must be delivered and the producer should slow to the consumer’s pace — a body pump, a log shipper, a work queue. Use try_send when dropping, coalescing or retrying is a deliberate producer policy — a metrics feed where the newest sample matters more than every sample.

Both return false on a closed stream, which is the canonical “stop producing” signal:

import task

fn produce(out task.Stream[int], count int) int {
    mut sent := 0
    mut i := 0
    for i < count {
        if !out.send(i) {
            return sent
        }
        sent = sent + 1
        i = i + 1
    }
    out.close()
    return sent
}

Ignoring the return value of a send is how items silently vanish. Branch on it.

Receiving

recv() removes the oldest buffered element and answers Some(v). When the ring is empty it suspends — the task parks on the stream’s consumer chain and a later send or close wakes it. It answers None only once the stream is both closed and drained.

import task

fn drain_all(events task.Stream[int]) int {
    mut total := 0
    for Some(event) := events.recv() {
        total = total + event
    }
    return total
}

That is the whole drain loop. No is_closed() check, no spin: a closed stream hands out everything it buffered before it answers None, so the loop cannot stop early and cannot fail to stop.

try_recv() is the same dequeue without the wait:

import task

fn consume_one_if_ready(events task.Stream[int]) int {
    match events.try_recv() {
        Some(event) => return event
        None => return -1
    }
}

Its None does not mean the stream is over. A loop written on try_recv that treats None as the end exits on the first momentarily-empty ring, which is the classic way to drop the tail of a queue. If you need that shape, ask is_closed() as well — or use recv, which already asks for you.

Either receive frees a ring slot, which wakes one producer parked in send. The received value moves out of the channel; the vacated slot is never read again.

Closing

close() rejects further sends, wakes every parked producer and consumer, and leaves buffered elements drainable.

import task

fn close_then_drain() int {
    events := task.Stream.new[int](4)
    events.send(1)
    events.send(2)
    events.close()

    mut total := 0
    for Some(value) := events.recv() {
        total = total + value
    }
    return total
}

Waking all of both chains is not an optimization detail — close is the last event a stream has, so anything still parked when it runs has no other waker. A recv blocked on an empty ring would never answer None, and a send blocked on a full one would never answer false.

Closing twice leaves the stream closed. Producers should treat send(...) == false as a request to stop.

Inspection

Method Meaning
len() Number of buffered, unconsumed items
is_empty() Whether len() is zero
is_closed() Whether close() has been called
import task

fn describe(events task.Stream[int]) string {
    if events.is_closed() && events.is_empty() {
        return "finished"
    }
    return "${events.len()} buffered"
}

These are snapshots. In concurrent code, do not check is_empty() and then act as if a later receive will observe the same state — keep the decision inside one cooperative consumer loop, which recv already is.

Producer and consumer as separate tasks

The point of the shared handle is crossing a task boundary.

import task

fn produce(out task.Stream[int], count int) void {
    mut i := 1
    for i <= count {
        if !out.send(i) {
            return
        }
        i = i + 1
    }
    out.close()
}

fn run(count int) int {
    events := task.Stream.new[int](2)
    producer := spawn { produce(events, count) }

    mut total := 0
    for Some(v) := events.recv() {
        total = total + v
    }

    producer.await()
    return total
}

Capacity 2 with count well above it means both sides really do park: the producer on a full ring, the consumer on an empty one, each woken by the other. Neither one spins.

Multiple producers, one consumer

Handles copy freely, so several children can share one channel. Closing then becomes a coordination question: the last producer to finish should close, or the coordinator should close after joining all of them.

import task

fn produce(out task.Stream[int], base int, count int) int {
    mut sent := 0
    mut i := 0
    for i < count {
        if !out.send(base + i) {
            return sent
        }
        sent = sent + 1
        i = i + 1
    }
    return sent
}

fn collect(producers int, per_producer int) int {
    queue := task.Stream.new[int](8)

    mut workers: []task.Task[int] = []
    for p in 0..producers {
        workers.push(spawn { produce(queue, p * 100, per_producer) })
    }

    mut consumed := 0
    mut drained := 0
    for drained < producers * per_producer {
        match queue.recv() {
            Some(v) => {
                consumed = consumed + v
                drained = drained + 1
            }
            None => drained = producers * per_producer
        }
    }

    for Some(worker) := workers.pop() {
        worker.await()
    }
    queue.close()
    return consumed
}

The coordinator owns close() here, because no single producer knows it is last. The counted loop is what ends the drain: nobody has closed the stream yet, so recv would otherwise wait for a producer that has already finished.

The one block a stream leaves behind

task.Stream.new allocates the control block once, and nothing frees it. That is deliberate rather than a defect: a Stream is a shared handle, so a value-copy across a spawn capture or an argument aliases the same block — a Drop would free it on the first copy to fall out of scope and free it again on the second.

So a leak measurement over a program that uses a stream expects exactly one outstanding block per stream, and anything above that is a real leak. Fully draining a stream before abandoning it leaks nothing else: each element moves out exactly once and is dropped by whoever received it.

As a select source

A stream is a select source, and the arm’s await is recv — so what it binds is the next element, and its None means closed and drained.

A select arm and a blocking recv are the same wait: both join the stream’s consumer chain, in the same fairness order, and a send wakes whichever has been waiting longest. That is why a select arm cannot starve a recv running beside it, and why neither has to know the other exists.

Stream.raw_handle() answers a handle whose top four bits carry the source’s kind, so the scheduler tells a stream arm from a task by the handle alone; see Select.

Type to search…

↑↓ navigate↵ selectEsc close