Created
October 31, 2012 14:31
-
-
Save xsawyerx/3987355 to your computer and use it in GitHub Desktop.
using send_file for full non-blocking async fork w/ condvars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this function lets you run code in a fork | |
# and use a condvar on it to get the data | |
# and return it to the client in JSON form, all non-blocking and async | |
# based heavily on a trick by Assaf Gordon | |
sub async_response (&) { | |
my $cb = shift; | |
send_file( | |
\'noop', | |
streaming => 1, | |
callbacks => { | |
override => sub { | |
my ( $respond, $response ) = @_; | |
my $return = {}; | |
my $cv = AnyEvent->condvar; | |
$cv->begin( sub { | |
$respond->( Plack::Response->new( | |
200, | |
[ 'Content-type' => 'text/json' ], | |
to_json $return | |
)->finalize ); | |
} ); | |
$cv->begin; | |
fork_call { $cb->() } sub { | |
$return = shift; | |
$cv->end; | |
}; | |
$cv->end; | |
}, | |
}, | |
); | |
} | |
get '/do/something' => sub { | |
async_response { | |
# some blocking code | |
# for example: VM::EC2 | |
my $ec2 = VM::EC2->new( ... ); | |
return { | |
instance_names => [ map { $_->tags->{'Name'} } $ec2->instances ], | |
}; | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment