NAME

Ekorn::Pipeline::Futures::Manual::HowTo - Ekorn::Pipeline::Futures user guide

DESCRIPTION

Ekorn::Pipeline::Futures gives you two stages, in_futures and in_futures_as_ready. Each one lets a pipeline wait on many slow things at once, such as web requests, instead of one after another.

You write a small block that starts the work for one value. The stage runs that block for several values at a time and waits for their results. It then passes the results on to the rest of the pipeline, like any other stage.

The rest of your program doesn't change. It still runs one line after another. Only the stage does the waiting.

This guide is a set of recipes. Each one solves a single problem, and each one is a complete program: copy it into a file, run it, and it prints what the guide says it prints. Every recipe is tested that way, on Linux, macOS and Windows.

Is this the guide you need?

Ekorn::Pipeline has two distributions for doing many things at once. Which one fits depends on what each value's work waits for:

  • Waiting on the network, with a library that can wait without stopping the program, such as Mojo::UserAgent or IO::Async: use this one. One process waits on many requests at once, and your block sits beside the call.

  • Waiting on something that stops the program while it waits, such as a database query through the DBI, or a module with only an ordinary, blocking interface; or keeping the CPU busy, such as compressing files or crunching numbers: use Ekorn::Pipeline::Workers, and its own guide, Ekorn::Pipeline::Workers::Manual::HowTo. Each value's work runs in a worker of its own, so it must be a function in a module, which the worker loads.

  • Neither, because each value's work takes microseconds: use an ordinary stage. The stage costs a few microseconds a value, so it pays only for work that waits longer.

Where to start

The guide is long, but you needn't read it all. Pick the path that fits you:

Contents

Before you start: Futures, promises and loops

If you've used Futures and event loops before, skip to chapter 1. If not, these few short programs show the ideas the rest of the guide is built on. Each runs as it stands.

A Future is an answer that isn't here yet

A Future is an object standing for an answer that will come later: a web page, say, that's still on its way. Until then, it's waiting. Once the answer comes, it's ready, and you can get the answer from it:

use v5.36;
use Future;

my $answer = Future->new;
say $answer->is_ready ? 'ready' : 'waiting';    # waiting

$answer->done('found Abba');    # the answer comes
say $answer->is_ready ? 'ready' : 'waiting';    # ready
say $answer->get;                               # found Abba

Here the program gives the answer itself, with done. Usually a library gives it: when a web server replies, say. A Future can also fail, with an error in place of an answer.

An event loop finishes the Futures

Something has to notice when a reply arrives, or a timer runs out, and make the right Future ready. That's an event loop. IO::Async's is one:

use v5.36;
use IO::Async::Loop;

my $loop  = IO::Async::Loop->new;
my $timer = $loop->delay_future(after => 0.1);
say $timer->is_ready ? 'ready' : 'waiting';    # waiting

$timer->get;    # runs the loop until the timer is ready
say $timer->is_ready ? 'ready' : 'waiting';    # ready

delay_future gives a Future that the loop makes ready after a tenth of a second. Nothing happens while nobody runs the loop. get runs it until the Future is ready.

The point of a loop is that it can watch many things at once: a hundred timers, or a hundred web requests, each made ready as it finishes. Many waits overlap, so they take the time of the longest, not of them all added up.

async and await write it as ordinary code

Future::AsyncAwait gives you async sub and await. Called, an async sub runs at once, up to its first await. There it stops, and returns a Future of its answer. When what it awaits is ready, the loop carries it on from where it stopped:

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;

my $loop = IO::Async::Loop->new;

async sub look_up ($name) {
    await $loop->delay_future(after => 0.1);
    return "found $name";
}

my $abba = look_up('Abba');
say $abba->is_ready ? 'ready' : 'waiting';    # waiting
say $abba->get;                               # found Abba

look_up('Abba') doesn't wait: it returns a Future of its answer, the string it returns. That's what in_futures uses: it calls your block for many values, keeps their Futures, and runs the loop while it waits for them.

A promise is Mojolicious's Future

Mojolicious calls the same idea a promise, a Mojo::Promise, and has its own loop. A promise is resolved with an answer, or rejected with an error, and then says what to do with the answer:

use v5.36;
use Mojo::Promise;

my $found;
Mojo::Promise->timer(0.1)->then(sub { $found = 'found Abba' })->wait;
say $found;    # found Abba

Mojo::Promise->timer(0.1) is resolved after a tenth of a second, on Mojo's loop, and ->wait runs that loop until it is. The stages take promises just as they take Futures, as chapter 2 shows.

Which to choose

Both work with these stages, in the same way. Choose the one your other code uses. If there's none yet: for web requests, this guide uses Mojolicious's Mojo::UserAgent, as chapter 2 explains; for timers and other I/O, IO::Async has a wide range of modules on CPAN.

1. First steps

These recipes show what the stages do, using timers in place of real work, so that every one runs anywhere, with no network. A timer that waits for a second behaves like a request that takes a second. Chapter 2 swaps them for real web requests.

Run three slow look-ups at once

The problem

You have a list of names. Looking each one up takes a second. One after another, three names take three seconds. You'd like them to take one.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async. Install them from CPAN:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# This stands in for a slow look-up, such as a web request.
# It waits for one second, then gives its answer.
async sub look_up ($name) {
    await $loop->delay_future(after => 1);
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Abba
# found Blur
# found Cream

How it works

use Future::AsyncAwait gives you async sub and await. An async sub can stop at an await and carry on later, once the thing it waits for is ready.

IO::Async::Loop->new makes an event loop. The loop is what keeps track of everything that's waiting, here the one-second timers.

look_up is the work for one name. $loop->delay_future(after => 1) gives something that will be ready in one second, and await waits for it. Calling look_up doesn't wait, though. It hands back a Future at once: a promise of the answer to come.

use Ekorn::Pipeline::Futures qw(in_futures) imports the stage. Both stages are imported by default, so qw(in_futures) isn't needed, but this guide names what each program uses, so you can see where every name comes from.

in_futures(3, \&look_up) is the stage. For each name, it calls look_up and keeps the Future it gets. The 3 says how many can be waiting at once. When it can't start any more, the stage runs the loop until a result is ready.

So all three timers run together, and the whole run takes about one second, not three.

The results come out in the order the names went in, whichever finishes first.

What can go wrong

Waiting with sleep in place of await is the easiest mistake to make. sleep stops the whole program, the stage included, so nothing else can happen while it waits. The look-ups run one after another, and there's no warning:

use v5.36;
use Future::AsyncAwait;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

# A mistake: sleep stops the whole program, so nothing else can run.
async sub look_up ($name) {
    sleep 1;
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);
my $started = time;
my @found   = $pipeline->(qw(Abba Blur Cream));
printf "%d found in %d s\n", scalar @found, time - $started;    # 3 found in 3 s

The fix is to wait only with await, on something the loop runs: a timer, a web request, or anything else your loop's libraries give you. The same goes for any call that waits by itself, such as an ordinary LWP::UserAgent request: it holds up every other look-up.

Where next

See the time it saves measures the difference.

See the time it saves

The problem

You'd like to see the difference for yourself: the same look-ups, one at a time and all at once.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async, as before:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# A look-up that takes one second.
async sub look_up ($name) {
    await $loop->delay_future(after => 1);
    return "found $name";
}

my @names = qw(Abba Blur Cream Dido);

for my $at_once (1, 4) {
    my $pipeline = Ekorn::Pipeline->new(
        in_futures($at_once, \&look_up),
    );
    my $started = time;
    my @found   = $pipeline->(@names);
    printf "%d at once took %d s\n", $at_once, time - $started;
}
# 1 at once took 4 s
# 4 at once took 1 s

How it works

The program runs the same four look-ups twice. The only difference is the first argument to in_futures.

With 1, the stage starts one look-up and waits for it before starting the next. That's the same as calling them one after another: four seconds.

With 4, the stage starts all four, then waits. The four timers run at the same time, so the run takes about one second.

time here is Time::HiRes's, which measures in fractions of a second. %d gives whole seconds, rounded down, as the exact time varies a little from run to run, and each wait here is a whole second.

What can go wrong

Nothing here, but the saving depends on the work. Waiting on a timer, a web server or a database server costs your program nothing, so many waits can overlap. Work that keeps the CPU busy, such as resizing an image, can't overlap like that in one process. For that work, use Ekorn::Pipeline::Workers instead.

Where next

Choose how many run at once shows what the first argument does when there are more values than that.

Choose how many run at once

The problem

You have more values than you want to look up at the same time. A web server may refuse you if you send it a hundred requests at once, for one. You'd like to set a limit.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# Count how many look-ups are waiting at once, and the most there were.
my $waiting = 0;
my $most    = 0;

async sub look_up ($name) {
    $waiting++;
    $most = $waiting if $waiting > $most;
    await $loop->delay_future(after => 0.1);
    $waiting--;
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(2, \&look_up),
);
my @found = $pipeline->(qw(Abba Blur Cream Dido Elbow Free));

say scalar(@found), " found, at most $most at once";    # 6 found, at most 2 at once

How it works

The first argument to in_futures, 2 here, is the most it will have on the go at once. When two are waiting, the stage stops taking new values and waits for one to finish. Then it takes the next.

So six look-ups run two at a time, and every one still gets done.

The count includes results that are ready but waiting for their turn to go on, as the next recipe explains. So it's a limit on what the stage holds, as well as on what it's waiting for.

What can go wrong

The number must be a whole number, 1 or more. Anything else croaks as the stage is made:

use v5.36;
use Ekorn::Pipeline::Futures qw(in_futures);

eval { in_futures(0, sub ($name) {"found $name"}) };
print $@;    # Expected a number in flight of 1 or more at ...

The limit is on the stage as a whole. It isn't a limit on how fast requests are sent, and it isn't a limit for each web server. Fetch many pages at once says what it means for web requests.

Where next

Get the results in the order the values came shows what happens when some look-ups finish before others.

Get the results in the order the values came

The problem

Some look-ups are quicker than others. You want the results in the same order as the values you gave, so that each result lines up with its value.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# Abba is the slowest, Blur the quickest.
my %seconds = (Abba => 0.3, Blur => 0.1, Cream => 0.2);

async sub look_up ($name) {
    await $loop->delay_future(after => $seconds{$name});
    say "$name is ready";
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);
my @found = $pipeline->(qw(Abba Blur Cream));

say for @found;
# Blur is ready
# Cream is ready
# Abba is ready
# found Abba
# found Blur
# found Cream

How it works

The first three lines are printed by look_up, as each one finishes: Blur first, Abba last.

The last three are the results. They're in the order the names went in, not the order they finished. in_futures holds Blur's and Cream's results until Abba's is ready, then passes all three on in turn.

This is what in_futures always does, so you can rely on it.

What can go wrong

Holding results back has a cost. While Abba is still waiting, the results behind it can't go on, and they count towards the limit. With a limit of 2 and one very slow value, the stage can sit idle, waiting for it.

If the order doesn't matter to you, the next recipe avoids that.

Where next

Get each result as soon as it's ready.

Get each result as soon as it's ready

The problem

You don't mind what order the results come in. You'd rather each one went on as soon as it's ready, so one slow value holds up nothing else.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures_as_ready);

my $loop = IO::Async::Loop->new;

my %seconds = (Abba => 0.3, Blur => 0.1, Cream => 0.2);

async sub look_up ($name) {
    await $loop->delay_future(after => $seconds{$name});
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures_as_ready(3, \&look_up),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Blur
# found Cream
# found Abba

How it works

in_futures_as_ready is the same as in_futures in every way but one: it passes each result on as soon as it's ready. Blur finishes first, so its result comes first.

The use line names it, qw(in_futures_as_ready), as this program uses no other.

What can go wrong

Every value still gets its result: the stage doesn't stop at the first one. To keep only the first, put a stage after it that stops the run, as Take the answer from whichever server is quickest shows.

Once results can come in any order, you can't tell which value a result belongs to by its place. Put what you need in the result itself, as "found $name" does here.

Where next

Name the value, rather than reading $_ after waiting.

Name the value, rather than reading $_ after waiting

The problem

Ekorn stages let you write $_ for the value, as map and grep do. in_futures does too. But a block that waits needs care with it.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, async sub {
        my $name = $_;    # read $_ before the first await
        await $loop->delay_future(after => 0.1);
        return "found $name";
    }),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Abba
# found Blur
# found Cream

How it works

The stage calls the block with the value in $_, and as its argument. Until the block's first await, $_ is its value, as you'd expect.

At an await, the block stops, and Perl goes back to the stage. When the block carries on, $_ is whatever the stage was doing then, which is usually another value.

So the block copies $_ into $name first, and uses $name after. Naming the value in the sub's signature, as in async sub ($name), does the same, and is the safest habit.

What can go wrong

Read $_ after the await, and you get the wrong value, with no warning:

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, async sub {
        await $loop->delay_future(after => 0.1);
        return "found $_";    # a mistake: $_ is read after waiting
    }),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Cream
# found Cream
# found Cream

Each block carries on while the stage is handling Cream, the last value, so every result says Cream. With other values or stages, it could be any of them.

The same goes for anything else that changes as the run goes on, such as Ekorn's result_original and result_number: read them before the first await.

Where next

Skip the wait when you already know the answer.

Skip the wait when you already know the answer

The problem

Some answers you already have, perhaps from an earlier run. Only the others need looking up.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

my %known = (Blur => 'found Blur, without waiting');

async sub look_up ($name) {
    return $known{$name} if exists $known{$name};
    await $loop->delay_future(after => 0.1);
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Abba
# found Blur, without waiting
# found Cream

How it works

An async sub doesn't have to wait. When it returns before reaching an await, its answer is ready at once, and the stage passes it on in its turn.

The block doesn't even have to be an async sub. If it returns anything other than something to wait on, such as a plain string, the stage takes that as its result:

use v5.36;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, sub ($name) {"found $name"}),
);

say for $pipeline->(qw(Abba Blur));
# found Abba
# found Blur

What can go wrong

Results still come in order. Blur's answer is ready at once, but with in_futures it waits for Abba's before it goes on. Use in_futures_as_ready if it shouldn't.

Where next

Use Mojolicious instead of IO::Async.

Use Mojolicious instead of IO::Async

The problem

Your program uses Mojolicious, or you'd rather it did. You'd like the same stages, with Mojo's own event loop and its own async and await.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait. Mojo's async and await are built on Future::AsyncAwait, version 0.52 or later, but installing Mojolicious doesn't install it, so ask for it:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::Promise;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

# A look-up that takes one second, on Mojo's loop.
async sub look_up ($name) {
    await Mojo::Promise->timer(1);
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);

say for $pipeline->(qw(Abba Blur Cream));
# found Abba
# found Blur
# found Cream

How it works

It's the first recipe again, with two lines changed.

use Mojo::Base -strict, -async_await gives you Mojo's async and await in place of Future::AsyncAwait's. Its async sub returns a Mojo::Promise, which is Mojo's kind of Future.

Mojo::Promise->timer(1) is a promise that's kept after one second, on Mojo's loop. There's no loop to make: Mojo has one already.

The stage doesn't need to be told which loop you use. It waits on whatever it's given, in the way await would.

What can go wrong

Without Future::AsyncAwait 0.52 or later, the use Mojo::Base line croaks, before anything runs: "Future::AsyncAwait 0.52+ is required for async/await". Install it, as above.

Once -async_await is on a package's use Mojo::Base line, every async sub in that package returns a Mojo::Promise, even with use Future::AsyncAwait there too. That's no problem for these stages, which wait on either.

Don't run these stages inside a Mojolicious web app's request handler, where Mojo's loop is already running. That has a chapter of its own.

Where next

Chapter 2 makes real web requests.

2. Web requests, with Mojo::UserAgent

These recipes fetch web pages and call web APIs, many at a time, with Mojo::UserAgent, the HTTP client that comes with Mojolicious.

So that each one runs anywhere, with no network, each program starts a small web server of its own, inside the program, and fetches from that. It's marked as the part to leave out. With your own URLs, give them in full, such as https://example.com/page/1, and leave the server out.

Why Mojo::UserAgent, rather than Net::Async::HTTP, the client that goes with IO::Async? A note on Net::Async::HTTP at the end of the chapter explains.

Fetch many pages at once

The problem

You have a list of web pages to fetch, and each one is slow to answer. You'd like to fetch several at a time.

You'll need

Ekorn::Pipeline::Futures and Mojolicious, which includes Mojo::UserAgent. For https:// URLs, IO::Socket::SSL too:

cpanm Ekorn::Pipeline::Futures Mojolicious IO::Socket::SSL

The program

use v5.36;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# A server to try it against, inside this program, where each page
# takes a second. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $tx = $c->render_later->tx;
        Mojo::IOLoop->timer(1 => sub { $c->render(text => 'page ' . $c->param('n')) });
    },
);
$ua->server->app($app);

# Fetch a page, and give its text.
sub fetch ($url) {
    return $ua->get_p($url)->then(sub ($tx) { $tx->result->text });
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);
my $started = time;

say for $pipeline->(
    '/page/1',
    '/page/2',
    '/page/3',
    '/page/4',
);
# page 1
# page 2
# page 3
# page 4
printf "%d s\n", time - $started;    # 1 s

How it works

$ua->get_p($url) starts a GET request, and gives at once a Mojo::Promise of the finished request. ->then(...) makes a second promise from the first: of the page's text, once the request is done. fetch returns that one. It isn't an async sub: a promise is something the stage can wait on, wherever it came from.

in_futures(10, \&fetch) fetches up to ten pages at once. Here there are four, so all four are fetched together, and the run takes about one second, not four.

The server part makes a Mojolicious app, and gives it to the user agent with $ua->server->app($app). The user agent then sends URLs without a host, such as /page/1, to that app. $app->log->level('fatal') stops the app logging each request. my $tx = $c->render_later->tx tells Mojolicious the page will come later, and keeps hold of the request until it does, as Mojolicious asks.

Mojo::UserAgent opens a connection for each request that's waiting, so the first argument to in_futures is also the most connections you'll have open at once. Nothing here limits how fast they're sent.

What can go wrong

A https:// URL needs IO::Socket::SSL, version 2.009 or later. Without it, the request fails, and so does the run, with "IO::Socket::SSL 2.009+ required for TLS support". Install it, as above.

$tx->result dies if there's no response at all, such as when nothing answers at the address. One request's error stops the whole run, in its turn. Check each response's status shows how to keep going instead.

Where next

Write the block with Mojo's async and await does the same in a way that reads more like ordinary code.

Write the block with Mojo's async and await

The problem

Chains of ->then(...) get hard to read once a block does more than one thing. You'd rather write it as ordinary code, one step after another.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait, which Mojo's async and await are built on:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $tx = $c->render_later->tx;
        Mojo::IOLoop->timer(0.1 => sub { $c->render(text => 'page ' . $c->param('n')) });
    },
);
$ua->server->app($app);

# Fetch a page, and give its text, and how long it is.
async sub fetch ($url) {
    my $tx   = await $ua->get_p($url);
    my $text = $tx->result->text;
    return "$text, " . length($text) . ' characters';
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

say for $pipeline->(
    '/page/1',
    '/page/22',
);
# page 1, 6 characters
# page 22, 7 characters

How it works

use Mojo::Base -strict, -async_await gives you async and await, as chapter 1's Use Mojolicious instead of IO::Async showed.

Inside fetch, await $ua->get_p($url) waits for the request, and gives the finished transaction, $tx. The lines after it run once the page has come. Meanwhile, the stage gets on with the other pages.

What can go wrong

The same as before: read anything that changes as the run goes on, such as $_, before the first await, as Name the value, rather than reading $_ after waiting explains. Naming the URL in the signature, async sub fetch ($url), does that for you.

Where next

Check each response's status.

Check each response's status

The problem

Some of your URLs may not work: a page that's gone, or a server having a bad day. You'd like to know which, and keep going with the rest.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# A server to try it against, with one page that's broken. Leave this
# part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$app->routes->get('/broken' => sub ($c) { $c->render(text => 'oops', status => 500) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx  = await $ua->get_p($url);
    my $res = $tx->result;
    return "$url: " . $res->text if $res->is_success;
    return "$url failed: " . $res->code . ' ' . $res->message;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

say for $pipeline->(
    '/page/1',
    '/missing',
    '/broken',
    '/page/2',
);
# /page/1: page 1
# /missing failed: 404 Not Found
# /broken failed: 500 Internal Server Error
# /page/2: page 2

How it works

A response that comes back isn't an error, whatever its status, so $tx->result gives it to you. is_success says whether its status is in the 200s. code is the number, and message the words that go with it.

fetch gives a line for every URL, worked or not, so the run carries on to the end. Each result says which URL it's for, so you can tell them apart, whatever order they come in.

The server has no page called /missing, so it answers 404, as a real one would.

What can go wrong

A request that gets no response at all, because nothing answers at the address or the connection drops, is different. $tx->result dies, the block's promise is rejected, and the whole run stops, in its turn. To keep going then too, catch the error in the block. The program below asks for a page from a port where nothing is listening:

use v5.36;
use Mojo::Base -strict, -async_await;
use experimental qw(try);
use Mojo::IOLoop::Server;
use Mojo::UserAgent;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# A port on this computer with nothing listening on it.
my $port = Mojo::IOLoop::Server->generate_port;

async sub fetch ($url) {
    try {
        my $tx = await $ua->get_p($url);
        return "$url: " . $tx->result->text;
    }
    catch ($e) {
        return "$url failed: no response";
    }
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

say for $pipeline->("http://127.0.0.1:$port/");
# http://127.0.0.1:.../ failed: no response

The error itself, in $e, says why, such as "Connection refused". The words depend on the operating system, so this program doesn't print them.

use experimental qw(try) turns on try and catch, and must come after use Mojo::Base. That line turns every warning back on, including the one for using try, so in the other order, Perl warns "try/catch is experimental" each time.

Where next

Read JSON from an API.

Read JSON from an API

The problem

You're calling a web API that answers in JSON, once for each of your values, and you want the answers as Perl data.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# An API to try it against, which looks tracks up by title. Leave this
# part out, and use your own.
my %tracks = (
    'Dancing Queen'         => {artist => 'Abba',  year => 1976},
    'Parklife'              => {artist => 'Blur',  year => 1994},
    'Sunshine of Your Love' => {artist => 'Cream', year => 1967},
);
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/track' => sub ($c) {
        my $title = $c->param('title');
        $c->render(json => {title => $title, %{ $tracks{$title} }});
    },
);
$ua->server->app($app);

# Look a title up, and give the API's answer as a hash.
async sub look_up ($title) {
    my $tx = await $ua->get_p('/track' => form => {title => $title});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&look_up),
);

for my $track ($pipeline->(
    'Parklife',
    'Dancing Queen',
)) {
    say "$track->{title}, by $track->{artist}, $track->{year}";
}
# Parklife, by Blur, 1994
# Dancing Queen, by Abba, 1976

How it works

$ua->get_p('/track' => form => {title => $title}) adds the title to the URL, as /track?title=Parklife, taking care of spaces and other characters that need it.

$tx->result->json decodes the JSON in the response, and gives Perl data: here, a hash for each track. Each result of the pipeline is one of those hashes.

What can go wrong

json gives undef if the response isn't JSON, such as an error page in HTML. Check the status first, as Check each response's status does, before you trust what json gives.

Where next

Send JSON to an API.

Send JSON to an API

The problem

Now you want to send data: one POST request for each record, with the record as JSON.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# An API to try it against, which saves a track and says it has.
# Leave this part out, and use your own.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->post(
    '/tracks' => sub ($c) {
        my $track = $c->req->json;
        $c->render(json => {saved => $track->{title}}, status => 201);
    },
);
$ua->server->app($app);

# Send a track, and say what the API said.
async sub save ($track) {
    my $tx  = await $ua->post_p('/tracks' => json => $track);
    my $res = $tx->result;
    return $res->code . ': saved ' . $res->json->{saved};
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&save),
);

say for $pipeline->(
    {title => 'Song 2',      artist => 'Blur'},
    {title => 'Waterloo',    artist => 'Abba'},
    {title => 'White Room',  artist => 'Cream'},
);
# 201: saved Song 2
# 201: saved Waterloo
# 201: saved White Room

How it works

$ua->post_p('/tracks' => json => $track) sends a POST request, with the hash encoded as JSON and the content type set to say so.

Each value of the pipeline is a hash, a whole record, and the block gets each one as $track. Values don't have to be strings.

What can go wrong

Sending many changes at once can be more than an API allows. Many answer 429, "Too Many Requests", when you go too fast. Keep the first argument to in_futures small, check each status, and see the API's own guidance for how many to send at once.

Where next

Give up on a slow request.

Give up on a slow request

The problem

A server sometimes takes far too long to answer. You'd rather give up on that request after a while than wait for ever.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use experimental qw(try);
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

# Give up on any request that takes more than half a second.
my $ua = Mojo::UserAgent->new(request_timeout => 0.5);

# A server to try it against, with one page that takes two seconds.
# Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $tx      = $c->render_later->tx;
        my $seconds = $c->param('n') eq 'slow' ? 2 : 0.1;
        Mojo::IOLoop->timer($seconds => sub { $c->render(text => 'page ' . $c->param('n')) });
    },
);
$ua->server->app($app);

async sub fetch ($url) {
    try {
        my $tx = await $ua->get_p($url);
        return "$url: " . $tx->result->text;
    }
    catch ($e) {
        return "$url failed: $e" =~ s( \s+ \z )()xr;
    }
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

say for $pipeline->(
    '/page/1',
    '/page/slow',
    '/page/2',
);
# /page/1: page 1
# /page/slow failed: Request timeout at ... line ...
# /page/2: page 2

How it works

request_timeout => 0.5 tells the user agent to give up on any request that hasn't finished within half a second. That request's promise is rejected with "Request timeout", which the block catches, so the run goes on.

The timeout is for each request, not for the run. The other pages are fetched as normal, at the same time.

Mojo gives the reason as a string without a line ending, so Perl adds where it was raised: the line of your await. s( \s+ \z )()xr takes the line ending off the end of it all, so the result reads as one line.

What can go wrong

Without the try, a timeout stops the whole run, in its turn, as any error does:

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new(request_timeout => 0.5);

# A server to try it against, where every page takes two seconds.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $tx = $c->render_later->tx;
        Mojo::IOLoop->timer(2 => sub { $c->render(text => 'page ' . $c->param('n')) });
    },
);
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

eval { $pipeline->('/page/1') };
print $@;
# Pipeline stage #1 failed at ... line ...:
#     Request timeout at ... line ...

The first line names the line of your program that ran the pipeline. The second is the error itself, with the line of the await that met it.

Where next

A note on Net::Async::HTTP.

A note on Net::Async::HTTP

If you use IO::Async, you'd expect to use Net::Async::HTTP, its HTTP client, and it does work with these stages. But for now, this guide uses Mojo::UserAgent, as Net::Async::HTTP doesn't yet do quite what the stages promise. Here's why, and what to do if you need it.

What happens. By default, Net::Async::HTTP opens one connection to each server, and sends every request down it, one after another. So however many requests the stage has waiting, a server that answers a connection's requests one at a time, as many do, answers them one at a time. Four requests that take a second each take four seconds.

Setting max_connections_per_host => 0 lets it open as many connections as it needs, and that mostly fixes it. But in version 0.50, the newest when this was written, a request can still end up waiting for a connection that's busy, instead of getting one of its own. Four requests that take a second each take two seconds, not one. With eight or sixteen, it's still two: one extra round of waiting, whatever the number.

These are the times we measured, on macOS with Perl 5.36, with Net::Async::HTTP 0.50, IO::Async 0.805 and Future 0.54, for four requests that a server answers after one second each:

Net::Async::HTTP, as it comes

4 seconds

Net::Async::HTTP, max_connections_per_host => 0

2 seconds

Mojo::UserAgent, as it comes

1 second

Why. When a connection becomes free, Net::Async::HTTP gives it to the request that's been waiting longest, and cancels the connection that was being opened for that request. When several new connections open at once and finish in a different order, that cancels a connection another request was counting on. It came in with version 0.37, of 2014, so every version since has it. It hasn't yet been reported to the module's author.

What to do. If you can, use Mojo::UserAgent, as this guide does. If you need Net::Async::HTTP, give it max_connections_per_host => 0 always: it's twice as fast as the default for slow requests, and the extra round costs little when there are many. For example:

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Net::Async::HTTP;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;
my $http = Net::Async::HTTP->new(max_connections_per_host => 0);
$loop->add($http);

async sub fetch ($url) {
    my $response = await $http->GET($url);
    return $response->decoded_content;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);
say 'ready to fetch';    # ready to fetch

This guide will add recipes for Net::Async::HTTP once a version without the extra round is released.

Where next

Chapter 3 takes the values from files and other sources, rather than a list in the program.

3. Values from Ekorn's sources

So far, every program has given the pipeline a list it already had. Often, though, the values are somewhere else: in a file, in JSON or CSV, or made one at a time. Ekorn::Pipeline's sources read them, and its iterator pulls them through the stages a value at a time.

The two work together with in_futures: the stage pulls a new value from the source only when it has room for another, so a long file is read as the work goes, not all at once.

Each program writes a small file to read, so that it runs as it stands. With your own file, leave that part out.

Fetch the URLs listed in a file

The problem

You have a file of URLs, one to a line, and you'd like to fetch them all, several at a time.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_file);

# A file of URLs to try it with, one to a line. Use your own.
open my $out, '>', 'urls.txt' or die "Can't write urls.txt: $!\n";
print {$out} "/page/1\n/page/2\n/page/3\n";
close $out or die "Can't write urls.txt: $!\n";

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);
my $pages = $pipeline->iterator(from_file('urls.txt'));

say for $pages->all;
# page 1
# page 2
# page 3

How it works

from_file('urls.txt') is a source: it reads the file a line at a time, and gives each line without its line ending. It comes from Ekorn::Pipeline::Tooling, which gathers Ekorn's sources, stages and sinks in one place, so the use line names it.

$pipeline->iterator(...) joins the pipeline to the source, and gives an iterator: something you pull results from. ->all pulls every result there is, and gives them as a list.

The stage reads a line only when it has room to start another request. With up to ten at once, it reads ten lines, then one more each time a request finishes. A file of a million URLs is never all in memory.

from_file opens the file as the run starts, and closes it as the run ends, however it ends.

What can go wrong

If the file isn't there, the run croaks as it starts, with Perl's own reason:

use v5.36;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_file);

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, sub ($url) {"fetched $url"}),
);

eval { $pipeline->iterator(from_file('no-such-file.txt'))->all };
print $@;    # Can't read no-such-file.txt: No such file or directory at ... line ...

A blank line in the file is a value too: an empty URL, which fails. Drop blank lines and comments before they're fetched shows how to drop them before they reach the stage.

Where next

Look up each record in a JSON Lines file.

Look up each record in a JSON Lines file

The problem

Your values are records, kept as JSON Lines: one JSON object to a line. For each, you want to call an API with one of its fields.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_jsonl);

# A JSON Lines file to try it with. Use your own.
open my $out, '>', 'tracks.jsonl' or die "Can't write tracks.jsonl: $!\n";
print {$out} qq({"title":"Parklife","plays":5800}\n{"title":"Waterloo","plays":8000}\n);
close $out or die "Can't write tracks.jsonl: $!\n";

my $ua = Mojo::UserAgent->new;

# An API to try it against, which gives a title's artist. Leave this
# part out, and use your own.
my %artist = (Parklife => 'Blur', Waterloo => 'Abba');
my $app    = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/artist' => sub ($c) { $c->render(json => {artist => $artist{ $c->param('title') }}) },
);
$ua->server->app($app);

# Add the artist to a track, from the API.
async sub add_artist ($track) {
    my $tx = await $ua->get_p('/artist' => form => {title => $track->{title}});
    return {%$track, artist => $tx->result->json->{artist}};
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&add_artist),
);
my $tracks = $pipeline->iterator(from_jsonl(file => 'tracks.jsonl'));

for my $track ($tracks->all) {
    say "$track->{title}, by $track->{artist}: $track->{plays} plays";
}
# Parklife, by Blur: 5800 plays
# Waterloo, by Abba: 8000 plays

How it works

from_jsonl(file => 'tracks.jsonl') reads the file a line at a time, and decodes each line's JSON. Each value is a hash.

add_artist gets a whole track, and gives back a new hash, with everything the track had and its artist added. It doesn't change the hash it was given: a new one, {%$track, artist => ...}, is the safe habit, as another stage may still be looking at the old.

What can go wrong

A line that isn't valid JSON stops the run, saying which. "Read JSON, or JSON Lines", in Ekorn's own user guide, has the details, and from_json, for a file that's one JSON document.

Where next

Look up each row of a CSV file.

Look up each row of a CSV file

The problem

Your values are rows of a spreadsheet, saved as CSV, with a header row naming the columns.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait. Ekorn reads CSV with Text::CSV, which comes with it:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_csv);

# A CSV file to try it with. Use your own.
open my $out, '>', 'plays.csv' or die "Can't write plays.csv: $!\n";
print {$out} qq(Title,Plays\nParklife,5800\n"Knowing Me, Knowing You",4200\n);
close $out or die "Can't write plays.csv: $!\n";

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my %artist = ('Parklife' => 'Blur', 'Knowing Me, Knowing You' => 'Abba');
my $app    = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/artist' => sub ($c) { $c->render(json => {artist => $artist{ $c->param('title') }}) },
);
$ua->server->app($app);

async sub artist_of ($row) {
    my $tx = await $ua->get_p('/artist' => form => {title => $row->{title}});
    return "$row->{title} ($row->{plays} plays): " . $tx->result->json->{artist};
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&artist_of),
);
my $rows = $pipeline->iterator(from_csv(file => 'plays.csv', header => 1, munge => 'lc'));

say for $rows->all;
# Parklife (5800 plays): Blur
# Knowing Me, Knowing You (4200 plays): Abba

How it works

from_csv(file => 'plays.csv', header => 1) reads the file a row at a time. With header => 1, each row is a hash, keyed by the names in the first row. munge => 'lc' makes those names lower case, so Title becomes title.

A title with a comma in it, such as "Knowing Me, Knowing You", is in quotes in the file, as CSV needs. Text::CSV reads it as one field.

What can go wrong

A row that won't parse, such as one with a quote left open, stops the run as from_csv reaches it, with a message naming the file and the record: "Can't parse CSV from plays.csv, record 3, field 1: EIQ - Quoted field not terminated".

Where next

Fetch numbered pages until one comes back empty.

Fetch numbered pages until one comes back empty

The problem

An API gives its results a page at a time: page 1, page 2, and so on, until a page comes back empty. You don't know how many there are, but you'd like to fetch several at once.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(counter take_while);

my $ua = Mojo::UserAgent->new;

# An API to try it against, with four pages of results. Leave this part
# out, and use your own.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/results' => sub ($c) {
        my $page = $c->param('page');
        $c->render(json => $page <= 4 ? ["result $page.1", "result $page.2"] : []);
    },
);
$ua->server->app($app);

# Fetch a page of results, as an array.
async sub fetch_page ($page) {
    my $tx = await $ua->get_p('/results' => form => {page => $page});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&fetch_page),
    take_while { @$_ > 0 },
);

for my $results ($pipeline->iterator(counter(1))->all) {
    say "@$results";
}
# result 1.1 result 1.2
# result 2.1 result 2.2
# result 3.1 result 3.2
# result 4.1 result 4.2

How it works

counter(1) is a source that gives 1, 2, 3, and so on, for ever.

take_while { @$_ > 0 } passes each page on while it has results in it, and stops the run at the first page that doesn't. Because in_futures gives the pages in order, the first empty page really is the end, even if a later page finished first.

Stopping the run stops the counter too, so it never counts for ever.

What can go wrong

With three at once, the stage has asked for pages 5, 6 and perhaps 7 before it learns that 5 is empty. Those extra requests are wasted. Keep the first argument small when each request costs something.

Mojo::UserAgent can't call a request back once it's sent, so the extra ones finish later, and their answers are thrown away. With an IO::Async Future, the stage cancels them.

Where next

Handle each result as soon as it comes.

Handle each result as soon as it comes

The problem

->all waits for every result before it gives you any. With a long list, you'd rather handle each result as soon as it's ready: show progress, or save it, as you go.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures_as_ready);
use Ekorn::Pipeline::Tooling qw(from_array);

my $ua = Mojo::UserAgent->new;

# A server to try it against, where page N takes N times three tenths
# of a second. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $tx = $c->render_later->tx;
        Mojo::IOLoop->timer($c->param('n') * 0.3 => sub { $c->render(text => 'page ' . $c->param('n')) });
    },
);
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures_as_ready(10, \&fetch),
);
my $next = $pipeline->iterator(from_array(
    '/page/3',
    '/page/1',
    '/page/2',
));

while (my($page) = $next->()) {
    say "got $page";
}
# got page 1
# got page 2
# got page 3

How it works

Calling the iterator, $next->(), gives the next result, or an empty list when there are no more. while (my($page) = $next->()) loops until then, handling each result as it comes.

in_futures_as_ready passes each page on as soon as it's ready, so the quickest comes first, whatever order the URLs were in.

from_array is the simplest source: the values it's given, in turn.

What can go wrong

Write my($page) = $next->(), with the brackets. Without them, my $page = $next->() takes the iterator's answer in scalar context, which isn't how you tell the end from a result.

Where next

Write the whole thing as one chain, with |.

Write the whole thing as one chain, with |

The problem

A source, a stage and somewhere for the results to go: you'd like to write them as one line, in the order the values flow.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Operators;
use Ekorn::Pipeline::Tooling qw(from_file keep_all);

# A file of URLs to try it with. Use your own.
open my $out, '>', 'urls.txt' or die "Can't write urls.txt: $!\n";
print {$out} "/page/1\n/page/2\n";
close $out or die "Can't write urls.txt: $!\n";

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pages = from_file('urls.txt')
    | in_futures(10, \&fetch)
    | keep_all;

say for @$pages;
# page 1
# page 2

How it works

use Ekorn::Pipeline::Operators lets you join a source, stages and a sink with |, for the rest of the file. A chain that starts with a source and ends with a sink runs at once, and gives the sink's result.

keep_all is a sink that keeps every result. A chain gives one value, so it gives them as an array reference: @$pages is the list.

What can go wrong

| means this only between Ekorn's parts. Between two numbers, it's still Perl's bitwise or, so keep a chain to sources, stages and sinks. "Mind Perl's own |", in Ekorn's own user guide, says more.

Where next

Chapter 4 puts Ekorn's other stages before and after in_futures.

4. Ekorn's stages, before and after

in_futures is one stage among others. Put Ekorn's stages before it, and they choose and shape what it's given. Put them after it, and they work on its results, as they arrive, in order. Nothing about either changes because the stage in the middle waits.

Drop blank lines and comments before they're fetched

The problem

Your file of URLs has blank lines and comments in it, to keep it readable. They aren't URLs, and shouldn't be fetched.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(drop_if from_file);

# A file of URLs to try it with, with a comment and a blank line.
open my $out, '>', 'urls.txt' or die "Can't write urls.txt: $!\n";
print {$out} "# The pages to check\n/page/1\n\n/page/2\n";
close $out or die "Can't write urls.txt: $!\n";

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    drop_if { m( \A \s* (?: \# | \z ) )x },
    in_futures(10, \&fetch),
);

say for $pipeline->iterator(from_file('urls.txt'))->all;
# page 1
# page 2

How it works

drop_if { ... } drops each value its block is true for, with the value in $_, and passes the rest on. Here, the block is true for a line that's empty, only spaces, or starts with #.

Because drop_if comes first, in_futures never sees those lines, so nothing is fetched for them.

What can go wrong

A regular expression without \A and \z matches anywhere in the line, not the whole of it. m( \# )x would drop a URL with a # in it, such as /page#top.

Where next

Keep only the results you want.

Keep only the results you want

The problem

You've fetched a list of records, but you only want some of them: the ones that match a test you can only apply once you have the answer.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(take_if);

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my %year = ('Dancing Queen' => 1976, 'Parklife' => 1994, 'Song 2' => 1997);
my $app  = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/track' => sub ($c) {
        my $title = $c->param('title');
        $c->render(json => {title => $title, year => $year{$title}});
    },
);
$ua->server->app($app);

async sub look_up ($title) {
    my $tx = await $ua->get_p('/track' => form => {title => $title});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&look_up),
    take_if { $_->{year} >= 1990 },
);

for my $track ($pipeline->(
    'Dancing Queen',
    'Parklife',
    'Song 2',
)) {
    say "$track->{title}, $track->{year}";
}
# Parklife, 1994
# Song 2, 1997

How it works

take_if { ... } is drop_if's opposite: it passes on each value its block is true for, and drops the rest.

After in_futures, the values it sees are the results: here, the hashes the API gave. So it can test what only the answer knows, such as a track's year.

What can go wrong

A result dropped after the stage was still fetched. When you can tell from the value alone that it isn't wanted, drop it before, as the previous recipe does, and save the request.

Where next

Stop after the first few, and cancel the rest.

Stop after the first few, and cancel the rest

The problem

You only need the first few results. Once you have them, the look-ups still waiting are wasted, and you'd like them stopped.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(take);

my $loop     = IO::Async::Loop->new;
my $finished = 0;

# Look-up N takes N tenths of a second, and counts itself when it's done.
async sub look_up ($n) {
    await $loop->delay_future(after => $n / 10);
    $finished++;
    return "found $n";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(5, \&look_up),
    take(2),
);

say for $pipeline->(1 .. 10);
say "$finished of 10 look-ups finished";
# found 1
# found 2
# 2 of 10 look-ups finished

How it works

take(2) passes on two values, then stops the run.

When the run stops, in_futures cancels the look-ups it's still waiting for. Cancelling an async sub's Future cancels what it's waiting on, here a timer, so those look-ups never reach $finished++. Look-ups 6 to 10 were never started at all.

This uses IO::Async's timers, as their Futures can be cancelled.

What can go wrong

A Mojo::Promise can't be cancelled. With Mojo::UserAgent, requests already sent go on to the end, after the run has stopped, and their answers are thrown away. Nothing goes wrong, but the requests aren't saved. The first argument to in_futures is the most that can be wasted.

Where next

Send values to an API in batches.

Send values to an API in batches

The problem

Your API takes many records in one request, and limits how many requests you make. Sending a request for each record would be slow, and might be refused.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(batch);

my $ua = Mojo::UserAgent->new;

# An API to try it against, which saves a list of tracks at once.
# Leave this part out, and use your own.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->post(
    '/tracks' => sub ($c) {
        my $tracks = $c->req->json;
        $c->render(json => {saved => scalar @$tracks});
    },
);
$ua->server->app($app);

# Send a batch of tracks in one request.
async sub save ($tracks) {
    my $tx = await $ua->post_p('/tracks' => json => $tracks);
    return 'saved ' . $tx->result->json->{saved};
}

my $pipeline = Ekorn::Pipeline->new(
    batch(2),
    in_futures(10, \&save),
);

say for $pipeline->(
    {title => 'Waterloo'},
    {title => 'Parklife'},
    {title => 'Song 2'},
    {title => 'Tender'},
    {title => 'SOS'},
);
# saved 2
# saved 2
# saved 1

How it works

batch(2) gathers values into arrays of two, and passes each array on as one value. The last array is shorter if there aren't enough to fill it.

So in_futures gets three values, not five: each an array of tracks, which save sends as one JSON list.

What can go wrong

batch holds values back until it has a full batch. A run that stops early, or a source that's slow, means a batch waits. That's what a batch is for, but it's worth knowing when results seem late.

Where next

Turn one response into several results.

Turn one response into several results

The problem

Each request gives you a list: the tracks on an album, the links on a page. You want each item in the list to go on as a result of its own.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# An API to try it against, which lists an album's tracks. Leave this
# part out, and use your own.
my %tracks = (
    'Parklife'       => ['Girls & Boys', 'Tracy Jacks'],
    'The Great Escape' => ['Stereotypes', 'Country House', 'Charmless Man'],
);
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/album' => sub ($c) { $c->render(json => $tracks{ $c->param('title') }) },
);
$ua->server->app($app);

# Give each track on an album, as a result of its own.
async sub tracks_of ($album) {
    my $tx = await $ua->get_p('/album' => form => {title => $album});
    return map {"$album: $_"} @{ $tx->result->json };
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&tracks_of),
);

say for $pipeline->(
    'Parklife',
    'The Great Escape',
);
# Parklife: Girls & Boys
# Parklife: Tracy Jacks
# The Great Escape: Stereotypes
# The Great Escape: Country House
# The Great Escape: Charmless Man

How it works

An async sub can return a list. The stage passes each item on as a result of its own, in the order of the list, as any Ekorn stage does with the values it returns.

Return an empty list, and that value gives no results at all.

What can go wrong

Return a reference to the list, return [ ... ], and it's one result: the whole array. That's what you want when the stages after it expect a list, and not otherwise.

Where next

Wait twice: one request leads to another.

Wait twice: one request leads to another

The problem

What you fetch first tells you what to fetch next: an album's tracks, then each track's details. Both steps are slow, and you'd like each to run several at once.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# An API to try it against, with albums and tracks. Leave this part out,
# and use your own.
my %tracks = (Parklife => ['Girls & Boys', 'Parklife'], Blur => ['Song 2']);
my %length = ('Girls & Boys' => '4:50', 'Parklife' => '3:05', 'Song 2' => '2:02');
my $app    = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/album' => sub ($c) { $c->render(json => $tracks{ $c->param('title') }) });
$app->routes->get('/track' => sub ($c) { $c->render(text => $length{ $c->param('title') }) });
$ua->server->app($app);

async sub tracks_of ($album) {
    my $tx = await $ua->get_p('/album' => form => {title => $album});
    return @{ $tx->result->json };
}

async sub length_of ($track) {
    my $tx = await $ua->get_p('/track' => form => {title => $track});
    return "$track, " . $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(5,  \&tracks_of),
    in_futures(10, \&length_of),
);

say for $pipeline->(
    'Parklife',
    'Blur',
);
# Girls & Boys, 4:50
# Parklife, 3:05
# Song 2, 2:02

How it works

Each in_futures is a stage of its own, with its own limit. The first fetches albums, five at a time. Each track it gives goes on to the second, which fetches tracks, ten at a time.

Both stages wait on the same loop, so while the second is waiting for tracks, the first's requests carry on too.

The order holds all the way through: tracks come out in the order of their albums, and in each album's order.

What can go wrong

Two limits multiply what can be in flight: here, up to five album requests and ten track requests at once, fifteen in all, to what may be the same server. Count both when you choose them.

Where next

Count what goes in and what comes out.

Count what goes in and what comes out

The problem

At the end of a run, you'd like to know how many values went in, and how many results came out: how many pages were checked, and how many were fine.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(count_into take_if);

my $ua = Mojo::UserAgent->new;

# A server to try it against, where only /page/N works. Leave this part
# out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

# Give a URL with its status.
async sub check ($url) {
    my $tx = await $ua->get_p($url);
    return {url => $url, ok => $tx->result->is_success};
}

my($checked, $fine);
my $pipeline = Ekorn::Pipeline->new(
    count_into(\$checked),
    in_futures(10, \&check),
    take_if { $_->{ok} },
    count_into(\$fine),
);

my @fine = $pipeline->(
    '/page/1',
    '/gone',
    '/page/2',
    '/old',
);
say "$fine of $checked pages are fine";    # 2 of 4 pages are fine

How it works

count_into(\$checked) counts each value that goes by into $checked, and passes it on. It sets the count to 0 as each run starts.

The first counts the URLs going into in_futures. The second, after take_if, counts the results that were kept.

What can go wrong

Give count_into a reference, \$checked, not the variable itself. It needs to know where to count, not what's there now.

Where next

See every result while debugging.

See every result while debugging

The problem

Something's wrong with your results, and you'd like to see exactly what the stage gives, without changing what the program does.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(dump_to);

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/track' => sub ($c) { $c->render(json => {title => $c->param('title'), year => 1994}) },
);
$ua->server->app($app);

async sub look_up ($title) {
    my $tx = await $ua->get_p('/track' => form => {title => $title});
    return $tx->result->json;
}

# Dump each result into $dumped, to print once the run is over.
open my $out, '>', \my $dumped or die "Can't write the dump: $!\n";

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&look_up),
    dump_to($out),
);

my @tracks = $pipeline->('Parklife');
print $dumped;
# {
#   'title' => 'Parklife',
#   'year' => 1994
# }

How it works

dump_to($out) writes each value that goes by to the filehandle $out, laid out with Data::Dumper, its keys sorted, and passes the value on unchanged. Here, $out writes into the string $dumped. Leave out the filehandle, dump_to(), and it writes to STDERR, which keeps the dumps apart from your program's own output: that's the usual way while debugging.

Put it anywhere in the pipeline: before in_futures to see what it's given, after to see what it gives.

What can go wrong

If Text::Redact::Secrets is installed, dump_to hides anything that looks like a secret, such as a password or a token, in what it writes. That's on purpose. Ekorn's own user guide says how to turn it off while you're debugging.

Where next

Chapter 5 sends the results somewhere: a count, a file, or the first that matters.

5. Where the results go: Ekorn's sinks

A sink is the last part of a pipeline. It takes every result, and when they run out, gives one answer: a count, the first result, or the number of lines it wrote to a file. Call the pipeline for one value, in scalar context, and you get the sink's answer.

Some sinks also stop the run early, once they have what they need. After in_futures, that means no more requests are started.

Count the results, or keep the last

The problem

You don't need the results themselves, only how many there were, or only the last.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(count_items keep_last take_if);

my $ua = Mojo::UserAgent->new;

# A server to try it against, where only /page/N works. Leave this part
# out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->is_success ? $tx->result->text : ();
}

my @urls = (
    '/page/1',
    '/gone',
    '/page/2',
    '/page/3',
);

my $count = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
    count_items,
)->(@urls);
say "$count pages fetched";    # 3 pages fetched

my $last = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
    keep_last,
)->(@urls);
say "the last: $last";    # the last: page 3

How it works

count_items counts the results it's given, and gives the count. keep_last keeps only the latest result, and gives the last one.

fetch gives no result at all for a page that didn't work, by returning an empty list, so /gone isn't counted.

my $count = ... asks for one value, so the pipeline gives the sink's answer.

What can go wrong

With no results at all, count_items gives 0, and keep_last gives undef. Check for undef before you use what keep_last gives.

Where next

Take the answer from whichever server is quickest.

Take the answer from whichever server is quickest

The problem

The same file is on several mirrors, and you don't know which is quickest today. You'd like to ask them all at once, and take the first answer.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::IOLoop;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures_as_ready);
use Ekorn::Pipeline::Tooling qw(keep_first);

my $ua = Mojo::UserAgent->new;

# Three mirrors to try it against, at different speeds. Leave this part
# out, and use your own URLs.
my %seconds = (north => 0.3, south => 0.1, west => 0.2);
my $app     = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/:mirror/file' => sub ($c) {
        my $tx     = $c->render_later->tx;
        my $mirror = $c->param('mirror');
        Mojo::IOLoop->timer($seconds{$mirror} => sub { $c->render(text => "the file, from $mirror") });
    },
);
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures_as_ready(3, \&fetch),
    keep_first,
);

say scalar $pipeline->(
    '/north/file',
    '/south/file',
    '/west/file',
);
# the file, from south

How it works

in_futures_as_ready asks all three mirrors at once, and passes on each answer as soon as it comes. keep_first keeps the first answer it's given, and stops the run. So the run ends as soon as the quickest mirror answers.

say scalar ... asks for one value, so the pipeline gives what keep_first kept.

What can go wrong

in_futures_as_ready alone gives every answer, as each comes. It's keep_first that stops the run.

The other two requests have already been sent. Mojo::UserAgent can't call them back, so they finish later, and their answers are thrown away. With IO::Async Futures, the stage would cancel them.

Where next

Stop fetching once you've found what you need.

Stop fetching once you've found what you need

The problem

You're looking through pages for the first that mentions something. Once you've found it, there's no point fetching the rest.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(counter keep_first take_if);

my $ua = Mojo::UserAgent->new;

# A server to try it against, with a hundred pages, and the one we're
# looking for on page 7. Leave this part out, and use your own.
my $asked = 0;
my $app   = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        $asked++;
        my $n = $c->param('n');
        $c->render(text => $n == 7 ? "page $n: Parklife" : "page $n");
    },
);
$ua->server->app($app);

async sub fetch ($n) {
    my $tx = await $ua->get_p("/page/$n");
    return $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&fetch),
    take_if { m( Parklife )x },
    keep_first,
);

my $found = $pipeline->iterator(counter(1))->();
say $found;    # page 7: Parklife
say $asked < 100 ? 'stopped early' : 'fetched them all';    # stopped early

How it works

counter(1) gives page numbers, 1, 2, 3, and on. take_if drops each page that doesn't mention Parklife, and keep_first keeps the first that does, then stops the run. Stopping the run stops the counter, so no more pages are asked for.

Because in_futures gives the pages in order, the page found is the first in order that matches, even if a later one answered first.

Calling the iterator, ->(), runs it until the sink has its answer.

What can go wrong

A few pages after the one found have usually been asked for too, as the stage keeps up to three on the go. Use in_futures_as_ready instead if any match will do, not only the first in order: it stops as soon as any page matches.

Where next

Write each result to a file.

Write each result to a file

The problem

You want the results saved to a file, one to a line, as they come, rather than kept in memory.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(to_file);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return "$url: " . $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
    to_file('pages.txt'),
);

my $written = $pipeline->(
    '/page/1',
    '/page/2',
    '/page/3',
);
say "$written written";    # 3 written

open my $in, '<', 'pages.txt' or die "Can't read pages.txt: $!\n";
print <$in>;
# /page/1: page 1
# /page/2: page 2
# /page/3: page 3

How it works

to_file('pages.txt') opens the file as the run starts, emptying it, writes each result on a line of its own, and closes the file as the run ends. It gives the number of lines it wrote.

Each result is written as soon as it reaches the sink, so a long run never holds them all in memory.

What can go wrong

to_file empties the file as the run starts. A run that fails part of the way leaves the file with only what it wrote before the failure. Keep the old file unless every request worked shows a sink that doesn't.

Where next

Save the results as JSON Lines.

Save the results as JSON Lines

The problem

Your results are records, and you'd like to save them so that another program can read them back: one JSON object to a line.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(to_jsonl);

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my %artist = (Parklife => 'Blur', Waterloo => 'Abba');
my $app    = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/track' => sub ($c) {
        my $title = $c->param('title');
        $c->render(json => {title => $title, artist => $artist{$title}});
    },
);
$ua->server->app($app);

async sub look_up ($title) {
    my $tx = await $ua->get_p('/track' => form => {title => $title});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&look_up),
    to_jsonl(file => 'tracks.jsonl', json => {canonical => 1}),
);

my $written = $pipeline->(
    'Parklife',
    'Waterloo',
);
say "$written written";    # 2 written

open my $in, '<', 'tracks.jsonl' or die "Can't read tracks.jsonl: $!\n";
print <$in>;
# {"artist":"Blur","title":"Parklife"}
# {"artist":"Abba","title":"Waterloo"}

How it works

to_jsonl writes each result as JSON, on a line of its own, and gives how many it wrote. json => {canonical => 1} asks the encoder to write each object's keys in order, so the same data always gives the same line.

Look up each record in a JSON Lines file reads such a file back, with from_jsonl.

What can go wrong

JSON has no way to write some Perl values, such as a code reference or an object, and the encoder croaks if a result holds one. Give the sink plain hashes, arrays, strings and numbers.

Where next

Save the results as CSV.

Save the results as CSV

The problem

You want the results in a spreadsheet: a CSV file, with a header row.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(to_csv);

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my %year = ('Parklife' => 1994, 'Knowing Me, Knowing You' => 1977);
my $app  = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/track' => sub ($c) {
        my $title = $c->param('title');
        $c->render(json => {title => $title, year => $year{$title}});
    },
);
$ua->server->app($app);

async sub look_up ($title) {
    my $tx = await $ua->get_p('/track' => form => {title => $title});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&look_up),
    to_csv(file => 'tracks.csv', header => [qw(title year)]),
);

my $written = $pipeline->(
    'Parklife',
    'Knowing Me, Knowing You',
);
say "$written written";    # 2 written

open my $in, '<', 'tracks.csv' or die "Can't read tracks.csv: $!\n";
print <$in>;
# title,year
# Parklife,1994
# "Knowing Me, Knowing You",1977

How it works

to_csv(file => 'tracks.csv', header => [qw(title year)]) writes the names in header as the first row, then each result as a row, taking each hash's fields in that order.

A field with a comma in it, such as "Knowing Me, Knowing You", is put in quotes, so that a spreadsheet reads it as one field.

What can go wrong

A hash with a key that isn't in header loses that field: only the names in header are written. List every column you want.

Where next

Keep the old file unless every request worked.

Keep the old file unless every request worked

The problem

Each run replaces a file of results. If a run fails half way, you'd rather keep the last good file than be left with half a new one.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use File::Temp qw(tempfile);
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(count_items from_file sink_one);

my $ua = Mojo::UserAgent->new;

# A server to try it against, where only /page/N works. Leave this part
# out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

# Fetch a page, dying if it didn't work.
async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    die "$url: " . $tx->result->code . "\n" unless $tx->result->is_success;
    return $tx->result->text;
}

# A sink that writes to a new file, and puts it in place of the old one
# only if the run went through.
sub save_to ($path) {
    return sink_one {
        my($fh, $new) = tempfile(DIR => '.');
        my $lines = 0;
        return {
            step  => sub ($line) { say {$fh} $line; $lines++ },
            flush => sub ()      { $lines },
            end   => sub ($how) {
                close $fh;
                $how eq 'done' ? rename $new, $path : unlink $new;
            },
        };
    };
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
    save_to('pages.txt'),
);

say scalar $pipeline->(
    '/page/1',
    '/page/2',
    '/page/3',
);
# 3

eval {
    $pipeline->(
        '/page/4',
        '/gone',
    );
};
print $@ =~ s( \A .*? \n \s* )()xsr;    # /gone: 404

my $kept = Ekorn::Pipeline->new(
    count_items,
)->iterator(from_file('pages.txt'))->();
say "pages.txt still has $kept lines";    # pages.txt still has 3 lines

How it works

sink_one { ... } makes a sink of your own. Its block is run as each run starts, and gives a hash: step for each result, flush for the sink's answer when the results run out, and end once the run is over, told how it ended.

save_to writes to a new temporary file beside the old one. In end, it renames the new file over the old only if the run is done, ending as it should. Otherwise it deletes the new file, and the old one stays as it was.

The second run dies at /gone, so pages.txt keeps the three lines of the first.

$@ =~ s( \A .*? \n \s* )()xsr takes off the first line of the error, which names your program's line, to leave the reason.

What can go wrong

The temporary file must be on the same disk as the file it replaces, or rename can't move it. tempfile(DIR => '.') puts it in the current folder: give the same folder as the file's.

The same shape commits a database transaction only when the run is done, and rolls it back otherwise.

Where next

Chapter 6 says which value each result came from, and what order they come in.

6. Order, and where each result came from

A stage after in_futures gets results, not the values they were made from: a page's text, say, not its URL. Ekorn::Pipeline remembers each result's original, the value it started from, and a stage can ask for it. in_futures keeps track of it for every result, whatever order the results come in.

This chapter shows how to ask, how not to, and what order costs.

Know which value each result came from

The problem

Your block gives only what it fetched, a page's text. A later stage needs to know which URL that text came from.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(result_original);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return length $tx->result->text;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
    sub ($length) { result_original . " is $length characters long" },
);

say for $pipeline->(
    '/page/1',
    '/page/22',
);
# /page/1 is 6 characters long
# /page/22 is 7 characters long

How it works

fetch gives only a length. The stage after it calls result_original, from Ekorn::Pipeline::Context, which Ekorn::Pipeline::Tooling gathers too. It gives the value this result was made from: here, the URL.

in_futures holds results back, until they're ready and it's their turn. A stage that holds results back has to say where each came from, or the stages after it would see the value the run had got to. It does.

What can go wrong

It's easy to forget there's a simpler way: put what you need in the result itself, as return {url => $url, length => ...}. Do that when the next stage is yours. result_original is for when it isn't: a stage from somewhere else, or a function that takes stages from its caller, whose caller can't change what you return.

Where next

Know it when the results come in any order.

Know it when the results come in any order

The problem

With in_futures_as_ready, the results come in the order they're ready. You'd like to be sure each still knows its own original.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures_as_ready);
use Ekorn::Pipeline::Tooling qw(result_original);

my $loop = IO::Async::Loop->new;

# Abba is the slowest, Blur the quickest.
my %seconds = (Abba => 0.3, Blur => 0.1, Cream => 0.2);

async sub look_up ($name) {
    await $loop->delay_future(after => $seconds{$name});
    return "took $seconds{$name} s";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures_as_ready(3, \&look_up),
    sub ($result) { result_original . " $result" },
);

say for $pipeline->(qw(Abba Blur Cream));
# Blur took 0.1 s
# Cream took 0.2 s
# Abba took 0.3 s

How it works

The results come out quickest first, and each is still matched to its own name. The stage keeps each value's original as it starts, and hands it on with that value's result, whenever that is.

What can go wrong

Nothing here: this is what the stage promises. A stage of your own that holds values back has to do the same, or it breaks the promise for every stage after it. Ekorn's own user guide shows how, in "Say where held values came from".

Where next

Number the results.

Number the results

The problem

You'd like to number the results as they come out, 1, 2, 3, to show progress, or to label lines in a report.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures_as_ready);
use Ekorn::Pipeline::Tooling qw(result_number result_original);

my $loop = IO::Async::Loop->new;

my %seconds = (Abba => 0.3, Blur => 0.1, Cream => 0.2);

async sub look_up ($name) {
    await $loop->delay_future(after => $seconds{$name});
    return "found $name";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures_as_ready(3, \&look_up),
    sub ($found) { result_number . ". $found" },
);

say for $pipeline->(qw(Abba Blur Cream));
# 1. found Blur
# 2. found Cream
# 3. found Abba

How it works

result_number counts the results the run has made, from 1. It numbers them in the order they come out of the stage, which with in_futures_as_ready is the order they were ready.

What can go wrong

The number counts results, not values. A value that gives no result, because a stage dropped it, isn't counted; one that gives several, as in Turn one response into several results, counts each.

Where next

Ask before the first await, not after.

Ask before the first await, not after

The problem

Your block itself wants something from the run: the original record, from before an earlier stage turned it into a URL. When does it ask?

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(result_original);

my $loop = IO::Async::Loop->new;

async sub fetch ($url) {
    my $track = result_original;    # read before the first await
    await $loop->delay_future(after => 0.1);
    return "$url, for $track->{title}";
}

my $pipeline = Ekorn::Pipeline->new(
    sub ($track) { "/track/$track->{id}" },
    in_futures(3, \&fetch),
);

say for $pipeline->(
    {id => 1, title => 'Parklife'},
    {id => 2, title => 'Waterloo'},
);
# /track/1, for Parklife
# /track/2, for Waterloo

How it works

The first stage turns each track into a URL. The block gets the URL, but result_original still gives the whole track, the value the run started from.

The block is called inside the stage, as any stage is, so until its first await, it sees its own value's original. It reads it then, and keeps it in $track.

What can go wrong

After an await, the block carries on inside whatever the stage is doing then. result_original then gives another value's original, or none at all, much as $_ does in Name the value, rather than reading $_ after waiting:

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(result_original);

my $loop = IO::Async::Loop->new;

async sub fetch ($url) {
    await $loop->delay_future(after => 0.1);
    my $track = result_original;    # a mistake: read after waiting
    return "$url, for " . ($track ? $track->{title} : 'no track at all');
}

my $pipeline = Ekorn::Pipeline->new(
    sub ($track) { "/track/$track->{id}" },
    in_futures(3, \&fetch),
);

say for $pipeline->(
    {id => 1, title => 'Parklife'},
    {id => 2, title => 'Waterloo'},
);
# /track/1, for no track at all
# /track/2, for no track at all

Here both blocks carry on after the input has run out, as the stage gives what's left, where there's no value for result_original to give. In a longer run, a block may carry on while the stage is handling another value, and get that value's original instead. Either way it's wrong, and without the check for $track, Perl warns "Use of uninitialized value" when there's none.

The same goes for result_number, and anything else the run tells its stages.

Where next

See one slow value hold up the rest.

See one slow value hold up the rest

The problem

One of your values is much slower than the others. You'd like to see what that costs with in_futures, which keeps the order, and what in_futures_as_ready saves.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures in_futures_as_ready);

my $loop = IO::Async::Loop->new;

# The first look-up takes two seconds; the twenty after it, two tenths
# each.
async sub look_up ($name) {
    await $loop->delay_future(after => $name eq 'slow' ? 2 : 0.2);
    return $name;
}

my @names = ('slow', map {"quick $_"} 1 .. 20);

for my $stage (\&in_futures, \&in_futures_as_ready) {
    my $pipeline = Ekorn::Pipeline->new(
        $stage->(3, \&look_up),
    );
    my $started = time;
    my @found   = $pipeline->(@names);
    printf "%d s, %s first\n", time - $started, $found[0];
}
# 3 s, slow first
# 2 s, quick 1 first

How it works

The program runs the same look-ups through each stage, three at a time. \&in_futures and \&in_futures_as_ready are references to the stages themselves, so the loop can make a pipeline with each.

With in_futures, the slow look-up is first in the order, so nothing after it can go on until it's done. Two quick results are soon ready, but they're held for their turn, and with the slow one they fill all three places. The stage waits the whole two seconds, then does the rest.

With in_futures_as_ready, the quick ones go on as they finish. The slow one keeps one place for the two seconds it takes, and the quick ones use the other two. The run takes about as long as the slow look-up.

The times are in whole seconds, rounded down, as %d gives them.

What can go wrong

A bigger first argument hides the cost, by leaving more places while the slow one waits, but it's still there. If order matters, keep it. If it doesn't, in_futures_as_ready is never slower, and Know it when the results come in any order shows you can still tell which result is which.

Where next

Chapter 7 is about what happens when a request fails, and what you can do about it.

7. When things go wrong

A request that fails, a server that's down, a block that dies: each becomes a failure, which the stage passes on in its turn, after the results before it, just as a stage would die in its turn. By default, a failure ends the run.

These recipes show that, and the ways to keep going: catching the failure in the block, keeping the failures apart, trying again, and stopping on purpose.

See a failure stop the run, in its turn

The problem

You'd like to know exactly what happens when one look-up fails: what you get before it, and what you're told.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_array);

my $loop = IO::Async::Loop->new;

# Look-up 3 fails.
async sub look_up ($n) {
    await $loop->delay_future(after => 0.1);
    die "no track $n\n" if $n == 3;
    return "track $n";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(2, \&look_up),
);
my $next = $pipeline->iterator(from_array(1 .. 6));

eval {
    while (my($track) = $next->()) {
        say $track;
    }
};
print $@;
# track 1
# track 2
# Pipeline stage #1 failed at ... line ...:
#     no track 3

How it works

Look-up 3 dies after its await. The stage holds that failure until it's look-up 3's turn: tracks 1 and 2 go on first, and then the run dies, with the error.

The error names the stage that failed, by its place in the pipeline, and the line of your program that asked for the result. The second line is the block's own error, as it was.

Look-ups after 3 that were still waiting are cancelled, as the run is over.

What can go wrong

The run is over: the iterator has nothing more to give, even though look-ups 4, 5 and 6 would have worked. If one failure shouldn't end everything, catch it in the block, as the next recipe does.

Where next

Keep going: turn each failure into a result.

Keep going: turn each failure into a result

The problem

A few of your look-ups will fail, and that's fine. You'd like a result for every value, saying whether it worked, and the run to carry on.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use experimental qw(try);
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

async sub look_up ($n) {
    await $loop->delay_future(after => 0.1);
    die "no track $n\n" if $n == 3 || $n == 5;
    return "track $n";
}

# Look a value up, giving a hash that says how it went.
async sub try_look_up ($n) {
    try {
        return {n => $n, found => await look_up($n)};
    }
    catch ($e) {
        return {n => $n, error => $e =~ s( \s+ \z )()xr};
    }
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&try_look_up),
);

for my $result ($pipeline->(1 .. 6)) {
    say "$result->{n}: ", $result->{found} // "failed, $result->{error}";
}
# 1: track 1
# 2: track 2
# 3: failed, no track 3
# 4: track 4
# 5: failed, no track 5
# 6: track 6

How it works

try_look_up wraps the real look-up in try and catch. When look_up dies, catch gets the error, in $e, and the block returns a result anyway: a hash with the error in it. So the stage sees no failure at all, and every value gets its result.

await look_up($n) inside the try waits for the look-up, and turns its failure back into an error that catch can catch.

use experimental qw(try) turns on try and catch, which Perl 5.36 has, but still calls experimental.

What can go wrong

Each result is now either a success or a failure, and every stage after this one has to know which. A hash with found or error, as here, makes that easy to test.

If you use Mojo's async, from use Mojo::Base -async_await, put use experimental qw(try) after it, as Check each response's status explains.

Where next

Keep the failures in a file of their own.

Keep the failures in a file of their own

The problem

Now that every value gives a result, you'd like the failures saved somewhere you can look at later, while the successes carry on.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use experimental qw(try);
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(drop_if take_if tee to_jsonl);

my $loop = IO::Async::Loop->new;

async sub try_look_up ($n) {
    try {
        await $loop->delay_future(after => 0.1);
        die "no track $n\n" if $n == 3 || $n == 5;
        return {n => $n, found => "track $n"};
    }
    catch ($e) {
        return {n => $n, error => $e =~ s( \s+ \z )()xr};
    }
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&try_look_up),
    tee(
        take_if { $_->{error} },
        to_jsonl(file => 'failures.jsonl', json => {canonical => 1}),
    ),
    drop_if { $_->{error} },
    sub ($result) { $result->{found} },
);

say for $pipeline->(1 .. 6);
# track 1
# track 2
# track 4
# track 6

open my $in, '<', 'failures.jsonl' or die "Can't read failures.jsonl: $!\n";
print <$in>;
# {"error":"no track 3","n":3}
# {"error":"no track 5","n":5}

How it works

tee(...) gives each result to a pipeline of its own, a branch, and passes the result on unchanged, whatever the branch does with it. Here the branch keeps only the failures, take_if { $_->{error} }, and writes them to failures.jsonl.

After the tee, drop_if { $_->{error} } drops the failures from the main run, and the last stage takes each success's track.

What can go wrong

The branch is a run of its own. If a stage in it dies, such as a sink that can't open its file, the whole run dies with it.

Where next

Try a request again when it fails.

Try a request again when it fails

The problem

A server sometimes fails for a moment, answering 503, "Service Unavailable", and works if you ask again. You'd like each request tried a few times before it counts as a failure.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::Promise;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $ua = Mojo::UserAgent->new;

# A server to try it against, where /page/2 fails the first time it's
# asked for, and /page/3 every time. Leave this part out, and use your
# own URLs.
my %asked;
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        my $n     = $c->param('n');
        my $times = ++$asked{$n};
        return $c->render(text => 'busy', status => 503)
            if $n == 3 || ($n == 2 && $times == 1);
        $c->render(text => "page $n");
    },
);
$ua->server->app($app);

# Fetch a page, trying up to three times, a tenth of a second apart.
async sub fetch ($url) {
    for my $try (1 .. 3) {
        my $tx = await $ua->get_p($url);
        return $tx->result->text . ", on try $try" if $tx->result->is_success;
        await Mojo::Promise->timer(0.1);
    }
    return "$url still failing after 3 tries";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(10, \&fetch),
);

say for $pipeline->(
    '/page/1',
    '/page/2',
    '/page/3',
);
# page 1, on try 1
# page 2, on try 2
# /page/3 still failing after 3 tries

How it works

fetch loops up to three times. When a response works, it returns at once. When it doesn't, await Mojo::Promise->timer(0.1) waits a tenth of a second before the next try.

The wait is an await, not a sleep, so while one request waits to try again, the others go on.

After the last try, fetch returns a result saying so, rather than dying, so the run goes on. Return a hash, as in Keep going: turn each failure into a result, if a later stage needs to tell them apart.

What can go wrong

Trying again is right for a failure that may pass, such as 503 or a timeout. It's wrong for one that won't, such as 404, "Not Found": three tries take three times as long, and fail anyway. Check the status before you try again.

Waiting longer after each try, such as a tenth of a second, then two, then four, is kinder to a server that's struggling.

Where next

Stop the run from inside the block.

Stop the run from inside the block

The problem

You're looking through values for one answer. When the block finds it, you'd like the run to end there, with that answer as the last result.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Stop qw(Stop);

my $loop = IO::Async::Loop->new;

# Track 4 is the one we're after.
async sub look_up ($n) {
    await $loop->delay_future(after => 0.1);
    Stop("found it: track $n") if $n == 4;
    return "not track $n";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);

say for $pipeline->(1 .. 10);
# not track 1
# not track 2
# not track 3
# found it: track 4

How it works

Stop(...), from Ekorn::Pipeline::Stop, ends the run from inside the block. The values given to it go on, as the run's last results.

Like a failure, a stop takes its turn: the results before it go on first, in order. Then the run ends, and the look-ups still waiting, such as 5 and 6, are cancelled.

A stop isn't an error: the run gives its results as normal, and nothing dies.

What can go wrong

Stop is exported by default, so use Ekorn::Pipeline::Stop qw(Stop) could leave out the qw(Stop). As with the stages, this guide names what each program uses.

With in_futures_as_ready, a stop ends the run as soon as it's ready, not in order, so results that would have come before it in order may be lost.

Where next

Know what a failure at the end costs.

Know what a failure at the end costs

The problem

You've seen that results before a failure go on first. There's one case where they don't, and it's worth knowing when.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(peek);

my $loop = IO::Async::Loop->new;

# Look-up 3, the last, fails.
async sub look_up ($n) {
    await $loop->delay_future(after => 0.1);
    die "no track $n\n" if $n == 3;
    return "track $n";
}

for my $at_once (2, 10) {
    my @seen;
    my $pipeline = Ekorn::Pipeline->new(
        in_futures($at_once, \&look_up),
        peek { push @seen, $_ },
    );
    eval { $pipeline->(1 .. 3) };
    say "$at_once at once: ", scalar(@seen), ' went on before the failure';
}
# 2 at once: 2 went on before the failure
# 10 at once: 0 went on before the failure

How it works

peek { ... } sees each result go by, and passes it on, so @seen holds every result that got past the stage.

With two at once, the stage passes on tracks 1 and 2 while it's still being given values. Track 3's failure comes after.

With ten at once, all three are still waiting when the values run out. Then the stage's flush gives what's left, and a flush can't give some results and then die: the failure takes the results with it. That's a limit of every Ekorn stage that holds values back, not only this one.

What can go wrong

This bites when the failure is in the last few values, about as many as the first argument to in_futures. Catch failures in the block, as Keep going: turn each failure into a result does, and no failure reaches the stage, so nothing is lost.

Where next

Tell an error object from an error message.

Tell an error object from an error message

The problem

Some libraries fail with an object, not a message, carrying details such as a response's status. You'd like to catch the run's failure and get at those details.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# Fails as an HTTP client might, with a category and details.
async sub look_up ($n) {
    await $loop->delay_future(after => 0.1);
    return await Future->fail("Not Found", http => {status => 404, n => $n})
        if $n == 2;
    return "track $n";
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&look_up),
);

eval { $pipeline->(1, 2) };
my $error = $@;

if (ref $error && $error->isa('Future::Exception')) {
    my($details) = $error->details;
    say $error->message, ', a failure of category ', $error->category;
    say "status $details->{status}, for look-up $details->{n}";
}
# Not Found, a failure of category http
# status 404, for look-up 2

How it works

Future->fail("Not Found", http => {...}) fails with a message, a category, http, and details. Awaiting it throws a Future::Exception: an object with message, category and details methods.

Ekorn adds its "Pipeline stage #1 failed" line only to an error that's a message. An object is passed on as it is, so you can ask it for its details, as here.

Net::Async::HTTP, for one, fails this way, with the response among the details.

What can go wrong

Test that it's an object before you call its methods: ref $error && $error->isa(...). An error that's a message is a plain string, and calling a method on it dies.

Where next

Chapter 8 builds functions, stages and pipelines of your own on in_futures.

8. Building on it

Ekorn::Pipeline is for functions that let their callers finish the job: a function takes a list of stages from its caller, and runs what it would return through them. in_futures is a stage like any other, so it fits there too: inside a function, as a caller's stage, in a named pipeline, or in a module of stages of your own.

Write a function that fetches, and let its caller finish the job

The problem

You're writing a function that fetches pages for other code. Each caller wants something different done with them: one wants only some, another wants them shorter, a third wants a count. You'd rather not add an option for each.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(count_items take_if);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

# Fetch the pages, ten at a time, and run them through the caller's
# stages.
sub fetch_pages ($urls, @stages) {
    return Ekorn::Pipeline->new(
        in_futures(10, \&fetch),
        @stages,
    )->(@$urls);
}

my @urls = map {"/page/$_"} 1 .. 12;

say for fetch_pages(
    \@urls,
    take_if { m( 1 \z )x },
);
# page 1
# page 11

say scalar fetch_pages(
    \@urls,
    count_items,
);
# 12

How it works

fetch_pages takes its URLs, then any stages its caller gives, and puts them after in_futures in its own pipeline. It fetches; the caller decides what happens next.

The first caller keeps only pages ending in 1. The second wants a count, and gives count_items, a sink, so the function gives the count. A caller that gives no stages gets every page.

The function never changes to suit a caller.

What can go wrong

The URLs are given as an array reference, \@urls, so the function knows where they end and the stages start. Given as a list, it couldn't tell the last URL from the first stage.

Where next

Return an iterator, so the caller can stop the fetching.

Return an iterator, so the caller can stop the fetching

The problem

Your function might be given thousands of URLs, but a caller often needs only the first few results. You'd like a caller's stop to stop the fetching too.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(from_array take);

my $ua = Mojo::UserAgent->new;

# A server to try it against, counting what it's asked for. Leave this
# part out, and use your own URLs.
my $asked = 0;
my $app   = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/page/:n' => sub ($c) {
        $asked++;
        $c->render(text => 'page ' . $c->param('n'));
    },
);
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

# An iterator of the pages, fetched three at a time, as they're wanted.
sub pages ($urls, @stages) {
    return Ekorn::Pipeline->new(
        in_futures(3, \&fetch),
        @stages,
    )->iterator(from_array(@$urls));
}

my $first_two = pages(
    [map {"/page/$_"} 1 .. 1000],
    take(2),
);

say for $first_two->all;
# page 1
# page 2
say $asked < 10 ? 'stopped early' : "asked for $asked";    # stopped early

How it works

pages returns an iterator, not the results. Nothing is fetched until the caller pulls from it.

The caller's take(2) stops the run after two pages. Stopping the run stops from_array too, so the stage asks for no more URLs, and of a thousand, only a few are ever fetched.

What can go wrong

A function that returns a list, as in the recipe before, has to fetch everything before it returns, whatever its caller wanted. Return an iterator whenever a caller may want less than all of it.

Where next

Make a stage for others to use.

Make a stage for others to use

The problem

Your team fetches JSON from APIs all the time, always the same way. You'd like one stage, from a module of your own, that does it.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;

package My::Stages::Fetch {
    use Mojo::Base -strict, -async_await;
    use Ekorn::Pipeline::Errors qw(croakf);
    use Ekorn::Pipeline::Futures qw(in_futures);

    # A stage fetching each URL's JSON with the user agent given, up to
    # $n at a time.
    sub fetch_json ($ua, $n = 10) {
        croakf 'Expected a user agent, not %s', $ua // 'undef'
            unless ref $ua && $ua->can('get_p');
        return in_futures(
            $n,
            async sub ($url) {
                my $tx = await $ua->get_p($url);
                return $tx->result->json;
            },
        );
    }
}

use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/track/:n' => sub ($c) { $c->render(json => {track => $c->param('n')}) });
$ua->server->app($app);

my $pipeline = Ekorn::Pipeline->new(
    My::Stages::Fetch::fetch_json($ua, 5),
    sub ($json) { "track $json->{track}" },
);

say for $pipeline->(
    '/track/1',
    '/track/2',
);
# track 1
# track 2

eval { My::Stages::Fetch::fetch_json('a string') };
print $@ =~ s( \ at \ .* )( at your line)xsr;    # Expected a user agent, not a string at your line

How it works

fetch_json is a function that makes a stage. It checks what it's given once, when it's called, and returns in_futures with a block that uses the user agent. Each call makes a stage of its own, with its own user agent and limit.

croakf, from Ekorn::Pipeline::Errors, reports a mistake at the line that called fetch_json, not inside it, with a message made as sprintf makes one.

In a real project, the package goes in a file of its own, lib/My/Stages/Fetch.pm, exports fetch_json, and ends with 1;. It's in the same file here only so the program runs as it stands.

What can go wrong

Check what the function is given when it's called, as here, not in the block. A mistake in the block would show only when the first value came, and as a failure of the run, far from the line that made it.

Where next

Give a pipeline a name, and use it by name.

Give a pipeline a name, and use it by name

The problem

Several parts of your program fetch pages the same way. You'd like to define that once, give it a name, and use the name wherever it's wanted.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(drop_if pipeline take);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

# How pages are fetched, everywhere in the program.
Ekorn::Pipeline->named(
    fetch_pages =>
        drop_if { m( \A \s* \z )x },
        in_futures(10, \&fetch),
);

my @first = pipeline(
    'fetch_pages',
    take(2),
)->(
    '/page/1',
    '',
    '/page/2',
    '/page/3',
);
say for @first;
# page 1
# page 2

How it works

Ekorn::Pipeline->named(fetch_pages => ...) keeps a pipeline under the name fetch_pages: dropping blank URLs, then fetching.

pipeline(...), from Ekorn::Pipeline::Tooling, makes a pipeline in which a name stands for the pipeline it names. Here it's the named pipeline, then take(2).

A named pipeline's name also appears in its error messages, so a failure says which part of the program it came from.

What can go wrong

named takes the name with =>, and pipeline with a comma. The name in pipeline is a value among the stages, so a comma reads best there.

A name can be given once: naming another pipeline fetch_pages croaks, "A pipeline named main::fetch_pages is already defined". Names belong to the package that gives them, here main. Name a pipeline in one place, such as where the program starts, and use it everywhere else.

Where next

Use a pipeline as a stage.

Use a pipeline as a stage

The problem

You've built a pipeline that cleans URLs and fetches them. You'd like to use it, as it is, as one step of a bigger pipeline.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(take);

my $ua = Mojo::UserAgent->new;

# A server to try it against. Leave this part out, and use your own URLs.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/page/:n' => sub ($c) { $c->render(text => 'page ' . $c->param('n')) });
$ua->server->app($app);

async sub fetch ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->text;
}

# Trim each URL, and fetch it.
my $fetch_clean = Ekorn::Pipeline->new(
    sub ($url) { $url =~ s( \A \s+ | \s+ \z )()xgr },
    in_futures(10, \&fetch),
);

my $pipeline = Ekorn::Pipeline->new(
    $fetch_clean,
    sub ($page) { uc $page },
    take(2),
);

say for $pipeline->(
    '  /page/1',
    '/page/2  ',
    '/page/3',
);
# PAGE 1
# PAGE 2

How it works

A pipeline can go wherever a stage goes. Its stages join the bigger pipeline where it stands, as if you'd written them out there.

So $fetch_clean trims and fetches, the next stage makes each page upper case, and take(2) stops the whole run after two.

What can go wrong

Because the stages join the bigger run, a stop anywhere in it, such as take(2), ends the whole run, $fetch_clean's fetching included. That's usually what you want, and it's why the third page isn't fetched.

Where next

Give each server a limit of its own.

Give each server a limit of its own

The problem

Your URLs are spread across several servers. You'd like no more than two requests at once to any one server, however many servers there are, and all the servers at the same time.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Gather qw(gather);

my $loop = IO::Async::Loop->new;

# A stage running each key's values through a run of their own, of the
# stages given, and passing on what comes out of each.
sub per_key ($key_of, @stages) {
    my $each = Ekorn::Pipeline->new(@stages);
    return gather {
        my(%feeds, @keys);
        return (
            sub ($value) {
                my $key  = $key_of->($value);
                my $feed = $feeds{$key} //= do { push @keys, $key; $each->feed };
                return $feed->push($value);
            },
            sub () { map { $_->close } @feeds{@keys} },
            sub ($how) { $_->finish for values %feeds },
        );
    };
}

# Stands in for a request to a server: counts how many are waiting at
# each server, and the most there were.
my(%waiting, %most);
async sub fetch ($url) {
    my($server) = $url =~ m( \A (\w+) / )x;
    $most{$server} = $waiting{$server}
        if ++$waiting{$server} > ($most{$server} // 0);
    await $loop->delay_future(after => 0.1);
    $waiting{$server}--;
    return $url;
}

my $pipeline = Ekorn::Pipeline->new(
    per_key(
        sub ($url) { $url =~ s( / .* )()xsr },
        in_futures(2, \&fetch),
    ),
);

my @fetched = $pipeline->(map { ("north/$_", "south/$_") } 1 .. 6);

say scalar(@fetched), ' fetched';    # 12 fetched
say "$_: at most $most{$_} at once" for sort keys %most;
# north: at most 2 at once
# south: at most 2 at once

How it works

per_key is a stage that gives each key its own run of the stages it's given, here in_futures(2, \&fetch). The key of a URL is its server, the part before the first /.

Each server's run has its own in_futures, so its own limit of two. All the runs wait on the same loop, so both servers are fetched from at the same time.

gather, from Ekorn::Pipeline::Gather, makes a stage that keeps what it needs for each run: here, a feed for each key. A feed is a run you push values into one at a time. Pushing a value returns whatever came out of the run, and close returns what's left at the end.

Ekorn's own user guide builds the same stage, in "Run each key's values through a run of their own", and says more.

What can go wrong

A server's results come out of its own run, so with several servers, results come in the order each server's run gives them, not the order the URLs came in. Use result_original to tell which came from where, as in Know which value each result came from.

Where next

Feed values in as they arrive.

Feed values in as they arrive

The problem

Your values don't come in a list. Something hands them to you one at a time, as they arrive: a callback, a queue, a file being written to. You'd like to start each look-up as its value arrives, and handle the results as they come.

You'll need

Ekorn::Pipeline::Futures, Future::AsyncAwait and IO::Async:

cpanm Ekorn::Pipeline::Futures Future::AsyncAwait IO::Async

The program

use v5.36;
use Future::AsyncAwait;
use IO::Async::Loop;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $loop = IO::Async::Loop->new;

# Look-up 2 takes half a second; the others, a tenth.
async sub look_up ($n) {
    await $loop->delay_future(after => $n == 2 ? 0.5 : 0.1);
    return "found $n";
}

my $feed = Ekorn::Pipeline->new(
    in_futures(2, \&look_up),
)->feed;

for my $n (1 .. 3) {
    my @results = $feed->push($n);
    say "pushed $n, got: @results";
}
say 'closed, got: ', join ' ', $feed->close;
# pushed 1, got:
# pushed 2, got: found 1
# pushed 3, got: found 2 found 3
# closed, got:

How it works

->feed makes a run you give values to one at a time, with push. Each push returns whatever came out of the run as a result, there and then; close says there are no more, and returns the rest.

Pushing 1 starts its look-up, and returns nothing yet. Pushing 2 starts the second: now two are waiting, the most allowed, so the push waits for the oldest, and returns found 1. Pushing 3 waits for 2, the slow one, by which time 3 is ready too, so it returns both.

What can go wrong

A push can wait: when as many look-ups are waiting as are allowed, it waits for one to finish before it returns. That's what keeps the limit. If what hands you values can't wait, push them into a queue of your own, and feed the run from that.

Call close when there are no more values, or the look-ups still waiting are never finished.

Where next

Chapter 9 puts it all together, to solve whole problems.

9. Whole problems, start to finish

The recipes so far each show one thing. These solve a whole problem, with Ekorn's sources, stages and sinks around in_futures, as you'd write them for real. Each is longer, but every part of it is a recipe from an earlier chapter, linked from its "How it works".

The problem

You keep a list of links, perhaps from a site's pages. Some will have broken since you last looked. You'd like to check them all, many at a time, and get a spreadsheet of the broken ones, and a count.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use experimental qw(try);
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(count_into drop_if from_file take_if to_csv);

# A list of links to try it with. Use your own.
open my $out, '>', 'links.txt' or die "Can't write links.txt: $!\n";
print {$out} "# The site's links\n/about\n/old-page\n\n/contact\n/broken\n";
close $out or die "Can't write links.txt: $!\n";

my $ua = Mojo::UserAgent->new(request_timeout => 10);

# A site to try it against, with /old-page gone and /broken failing.
# Leave this part out, and use your own links.
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get('/about'   => sub ($c) { $c->render(text => 'About us') });
$app->routes->get('/contact' => sub ($c) { $c->render(text => 'Contact us') });
$app->routes->get('/broken'  => sub ($c) { $c->render(text => 'oops', status => 500) });
$ua->server->app($app);

# Check a link, giving it with its status, or why there was none.
async sub check ($url) {
    try {
        my $tx = await $ua->head_p($url);
        return {url => $url, status => $tx->result->code};
    }
    catch ($e) {
        return {url => $url, status => $e =~ s( \s+ \z )()xr};
    }
}

my($checked, $broken);
my $pipeline = Ekorn::Pipeline->new(
    drop_if { m( \A \s* (?: \# | \z ) )x },
    count_into(\$checked),
    in_futures(10, \&check),
    take_if { $_->{status} !~ m( \A [23] \d\d \z )x },
    count_into(\$broken),
    to_csv(file => 'broken.csv', header => [qw(url status)]),
);

$pipeline->iterator(from_file('links.txt'))->();
say "$broken of $checked links are broken";    # 2 of 4 links are broken

open my $in, '<', 'broken.csv' or die "Can't read broken.csv: $!\n";
print <$in>;
# url,status
# /old-page,404
# /broken,500

How it works

Each part is one you've met:

Calling the iterator, ->(), runs it to the end, as the sink has the only answer, the number of rows it wrote.

request_timeout => 10 gives up on a link that takes more than ten seconds, so a server that never answers can't hold the run up.

What can go wrong

Some servers answer HEAD requests wrongly, or not at all, while GET works. If a link you know is fine shows as broken, try get_p in place of head_p, which fetches the whole page.

Be polite to other people's sites: ten at a time, to many servers, is fine; ten at a time to one small site may not be. See Give each server a limit of its own.

Where next

Copy a whole API collection to a file.

Copy a whole API collection to a file

The problem

An API gives you its records a page at a time, and you want all of them, saved to a file that other programs can read: every page fetched, several at once, and every record written out.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(counter take_while to_jsonl);

my $ua = Mojo::UserAgent->new;

# An API to try it against, with five tracks, two to a page. Leave this
# part out, and use your own.
my @tracks = (
    {title => 'Waterloo',      artist => 'Abba'},
    {title => 'Parklife',      artist => 'Blur'},
    {title => 'Song 2',        artist => 'Blur'},
    {title => 'White Room',    artist => 'Cream'},
    {title => 'Dancing Queen', artist => 'Abba'},
);
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/tracks' => sub ($c) {
        my $first = ($c->param('page') - 1) * 2;
        my $last  = $first + 1 > $#tracks ? $#tracks : $first + 1;
        $c->render(json => $first > $#tracks ? [] : [@tracks[$first .. $last]]);
    },
);
$ua->server->app($app);

# Fetch a page of tracks, as an array.
async sub fetch_page ($page) {
    my $tx = await $ua->get_p('/tracks' => form => {page => $page});
    return $tx->result->json;
}

my $pipeline = Ekorn::Pipeline->new(
    in_futures(3, \&fetch_page),
    take_while { @$_ > 0 },
    sub ($page) { @$page },
    to_jsonl(file => 'tracks.jsonl', json => {canonical => 1}),
);

my $written = $pipeline->iterator(counter(1))->();
say "$written tracks written";    # 5 tracks written

open my $in, '<', 'tracks.jsonl' or die "Can't read tracks.jsonl: $!\n";
print <$in>;
# {"artist":"Abba","title":"Waterloo"}
# {"artist":"Blur","title":"Parklife"}
# {"artist":"Blur","title":"Song 2"}
# {"artist":"Cream","title":"White Room"}
# {"artist":"Abba","title":"Dancing Queen"}

How it works

Each page's tracks are written as soon as the page comes, so a collection of millions is never all in memory.

What can go wrong

If the API's records can change while you're copying, a record can move from one page to the next between requests, and be copied twice, or not at all. Many APIs offer a cursor, or a way to sort by a field that doesn't change, for that.

Where next

Crawl a site, a few links deep.

The problem

Starting from one page, you want to find the pages it links to, the pages those link to, and so on, to a set depth: each page fetched once, and each level's pages fetched several at once.

You'll need

Ekorn::Pipeline::Futures, Mojolicious and Future::AsyncAwait:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);
use Ekorn::Pipeline::Tooling qw(drop_if);

my $ua = Mojo::UserAgent->new;

# A site to try it against. Leave this part out, and use your own.
my %links = (
    '/'  => ['/a', '/b'],
    '/a' => ['/b', '/c'],
    '/b' => ['/'],
    '/c' => ['/d'],
    '/d' => [],
);
my $app = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/*page' => {page => ''} => sub ($c) {
        my $page = '/' . $c->param('page');
        $c->render(text => join '', map {qq(<a href="$_">$_</a>\n)} @{ $links{$page} });
    },
);
$ua->server->app($app);

# Fetch a page, and give each link on it.
async sub links_of ($url) {
    my $tx = await $ua->get_p($url);
    return $tx->result->dom->find('a[href]')->map(attr => 'href')->each;
}

my %seen  = ('/' => 1);
my @level = ('/');

for my $depth (0 .. 2) {
    say "depth $depth: @level";
    last if $depth == 2;
    @level = Ekorn::Pipeline->new(
        in_futures(10, \&links_of),
        drop_if { $seen{$_}++ },
    )->(@level);
    last unless @level;
}
# depth 0: /
# depth 1: /a /b
# depth 2: /c

How it works

The crawl goes a level at a time. Each level is one run of a pipeline: the level's pages go in, ten at a time, and the links found on them come out.

  • links_of fetches a page and gives each link on it, as a result of its own. ->dom parses the page's HTML with Mojo::DOM, and find('a[href]') finds its links.

  • drop_if { $seen{$_}++ } drops each link already seen, and marks the rest seen as it goes, so no page is fetched twice: /b links back to /, which isn't fetched again.

  • The next level is the links that are left. The loop stops at depth 2, or sooner if a level finds nothing new.

So /, /a and /b are fetched, and /c is found but not fetched, as it's at the last depth.

What can go wrong

A real site has links to other sites, to images, and with # parts and query strings. Turn each link into a full URL, Mojo::URL->new($href)->to_abs($base), and keep only those on the site you mean to crawl, before they reach the next level, or the crawl wanders off.

Check the site's robots.txt before you crawl it, and keep the limit small: a crawler can ask a site for a great deal very quickly.

Where next

Fill in database rows from an API.

Fill in database rows from an API

The problem

A table in your database has a column to fill in, from a web API: each row's title, looked up to find its artist. There are many rows, and you'd like several looked up at once, with the database read and written as usual.

You'll need

Ekorn::Pipeline::Futures, Mojolicious, Future::AsyncAwait, DBIx::Squirrel, which reads the rows through Ekorn's stages, and DBD::SQLite, for the database in the program:

cpanm Ekorn::Pipeline::Futures Mojolicious Future::AsyncAwait DBIx::Squirrel DBD::SQLite

The program

use v5.36;
use Mojo::Base -strict, -async_await;
use DBIx::Squirrel;
use Mojo::UserAgent;
use Mojolicious;
use Ekorn::Pipeline::Futures qw(in_futures);

# A database to try it with, in memory, with no artists yet. Use your
# own.
my $dbh = DBIx::Squirrel->connect('dbi:SQLite:dbname=:memory:', '', '', {RaiseError => 1});
$dbh->do('CREATE TABLE track (id INTEGER PRIMARY KEY, title TEXT, artist TEXT)');
$dbh->do('INSERT INTO track (title) VALUES (?)', undef, $_)
    for 'Parklife', 'Waterloo', 'White Room';

my $ua = Mojo::UserAgent->new;

# An API to try it against. Leave this part out, and use your own.
my %artist = (Parklife => 'Blur', Waterloo => 'Abba', 'White Room' => 'Cream');
my $app    = Mojolicious->new;
$app->log->level('fatal');
$app->routes->get(
    '/artist' => sub ($c) { $c->render(json => {artist => $artist{ $c->param('title') }}) },
);
$ua->server->app($app);

# Look a row's title up, giving its id and artist.
async sub artist_of ($row) {
    my $tx = await $ua->get_p('/artist' => form => {title => $row->title});
    return {id => $row->id, artist => $tx->result->json->{artist}};
}

# Write a row's artist back.
sub save ($found) {
    $dbh->do('UPDATE track SET artist = ? WHERE id = ?', undef, $found->{artist}, $found->{id});
    return $found->{id};
}

my @saved = $dbh->results(
    'SELECT id, title FROM track WHERE artist IS NULL',
    in_futures(5, \&artist_of),
    \&save,
)->all;
say scalar(@saved), ' rows filled in';    # 3 rows filled in

for my $row ($dbh->results('SELECT title, artist FROM track ORDER BY id')->all) {
    say $row->title, ', by ', $row->artist;
}
# Parklife, by Blur
# Waterloo, by Abba
# White Room, by Cream

How it works

DBIx::Squirrel is a DBI wrapper that runs a query's rows through Ekorn stages. $dbh->results($sql, @stages) gives an iterator of the rows, each as an object with a method for each column, through the stages after the SQL.

So the rows are the source: the database is read a row at a time, and in_futures(5, \&artist_of) looks up five at a time. artist_of is given each row, and reads $row->title from it.

\&save is an ordinary stage after it, which writes each answer back with an UPDATE, as each comes. ->all runs it all, and gives what save returns: each row's id.

The database work is done outside the block, before and after it: the SELECT that gives the rows, and the UPDATE in the stage after. Only the web requests are in the block.

What can go wrong

Don't call the database from inside the block. The DBI waits for the database by stopping the whole program, as sleep does, so every request in flight would wait with it, as Run three slow look-ups at once's mistake shows. Reading and writing around the stage, as here, is fine. When the slow work is the database, such as many slow queries, use Ekorn::Pipeline::Workers, whose workers each run their own.

save runs between the stage's waits, so while it writes, the requests in flight wait to be answered. A quick UPDATE costs little. If each write is slow, gather the answers with batch, as in Send values to an API in batches, and write each batch in one transaction.

Where next

Chapter 10 says where the stages don't fit, and what each of their messages means.

10. Limits, and every message explained

The stages are for programs that run no event loop of their own: scripts, batch jobs, scrapers and command-line tools. A pipeline's run is synchronous: it runs the loop only while the stage waits. That's what lets everything else about Ekorn work as it does, and it's also where the limits are.

Don't run the stages inside a running loop

The problem

Your program already runs an event loop: a web app, a server, a bot. Can it use these stages in one of its callbacks?

You'll need

Ekorn::Pipeline::Futures and Mojolicious:

cpanm Ekorn::Pipeline::Futures Mojolicious

The program

use v5.36;
use Mojo::IOLoop;
use Mojo::Promise;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

my $pipeline = Ekorn::Pipeline->new(
    in_futures(2, sub ($n) { Mojo::Promise->timer(0.1)->then(sub {"found $n"}) }),
);

# A callback of Mojo's loop, as a web app's handler would be.
my $error;
Mojo::IOLoop->timer(
    0 => sub {
        eval { $pipeline->(1, 2) };
        $error = $@;
        Mojo::IOLoop->stop;
    },
);
Mojo::IOLoop->start;

print $error;
# Pipeline stage #1 failed at ... line ...:
#     Can't wait for a result: its event loop is already running, and a pipeline runs synchronously inside it at ... line ...

How it works

To wait, the stage runs the loop its promises belong to, until they're ready. Inside a callback, that loop is already running: it's what called the callback. Mojo's loop can't run inside itself, so the stage croaks, saying why, rather than wait for ever.

What can go wrong

Not every loop can say it's running. IO::Async's runs again inside itself, so there the pipeline may seem to work. But the loop then runs the program's other callbacks in the middle of the pipeline, at times your program doesn't expect. Don't rely on it.

Inside a running loop, use the loop's own tools, as the next recipe does. Outside one, in a script, a batch job or a test, use these stages.

Where next

In a Mojolicious app, use Mojo::Promise's map instead.

In a Mojolicious app, use Mojo::Promise's map instead

The problem

A page of your Mojolicious app needs several requests made, a few at a time, and can't use these stages, as its handler runs inside Mojo's loop.

You'll need

Mojolicious:

cpanm Mojolicious

The program

use v5.36;
use Mojo::IOLoop;
use Mojo::Promise;
use Mojo::UserAgent;
use Mojolicious;

# The user agent the app calls its API with, and the app.
my $ua  = Mojo::UserAgent->new;
my $app = Mojolicious->new;
$app->log->level('fatal');
$ua->server->app($app);

# Each part of the page, from the API, which takes a tenth of a second.
$app->routes->get(
    '/part/:n' => sub ($c) {
        my $tx = $c->render_later->tx;
        Mojo::IOLoop->timer(0.1 => sub { $c->render(text => 'part ' . $c->param('n')) });
    },
);

# The page, fetching its six parts, three at a time, inside Mojo's loop.
$app->routes->get(
    '/page' => sub ($c) {
        $c->render_later;
        Mojo::Promise->map(
            {concurrency => 3},
            sub { $ua->get_p("/part/$_")->then(sub ($tx) { $tx->result->text }) },
            1 .. 6,
        )->then(sub (@parts) { $c->render(text => join ', ', map { $_->[0] } @parts) });
    },
);

# Ask the app for the page, as a browser would, and wait for it.
my $page;
$ua->get_p('/page')->then(sub ($tx) { $page = $tx->result->text })->wait;
say $page;    # part 1, part 2, part 3, part 4, part 5, part 6

How it works

Mojo::Promise->map({concurrency => 3}, $block, @values) calls the block for each value, with the value in $_, keeping up to three of its promises waiting at once, and gives a promise of all the results, in order. It never runs the loop itself, so it's safe inside a handler.

$ua is the app's user agent for the API it calls. Here the API is a route of the same app, so the program runs as it stands; in your app, it would be the API's own URLs. The last lines ask for the page as a browser would, and ->wait runs Mojo's loop until it's come: that's the program, outside the app, so it may wait.

$c->render_later tells Mojolicious the page will come later; the handler returns at once, and then renders the page when every part has come. Each result is given as an array, so $_->[0] takes the text.

It's the same idea as in_futures, made for code that's already inside the loop. What it doesn't have is everything around the stage: Ekorn's sources, stages and sinks, stops, and functions that take your stages.

What can go wrong

A handler that waits, with ->wait or a pipeline, holds up every other request the app is serving. Keep a handler to promises, and return.

Where next

Don't run a pipeline inside the block.

Don't run a pipeline inside the block

The problem

Your block itself has several things to wait for, such as each track of an album. It's tempting to run a pipeline with in_futures inside the block. It works, but it costs you the outer stage's concurrency.

You'll need

Ekorn::Pipeline::Futures and Mojolicious:

cpanm Ekorn::Pipeline::Futures Mojolicious

The program

use v5.36;
use Mojo::Promise;
use Time::HiRes qw(time);
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

# Looking a track up takes a second.
sub look_up ($track) {
    return Mojo::Promise->timer(1)->then(sub {"found $track"});
}

my $tracks = Ekorn::Pipeline->new(
    in_futures(2, \&look_up),
);

# A mistake: a pipeline run inside the block, for each album.
my $nested = Ekorn::Pipeline->new(
    in_futures(
        3,
        sub ($album) {
            my @found = $tracks->("$album 1", "$album 2");
            return Mojo::Promise->resolve(scalar @found);
        },
    ),
);

# The same work, as two stages in a row.
my $in_a_row = Ekorn::Pipeline->new(
    sub ($album) { ("$album 1", "$album 2") },
    in_futures(6, \&look_up),
);

my $started = time;
$nested->(qw(Abba Blur Cream));
printf "inside the block: %d s\n", time - $started;    # inside the block: 3 s

$started = time;
$in_a_row->(qw(Abba Blur Cream));
printf "in a row: %d s\n", time - $started;    # in a row: 1 s

How it works

A pipeline's run is synchronous: calling $tracks doesn't return until its look-ups are done. So inside the outer block, it waits for one album's tracks before the block returns, and the outer stage can't start the next album until then. The albums go one at a time: three seconds.

Written as two stages in a row, the first turns each album into its tracks, and the second looks up to six at once, whichever album they're from: one second.

Wait twice: one request leads to another does the same when the tracks come from a request too.

What can go wrong

Run inside the block after an await, the inner pipeline is inside the loop's callback, as in Don't run the stages inside a running loop, and on Mojo it croaks. Before the first await, as here, it works, only slowly. Either way, use two stages.

Where next

Every message the stages give.

Every message the stages give

The problem

The stages croaked with a message, and you'd like to know what it means, and what to do about it.

You'll need

Ekorn::Pipeline::Futures:

cpanm Ekorn::Pipeline::Futures

The program

use v5.36;
use Future;
use Ekorn::Pipeline;
use Ekorn::Pipeline::Futures qw(in_futures);

for my $mistake (
    sub { in_futures(0, sub ($n) {$n}) },
    sub { in_futures(2, 'look_up') },
    sub { in_futures(2, sub ($n) {$n}, ordered => 0) },
    sub { Ekorn::Pipeline->new(in_futures(2, sub ($n) { Future->new }))->(1) },
) {
    eval { $mistake->() };
    print $@ =~ s( \A Pipeline .*? \n \s* )()xsr;
}
# Expected a number in flight of 1 or more at ... line ...
# Expected a code reference at ... line ...
# Expected no option ordered at ... line ...
# 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 at ... line ...

How it works

Each message, what it means, and what to do:

Expected a number in flight of 1 or more

The first argument must be a whole number, 1 or more.

Expected a code reference

The block must be code: a sub, or a reference to one, \&look_up, not its name.

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 wait on: see Don't run the stages 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.

The last one most often means the block gave something that no loop will ever finish: here, Future->new, a plain Future that nothing completes. It can also mean a Future tied to a loop that was already running and couldn't say so.

s( \A Pipeline .*? \n \s* )()xsr takes off the first line of a failure in a run, which names your program's line, so that only the message is printed.

What can go wrong

The first three croak as the stage is made, so they name the line that made it. The last two come as the run waits, so they come after "Pipeline stage #1 failed at ...", which names the line that ran the pipeline.

Messages from your own block, or from a library it calls, are passed on as they were. The module's documentation, Ekorn::Pipeline::Futures, has these messages under DIAGNOSTICS.

Where next

Chapter 11 answers questions you may have, and the appendix says what the recipes, taken together, prove.

11. Questions you may have

How fast is it?

The stage costs about 6 microseconds a value, on top of the waiting, measured on an Apple M2 with Futures that are already ready, against 0.4 for a plain Ekorn stage. A web request takes thousands of times that, so the stage's own cost doesn't show: what you save is the waiting, as See the time it saves shows.

How much does it hold in memory?

No more than the first argument's worth of values and their results: those waiting, and those ready but waiting their turn. It takes a new value from its source only when it has room. A file of a million URLs is read as the work goes, never all at once, as Fetch the URLs listed in a file says.

Does it start threads, or processes?

No. Everything happens in one process, in one thread: the loop waits on many things at once, and the stage runs your blocks one at a time, in between. That's why it suits waiting, and not work for the CPU.

Should I use this, Ekorn::Pipeline::Workers, or neither?

  • Use Ekorn::Pipeline::Futures when the work is waiting on I/O that a library can do asynchronously, giving Futures or promises: web requests, APIs, anything on IO::Async or Mojolicious.

  • Use Ekorn::Pipeline::Workers when the work blocks, as the DBI does, or a module with only a synchronous API, or keeps the CPU busy, such as resizing images. It runs each value in a worker process.

  • Use neither, an ordinary stage, when each value's work is quick.

To see the difference for yourself, Ekorn::Pipeline::Workers' own guide, Ekorn::Pipeline::Workers::Manual::HowTo, solves one problem all three ways, timed, in its recipe "One problem, three ways: an ordinary stage, Futures and Workers". Its next recipe, "Fetch, then compute: Futures feeding Workers", puts the two together in one pipeline, for work that fetches and then computes.

Which event loops does it work with?

Any whose Futures or promises Future::AsyncAwait's await can wait on, as the stage waits the same way. This guide shows IO::Async and Mojolicious, which its tests run on every change. The stage names no loop itself.

Does it need IO::Async or Mojolicious?

No. Beyond what comes with Perl, Ekorn::Pipeline::Futures needs only Ekorn::Pipeline and Future to run. The loop and the clients are yours to choose and install, as each recipe's "You'll need" says.

Does it work on Windows?

Yes. Every recipe in this guide runs on Windows, with Strawberry Perl, on every change, as well as on Linux and macOS, and nothing in it needed changing for Windows.

Can I use it in a web app?

Not inside a request's handler, as the app's loop is already running there: see Don't run the stages inside a running loop, and In a Mojolicious app, use Mojo::Promise's map instead. In the app's scripts, its jobs and its tests, which run no loop of their own, yes.

Where can I read more?

  • The module's own documentation, Ekorn::Pipeline::Futures, has the rules for a block, what happens on a failure or a stop, and every message.

  • Ekorn::Pipeline's user guide, Ekorn::Pipeline::Manual::HowTo, covers everything around the stage: sources, stages, sinks, and functions that take stages.

  • Future, Future::AsyncAwait, IO::Async and Mojo::Promise each have documentation of their own, for what a block can do.

Appendix: what writing this guide proved, and found

Every program in this guide is a test. Each runs as it stands, alone, on Linux, macOS and Windows, on every change to the module, and must print exactly what it says it prints. So, taken together, the recipes check the stages' promises from a reader's side, with real loops, clients and Ekorn's own parts. Writing them also found things that needed changing, and traps that a reader can still fall into.

What the recipes prove

Up to the number given are waiting at once, and no more

Run three slow look-ups at once, See the time it saves, Choose how many run at once

in_futures gives results 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_ready gives each result as soon as it's ready

Get each result as soon as it's ready, Take the answer from whichever server is quickest

Each result knows the value it came from

Know which value each result came from, Know it when the results come in any order

Any loop that await knows, with nothing between

Use Mojolicious instead of IO::Async, and chapters 1 and 2

A failure takes its turn, after the results before it

See a failure stop the run, in its turn

A stop takes its turn, with its values

Stop the run from inside the block

A stop after the stage cancels what's waiting, where it can be

Stop after the first few, and cancel the rest, Take the answer from whichever server is quickest

A failure met in the flush loses the results taken with it

Know what a failure at the end costs

An error object is passed on as it is

Tell an error object from an error message

The stage is a stage like any other, beside all of Ekorn's parts

chapters 3, 4, 5 and 8: sources, stages, sinks, iterators, chains, named pipelines, pipelines as stages, feeds, and a run for each key

Inside a running loop, it croaks, saying why

Don't run the stages inside a running loop, Every message the stages give

What writing them found

Some of what the recipes found changed the module before it was ever released:

  • The stages are exported by default. Every recipe needed qw(in_futures), and leaving it off failed only when the stage was made, so the module now exports both, as Ekorn::Pipeline::Stop does Stop. This guide still names what each program uses.

  • **in_futures_any became in_futures_as_ready.** The old name read like Future's needs_any, which finishes at the first, and the guide had to say twice that it doesn't. A future is ready when it's done, failed or cancelled, which is when this stage passes a result on.

  • A failure that's a string is passed on as it was given. A rejection such as Mojo's "Connection refused" used to name a line inside the stage, which told you nothing.

  • This guide uses Mojo::UserAgent, not Net::Async::HTTP. Version 0.50 of Net::Async::HTTP leaves a request waiting a round for a busy connection, as A note on Net::Async::HTTP explains; it hasn't yet been reported to its author.

Others are traps that remain, as they come from Perl or the libraries, not from the stages. Each has a recipe:

The whole account, with each decision taken and why, is in Ekorn-Pipeline's change record for these stages, 2026-0064.

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.