stream

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 3, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package stream contains the OpenFlange data plane: items, immutable batches, port kinds and media types, codecs (NDJSON, text, binary, CSV, window frames) and bounded pipes with backpressure and cancellation.

An Item on a records/values/windows port is exactly one JSON value kept as its original bytes, so number literals (big integers, decimals) survive byte-for-byte when an item is passed through. An Item on a text, binary or batches port is an opaque chunk of bytes.

Index

Constants

View Source
const (
	MediaNDJSON  = "application/x-ndjson"
	MediaJSONL   = "application/jsonl" // alias of MediaNDJSON
	MediaWindows = `application/x-ndjson; profile="openflange-windows"`
	MediaArrow   = "application/vnd.apache.arrow.stream"
	MediaText    = "text/plain; charset=utf-8"
	MediaBinary  = "application/octet-stream"
	MediaCSV     = "text/csv"
)

Canonical media types.

View Source
const ChunkBytes = 64 << 10

ChunkBytes is the read size for text and binary streams.

View Source
const (
	ConvJSONLAlias = "jsonl-alias" // application/jsonl ↔ application/x-ndjson (identity)
)

Conversion names used in execution plans.

View Source
const DefaultPipeCapacity = 64

DefaultPipeCapacity is the default number of batches buffered between nodes.

View Source
const MaxBatchItems = 256

MaxBatchItems is the default maximum number of items per batch.

View Source
const MaxLineBytes = 64 << 20

MaxLineBytes bounds one NDJSON line (and therefore one JSON item) on read.

Variables

View Source
var ErrClosed = errors.New("openflange/stream: all consumers closed")

ErrClosed is returned by Write when every consumer of the stream has finished reading. Producers should stop and return it (wrapped or not); a runner treats that as a normal early completion, like SIGPIPE for `head`.

Functions

func AppendObject

func AppendObject(dst []byte, fields []Field) []byte

AppendObject appends the JSON object made of the ordered fields to dst.

func CanonicalMediaType

func CanonicalMediaType(s string) string

CanonicalMediaType normalises s and folds aliases (application/jsonl → application/x-ndjson). Invalid input is returned lower-cased.

func Copy

func Copy(ctx context.Context, w Writer, r Reader) (int64, error)

Copy moves batches from r to w until EOF and returns the number of items.

func DefaultMediaType

func DefaultMediaType(k Kind) string

DefaultMediaType returns the default media type of a port kind.

func JSONLinesMedia

func JSONLinesMedia(mediaType string) bool

JSONLinesMedia reports whether a media type is an NDJSON family type.

func Negotiate

func Negotiate(producer, consumer []string) (mediaType, conversion string, ok bool)

Negotiate picks the media type for an edge. It returns the consumer's most preferred type that the producer can emit, plus the name of the lossless conversion that makes them agree ("" when identical). ok=false means there is no common media type and no lossless conversion (E_MEDIA).

func NormalizeMediaType

func NormalizeMediaType(s string) (string, error)

NormalizeMediaType parses and canonicalises a media type: lower-case type, sorted parameters, text/plain defaulting to charset=utf-8. The jsonl alias is NOT folded here (see CanonicalMediaType) so that plans can show the conversion.

Types

type Batch

type Batch struct {
	// contains filtered or unexported fields
}

Batch is an immutable, ordered group of items: the transport unit between nodes. Batches never imply logical (window) boundaries. The same Batch value may be delivered to several consumers; nobody may modify it.

func BatchOf

func BatchOf(items ...Item) Batch

BatchOf creates a batch from the given items.

func NewBatch

func NewBatch(items []Item) Batch

NewBatch creates a batch that takes ownership of items (the caller must not modify the slice afterwards).

func SpooledBatch

func SpooledBatch(n, size int) Batch

SpooledBatch describes n items of size payload bytes that are stored somewhere else — a batch file written through SlicerOptions.Spool — and are not held in memory. Len and Bytes report them, so counters stay right; All yields nothing, Items is empty and At panics. Only a Slicer whose Spool keeps the items returns such a batch, and only the adapter that registered that Spool reads it.

func (Batch) All

func (b Batch) All() iter.Seq2[int, Item]

All iterates over the items in order.

func (Batch) At

func (b Batch) At(i int) Item

At returns item i.

func (Batch) Bytes

func (b Batch) Bytes() int

Bytes returns the total payload size of the items in bytes.

func (Batch) Items

func (b Batch) Items() []Item

Items returns a copy of the items.

func (Batch) Len

func (b Batch) Len() int

Len returns the number of items.

func (Batch) Slice

func (b Batch) Slice(i, j int) Batch

Slice returns the sub-batch [i, j) sharing the same immutable items.

func (Batch) Spooled

func (b Batch) Spooled() bool

Spooled reports whether the batch's items are stored outside memory.

func (Batch) String

func (b Batch) String() string

type Batcher

type Batcher struct {
	// contains filtered or unexported fields
}

Batcher accumulates items and writes them to w in batches of at most Max items. Call Flush at natural boundaries (e.g. after each input batch) so that downstream latency stays bounded.

func NewBatcher

func NewBatcher(w Writer, max int) *Batcher

NewBatcher creates a Batcher (max <= 0 selects MaxBatchItems).

func (*Batcher) Add

func (b *Batcher) Add(ctx context.Context, it Item) error

Add appends an item, writing a batch when full.

func (*Batcher) Flush

func (b *Batcher) Flush(ctx context.Context) error

Flush writes any pending items.

type CSVDecoder

type CSVDecoder struct {
	// contains filtered or unexported fields
}

CSVDecoder converts CSV text into records. With Header, each row becomes an object of string values keyed by the header; otherwise an array of strings. Values are never type-guessed (use std:cast).

func NewCSVDecoder

func NewCSVDecoder(r io.Reader, o CSVOptions) *CSVDecoder

NewCSVDecoder creates a CSVDecoder reading from r.

func (*CSVDecoder) Read

func (d *CSVDecoder) Read(ctx context.Context) (Batch, error)

Read implements Reader.

type CSVEncoder

type CSVEncoder struct {
	// contains filtered or unexported fields
}

CSVEncoder converts records (JSON objects, or arrays when no fields are known) into CSV text. Strings are written as-is, numbers by their literal, booleans as true/false, null as empty, nested values as compact JSON.

func NewCSVEncoder

func NewCSVEncoder(o CSVOptions) *CSVEncoder

NewCSVEncoder creates a CSVEncoder.

func (*CSVEncoder) Encode

func (e *CSVEncoder) Encode(b Batch) (Item, error)

Encode converts a batch of records to one CSV text chunk.

type CSVOptions

type CSVOptions struct {
	Header    bool     // decode: first row holds field names; encode: write a header row
	Delimiter rune     // default ','
	Fields    []string // encode: column order (default: keys of the first record)
}

CSVOptions configures CSV conversion.

type Clock

type Clock interface {
	Now() time.Time
	// NewTimer returns a timer that fires once after d.
	NewTimer(d time.Duration) Timer
}

Clock abstracts time for the batch-mode wait so that tests can drive it. The zero configuration uses the real clock.

var RealClock Clock = realClock{}

RealClock is the Clock backed by package time.

type Collector

type Collector struct {
	Limit int
	// contains filtered or unexported fields
}

Collector is a Writer that keeps every item in memory. It is meant for tests and small in-memory runs; it is unbounded unless Limit is set, in which case Write fails with E_RESOURCE beyond Limit items.

func (*Collector) Items

func (c *Collector) Items() []Item

Items returns a copy of the collected items.

func (*Collector) Strings

func (c *Collector) Strings() []string

Strings returns the collected items as strings (their JSON text).

func (*Collector) Write

func (c *Collector) Write(ctx context.Context, b Batch) error

Write implements Writer.

type Counter

type Counter struct {
	// contains filtered or unexported fields
}

Counter counts records and bytes; safe for concurrent use.

func (*Counter) Add

func (c *Counter) Add(b Batch)

Add records a batch.

func (*Counter) Bytes

func (c *Counter) Bytes() int64

Bytes returns the payload bytes counted.

func (*Counter) Records

func (c *Counter) Records() int64

Records returns the number of items counted.

type Field

type Field struct {
	Name  string
	Value Item
}

Field is one member of a JSON object, with its value kept raw.

type Item

type Item struct {
	// contains filtered or unexported fields
}

Item is one immutable stream element. The zero Item is an empty chunk.

func Array

func Array(items []Item) Item

Array builds a JSON array item from items.

func Marshal

func Marshal(v any) (Item, error)

Marshal encodes a Go value as a JSON Item. json.Number and json.RawMessage values are emitted verbatim; HTML escaping is disabled. Map keys are sorted (use Object for ordered output).

func MustMarshal

func MustMarshal(v any) Item

MustMarshal is Marshal for values known to be encodable; it panics on error.

func Object

func Object(fields []Field) Item

Object builds a JSON object item from ordered fields.

func ParseJSON

func ParseJSON(b []byte) (Item, error)

ParseJSON validates that b is exactly one JSON value in valid UTF-8 and returns it as an Item. Surrounding whitespace is trimmed; interior formatting and number literals are preserved. Values containing raw newlines are compacted so the item is always a single NDJSON line.

func Raw

func Raw(b []byte) Item

Raw wraps bytes as an Item without copying or validating. The caller must not modify b afterwards. Use it for text/binary chunks or JSON that is already known to be one valid, single-line value.

func ReadAll

func ReadAll(ctx context.Context, r Reader) ([]Item, error)

ReadAll drains r and returns every item.

func String

func String(s string) Item

String returns a JSON string Item.

func (Item) AppendFields

func (it Item) AppendFields(dst []Field) (fields []Field, ok bool, err error)

AppendFields is Fields with a caller-provided buffer: the members are appended to dst[:0], so a loop over many items allocates nothing.

func (Item) Bytes

func (it Item) Bytes() []byte

Bytes returns the item's bytes. The caller must not modify them.

func (Item) Elements

func (it Item) Elements() (elems []Item, ok bool, err error)

Elements splits a JSON array item into raw elements; ok=false if the item is not an array. The elements share the item's memory.

func (Item) Fields

func (it Item) Fields() (fields []Field, ok bool, err error)

Fields splits a JSON object item into its top-level members in document order, keeping every value as raw bytes (lossless). It reports ok=false if the item is not an object.

func (Item) Len

func (it Item) Len() int

Len returns the item's size in bytes.

func (Item) String

func (it Item) String() string

func (Item) ValidElements

func (it Item) ValidElements() (elems []Item, ok bool, err error)

ValidElements is Elements for an item that is known to be valid JSON (one that ParseJSON or a codec produced): it does not validate again.

func (Item) Value

func (it Item) Value() (any, error)

Value decodes a JSON item into Go values: map[string]any, []any, string, bool, nil and json.Number (numbers are never converted to float64).

type Kind

type Kind string

Kind is a port kind.

const (
	Records Kind = "records"
	Values  Kind = "values"
	Batches Kind = "batches"
	Windows Kind = "windows"
	Text    Kind = "text"
	Binary  Kind = "binary"
)

Port kinds of the v0.1 baseline.

func (Kind) JSONLines

func (k Kind) JSONLines() bool

JSONLines reports whether items of this kind are JSON values (one per NDJSON line) rather than opaque chunks.

func (Kind) Valid

func (k Kind) Valid() bool

Valid reports whether k is a known kind.

type NDJSONReader

type NDJSONReader struct {
	// contains filtered or unexported fields
}

NDJSONReader decodes NDJSON under the baseline rules: UTF-8, one JSON value per "\n"-terminated line, a missing final newline is tolerated, blank lines and a byte order mark are E_FORMAT errors.

func NewNDJSONReader

func NewNDJSONReader(r io.Reader) *NDJSONReader

NewNDJSONReader creates an NDJSONReader.

func (*NDJSONReader) Read

func (r *NDJSONReader) Read(ctx context.Context) (Batch, error)

Read implements Reader. It returns as soon as at least one item is available and no further complete data is buffered, so slow producers are forwarded promptly.

type NDJSONWriter

type NDJSONWriter struct {
	// contains filtered or unexported fields
}

NDJSONWriter encodes items as NDJSON lines; every line (including the last) ends with "\n".

func NewNDJSONWriter

func NewNDJSONWriter(w io.Writer) *NDJSONWriter

NewNDJSONWriter creates an NDJSONWriter.

func (*NDJSONWriter) Write

func (w *NDJSONWriter) Write(ctx context.Context, b Batch) error

Write implements Writer with one underlying write per batch.

type Pipe

type Pipe struct {
	// contains filtered or unexported fields
}

Pipe is a bounded, single-producer single-consumer queue of batches with blocking backpressure. It never drops data.

func NewPipe

func NewPipe(capacity int) *Pipe

NewPipe creates a pipe buffering at most capacity batches (minimum 1; capacity <= 0 selects DefaultPipeCapacity).

func (*Pipe) Buffered

func (p *Pipe) Buffered() int

Buffered returns the number of batches currently queued.

func (*Pipe) Capacity

func (p *Pipe) Capacity() int

Capacity returns the pipe capacity in batches.

func (*Pipe) Close

func (p *Pipe) Close()

Close marks the end of the stream (EOF for the reader). Idempotent.

func (*Pipe) CloseRead

func (p *Pipe) CloseRead()

CloseRead declares that the reader will not read again. Pending and future writes return ErrClosed. Idempotent.

func (*Pipe) CloseWithError

func (p *Pipe) CloseWithError(err error)

CloseWithError ends the stream; the reader receives err after draining buffered batches (io.EOF when err is nil).

func (*Pipe) HighWater

func (p *Pipe) HighWater() int

HighWater returns the maximum number of batches that were ever queued.

func (*Pipe) Read

func (p *Pipe) Read(ctx context.Context) (Batch, error)

Read dequeues the next batch.

func (*Pipe) ReadClosed

func (p *Pipe) ReadClosed() bool

ReadClosed reports whether CloseRead was called.

func (*Pipe) Write

func (p *Pipe) Write(ctx context.Context, b Batch) error

Write enqueues a batch, blocking while the pipe is full. Empty batches are ignored.

type Reader

type Reader interface {
	Read(ctx context.Context) (Batch, error)
}

Reader is the consuming end of a stream. Read blocks until a batch is available, the stream ends (io.EOF), the stream fails, or ctx is done. Read never returns an empty batch together with a nil error.

func Empty

func Empty() Reader

Empty returns a Reader that is immediately at EOF.

func FromBatches

func FromBatches(batches ...Batch) Reader

FromBatches returns a Reader yielding the given batches, then io.EOF.

func FromItems

func FromItems(items ...Item) Reader

FromItems returns a Reader yielding the items in batches of at most MaxBatchItems, then io.EOF.

func NewDecoder

func NewDecoder(mediaType string, r io.Reader) Reader

NewDecoder returns a Reader decoding r according to mediaType: NDJSON family types yield one JSON item per line, text/plain yields UTF-8-safe chunks, everything else yields opaque binary chunks. The Reader does not close r. Cancellation is honoured between reads; a Read blocked inside r.Read only returns when r does (close r to interrupt it).

type ReaderFunc

type ReaderFunc func(ctx context.Context) (Batch, error)

ReaderFunc adapts a function to Reader.

func (ReaderFunc) Read

func (f ReaderFunc) Read(ctx context.Context) (Batch, error)

Read implements Reader.

type Slicer

type Slicer struct {
	// contains filtered or unexported fields
}

Slicer re-slices a stream for a pipe in batch mode (pipe/v0.1 section 5.7, pipeline/v0.1 section 8.11). It is a Reader whose every Read returns one slice of 1..maxItems consecutive items.

It works with two slots. One slice is IN FLIGHT: the one the last Read returned, which the consumer is processing. One slice is ACCUMULATING: a helper goroutine keeps reading upstream into it the whole time, also while the consumer is busy. A Read (the consumer saying "I am done with the previous slice") returns the accumulating slice as soon as it is READY:

  1. it holds maxItems items; or
  2. maxWait has elapsed since its first item arrived — also when that item arrived while the previous slice was still in flight; or
  3. the upstream ended (the remainder is delivered; never an empty slice).

A slice that became ready while the consumer was busy keeps growing, up to maxItems, until the consumer asks for it: under load slices fill up by themselves. With maxWait == 0 a non-empty slice is always ready: a lone item is never delayed.

Order is preserved and nothing is dropped. When the accumulating slice is full and the consumer is still busy the helper stops reading upstream, so backpressure reaches the producer and the Slicer never holds more than 2 × maxItems items (one slice in flight, one accumulating); the unplaced rest of the one transport batch the helper has in hand is extra. With a Spool that keeps the items (file delivery) not even those are in memory: the Slicer holds counts, and the slices are files. The helper is bound to the context of the first Read; cancelling that context or calling CloseRead stops it. A Slicer is for a single consumer: Read must not be called concurrently.

func NewSlicer

func NewSlicer(r Reader, maxItems int, maxWait time.Duration, o ...SlicerOptions) *Slicer

NewSlicer wraps r. maxItems < 1 is treated as 1 and a negative maxWait as 0.

func (*Slicer) CloseRead

func (s *Slicer) CloseRead()

CloseRead tells the upstream that nobody will read again, stops the helper and waits for it. A later Read returns ErrClosed. It is idempotent.

func (*Slicer) HighWater

func (s *Slicer) HighWater() int

HighWater returns the largest number of items the two slots held together (the slice in flight plus the accumulating slice): at most 2 × MaxItems.

func (*Slicer) LargestSlice

func (s *Slicer) LargestSlice() int

LargestSlice returns the size of the largest slice delivered so far.

func (*Slicer) MaxItems

func (s *Slicer) MaxItems() int

MaxItems returns the slice size limit.

func (*Slicer) MaxWait

func (s *Slicer) MaxWait() time.Duration

MaxWait returns the wait limit.

func (*Slicer) Pending

func (s *Slicer) Pending() int

Pending returns the size of the accumulating slice right now.

func (*Slicer) Read

func (s *Slicer) Read(ctx context.Context) (Batch, error)

Read implements Reader: it returns the next slice once it is ready. Calling Read tells the Slicer that the previous slice is no longer in flight.

func (*Slicer) Stats

func (s *Slicer) Stats() SlicerStats

Stats returns the delivery statistics so far.

type SlicerOptions

type SlicerOptions struct {
	// Clock drives the maxWait timer (default RealClock).
	Clock Clock
	// Spool, when set, is called with every group of items as it joins the
	// accumulating slice, in order, before that slice can be delivered; slice
	// is the zero-based index of the slice the items belong to. It lets a
	// consumer write a slice to a file while the previous one is still being
	// processed. It runs on the helper goroutine and must not call the Slicer.
	// An error fails the stream.
	//
	// If it returns kept == true it has stored the items durably (in the
	// slice's file) and the Slicer does not hold them in memory: Read then
	// returns a SpooledBatch that only carries the slice's item and byte
	// counts. A Spool must answer the same way for every call.
	Spool func(slice int, items []Item) (kept bool, err error)
}

SlicerOptions tunes a Slicer.

type SlicerStats

type SlicerStats struct {
	// Slices is the number of slices delivered and Items the items in them.
	Slices int
	Items  int64
	// Largest is the size of the largest slice.
	Largest int
	// Why the slices were delivered. Every slice counts once:
	// MaxFlushes — it held maxItems items;
	// EOFFlushes — it was the remainder at the end of the input;
	// WaitFlushes — it was smaller than maxItems and maxWait had elapsed
	// since its first item (with maxWait == 0 that is every slice that was
	// neither full nor the remainder).
	MaxFlushes, WaitFlushes, EOFFlushes int
	// HighWater is the largest number of items the two slots held together.
	HighWater int
}

SlicerStats describes the slices a Slicer has delivered so far.

type Timer

type Timer interface {
	C() <-chan time.Time
	// Stop releases the timer; it is safe to call after it fired.
	Stop()
}

Timer is the part of time.Timer a Slicer needs.

type Window

type Window struct {
	Meta  WindowMeta
	Items []Item
}

Window is one complete logical window.

func ParseWindow

func ParseWindow(it Item) (Window, error)

ParseWindow decodes a window frame item.

func (Window) Frame

func (w Window) Frame() Item

Frame encodes the window as one item for a `windows` port: {"window":{...},"items":[...]}.

type WindowMeta

type WindowMeta struct {
	Index     int64           `json:"index"`
	Partition json.RawMessage `json:"partition"`
	Start     int64           `json:"start"`
	End       int64           `json:"end"`
	Final     bool            `json:"final"`
	Partial   bool            `json:"partial"`
}

WindowMeta is the header of a window frame (proposed framing, baseline §3).

type Writer

type Writer interface {
	Write(ctx context.Context, b Batch) error
}

Writer is the producing end of a stream. Write blocks while the consumer is slow (backpressure) and returns ctx.Err() on cancellation, or ErrClosed when nobody will ever read the stream again.

var Discard Writer = WriterFunc(func(ctx context.Context, b Batch) error { return ctx.Err() })

Discard is a Writer that drops everything.

func NewEncoder

func NewEncoder(mediaType string, w io.Writer) Writer

NewEncoder returns a Writer encoding batches onto w according to mediaType (NDJSON family: one line per item; anything else: raw concatenation). Each batch is written with a single w.Write call.

type WriterFunc

type WriterFunc func(ctx context.Context, b Batch) error

WriterFunc adapts a function to Writer.

func (WriterFunc) Write

func (f WriterFunc) Write(ctx context.Context, b Batch) error

Write implements Writer.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL