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
- Variables
- func AppendObject(dst []byte, fields []Field) []byte
- func CanonicalMediaType(s string) string
- func Copy(ctx context.Context, w Writer, r Reader) (int64, error)
- func DefaultMediaType(k Kind) string
- func JSONLinesMedia(mediaType string) bool
- func Negotiate(producer, consumer []string) (mediaType, conversion string, ok bool)
- func NormalizeMediaType(s string) (string, error)
- type Batch
- type Batcher
- type CSVDecoder
- type CSVEncoder
- type CSVOptions
- type Clock
- type Collector
- type Counter
- type Field
- type Item
- func (it Item) AppendFields(dst []Field) (fields []Field, ok bool, err error)
- func (it Item) Bytes() []byte
- func (it Item) Elements() (elems []Item, ok bool, err error)
- func (it Item) Fields() (fields []Field, ok bool, err error)
- func (it Item) Len() int
- func (it Item) String() string
- func (it Item) ValidElements() (elems []Item, ok bool, err error)
- func (it Item) Value() (any, error)
- type Kind
- type NDJSONReader
- type NDJSONWriter
- type Pipe
- func (p *Pipe) Buffered() int
- func (p *Pipe) Capacity() int
- func (p *Pipe) Close()
- func (p *Pipe) CloseRead()
- func (p *Pipe) CloseWithError(err error)
- func (p *Pipe) HighWater() int
- func (p *Pipe) Read(ctx context.Context) (Batch, error)
- func (p *Pipe) ReadClosed() bool
- func (p *Pipe) Write(ctx context.Context, b Batch) error
- type Reader
- type ReaderFunc
- type Slicer
- type SlicerOptions
- type SlicerStats
- type Timer
- type Window
- type WindowMeta
- type Writer
- type WriterFunc
Constants ¶
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.
const ChunkBytes = 64 << 10
ChunkBytes is the read size for text and binary streams.
const (
ConvJSONLAlias = "jsonl-alias" // application/jsonl ↔ application/x-ndjson (identity)
)
Conversion names used in execution plans.
const DefaultPipeCapacity = 64
DefaultPipeCapacity is the default number of batches buffered between nodes.
const MaxBatchItems = 256
MaxBatchItems is the default maximum number of items per batch.
const MaxLineBytes = 64 << 20
MaxLineBytes bounds one NDJSON line (and therefore one JSON item) on read.
Variables ¶
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 ¶
AppendObject appends the JSON object made of the ordered fields to dst.
func CanonicalMediaType ¶
CanonicalMediaType normalises s and folds aliases (application/jsonl → application/x-ndjson). Invalid input is returned lower-cased.
func DefaultMediaType ¶
DefaultMediaType returns the default media type of a port kind.
func JSONLinesMedia ¶
JSONLinesMedia reports whether a media type is an NDJSON family type.
func Negotiate ¶
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 ¶
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 NewBatch ¶
NewBatch creates a batch that takes ownership of items (the caller must not modify the slice afterwards).
func SpooledBatch ¶
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.
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 ¶
NewBatcher creates a Batcher (max <= 0 selects MaxBatchItems).
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.
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.
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.
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter counts records and bytes; safe for concurrent use.
type Item ¶
type Item struct {
// contains filtered or unexported fields
}
Item is one immutable stream element. The zero Item is an empty chunk.
func Marshal ¶
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 ¶
MustMarshal is Marshal for values known to be encodable; it panics on error.
func ParseJSON ¶
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 ¶
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 (Item) AppendFields ¶
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) Elements ¶
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 ¶
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) ValidElements ¶
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.
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.
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.
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.
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 ¶
NewPipe creates a pipe buffering at most capacity batches (minimum 1; capacity <= 0 selects DefaultPipeCapacity).
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 ¶
CloseWithError ends the stream; the reader receives err after draining buffered batches (io.EOF when err is nil).
func (*Pipe) ReadClosed ¶
ReadClosed reports whether CloseRead was called.
type Reader ¶
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 FromBatches ¶
FromBatches returns a Reader yielding the given batches, then io.EOF.
func FromItems ¶
FromItems returns a Reader yielding the items in batches of at most MaxBatchItems, then io.EOF.
func NewDecoder ¶
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 ¶
ReaderFunc adapts a function to 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:
- it holds maxItems items; or
- maxWait has elapsed since its first item arrived — also when that item arrived while the previous slice was still in flight; or
- 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 (*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 ¶
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 ¶
LargestSlice returns the size of the largest slice delivered so far.
func (*Slicer) Read ¶
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 ¶
ParseWindow decodes a window frame item.
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).