NAME
Ekorn::Pipeline::Futures::Manual::Reference - Ekorn::Pipeline::Futures reference
DESCRIPTION
Ekorn::Pipeline::Futures gives Ekorn::Pipeline two stages, in_futures and in_futures_as_ready. Each calls a block for each value, and keeps several of what the blocks give, Futures or promises, waiting at once, in one process, while the stage waits on them. They are for I/O that a library can wait on without blocking: web requests, REST calls, anything on IO::Async or Mojolicious.
This reference says what the stages promise: their arguments, what a block may give and sees, how the stage waits, the order results come in, and what failures and stops do. The user guide shows how to use them, task by task, in tested recipes, and the Guarantees section links each promise to the recipes that show it. The module's POD says the same more briefly, and is the authority where they differ.
Ekorn::Pipeline::Futures needs Perl 5.36 or later, Ekorn::Pipeline v0.5.1 or later, and Future. What the blocks use, an event loop and a client such as IO::Async or Mojo::UserAgent, is the caller's to install. Its version is 0.x, so its interface may still change before 1.0. Changes says what each release changed.
Not inside a running loop. These stages are for programs that run no event loop of their own: scripts, batch jobs, scrapers and command-line tools. A pipeline runs synchronously, and the stage runs the loop only while it waits, so it can't run inside a callback of a loop that's already running, such as a Mojolicious app's request handler. Not inside a running loop says what happens if it is, and what to use instead.
Contents
At a glance
use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures;
my $loop = IO::Async::Loop->new;
# Each value waits a tenth of a second for each unit, as a slow
# look-up would, up to 3 at once; the results in the order the values
# came.
my $look_ups = Ekorn::Pipeline->new(
in_futures(3, async sub ($n) {
await $loop->delay_future(after => $n / 10);
return $n * 10;
}),
);
say join ' ', $look_ups->(3, 1, 2); # 30 10 20
# The same, each result passed on as soon as it's ready.
my $as_ready = Ekorn::Pipeline->new(
in_futures_as_ready(3, async sub ($n) {
await $loop->delay_future(after => $n / 10);
return $n * 10;
}),
);
say join ' ', $as_ready->(3, 1, 2); # 10 20 30
The block is an async sub, from Future::AsyncAwait, which gives a Future as soon as it reaches its first await. The stage calls it for each value, keeps up to 3 waiting, and runs IO::Async's loop while it waits for them. Each example after this one needs this program's first six lines, up to its first blank line, and leaves them out.
Importing
use Ekorn::Pipeline::Futures;
exports both stages. To name what you import:
use Ekorn::Pipeline::Futures qw(in_futures);
To import neither, and call each by its full name:
use Ekorn::Pipeline::Futures ();
The stages work with any of Ekorn::Pipeline's parts, its sources, sinks, iterators and feeds among them, and inside a pipeline given as a stage, or one given a name, as any stage does.
The stages
Each stage checks its arguments as it's made, and croaks, at the line that made it, if one is wrong (Diagnostics).
in_futures
in_futures($n, $block)
Calls $block for each value, and passes on what it gives, once it's ready, in the order the values came. $n is a whole number, 1 or more: the most values that may be waiting at once (Order, and how many wait at once). $block is a code reference: a sub, an async sub, or a reference to a named one, \&look_up. The stage takes no options; one given croaks.
in_futures_as_ready
in_futures_as_ready($n, $block)
The same, but passing each value's results on as soon as they're ready, in the order they're ready, so one slow value holds up none of the rest. A Future or promise is ready once it's done, failed or cancelled.
What a block may give
A block may give one of three things:
**One thing
awaittakes:** a Future, such as an IO::Async::Future, a Future::Mojo, or a Mojo::Promise, as Mojo::UserAgent'sget_pand Mojo's ownasyncsubs give. The stage waits for it, and its values, however many, are the results.Anything else, a plain value, several values, or none: they're the results, at once, with no waiting. Several values are never awaited, even if one of them is a Future.
An error, thrown before it gives anything: it's a failure, in its turn, as a failed Future would be.
What await takes is anything offering the methods Future::AsyncAwait calls on it: AWAIT_IS_READY, AWAIT_ON_READY, AWAIT_GET, AWAIT_WAIT, AWAIT_CLONE and AWAIT_DONE. The stage uses those, and nothing else, so it names no event loop and no one class.
Mojo's promises work the same, with nothing between:
use Mojo::Promise;
my $timers = Ekorn::Pipeline->new(
in_futures_as_ready(3, sub ($n) { Mojo::Promise->timer($n / 10 => $n) }),
);
say join ' ', $timers->(5, 1, 3); # 1 3 5
A Future done with several values gives several results; one done with none gives none:
my $pairs = Ekorn::Pipeline->new(
in_futures(2, sub ($n) { Future->done($n, "$n!") }),
);
say join ' ', $pairs->(1, 2); # 1 1! 2 2!
A block that knows its answer already can give it at once, and the stage passes it on without waiting:
my %known = (2 => 'two');
my $cached = Ekorn::Pipeline->new(
in_futures(2, async sub ($n) {
return $known{$n} if exists $known{$n};
await $loop->delay_future(after => 0.1);
return "looked up $n";
}),
);
say for $cached->(1, 2);
# looked up 1
# two
What a block sees
The block is called in the stage, as a map's would be, with the value in $_ and as its argument. Until its first await, it sees where its value stands in the run, as a stage would: result_original, result_number and the run's context, from Ekorn::Pipeline::Context and Ekorn::Pipeline.
Once it has waited, it resumes inside whatever the stage is doing then, waiting for another value, or taking results, and $_ and the run's context belong to that. So read what you need before the first await, and name the value, rather than reading $_ after:
use Ekorn::Pipeline::Context qw(result_original);
my $where = Ekorn::Pipeline->new(
sub ($name) { uc $name },
in_futures(2, async sub ($name) {
my $original = result_original;
await $loop->delay_future(after => 0.1);
return "$name came from $original";
}),
);
say for $where->('a', 'b');
# A came from a
# B came from b
A stage after this one sees each result's own original, as the stages keep each value's place with it, even when the results come out of order, as in_futures_as_ready's do.
How the stage waits
A pipeline runs synchronously, one value after another. The stage keeps the run synchronous: it calls a block, and goes on to the next value, until as many as may be are waiting; then it waits, and passes on what's ready.
It waits through AWAIT_WAIT, which runs the event loop the Future or promise is tied to, until it's ready. in_futures waits on the oldest value's; in_futures_as_ready on whichever is ready first. So the loop runs only while the stage waits, and only the loop the block's Futures use. A Future already done, such as Future->done's, needs no loop at all.
Something that's still waiting after the stage waited on it, as a plain Future->new that nothing will make ready is, croaks: "Can't wait for a result: it was still waiting after its wait".
Order, and how many wait at once
**in_futures passes results on in the order the values came. A value's results wait until every value before it has passed on its own. in_futures_as_ready** passes each value's results on as soon as they're ready.
At most $n values have been given to a block and not been passed on: those still waiting, and, for in_futures, those ready but waiting for an earlier one. While that many are, and none may go on, the stage waits, and so takes no new value; so a pipeline pulling from a source takes values from it only as there's room. With in_futures, a slow value can hold up the rest, leaving no room for more until it's done; in_futures_as_ready goes round it. The stage holds at most $n values and their results.
At the end of a run, once the values have run out, the stage's flush waits for every value it still holds, and passes on all their results together, in the stage's order, as a flush gives its values all at once.
Failures and stops
A failure, a failed Future, a rejected promise, or an error the block throws, is passed on in its turn, as it was: after the results before it, in the order the stage passes results on. A pipeline reports it as any stage's error, after "Pipeline stage #1 failed at ...", which names the line that ran it, and passes on an object as it is. A failure that's a string, such as Mojo's "Connection refused", keeps its text, without the line in the stage that Future or Mojo::Promise would otherwise say it came from:
use Mojo::Promise;
my $refused = Ekorn::Pipeline->new(
in_futures(2, sub ($url) { Mojo::Promise->reject('Connection refused') }),
);
eval { $refused->('http://localhost:1/') };
print $@;
# Pipeline stage #1 failed at ... line ...:
# Connection refused
Here the error at 3 comes after 1 and 2 have gone on:
my @seen;
my $run = Ekorn::Pipeline->new(
in_futures(2, async sub ($n) {
await $loop->delay_future(after => 0.01);
die "no $n\n" if $n == 3;
return $n;
}),
sub ($n) { push @seen, $n; $n },
);
eval { $run->(1 .. 20) };
print $@;
# Pipeline stage #1 failed at ... line ...:
# no 3
say "passed on first: @seen"; # passed on first: 1 2
A stop in the block, an Ekorn::Pipeline::Stop, before or after an await, stops the run in its turn, with its values after every result before it:
use Ekorn::Pipeline::Stop;
my $stopping = Ekorn::Pipeline->new(
in_futures(2, async sub ($n) {
await $loop->delay_future(after => 0.01);
return $n == 3 ? Stop('stopped at 3') : $n;
}),
);
say join ' ', $stopping->(1 .. 20); # 1 2 stopped at 3
It's thrown again as an Ekorn::Pipeline::Stop, whatever its class; a pipeline knows a stop by isa, so it stops the same. A stop that isn't an array, which carries nothing in Ekorn, carries nothing here.
A stop after the stage, such as take's, or a run ended from outside, as by an iterator's finish, cancels what's still waiting, where it can be: a Future is cancelled, which stops what it waits on where its library supports that, as IO::Async's timers and Net::Async::HTTP's requests do; a Mojo::Promise can't be, so its request goes on, and settles, unheeded, when Mojo's loop next runs. While values are still coming, the work stops with the run:
use Ekorn::Pipeline::Stages::Flow qw(take);
use Time::HiRes qw(time);
my $first_two = Ekorn::Pipeline->new(
in_futures(2, async sub ($n) {
await $loop->delay_future(after => $n / 10);
return $n;
}),
take(2),
);
my $started = time;
my @first = $first_two->(1, 2, (30) x 6);
say "@first"; # 1 2
say time - $started < 2 ? 'the 3-second waits were cancelled' : 'it waited for them';
# the 3-second waits were cancelled
Once the values have run out, though, the stage's flush waits for everything it still holds before it passes any on, as a flush gives its values all at once. So a stop after the stage then cancels nothing. Above, with only (1, 2, 30, 30), the stage has been given every value by the time 2 is ready, and the run waits for both.
The flush's limit. At the end of a run, the stage passes on what it still holds in its flush. A stop met there carries every result the flush took before it. But a failure met there loses them, with the run, as a flush can't pass values on and then die; they're results no stage after this one sees. A block that turns its failures into results, rather than failing, loses nothing: Keep going: turn each failure into a result shows how.
Not inside a running loop
The stage waits by running the event loop, so it can't wait inside a callback of a loop that's already running: the loop can't be run again from inside itself. What happens depends on the loop:
Mojolicious's loop, Mojo::IOLoop, croaks, as the stage can ask a Mojo::Promise whether its loop is running: "Can't wait for a result: its event loop is already running, and a pipeline runs synchronously inside it". A Future tied to it, such as a Future::Mojo, which the stage can't ask, croaks with the message for what's still waiting, below.
IO::Async's loop runs again, so a run inside it may seem to work, but runs the program's other callbacks in the middle of the pipeline.
Anything else still waiting after its wait croaks: "Can't wait for a result: it was still waiting after its wait, as no event loop ran for it, or its loop was already running".
Here a pipeline is run from a Mojo::IOLoop callback, as a request handler would run it:
use Mojo::IOLoop;
use Mojo::Promise;
my $timers = Ekorn::Pipeline->new(
in_futures(2, sub ($n) { Mojo::Promise->timer(0.1 => $n) }),
);
Mojo::IOLoop->next_tick(sub {
eval { $timers->(1, 2) };
say $@ =~ m( (Can't\ wait [^,]*) )x; # Can't wait for a result: its event loop is already running
Mojo::IOLoop->stop;
});
Mojo::IOLoop->start;
The message goes on: "and a pipeline runs synchronously inside it".
In a Mojolicious app, use Mojo::Promise's own map, which limits how many wait at once without running the loop, as In a Mojolicious app, use Mojo::Promise's map instead shows. And don't run a pipeline with these stages inside the block of another: each value's inner run waits for its own, one value at a time, as Don't run a pipeline inside the block shows.
What the stages don't do
Three things the stages may seem to promise, and don't:
No rate limit.
$ncaps how many values wait at once, overall. It doesn't space requests out in time, nor limit them to one host. A limit to a host is the client's: Mojo::UserAgent opens a connection for each request it's waiting on; Net::Async::HTTP opens one to a host by default, and sends every request down it, so give itmax_connections_per_host => 0. Even so, its version 0.50 leaves a request waiting a round for a busy connection, as A note on Net::Async::HTTP explains.**
in_futures_as_readyisn't Future'sneeds_any.**needs_anyfinishes with the first Future to be done.in_futures_as_readypasses on every value's results, each as soon as it's ready, and finishes only when they all have. To keep only the first, put atake(1)after it, as Take the answer from whichever server is quickest does.No help for work that blocks. A block runs in the program's one process, so work that blocks, as the DBI's does, or that keeps the CPU busy, holds up every value. That's Ekorn::Pipeline::Workers'. Moving work there isn't free: a worker is a new perl, so its work is a function in a module, which the worker loads, not a block beside the call.
Guarantees
What the stages promise, each with the how-to's recipes that show it. Every recipe runs as it stands, on Linux, macOS and Windows, on every change.
- Up to
$nvalues wait at once, and no more -
Run three slow look-ups at once, See the time it saves, Choose how many run at once
in_futurespasses results on in the order the values came-
Get the results in the order the values came, Fetch numbered pages until one comes back empty
in_futures_as_readypasses each value's results on as soon as they're ready-
Get each result as soon as it's ready, Take the answer from whichever server is quickest
- A block that knows its answer gives it at once
- Any loop that
awaitknows works, with nothing between -
Use Mojolicious instead of IO::Async, and chapters 1 and 2
- Each result knows the original of the value it came from, in order or not
-
Know which value each result came from, Know it when the results come in any order
- The block sees its value's place until its first
await - A failure takes its turn, after the results before it
- An error object is passed on as it is
- A stop in the block takes its turn, with its values
- A stop after the stage cancels what's waiting, where it can be
- A failure met in the flush loses the results it took with it
- Inside a running loop, it croaks, saying why
- Each mistake in a stage's arguments is refused as it's made
One promise has tests in the distribution's t/, rather than a recipe: that a stop met in the flush carries every result the flush took before it.
Diagnostics
Every message the stages give. The first three are given as a stage is made, at the line that made it. The last two come from a run, so a pipeline reports them after "Pipeline stage #1 failed at ...", naming the line that ran it. Failures from the block, or from a library it calls, are passed on as they were. Every message the stages give makes each, and says what to do about it.
Expected a number in flight of 1 or more:
$nwasn't a whole number, 1 or more.Expected a code reference: the block wasn't code, as when it's a sub's name rather than a reference to it.
Expected no option %s: the stages take no options; for results as soon as they're ready, use
in_futures_as_ready.Can't wait for a result: its event loop is already running, and a pipeline runs synchronously inside it: the stage was run in a callback of the loop it would have to run to wait, as in a Mojolicious app's request handler (Not inside a running loop).
Can't wait for a result: it was still waiting after its wait, as no event loop ran for it, or its loop was already running: what the block gave was still waiting after the stage waited on it: it's tied to no loop that can run, such as a plain Future nothing will make ready, or its loop was running and couldn't say so.
SEE ALSO
Ekorn::Pipeline::Futures, Ekorn::Pipeline, Ekorn::Pipeline::Manual::HowTo
AUTHOR
Iain Campbell <cpanic@cpan.org>
LICENSE
Copyright (c) 2026 by Iain Campbell.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.