Documentation
¶
Overview ¶
Package rill provides composable concurrency primitives: functions over plain channels that transform, filter, batch, reduce, and consume data streams while propagating errors and optionally preserving order.
Rill is not a framework: its functions can be used on their own or composed into multi-stage pipelines. Either way, they are compatible with existing channel-based code.
Pipelines and streams ¶
The pipeline model in this package is similar to the one described in the Go blog's "Pipelines and cancellation" (https://go.dev/blog/pipelines), but it unifies error handling by letting errors travel downstream along with values. In rill's terms, the post's definition of a pipeline becomes:
A pipeline is a series of stages connected by streams - channels whose items are Try structs, each holding either a value or an error. Under the hood, each stage runs one or more goroutines that:
- receive values and errors from upstream via input streams
- process the received values, usually producing new values or errors
- send the results downstream via output streams
- forward upstream errors to the output streams (Catch is the only exception)
The first stage in a pipeline has no input stream, and the last stage has no output stream. These stages are called the source and the sink, respectively. Other stages typically have one input and one output, though functions like Merge and Tee have more and can be used to build DAG pipelines.
ids := rill.FromSlice(userIDs, nil) // source filtered := rill.Filter(ids, 5, ...) // stage, concurrency = 5 batches := rill.Batch(filtered, ...) // stage transformed := rill.Map(batches, 3, ...) // stage, concurrency = 3 err := rill.ForEach(transformed, 2, ...) // sink, concurrency = 2
Intermediate stages return their output streams immediately, while their goroutines continue working in the background. These stages always fully consume and process their inputs before closing their outputs. A closed output becomes an "all upstream work has finished" signal that travels downstream along with values and errors.
Sinks ¶
Unlike intermediate stages, sinks return regular Go values, not channels. By default, a sink blocks until its outcome is known, then returns it, even if more work remains in the pipeline. Given a WithContext option, the sink blocks until the whole pipeline has finished.
When the outcome becomes known depends on the sink. It is always known after the whole input has been consumed and processed, but some sinks know it earlier, for example:
- ForEach - on the first error
- Any - on the first match or error, whichever comes first
- First - after consuming one item
After an early return, a sink keeps draining and discarding any remaining input in the background, so upstream stages don't block forever and leak their goroutines. While draining, the sink suppresses its own callbacks. The suppression is best effort: when the sink runs callbacks concurrently, a few extra calls can start after the early return.
An early return lets the caller cancel its own context right away, for example with a deferred cancel, and cooperatively stop the remaining background work. This gives early cancellation, but not structured concurrency.
Context and structured concurrency ¶
Rill can manage the context and give the pipeline structured concurrency semantics similar to errgroup's.
- WithContext derives a context
- User callbacks and custom stages capture and watch the context
- A sink cancels the context as soon as the outcome is known (typically on the first error that reaches the sink)
- Instead of returning the outcome immediately, the sink first waits for the pipeline to finish, as errgroup's Wait does
Example:
ctx, scope := rill.WithContext(ctx)
// Source and other pipeline stages go here
users := rill.Map(ids, 10, func(id int) (*User, error) {
return getUser(ctx, id)
})
// scope covers both the sink and the upstream stages
err := rill.ForEach(users, 5, func(u *User) error {
return process(ctx, u)
}, scope)
// Nothing is running anymore and ctx is canceled
Draining and callback suppression still apply, but they happen before the sink returns instead of after.
Ordered stages ¶
By default, stages write results to their output streams as soon as they are ready, in completion order. In concurrent stages, that order depends on how the Go runtime schedules the stages' goroutines and on the time it takes to produce each result.
For cases where the input order must be preserved, rill provides ordered functions, such as OrderedMap or OrderedFilter. They stay concurrent, but each worker holds its result until all earlier results are sent, so the output order matches the input order at the cost of some latency. This ordering guarantee holds for both values and errors.
Backpressure ¶
Backpressure means that sending to an unbuffered channel blocks until the receiver on the other end is ready to receive. Rill naturally inherits this property: a slow stage in the pipeline blocks the previous stage, and it, in turn, blocks the stage before that, and so on, until the slow stage catches up.
When this is not desirable, use Buffer to add slack between stages.
Nil handling ¶
A nil channel never emits values and never closes, and rill treats it as exactly that: stages with a nil input never close their outputs and can leak goroutines; sinks with a nil input can block forever. Nil channels never make sense within a pipeline.
Panics ¶
Rill validates the arguments to its functions and panics on misuse, such as zero or negative concurrency. Rill does not automatically recover from panics in user callbacks: a panicking callback can crash the process, as it would in any hand-written concurrent code.
Extending rill ¶
Almost any custom function that takes or returns streams is compatible with rill. For example, it's easy to write a context-aware source that streams rows from a database table, or a sink that collects all observed errors into a slice.
The easiest way to write a custom stage is to compose it from existing functions rill provides. For manually written stages, a few simple rules keep background draining and the "all upstream work has finished" signal working. Ordinary Go channel code usually satisfies most of them:
- Sources must eventually close their output stream; a source that can run forever must watch a context and be cancellable
- Intermediate stages must close their output stream, but only after the input is fully consumed and processed
- Non-concurrent sinks must start with a deferred rill.Discard(in, options...), followed by a for-range loop that returns as soon as the sink's outcome is known
Example ¶
This example demonstrates a rill pipeline that fetches users from an API, activates them, and saves the changes back. Each step runs concurrently with its own concurrency limit, and errors from both are handled in one place. On the first error, ForEach cancels the context, waits until nothing is running anymore, and returns that error.
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx, scope := rill.WithContext(context.Background())
// Convert a slice into a channel
ids := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Read users from the API. Concurrency = 3
users := rill.Map(ids, 3, func(id int) (*api.User, error) {
return api.GetUser(ctx, id)
})
// Process users. Concurrency = 2
err := rill.ForEach(users, 2, func(u *api.User) error {
if u.IsActive {
fmt.Printf("User %d is already active\n", u.ID)
return nil
}
u.IsActive = true
err := api.SaveUser(ctx, u)
if err != nil {
return err
}
fmt.Printf("User saved: %+v\n", u)
return nil
}, scope) // scope is a functional option
// Nothing is running anymore; the context is canceled.
// Handle the error (if any).
fmt.Println("Error:", err)
}
Output:
Example (Batching) ¶
This example demonstrates a rill pipeline that fetches users from an API in batches, activates them, and saves the changes back. Batch groups individual IDs into slices, so users are fetched with one bulk API call per batch instead of one call per user.
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx, scope := rill.WithContext(context.Background())
// Convert a slice of user IDs into a channel
ids := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}, nil)
// Group IDs into batches of 5
idBatches := rill.Batch(ids, 5, -1)
// Bulk fetch users from the API. Concurrency = 3
userBatches := rill.Map(idBatches, 3, func(ids []int) ([]*api.User, error) {
return api.GetUsers(ctx, ids)
})
// Transform the stream of batches back into a flat stream of users
users := rill.Unbatch(userBatches)
// Process users. Concurrency = 2
err := rill.ForEach(users, 2, func(u *api.User) error {
if u.IsActive {
fmt.Printf("User %d is already active\n", u.ID)
return nil
}
u.IsActive = true
err := api.SaveUser(ctx, u)
if err != nil {
return err
}
fmt.Printf("User saved: %+v\n", u)
return nil
}, scope)
// Nothing is running anymore; the context is canceled.
// Handle the error.
fmt.Println("Error:", err)
}
Output:
Example (OrderPreservation) ¶
This example demonstrates how to check 1000 large files and find the first file containing a given string. Downloading files one by one is slow, while traditional concurrency patterns find the fastest match instead of the first one. OrderedFilter and First solve this while downloading and keeping in memory at most 5 files at a time. On the first match or error, First cancels the context, waits until nothing is running anymore, and returns the result.
package main
import (
"bytes"
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx, scope := rill.WithContext(context.Background())
// The string to search for in the downloaded files
needle := []byte("26")
// Generate a stream of URLs from file-0.txt to file-999.txt.
// Stop generating URLs when the context is canceled
urls := rill.Generate(func(send func(string), sendError func(error)) {
for i := 0; i < 1000 && ctx.Err() == nil; i++ {
send(fmt.Sprintf("https://example.com/file-%d.txt", i))
}
})
// Download and process the files. Concurrency = 5
matchedUrls := rill.OrderedFilter(urls, 5, func(url string) (bool, error) {
fmt.Println("Downloading:", url)
content, err := api.DownloadFile(ctx, url)
if err != nil {
return false, err
}
// Keep only URLs of files that contain the needle
return bytes.Contains(content, needle), nil
})
// Get the first matched URL or error
firstMatchedUrl, found, err := rill.First(matchedUrls, scope)
// Nothing is running anymore; the context is canceled.
// Handle the result.
fmt.Println("Result:", firstMatchedUrl, found, err)
}
Output:
Example (ParallelStreaming) ¶
This example demonstrates how FlatMap can remove a slow-source bottleneck. The API is slow and paginated, so users are streamed from several departments concurrently and merged into a single stream. There can be any number of departments, while FlatMap streams at most 3 at a time.
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx, scope := rill.WithContext(context.Background())
// Start with a stream of department names
departments := rill.FromSlice([]string{"IT", "Finance", "Marketing", "Support", "Engineering"}, nil)
// Stream users from all departments concurrently.
// At most 3 departments at the same time.
users := rill.FlatMap(departments, 3, func(department string) <-chan rill.Try[*api.User] {
return StreamUsers(ctx, api.UserQuery{Department: department})
})
// Print the users from the combined stream
err := rill.ForEach(users, 1, func(user *api.User) error {
fmt.Printf("%+v\n", user)
return nil
}, scope)
// Nothing is running anymore; the context is canceled.
// Handle the error.
fmt.Println("Error:", err)
}
// StreamUsers streams users from a paginated API. It's a reusable streaming wrapper, useful both
// on its own and as part of larger pipelines.
func StreamUsers(ctx context.Context, query api.UserQuery) <-chan rill.Try[*api.User] {
return rill.Generate(func(send func(*api.User), sendError func(error)) {
for page := 0; ; page++ {
query.Page = page
users, err := api.ListUsers(ctx, query)
if err != nil {
sendError(err)
return
}
if len(users) == 0 {
break
}
for _, user := range users {
send(user)
}
}
})
}
Output:
Example (RealTimeBatching) ¶
This example demonstrates how Batch can group independent operations happening in real time. The main function makes 100 concurrent calls to the UpdateUserTimestamp function, which looks normal at the call site: it takes a user ID, waits for the database to respond, and returns an error. Under the hood, a background worker uses rill to combine concurrent calls into bulk updates and send results back to the corresponding callers.
Since calls happen at unpredictable times, waiting for a full batch can take arbitrarily long. To avoid this, Batch takes a timeout argument that limits how long each batch waits to fill. When the timeout expires, a partial batch is emitted.
package main
import (
"fmt"
"math/rand"
"strings"
"sync"
"time"
"github.com/destel/rill"
)
func main() {
// Start the background worker
go updateUserTimestampWorker()
// Make 100 concurrent calls
var wg sync.WaitGroup
for id := 1; id <= 100; id++ {
wg.Go(func() {
if err := UpdateUserTimestamp(id); err != nil {
fmt.Println("Error:", err)
}
})
}
wg.Wait()
}
func UpdateUserTimestamp(userID int) error {
req := request{userID: userID, replyTo: make(chan error, 1)}
queue <- req
err := <-req.replyTo
return err
}
func updateUserTimestampWorker() {
requests := rill.FromChan(queue, nil)
requestBatches := rill.Batch(requests, 10, 20*time.Millisecond)
_ = rill.ForEach(requestBatches, 2, func(batch []request) error {
ids := make([]int, len(batch))
for i, req := range batch {
ids[i] = req.userID
}
err := executeQuery("UPDATE users SET last_active_at = NOW() WHERE id IN (?)", ids)
for _, req := range batch {
req.replyTo <- err
}
return nil
})
}
// This type represents a single request to the worker
type request struct {
userID int
replyTo chan error
}
// Queue of update requests
var queue = make(chan request)
// executeQuery simulates a database query
func executeQuery(query string, args ...any) error {
simulateWork(100 * time.Millisecond)
for _, arg := range args {
query = strings.Replace(query, "?", fmt.Sprint(arg), 1)
}
fmt.Println("Executed:", query)
return nil
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
Index ¶
- func All[A any](in <-chan Try[A], n int, f func(A) (bool, error), options ...SinkOption) (bool, error)
- func Any[A any](in <-chan Try[A], n int, f func(A) (bool, error), options ...SinkOption) (bool, error)
- func Batch[A any](in <-chan Try[A], size int, timeout time.Duration) <-chan Try[[]A]
- func Buffer[A any](in <-chan A, size int) <-chan A
- func Catch[A any](in <-chan Try[A], n int, f func(error) error) <-chan Try[A]
- func Discard[A any](in <-chan A, options ...SinkOption)
- func Drain[A any](in <-chan A)
- func DrainNB[A any](in <-chan A)deprecated
- func Err[A any](in <-chan Try[A], options ...SinkOption) error
- func Filter[A any](in <-chan Try[A], n int, f func(A) (bool, error)) <-chan Try[A]
- func FilterMap[A, B any](in <-chan Try[A], n int, f func(A) (B, bool, error)) <-chan Try[B]
- func First[A any](in <-chan Try[A], options ...SinkOption) (value A, found bool, err error)
- func FlatMap[A, B any](in <-chan Try[A], n int, f func(A) <-chan Try[B]) <-chan Try[B]
- func ForEach[A any](in <-chan Try[A], n int, f func(A) error, options ...SinkOption) error
- func FromChan[A any](values <-chan A, err error) <-chan Try[A]
- func FromChans[A any](values <-chan A, errs <-chan error) <-chan Try[A]
- func FromSeq[A any](seq iter.Seq[A], err error) <-chan Try[A]
- func FromSeq2[A any](seq iter.Seq2[A, error]) <-chan Try[A]
- func FromSlice[A any](slice []A, err error) <-chan Try[A]
- func Generate[A any](f func(send func(A), sendError func(error))) <-chan Try[A]
- func Map[A, B any](in <-chan Try[A], n int, f func(A) (B, error)) <-chan Try[B]
- func MapReduce[A any, K comparable, V any](in <-chan Try[A], nm int, mapper func(A) (K, V, error), nr int, ...) (map[K]V, error)
- func Merge[A any](ins ...<-chan A) <-chan A
- func OrderedCatch[A any](in <-chan Try[A], n int, f func(error) error) <-chan Try[A]
- func OrderedFilter[A any](in <-chan Try[A], n int, f func(A) (bool, error)) <-chan Try[A]
- func OrderedFilterMap[A, B any](in <-chan Try[A], n int, f func(A) (B, bool, error)) <-chan Try[B]
- func OrderedFlatMap[A, B any](in <-chan Try[A], n int, f func(A) <-chan Try[B]) <-chan Try[B]
- func OrderedMap[A, B any](in <-chan Try[A], n int, f func(A) (B, error)) <-chan Try[B]
- func OrderedSplit2[A any](in <-chan Try[A], n int, f func(A) (bool, error)) (outTrue <-chan Try[A], outFalse <-chan Try[A])deprecated
- func Reduce[A any](in <-chan Try[A], n int, f func(A, A) (A, error), options ...SinkOption) (result A, hasResult bool, err error)
- func Split2[A any](in <-chan Try[A], n int, f func(A) (bool, error)) (outTrue <-chan Try[A], outFalse <-chan Try[A])deprecated
- func Tee[A any](in <-chan A) (<-chan A, <-chan A)
- func ToChans[A any](in <-chan Try[A]) (<-chan A, <-chan error)
- func ToSeq2[A any](in <-chan Try[A], options ...SinkOption) iter.Seq2[A, error]
- func ToSlice[A any](in <-chan Try[A], options ...SinkOption) ([]A, error)
- func Unbatch[A any](in <-chan Try[[]A]) <-chan Try[A]
- type SinkOption
- type Stream
- type Try
Examples ¶
- Package
- Package (Batching)
- Package (OrderPreservation)
- Package (ParallelStreaming)
- Package (RealTimeBatching)
- All
- Any
- Batch
- Catch
- Err
- Filter
- FilterMap
- First
- FlatMap
- ForEach
- FromSeq
- FromSeq2
- Generate
- Generate (Context)
- Map
- MapReduce
- Merge
- OrderedCatch
- OrderedFilter
- OrderedFilterMap
- OrderedFlatMap
- OrderedMap
- Reduce
- Tee
- ToSeq2
- ToSlice
- Unbatch
- WithContext
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func All ¶ added in v0.2.0
func All[A any](in <-chan Try[A], n int, f func(A) (bool, error), options ...SinkOption) (bool, error)
All reports whether every value in the stream matches f. It returns:
- (false, nil) if a mismatch is observed first
- (false, err) if an error is observed first
- (true, nil) if neither is observed
The argument n bounds the number of concurrent calls to f. When n = 1, f is called sequentially in stream order.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Are all numbers prime?
// Concurrency = 3
ok, err := rill.All(numbers, 3, func(x int) (bool, error) {
return isPrime(x), nil
})
fmt.Println("Result:", ok)
fmt.Println("Error:", err)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func Any ¶ added in v0.2.0
func Any[A any](in <-chan Try[A], n int, f func(A) (bool, error), options ...SinkOption) (bool, error)
Any reports whether the stream contains a value that matches f. It returns:
- (true, nil) if a match is observed first
- (false, err) if an error is observed first
- (false, nil) if neither is observed
The argument n bounds the number of concurrent calls to f. When n = 1, f is called sequentially in stream order.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Is there at least one prime number?
// Concurrency = 3
ok, err := rill.Any(numbers, 3, func(x int) (bool, error) {
return isPrime(x), nil
})
fmt.Println("Result: ", ok)
fmt.Println("Error: ", err)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func Batch ¶
Batch groups consecutive values of the stream into batches. With timeout = -1, it accumulates values until the batch reaches size, then emits it. When the input is exhausted, any pending values are emitted as a final batch.
Input errors create batch boundaries: any pending batch is emitted first, followed by the error as a separate item. This function never emits empty batches.
A positive timeout adds another trigger: each batch has that much time to fill, starting from its first value. When the timeout expires, the pending batch is emitted even if it is not full. This trades batch size for latency: sparse input produces smaller batches, but no value is ever held longer than timeout, assuming there's no backpressure.
A zero timeout panics. Use a small positive timeout instead.
Example ¶
See the package-level examples for more realistic uses of Batch.
package main
import (
"fmt"
"time"
"github.com/destel/rill"
)
func main() {
// Generate a stream of numbers 0 to 49, where a new number is emitted every 50ms
numbers := rill.Generate(func(send func(int), sendError func(error)) {
for i := range 50 {
send(i)
time.Sleep(50 * time.Millisecond)
}
})
// Group numbers into batches of up to 5
batches := rill.Batch(numbers, 5, 1*time.Second)
printStream(batches)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
func Buffer ¶
Buffer returns a channel of the specified capacity and forwards all input items to it. The output is closed once the input is exhausted.
users := getUsers(ctx, companyID) users = rill.Buffer(users, 100) // Up to 100 users can be buffered if subsequent stages of the // pipeline are slow.
func Catch ¶
Catch takes a stream and returns a new stream with the errors optionally handled by f. Each error is passed to f, which returns nil to drop it from the stream, the same error to keep it, or a different one to replace it. Values never reach f and are passed through as-is.
The argument n bounds the number of concurrent calls to f. Items are written to the output in completion order. Use OrderedCatch to preserve the input order.
Example ¶
package main
import (
"errors"
"fmt"
"math/rand"
"strconv"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of strings into a stream
strs := rill.FromSlice([]string{"1", "2", "3", "4", "5", "not a number 6", "7", "8", "9", "10"}, nil)
// Convert strings to ints
// Concurrency = 3
ids := rill.Map(strs, 3, func(s string) (int, error) {
simulateWork(500 * time.Millisecond)
return strconv.Atoi(s)
})
// Catch and ignore number parsing errors
// Concurrency = 2
ids = rill.Catch(ids, 2, func(err error) error {
if errors.Is(err, strconv.ErrSyntax) {
return nil // Ignore this error
}
return err
})
// No error will be printed
printStream(ids)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func Discard ¶ added in v0.8.0
func Discard[A any](in <-chan A, options ...SinkOption)
Discard drains and discards all items of the channel. By default it returns immediately and drains in the background. Given a WithContext option, it cancels the context, then blocks until the drain completes.
func Drain ¶
func Drain[A any](in <-chan A)
Drain consumes and discards all items of the channel, blocking until it is exhausted.
func Err ¶ added in v0.2.0
func Err[A any](in <-chan Try[A], options ...SinkOption) error
Err returns the first error in the stream.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx := context.Background()
// Convert a slice of users into a stream
users := rill.FromSlice([]*api.User{
{ID: 1, Name: "foo", Age: 25},
{ID: 2, Name: "bar", Age: 30},
{ID: 3}, // empty username is invalid
{ID: 4, Name: "baz", Age: 35},
{ID: 5, Name: "qux", Age: 26},
{ID: 6, Name: "quux", Age: 27},
}, nil)
// Save users. Use struct{} as a result type
// Concurrency = 2
results := rill.Map(users, 2, func(user *api.User) (struct{}, error) {
return struct{}{}, api.SaveUser(ctx, user)
})
// We only need to know if all users were saved successfully
err := rill.Err(results)
fmt.Println("Error:", err)
}
Output:
func Filter ¶
Filter takes a stream of values and returns a new stream, keeping only the values that match the condition f. When f returns an error, it's written to the output instead of the value. Errors are never filtered out.
The argument n bounds the number of concurrent calls to f. Results and errors are written to the output in completion order. Use OrderedFilter to preserve the input order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Keep only prime numbers
// Concurrency = 3
primes := rill.Filter(numbers, 3, func(x int) (bool, error) {
return isPrime(x), nil
})
printStream(primes)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func FilterMap ¶ added in v0.3.0
FilterMap takes a stream of values of type A and returns a stream of values of type B, using f to transform each value and decide whether to keep the result. When f returns an error, it's written to the output instead of a value. Errors are never filtered out.
The argument n bounds the number of concurrent calls to f. Results and errors are written to the output in completion order. Use OrderedFilterMap to preserve the input order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Keep only prime numbers and square them
// Concurrency = 3
squares := rill.FilterMap(numbers, 3, func(x int) (int, bool, error) {
if !isPrime(x) {
return 0, false, nil
}
return x * x, true, nil
})
printStream(squares)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func First ¶ added in v0.2.0
func First[A any](in <-chan Try[A], options ...SinkOption) (value A, found bool, err error)
First consumes the first item of the stream and returns:
- (value, true, nil) if the item is a value
- (zero, false, err) if the item is an error
- (zero, false, nil) if the stream is empty
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Keep only the numbers divisible by 4
// Concurrency = 3; Ordered
divisibleBy4 := rill.OrderedFilter(numbers, 3, func(x int) (bool, error) {
return x%4 == 0, nil
})
// Get the first number divisible by 4
first, ok, err := rill.First(divisibleBy4)
fmt.Println("Result:", first, ok)
fmt.Println("Error:", err)
}
Output:
func FlatMap ¶
FlatMap takes a stream of values of type A and returns a stream of values of type B, using f to expand each value into its own sub-stream. The sub-streams are flattened into the output: every item is forwarded, values and errors alike.
The argument n bounds the number of sub-streams consumed concurrently: each worker consumes one sub-stream to the end before starting the next. When n > 1, items from different sub-streams can interleave in the output. Use OrderedFlatMap to concatenate the sub-streams in the input order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5}, nil)
// Replace each number in the input stream with three strings
// Concurrency = 2
result := rill.FlatMap(numbers, 2, func(x int) <-chan rill.Try[string] {
simulateWork(500 * time.Millisecond)
return rill.FromSlice([]string{
fmt.Sprintf("foo%d", x),
fmt.Sprintf("bar%d", x),
fmt.Sprintf("baz%d", x),
}, nil)
})
printStream(result)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func ForEach ¶
ForEach calls f on the stream's values, like a concurrent for-range loop, and returns the first error it observes, or nil if there is none.
The argument n bounds the number of concurrent calls to f. When n = 1, f is called sequentially in stream order.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Square each number and print the result
// Concurrency = 3
err := rill.ForEach(numbers, 3, func(x int) error {
y := square(x)
fmt.Println(y)
return nil
})
// Handle errors
fmt.Println("Error:", err)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func FromChan ¶
FromChan converts a regular channel into a stream. If err is not nil, FromChan returns a stream with only that error and ignores values. Otherwise, values are forwarded to the output as they arrive, and the output is closed once the input is exhausted.
A nil input is never exhausted, so the output never closes.
This signature allows concise wrapping of functions that return a channel and an error. FromChan assumes a non-nil error means someFunc() could not construct the channel.
stream := rill.FromChan(someFunc())
func FromChans ¶
FromChans converts separate value and error channels into a single stream. Values and errors are forwarded to the output as they arrive, and nil errors are skipped. The output is closed only when both inputs are exhausted.
A nil input is never exhausted, so the output never closes.
This signature allows concise wrapping of functions that return two channels. FromChans assumes someFunc() returns two channels that eventually close.
stream := rill.FromChans(someFunc())
func FromSeq ¶ added in v0.4.0
FromSeq converts an iterator into a stream. If err is not nil, FromSeq returns a stream with only that error and ignores seq. Otherwise, the values of seq are forwarded to the output, and the output is closed once seq ends.
This signature allows concise wrapping of functions that return an iterator and an error. FromSeq assumes a non-nil error means someFunc() could not construct the iterator.
stream := rill.FromSeq(someFunc())
Example ¶
package main
import (
"fmt"
"math/rand"
"slices"
"time"
"github.com/destel/rill"
)
func main() {
// Start with an iterator that yields numbers from 1 to 10
numbersSeq := slices.Values([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
// Convert the iterator into a stream
numbers := rill.FromSeq(numbersSeq, nil)
// Transform each number
// Concurrency = 3
squares := rill.Map(numbers, 3, func(x int) (int, error) {
return square(x), nil
})
printStream(squares)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func FromSeq2 ¶ added in v0.4.0
FromSeq2 converts an iterator of value-error pairs into a stream. Each pair becomes one item. For pairs with a non-nil error, FromSeq2 emits an error item and ignores the value. The output is closed once seq ends.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Create an iter.Seq2 iterator that yields numbers from 1 to 10
numberSeq := func(yield func(int, error) bool) {
for i := 1; i <= 10; i++ {
if !yield(i, nil) {
return
}
}
}
// Convert the iterator into a stream
numbers := rill.FromSeq2(numberSeq)
// Transform each number
// Concurrency = 3
squares := rill.Map(numbers, 3, func(x int) (int, error) {
return square(x), nil
})
printStream(squares)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func FromSlice ¶
FromSlice converts a slice into a stream. If err is not nil, it is added to the end of the stream.
Modifying the slice before the stream is fully consumed is a data race.
This signature allows concise wrapping of functions that return a slice and an error. FromSlice assumes that a non-empty slice along with an error is a partial result and preserves both.
stream := rill.FromSlice(someFunc())
func Generate ¶ added in v0.6.0
Generate is shorthand for creating streams: it manages the goroutine and channel lifecycle. Inside f, send writes a value to the stream, and sendError writes an error unless it is nil.
stream := rill.Generate(func(send func(int), sendError func(error)) {
for i := 0; i < 100; i++ {
send(i)
}
sendError(someError)
})
The same stream without Generate:
stream := make(chan rill.Try[int])
go func() {
defer close(stream)
for i := 0; i < 100; i++ {
stream <- rill.Try[int]{Value: i}
}
stream <- rill.Try[int]{Error: someError}
}()
Example ¶
package main
import (
"fmt"
"github.com/destel/rill"
)
func main() {
urls := rill.Generate(func(send func(string), sendError func(error)) {
for i := range 10 {
send(fmt.Sprintf("https://example.com/file-%d.txt", i))
}
})
printStream(urls)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
Example (Context) ¶
package main
import (
"context"
"fmt"
"time"
"github.com/destel/rill"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Keep generating numbers until the context is canceled after 5s.
numbers := rill.Generate(func(send func(int), sendError func(error)) {
for i := 1; ctx.Err() == nil; i++ {
send(i)
time.Sleep(500 * time.Millisecond)
}
})
printStream(numbers)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
func Map ¶
Map takes a stream of values of type A and returns a stream of values of type B, using f to transform each. When f returns an error, it's written to the output instead of a value.
The argument n bounds the number of concurrent calls to f. Results and errors are written to the output in completion order. Use OrderedMap to preserve the input order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Transform each number
// Concurrency = 3
squares := rill.Map(numbers, 3, func(x int) (int, error) {
return square(x), nil
})
printStream(squares)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func MapReduce ¶ added in v0.2.0
func MapReduce[A any, K comparable, V any](in <-chan Try[A], nm int, mapper func(A) (K, V, error), nr int, reducer func(V, V) (V, error), options ...SinkOption) (map[K]V, error)
MapReduce builds a map from the stream: mapper turns each value into a key-value pair, and reducer combines the values that share a key.
For each key, the values are combined as in Reduce: in stream order, with unspecified parenthesization, so reducer must be associative. Commutativity is not required.
MapReduce returns (nil, err) if an error is observed, and (map, nil) otherwise.
The arguments nm and nr bound the number of concurrent calls to mapper and reducer, respectively.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"regexp"
"strings"
"github.com/destel/rill"
)
func main() {
var re = regexp.MustCompile(`\w+`)
text := "Early morning brings early birds to the early market. Birds sing, the market buzzes, and the morning shines."
// Convert a text into a stream of words
words := rill.FromSlice(re.FindAllString(text, -1), nil)
// Count the number of occurrences of each word
mr, err := rill.MapReduce(words,
// Map phase: Use the word as key and "1" as value
// Concurrency = 3
3, func(word string) (string, int, error) {
return strings.ToLower(word), 1, nil
},
// Reduce phase: Sum all "1" values for the same key
// Concurrency = 2
2, func(x, y int) (int, error) {
return x + y, nil
},
)
fmt.Println("Result:", mr)
fmt.Println("Error:", err)
}
Output:
func Merge ¶
func Merge[A any](ins ...<-chan A) <-chan A
Merge performs a fan-in: it combines multiple input channels into one output channel. It reads all inputs concurrently, so a slow input does not delay forwarding items from the others. Items are interleaved as they arrive, preserving the relative order of items from each input.
The output is closed only when all inputs are exhausted. A nil input is never exhausted, so the output never closes. Merge with no arguments returns an empty closed channel.
Example ¶
package main
import (
"fmt"
"github.com/destel/rill"
)
func main() {
// Convert slices of numbers into streams
numbers1 := rill.FromSlice([]int{1, 2, 3, 4, 5}, nil)
numbers2 := rill.FromSlice([]int{6, 7, 8, 9, 10}, nil)
numbers3 := rill.FromSlice([]int{11, 12}, nil)
numbers := rill.Merge(numbers1, numbers2, numbers3)
printStream(numbers)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
func OrderedCatch ¶
OrderedCatch is the ordered version of Catch: it writes items in input order rather than completion order.
Example ¶
package main
import (
"errors"
"fmt"
"math/rand"
"strconv"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of strings into a stream
strs := rill.FromSlice([]string{"1", "2", "3", "4", "5", "not a number 6", "7", "8", "9", "10"}, nil)
// Convert strings to ints
// Concurrency = 3; Ordered
ids := rill.OrderedMap(strs, 3, func(s string) (int, error) {
simulateWork(500 * time.Millisecond)
return strconv.Atoi(s)
})
// Catch and ignore number parsing errors
// Concurrency = 2; Ordered
ids = rill.OrderedCatch(ids, 2, func(err error) error {
if errors.Is(err, strconv.ErrSyntax) {
return nil // Ignore this error
}
return err
})
// No error will be printed
printStream(ids)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func OrderedFilter ¶
OrderedFilter is the ordered version of Filter: it writes results and errors in input order rather than completion order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Keep only prime numbers
// Concurrency = 3; Ordered
primes := rill.OrderedFilter(numbers, 3, func(x int) (bool, error) {
return isPrime(x), nil
})
printStream(primes)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func OrderedFilterMap ¶ added in v0.3.0
OrderedFilterMap is the ordered version of FilterMap: it writes results and errors in input order rather than completion order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Keep only prime numbers and square them
// Concurrency = 3
squares := rill.OrderedFilterMap(numbers, 3, func(x int) (int, bool, error) {
if !isPrime(x) {
return 0, false, nil
}
return x * x, true, nil
})
printStream(squares)
}
// isPrime checks if a number is prime
// and simulates some additional work by sleeping.
func isPrime(n int) bool {
simulateWork(500 * time.Millisecond)
if n < 2 {
return false
}
for i := 2; i*i <= n; i++ {
if n%i == 0 {
return false
}
}
return true
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func OrderedFlatMap ¶
OrderedFlatMap is the ordered version of FlatMap: the output consists of the sub-streams concatenated in the input order.
The argument n bounds the number of concurrent calls to f. The sub-streams are prepared concurrently but - unlike in FlatMap - are consumed one at a time and in order: nothing reads from a sub-stream before its turn. In practice, to keep the stage concurrent, a sub-stream must do all or part of its expensive work ahead of its turn.
Consider a stream of URLs: each file should be downloaded, and its lines should be streamed to the output, all in order. Downloading is the expensive work here.
Example 1: f downloads the whole file into memory and then streams the lines from there. Up to 5 downloads run concurrently.
rill.OrderedFlatMap(urls, 5, func(u string) <-chan rill.Try[string] {
lines, err := getFileLines(u)
return rill.FromSlice(lines, err)
})
Example 2: as the file is being downloaded, f streams the lines through a Buffer that lets the sub-stream run ahead of its turn. Again, up to 5 downloads run concurrently, but a download that runs ahead of its turn pauses after its first 100 lines until the turn comes.
rill.OrderedFlatMap(urls, 5, func(u string) <-chan rill.Try[string] {
lines := streamFileLines(u)
return rill.Buffer(lines, 100)
})
The two examples do the same thing: they buffer the lines, with or without a bound. Without any buffering, the downloads would run one at a time, and the stage would become sequential.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5}, nil)
// Replace each number in the input stream with three strings
// Concurrency = 2; Ordered
result := rill.OrderedFlatMap(numbers, 2, func(x int) <-chan rill.Try[string] {
simulateWork(500 * time.Millisecond)
return rill.FromSlice([]string{
fmt.Sprintf("foo%d", x),
fmt.Sprintf("bar%d", x),
fmt.Sprintf("baz%d", x),
}, nil)
})
printStream(result)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func OrderedMap ¶
OrderedMap is the ordered version of Map: it writes results and errors in input order rather than completion order.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Transform each number
// Concurrency = 3; Ordered
squares := rill.OrderedMap(numbers, 3, func(x int) (int, error) {
return square(x), nil
})
printStream(squares)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func OrderedSplit2
deprecated
func OrderedSplit2[A any](in <-chan Try[A], n int, f func(A) (bool, error)) (outTrue <-chan Try[A], outFalse <-chan Try[A])
OrderedSplit2 is the ordered version of Split2: the outputs preserve the input order for values and errors alike.
Deprecated: OrderedSplit2 will be removed in v1.0. Since the introduction of Tee in v0.8, splitting no longer needs a dedicated operation - it can be composed from existing ones. Unlike OrderedSplit2, the composition is also not limited to two branches.
Quite often, the predicate is a simple, pure check (a field comparison, a type switch, etc.). In such cases, splitting is just Tee plus an OrderedFilter on each branch:
adults, minors := rill.Tee(users)
adults = rill.OrderedFilter(adults, 1, func(u User) (bool, error) { return u.Age >= 18, nil })
minors = rill.OrderedFilter(minors, 1, func(u User) (bool, error) { return u.Age < 18, nil })
If the predicate is expensive or stateful, or if it can fail, it must be evaluated once per item, before Tee: inline this function's implementation, which tags each item with the decision and routes on the tag. The same pattern extends to n-way splitting by tagging with an index or key instead of a bool.
func Reduce ¶ added in v0.2.0
func Reduce[A any](in <-chan Try[A], n int, f func(A, A) (A, error), options ...SinkOption) (result A, hasResult bool, err error)
Reduce combines all values of the stream into a single value using the binary function f.
Treating f as a binary operator "*", Reduce computes in[0] * in[1] * ... * in[N-1]: values are combined in stream order, but the parenthesization is unspecified and may vary from run to run. This requires f to be associative - (a * b) * c == a * (b * c) - so that every parenthesization yields the same result. Commutativity is not required.
Reduce returns:
- (zero, false, err) if an error is observed
- (zero, false, nil) if the stream is empty
- (result, true, nil) otherwise
The argument n bounds the number of concurrent calls to f.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"strings"
"github.com/destel/rill"
)
func main() {
// A stream of 62 single-character strings
str := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
chars := rill.FromSlice(strings.Split(str, ""), nil)
// Reassemble the original string. Concurrency = 4
// String concatenation is a simple non-commutative operation
// and is used here for demonstration only.
res, ok, err := rill.Reduce(chars, 4, func(x, y string) (string, error) {
return x + y, nil
})
fmt.Println("Result:", res, ok)
fmt.Println("Error:", err)
}
Output:
func Split2
deprecated
func Split2[A any](in <-chan Try[A], n int, f func(A) (bool, error)) (outTrue <-chan Try[A], outFalse <-chan Try[A])
Split2 divides the stream into two streams: values that match the condition f go to outTrue, and the rest go to outFalse. Errors are sent to both outputs.
The streams must be consumed concurrently to avoid a deadlock.
The argument n bounds the number of concurrent calls to f. Items are written to the outputs as they become ready, so their order can differ from the input order when n > 1. Use OrderedSplit2 to preserve the order.
Deprecated: Split2 will be removed in v1.0. Since the introduction of Tee in v0.8, splitting no longer needs a dedicated operation - it can be composed from existing ones. Unlike Split2, the composition is also not limited to two branches.
Quite often, the predicate is a simple, pure check (a field comparison, a type switch, etc.). In such cases, splitting is just Tee plus a Filter on each branch:
adults, minors := rill.Tee(users)
adults = rill.Filter(adults, 1, func(u User) (bool, error) { return u.Age >= 18, nil })
minors = rill.Filter(minors, 1, func(u User) (bool, error) { return u.Age < 18, nil })
If the predicate is expensive or stateful, or if it can fail, it must be evaluated once per item, before Tee: inline this function's implementation, which tags each item with the decision and routes on the tag. The same pattern extends to n-way splitting by tagging with an index or key instead of a bool.
func Tee ¶ added in v0.8.0
func Tee[A any](in <-chan A) (<-chan A, <-chan A)
Tee returns two channels and forwards every item from the input to both of them. Both outputs are closed once the input is exhausted. Tee doesn't proceed to the next item until the current one is sent to both outputs, so the caller must consume the outputs concurrently to avoid a deadlock.
Example ¶
package main
import (
"fmt"
"sync"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Create two identical copies of the stream
// Each copy can be transformed separately
numbers1, numbers2 := rill.Tee(numbers)
// Keep only the odd numbers in the first copy
// Concurrency = 3
odd := rill.Filter(numbers1, 3, func(x int) (bool, error) {
return x%2 != 0, nil
})
// Double the numbers in the second copy
// Concurrency = 3
doubled := rill.Map(numbers2, 3, func(x int) (int, error) {
return x * 2, nil
})
// Both copies must be consumed concurrently, otherwise Tee deadlocks
var wg sync.WaitGroup
// First consumer prints the odd numbers
wg.Go(func() {
printStream(odd)
})
// Second consumer sums the doubled numbers
wg.Go(func() {
sum, _, err := rill.Reduce(doubled, 3, func(a, b int) (int, error) {
return a + b, nil
})
fmt.Println("Sum:", sum)
fmt.Println("Sum error:", err)
})
wg.Wait()
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
func ToChans ¶
ToChans splits the stream into two channels, one for values and one for errors, and forwards each item to the appropriate one. Both channels are closed once the input is exhausted. They must be consumed concurrently to avoid a deadlock.
func ToSeq2 ¶ added in v0.4.0
ToSeq2 converts the stream into an iterator of value-error pairs, typically consumed with a for-range loop. Error items do not stop the iteration: they are yielded as ordinary pairs.
The returned iterator is single-use and must be ranged over.
ToSeq2 is a sink like the others: its outcome is known once the iterator is consumed to the end or interrupted by break/return.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
ctx, scope := rill.WithContext(context.Background())
ids := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Read users from the API.
users := rill.Map(ids, 1, func(id int) (*api.User, error) {
return api.GetUser(ctx, id)
})
for user, err := range rill.ToSeq2(users, scope) {
if err != nil {
fmt.Println("Error:", err)
break
}
fmt.Println("Seen:", user.ID)
if user.ID == 5 {
break // blocks until the pipeline has finished
}
}
// The context is canceled and nothing is running anymore
}
Output:
func ToSlice ¶
func ToSlice[A any](in <-chan Try[A], options ...SinkOption) ([]A, error)
ToSlice collects the stream's values into a slice. It returns the prefix of the stream up to the first error, along with the error if any.
See the rill package documentation for the contract shared by all sinks.
Example ¶
package main
import (
"fmt"
"math/rand"
"time"
"github.com/destel/rill"
)
func main() {
// Convert a slice of numbers into a stream
numbers := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Transform each number
// Concurrency = 3; Ordered
squares := rill.OrderedMap(numbers, 3, func(x int) (int, error) {
return square(x), nil
})
resultsSlice, err := rill.ToSlice(squares)
fmt.Println("Result:", resultsSlice)
fmt.Println("Error:", err)
}
// square returns the square of x and simulates some additional work by sleeping.
func square(x int) int {
simulateWork(500 * time.Millisecond)
return x * x
}
func simulateWork(max time.Duration) {
time.Sleep(time.Duration(rand.Intn(int(max))))
}
Output:
func Unbatch ¶
Unbatch flattens a stream of slices into a stream of their values. This function is the inverse of Batch.
Example ¶
package main
import (
"fmt"
"github.com/destel/rill"
)
func main() {
// Create a stream of batches
batches := rill.FromSlice([][]int{
{1, 2, 3},
{4, 5},
{6, 7, 8, 9},
{10},
}, nil)
numbers := rill.Unbatch(batches)
printStream(numbers)
}
// printStream prints all items from a stream (one per line) and an error, if any.
func printStream[A any](stream <-chan rill.Try[A]) {
fmt.Println("Result:")
err := rill.ForEach(stream, 1, func(x A) error {
fmt.Printf("%+v\n", x)
return nil
})
fmt.Println("Error:", err)
}
Output:
Types ¶
type SinkOption ¶ added in v0.9.0
type SinkOption interface {
// contains filtered or unexported methods
}
A SinkOption is an optional argument accepted by every sink.
func WithContext ¶ added in v0.9.0
func WithContext(ctx context.Context) (context.Context, SinkOption)
WithContext returns a context derived from ctx and a SinkOption. A sink given this option cancels the context as soon as its outcome is known, then waits for the pipeline to finish before returning.
The returned option must be used exactly once: using it more than once panics, and never using it can leak the context. In particular, it can't cover branching pipelines where every branch ends with its own sink.
Example ¶
package main
import (
"context"
"fmt"
"github.com/destel/rill"
api "github.com/destel/rill/mockapi"
)
func main() {
// ctx is captured by the callbacks below.
// scope is a functional option passed to ForEach.
ctx, scope := rill.WithContext(context.Background())
// Convert a slice into a channel
ids := rill.FromSlice([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, nil)
// Read users from the API. Concurrency = 3
users := rill.Map(ids, 3, func(id int) (*api.User, error) {
return api.GetUser(ctx, id)
})
// Process users. Concurrency = 2
err := rill.ForEach(users, 2, func(u *api.User) error {
if u.IsActive {
return nil
}
u.IsActive = true
return api.SaveUser(ctx, u)
}, scope)
// Nothing is running anymore; the context is canceled.
// Handle the error (if any).
fmt.Println("Error:", err)
}
Output:
type Stream ¶ added in v0.8.0
Stream is a type alias for a receive-only channel of Try structs. Using it is optional but improves readability.
Before:
func StreamUsers() <-chan rill.Try[*User] {
...
}
After:
func StreamUsers() rill.Stream[*User] {
...
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
internal
|
|
|
list
Package list provides a doubly linked list built around reusable, caller-owned nodes.
|
Package list provides a doubly linked list built around reusable, caller-owned nodes. |
|
th
Package th provides basic test helpers.
|
Package th provides basic test helpers. |
|
Package mockapi provides a very basic mock API for examples and demos.
|
Package mockapi provides a very basic mock API for examples and demos. |