Custom Sources & Sinks¶
Integrate any external system—such as Kafka consumers, NATS JetStream subscriptions, gRPC streams, or database/sql cursors—without adding dependencies to automi itself. Three interfaces define the seam: FromFunc, Source[T], and Sink[T].
Option 1: Wrap a Pull Function with FromFunc¶
For client APIs that return one item per call, FromFunc handles looping, cancellation, skips, and EOF termination.
func SQLRowsSource[T any](rows *sql.Rows, scan func(*sql.Rows) (T, error)) automi.Stream[T] {
return automi.FromFunc(func(ctx context.Context) (T, error) {
var zero T
if ctx.Err() != nil {
return zero, ctx.Err()
}
if !rows.Next() {
if err := rows.Err(); err != nil {
return zero, err
}
return zero, io.EOF
}
return scan(rows)
})
}
Return io.EOF when the source finishes normally, or automi.ErrSkip to ignore an item and continue pulling.
Option 2: Implement Source[T]¶
Implement Source[T] when the source owns setup, subscriptions, cursors, or defer resource cleanup across the full iteration lifecycle:
Inside Stream(ctx), obey two iterator rules:
- Honor
<-ctx.Done()during blocking operations and yield(zero, ctx.Err()). - Stop immediately whenever
yield(v, nil)returnsfalse, and never callyieldagain after it returnsfalse.
type gRPCClientStream[T any] interface {
Recv() (T, error)
}
type GRPCSource[T any] struct {
Open func(context.Context) (gRPCClientStream[T], func(), error)
}
func (g GRPCSource[T]) Stream(ctx context.Context) iter.Seq2[T, error] {
return func(yield func(T, error) bool) {
var zero T
stream, closeFn, err := g.Open(ctx)
if err != nil {
yield(zero, err)
return
}
if closeFn != nil {
defer closeFn()
}
for {
if cerr := ctx.Err(); cerr != nil {
yield(zero, cerr)
return
}
msg, rerr := stream.Recv()
if rerr != nil {
if !errors.Is(rerr, io.EOF) {
yield(zero, rerr)
}
return
}
if !yield(msg, nil) {
return
}
}
}
}
Pass the source to automi.From:
Option 3: Implement Sink[T] or SinkFunc[T]¶
Implement Sink[T] when a destination manages transactions, connection pools, buffer flushes, or acknowledgments:
For inline custom sinks without defining a named struct, wrap a function in SinkFunc[T]:
func TransactionalBatchSink(db *sql.DB) automi.Sink[[]Record] {
return automi.SinkFunc[[]Record](func(ctx context.Context, seq iter.Seq2[[]Record, error]) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
for batch, serr := range seq {
if serr != nil {
return serr
}
if err := insertRecords(ctx, tx, batch); err != nil {
return err
}
}
return tx.Commit()
})
}
Because Consume receives the iter.Seq2 pull loop directly, defer statements inside Consume always run on normal completion, upstream error, write error, or context cancellation.