2020/12/06

2020 Perl Advent Calendar - Day 6

<< First | < Prev | Next >

By now we are beginning to build the impression that writing asynchronous code using async/await syntax looks and feels much neater, because its structure is much more similar to that of equivalent synchronous code which would do the same task. Aside from functions being marked with async and expressions having await at strategic points in them, the code all looks exactly the same as you'd find in a simpler synchronous style.

At this point I'm going to continue following the overall theme and topic of each of the original Futures blog post articles, but using real examples of code from real modules on CPAN (or at least, slightly reworded ones). These should give a more varied and interesting sense of actual code, than the rather artifical examples centered around the HTTP GET examples we have used so far.

The original day 10 article hinted at some ways to structure asynchronous code code using futures to have conditional parts to it. With async/await syntax no special considerations need to be taken. All of the usual conditional code flow styles - such as if blocks or shortcircuit evaluation - will apply just fine.

For example, this method from a module which communicates with an attached hardware device, implements a cache around reading a certain data register from it.

use Future::AsyncAwait;

async sub _read { ... }

async sub _cached_read_TIMING
{
    my $self = shift;
    
    return $self->{TIMINGbytes} //= await $self->_read(REG_TIMING, 1);
}

This would have been quite awkward to write using plain futures and ->then chaining, but using async/await and the ability to place the await expression anywhere makes this much simpler. If the key on $self is already defined then its value is returned immediately. If not, the entire asynchronous method is suspended while it performs a read operation on the underlying hardware, and when the result is available that is returned, as well as being stored into the object for next time.

The original day 11 article introduced the ->transform method, which tries to neaten certain forms of sequencing operation which calculate and return a new value based on the value returned by an asynchronous operation. This again is much simpler using async/await syntax, because we can put the await expression anywhere in the code.

For example, this method asynchronously fetches a byte string from the attached hardware, then unpacks it into an integer using the unpack function.

use Future::AsyncAwait;

async sub read_data0
{
    my $self = shift;
    
    return unpack "S<", await $self->_read(REG_DATA0, 2);
}

Here we wait for the bytes to be read from the hardware, and when they arrive pass them into the unpack core operator, and return that result.

<< First | < Prev | Next >

2020/12/05

2020 Perl Advent Calendar - Day 5

<< First | < Prev | Next >

Yesterday we took a look at how failure handling works when using async/await syntax. We saw the close association between Perl's exception throwing, and future instances in failed state. In forming this association, however, we did gloss over one detail. Futures can store an entire list of values in both a successful and failed state. When representing a failure, the first item in this list contains the message, but additional values are also permitted to provide more information on context.

In the original blog post series, day 7 talked about how to handle failed futures with these lists of values. When using async/await syntax and simply using die to throw an exception there's no obvious place to put extra values. For this problem we can use an instance of Future::Exception. This class is specifically designed for this problem; containing the extra values while appearing like a normal exception object for the purposes of die and catch.

For example, perhaps we want to check a GET request to ensure it responds with a 2xx or 3xx response code, and if not throw an exception in the http category, which also includes the received response object itself, in case the caller wants to inspect it.

use feature 'signatures';
use Future::AsyncAwait;
use Future::Exception;

async sub GET_checked($url)
{
    my $response = GET($url);

    if($response->code =~ m/^[23]/) {
        Future::Exception->throw("Unable to fetch $url",
            http => $response
        );
    }
    ...
}

Over the past 7 years since the original article was written, a pattern for using failures with values has been established. The first positional value should be a short string, describing the kind of failure, or in some way explaining why and when it happened, to give a clue to how to decode the other values. This "category name" can be used by exception dispatch logic when responding to the particular kind of failure, by inspecting the ->category method of a caught Future::Exception instance.

The original article on day 8 showed a combined success-or-failure handling using a two-argument ->then sequencing method on a future. There isn't a direct parallel using async/await and try/catch, but instead it becomes just a standard code shape for writing exception flow logic.

use Future::AsyncAwait;
use Syntax::Keyword::Try;

my $response;
try {
    $response = await GET("http://my-site-here.com/news");
}
catch($e isa Future::Exception) {
    if($e->category eq "http") {
        my ($response) = $e->details;
        
        return "(no title)" if $response->code == 204;
    }
    die $e;
}

return get_page_title($response->content);

The article for day 9 introduced another future construction methods, ->call, for ensuring that any exception thrown by a piece of code is always turned into a future in failed state. This isn't necessary when using async sub, because any exception thrown by that function immediately becomes a failed future, even if encountered very early on. This is ensured by the way that async sub works internally.

use Future::AsyncAwait;

async sub get_article($id_num)
{
    $id_num > 0 or die "Invalid ID number $id_num";
    return await GET("http://my-site-here.com/article-$id_num");
}

my $f = get_article(-123);

print "F is a failed future\n" if $f->is_failure;

Here when we call get_article with a bad argument, the future it returns is already ready, and in a failed state. The call itself does not throw an exception - remember, we only get that by applying such a failed future to the await keyword.

<< First | < Prev | Next >

2020/12/04

2020 Perl Advent Calendar - Day 4

<< First | < Prev | Next >

Now that we've seen some basic introduction on async/await syntax, lets return to exploring and updating the original Futures blog-post series. The next few posts all concerned themselves with error handling, so lets take a look at what that looks like using async/await.

The original day 4 post introduced the ->on_fail method, to apply a callback for handling failures. When using async/await syntax, there is a close relationship between thrown exceptions, and failed futures. Attempting to await on a future that is in a failed state will throw an exception.

We can use any of the usual forms of exception handling to cope with these exceptions. For example, we can use the try/catch syntax from Syntax::Keyword::Try.

use Future::AsyncAwait;
use Syntax::Keyword::Try;

try {
    my $response = await GET("http://my-site-here.com/");
    say "Got a response";
}
catch ($e) {
    print STDERR "It failed: $e\n";
}

The day 5 post then introduced the ->fail method to cause a failure. With an async function, any exceptions thrown by the body of the function become failure results on the returned future instance. The code inside an async sub can simply use regular die to cause a failure.

use feature 'signatures';
use Future::AsyncAwait;

async sub get_page_title($url)
{
    my $response = await GET($url);
    
    if($response->code != 200) {
        die "Unable to fetch page - HTTP status code " . $response->code;
    }

    ...
}

The post on original day 6 then introduced the ->else method on a future instance, which allows failure handling of a future to still be a future. We don't need to do anything special with async/await syntax, because any exception thrown inside an async sub becomes a failed future, and any await on a failed future will re-throw the exception it contains. Thus, failure handling with async/await looks the same as any other sort of exception in synchronous code.

When using Syntax::Keyword::Try we can also put an await expression inside a try block in an async sub, and it behaves entirely as expected. For example, if we wanted to fetch a list of images from an HTML page, but just ignore any failures to fetch and just return an empty list instead.

use feature 'signatures';
use Future::AsyncAwait;
use Syntax::Keyword::Try;

async sub get_page_images($url)
{
   my $response;
   
   try {
       $response = await GET($url);
   }
   catch {
       return ();
   }
   
   ...
}

While there are a number of try/catch modules on CPAN, Syntax::Keyword::Try is specifically known to be compatible in this manner. Both it and Future::AsyncAwait contain a cross-module test script, to ensure that cases like this work. This is one of the reasons why Syntax::Keyword::Try has become my preferred exception-handling module.

<< First | < Prev | Next >

2020/12/03

2020 Perl Advent Calendar - Day 3

<< First | < Prev | Next >

Yesterday, we saw await being used at the program toplevel, where its behaviour is simply to wait for a future to finish, and we saw some definitions of functions declared as async sub which return futures. One of the defining features of the async/await syntax is the way in which await expressions can be used inside async functions. Used in such a way, the asynchronous function will suspend itself until the result is available on the future it is waiting for, and then the function will be resumed. While suspended, the future returned by it remains pending, and the caller is free to perform other tasks while it continues. This lets us build a larger piece of asynchronous behaviour out of smaller pieces.

For example, we can use this to create a function that fetches an HTML page, then uses Mojo::DOM to parse and extract the page title from it.

use feature 'signatures';
use Future::AsyncAwait;
use Mojo::DOM;

async sub get_page_title($url)
{
    my $response = await GET($url);

    my $dom = Mojo::DOM->new($response->body);
    
    return $dom->at("title")->text;
}

As with yesterday's examples, we can now call this function in a toplevel await expression to wait for its result. Since this is all about concurrency and the efficiency gains by performing multiple tasks at once, lets now attempt to fetch the titles of three different pages. Similar to yesterday, we can do this by starting all three requests and returning three futures, then await each of them. (In a later post we will see a better way to perform logic like this, but for this small example of just three pages, this will do fine.)

use Future::AsyncAwait;

my @futures = (
    get_page_title("http://my-site-here.com/page1.html"),
    get_page_title("http://my-site-here.com/page2.html"),
    get_page_title("http://my-site-here.com/page3.html"),
);

say "The titles of the pages are:";
say await $_ for @futures;

In this way we can begin to build asynchronous functions by calling smaller ones in the same way that we would write synchronous code. This starts to give us a hint on how the GET function itself may be implemented in terms of some helpers for the various stages of an HTTP client request/response cycle:

use feature 'signatures';
use Future::AsyncAwait;

async sub connect_tcp($host, $port) { ... }

async sub send_http_request($sock, $request) { ... }

async sub recieve_http_response($sock) { ... }

async sub GET($url)
{
    my $sock = await connect_tcp($url->host, $url->port);
    
    my $request = HTTP::Request->new(GET => $url->path_query,
        [Host => $url->authority],
    );
    
    await send_http_request($sock, $request);
    
    my $response = await receive_http_response($sock);
    
    return $response;
}

Of course, this is just a toy example. Any real piece of robust and reliable code would have to deal with such subjects as error handling, conditional branching, repetitions and so on, as well as storing persistent state between invocations. Fortunately, these are all things for which async/await syntax is well-suited, so lets explore them next.

<< First | < Prev | Next >

2020/12/02

2020 Perl Advent Calendar - Day 2

<< First | < Prev | Next >

Yesterday we got our first look at the async/await syntax in a couple of simple examples. We saw how a function can be declared with async sub, and how a toplevel await expression can be used to invoke it and obtain its return value. So far we have only ever seen the await keyword being used directly on a call to an async sub, but that isn't the only way it can be used. To understand more fully what is going on here we need to take a look inbetween the two. Lets now begin to explore, in more detail, what these two keywords do individually.

The async part of the function definition changes the way its return value works. From the perspective of an outside caller it appears that any async sub always returns an instance of the Future class. Any value that the body of the function tries to return using its own return statement in fact becomes the result stored into that Future instance.

use Future::AsyncAwait;

async sub sum
{
    my @numbers = @_;
    my $total = 0;
    $total += $_ for @numbers;
    return $total;
}

my $f = sum(30, 40);

say "The future is ", $f;
say "The future is done" if $f->is_done;
say "The result of the future is ", $f->result;

# outputs:
The future is Future=HASH(0x5653a9bf4440)
The future is done
The result of the future is 70

Where the async keyword can be used to create a new future when the function is called, the await keyword is used to consume one and yield the result value stored inside it. As we have already seen, calling an async sub is one way to obtain such a Future instance, but any expression containing a future - such as a simple variable - can also be used.

use Future::AsyncAwait;

my $f = Future->done(50 + 60);

say "The result is ", await $f;

# outputs
The result is 110

So far these examples haven't been very interesting, because they all yield their result immediately. In order to better see what this new syntax provides for us, lets think again about the HTTP GET function we saw yesterday. To perform its task, this function will have to first send an HTTP request to a server, then wait for a response to be sent back from the server. It is this waiting part, that the Future instance represents.

We'll explore in more detail how the GET function can work in a later post, but suffice it for now to observe that by the time the function returns a future, it doesn't yet need to have received a response from the server. It can be waiting for that to arrive, and only later set the result of the future. After the GET function returns with this still-pending future, we have control once more and we can do something else while we wait for that result - perhaps send a second request.

use Future::AsyncAwait;

my $f1 = GET("http://my-site-here.com/page1");
my $f2 = GET("http://my-site-here.com/page2");

my $response1 = await $f1;
my $response2 = await $f2;

printf "page1 contains %d bytes; page2 contains %d bytes\n",
    length $response1->body, length $response2->body;

By calling the GET function twice and storing the futures in two variables, we have been able to start two concurrent requests, so we can wait for both of them to respond. Overall this means the program takes less time to complete, because it has been able to keep more than one thing up in the air at once. In effect, the act of calling an asynchronous function merely requests that it begin to perform its work. It isn't until we try to await on its future that we request that it must now finish, waiting for it if necessary. This is in contrast to calling a regular synchronous function, which must entirely complete its task before it can return.

This ability to start and manage possibly-multiple concurrent operations before requiring any of them to be finished is the central theme of what asynchronous programming with futures is all about. async/await syntax provides us many abilities to write asynchronous code on futures in a familiar way, which looks and feels much more like the more traditional synchronous style we have been used to. This is what we will explore over the next several days.

<< First | < Prev | Next >

2020/12/01

2020 Perl Advent Calendar - Day 1

<< First | < Prev | Next >

A few years ago I wrote an advent calendar series of blog posts about handling asynchronous control flow using Futures in Perl. I've decided it's about time to revisit that and update it with more modern style - namely, using the new async/await syntax provided by Future::AsyncAwait.

On Day 1 we began with a small simple function that didn't actually do anything asynchronous, but simply returned a calculated immediately by using the Future->new->done constructor. Using async/await syntax this is much simpler. In fact, apart from the presence of the async and await keywords here you'd be hard pushed to even realise anything different was going on:

use Future::AsyncAwait;

async sub sum
{
   my @numbers = @_;
   my $total = 0;
   $total += $_ for @numbers;
   return $total;
}

say "The total is " . await sum( 10, 20, 30 );

Already in this small example we can see the beginnings of a pattern - that any function declared as async sub needs to be called as part of an await expression. The await expression will eventually yield the result that the asynchronous function returned.

Of course, there's no reason for this particular code to be asynchronous, so by Day 2 I had invented a hypothetical GET function which took a URL and returned a future that will eventually resolve with some sort of HTTP response - we can imagine that being provided by some sort of asynchronous HTTP library. That example showed the on_done method on the future instance.

The await keyword simply suspends the function it is currently executing in, so we can come back later when a result arrives. This allows us to write an example where we wait for an HTTP request/response cycle to complete, and then perform some more work afterwards:

use Future::AsyncAwait;

my $response = await GET("http://my-site-here.com/");

print "Got a response\n";

In the original series we had to get to Day 3 to introduce the then method, which allows a sequence of operations to be performed. No such complication is required with async/await, because we can simply await a second time after the first one, to execute a whole sequence of operations. For example, now we can perform a second request based on some analysis of the result of the first.

use Future::AsyncAwait;

my $first_response = await GET("http://my-site-here.com/first");

my $path = path_from_response($first_response);
my $second_response = await GET("http://my-site-here.com/$path);

printf "Second response contains %d bytes\n", length $second_response->body;

If this is your first experience of futures, asynchronous code flow, and async/await syntax, it may not be immediately obvious currently why you want to do this. I hope to motivate all of this, and more, over the following posts...

<< First | < Prev | Next >

2020/11/24

Building for new ATmega 0-series chips on Debian

I previously wrote about building code for the Microchip ATtiny 1-series chips on Debian machines. It requires copying some files around into places the host OS can find them.

I've recently been looking at the equally new ATmega 0-series, and it seems to require similar steps to find those files.

Start off by downloading the "Atmel ATmega Series Device Support" file from http://packs.download.atmel.com/. This is a free and open download, licensed under Apache v2. This file carries the extension atpack but it's actually just a ZIP file:

$ file Atmel.ATmega_DFP.1.6.364.atpack
Atmel.ATmega_DFP.1.6.364.atpack: Zip archive data, at least v1.0 to extract

Note that by default it'll unpack into the working directory, so you'll want to create a temporary folder to work in:

$ mkdir pack

$ cd pack/

$ unzip ~/Atmel.ATmega_DFP.1.6.364.atpack 
Archive:  /home/leo/Atmel.ATmega_DFP.1.6.364.atpack
   creating: atdf/
   creating: avrasm/
   creating: avrasm/inc/
...

From here, you can now copy the relevant files out to where avr-gcc will find them. Since this time we also have to supply avr-gcc with some device spec files, we'll have to find out where it wants to keep them:

$ dpkg -S specs-attiny814
gcc-avr: /usr/lib/gcc/avr/5.4.0/device-specs/specs-attiny814

This now gives us the path to copy them into:

$ sudo cp gcc/dev/atmega*0[89]/device-specs/specs-atmega* /usr/lib/gcc/avr/5.4.0/device-specs/
$ sudo cp include/avr/iom*0[89].h /usr/lib/avr/include/avr/
$ sudo cp gcc/dev/atmega*0[89]/avrxmega3/*.{o,a} /usr/lib/avr/lib/avrxmega3/

Having done this we find we can now compile firmware for these new chips:

$ avr-gcc -std=gnu99 -Wall -Os -DF_CPU=20000000 -mmcu=atmega3208 -flto -ffunction-sections -fshort-enums -o .build/firmware.elf src/main.c
$ avr-size .build/firmware.elf
   text    data     bss     dec     hex filename
   4087      24      11    4122    101a .build/firmware.elf
$ avr-objcopy -j .text -j .rodata -j .data -O ihex .build/firmware.elf firmware-flash.hex