NAME

Langertha::Knarr::Stream - Async chunk iterator returned by streaming Knarr handlers

VERSION

version 1.100

SYNOPSIS

use Langertha::Knarr::Stream;

# From a fixed list of strings
my $stream = Langertha::Knarr::Stream->from_list('hel', 'lo');

# From a sync generator
my @parts = ('hel', 'lo');
my $stream = Langertha::Knarr::Stream->new(
    generator => sub { @parts ? shift @parts : undef },
);

# From a future-yielding source (real async)
my $stream = Langertha::Knarr::Stream->new(
    source => sub { $next_chunk_future },
);

# Drain it
while ( defined( my $chunk = $stream->next_chunk_f->get ) ) {
    print $chunk;
}

DESCRIPTION

The chunk iterator that streaming Knarr handlers return. Supports two construction modes: a sync generator coderef that returns the next chunk string each call (or undef for end), or a source coderef that returns a Future resolving to the next chunk string. The Future form is the one real async backends like Net::Async::HTTP use; the generator form is for tests and simple cases.

generator

Optional. CodeRef returning the next chunk synchronously.

source

Optional. CodeRef returning a Future that resolves to the next chunk.

next_chunk_f

Returns a Future resolving to the next chunk string, or undef when the stream is exhausted.

from_list

my $stream = Langertha::Knarr::Stream->from_list(@chunks);

Convenience constructor that builds a stream from a fixed list of chunk strings.

from_callback

my $stream = Langertha::Knarr::Stream->from_callback( sub {
    my ($emit, $done, $fail) = @_;
    my $f = $engine->simple_chat_stream_realtime_f(
        sub { $emit->( $_[0]->content ) },
        @messages,
    );
    $f->on_done( $done );
    $f->on_fail( $fail );
    $f->retain;
});

Builds a stream backed by a callback-driven producer. The setup sub receives three callbacks — $emit->($chunk), $done->(), $fail->($err) — and is expected to wire them to the underlying async source. Internally maintains a queue and pending Future so the consumer side can sit on next_chunk_f without polling.

This is the canonical replacement for the queue/pending/finished/error pump that engine-backed handlers used to inline.

SUPPORT

Issues

Please report bugs and feature requests on GitHub at https://github.com/Getty/langertha-knarr/issues.

IRC

Join #langertha on irc.perl.org or message Getty directly.

CONTRIBUTING

Contributions are welcome! Please fork the repository and submit a pull request.

AUTHOR

Torsten Raudssus <torsten@raudssus.de> https://raudssus.de/

COPYRIGHT AND LICENSE

This software is copyright (c) 2026 by Torsten Raudssus.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.