Skip to content

Commit

Permalink
Move nonblocking/streaming check to the middleware akin to Writer
Browse files Browse the repository at this point in the history
  • Loading branch information
miyagawa committed Oct 20, 2009
1 parent e39281d commit caec909
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 10 deletions.
5 changes: 2 additions & 3 deletions eg/demo.pl
Expand Up @@ -171,9 +171,8 @@ package main;
use Plack::Middleware::Static;
$app = Plack::Middleware::Static->wrap($app, path => qr/^\/static/, root => dirname(__FILE__));

# TODO should this be in Server
use Plack::Middleware::Writer;
$app = Plack::Middleware::Writer->wrap($app);
use Tatsumaki::Middleware::Blocking;
$app = Tatsumaki::Middleware::Blocking->wrap($app);

# TODO this should be an external services module
use Try::Tiny;
Expand Down
8 changes: 1 addition & 7 deletions lib/Tatsumaki/Handler.pm
Expand Up @@ -85,22 +85,16 @@ sub run {
}

if ($self->is_asynchronous) {
unless ($self->request->env->{'psgi.streaming'}) {
Tatsumaki::Error::HTTP->throw(500, "asynchronous handlers need PSGI servers with psgi.streaming");
}
my $cv = AE::cv;
$self->condvar($cv);
$self->request->env->{'tatsumaki.block'} = sub { $cv->recv };
return sub {
my $start_response = shift;
$cv->cb(sub {
my $w = $start_response->($_[0]->recv);
$self->writer($w) if $w;
});
$self->$method(@{$self->args});
unless ($self->request->env->{'psgi.nonblocking'}) {
$self->log("psgi.nonblocking is off: running " . ref($self) . " in a blocking mode\n");
$cv->recv;
}
};
} else {
$self->$method(@{$self->args});
Expand Down
30 changes: 30 additions & 0 deletions lib/Tatsumaki/Middleware/Blocking.pm
@@ -0,0 +1,30 @@
package Tatsumaki::Middleware::Blocking;
use strict;
use base qw(Plack::Middleware);
use Carp ();
use Plack::Util;

# Run asnynchronous Tatsumaki app in a blocking mode. See also Middleware::Writer
sub call {
my($self, $env) = @_;

my $caller_supports_streaming = $env->{'psgi.streaming'};
$env->{'psgi.streaming'} = Plack::Util::TRUE;

my $res = $self->app->($env);
return $res if $caller_supports_streaming;

if (ref $res eq 'CODE') {
$env->{'psgi.errors'}->print("psgi.nonblocking is off: running $env->{PATH_INFO} in a blocking mode\n");
$res->(sub { $res = shift });
$env->{'tatsumaki.block'}->();
}

unless (defined $res->[2]) {
Carp::croak("stream_write is not supported on this server");
}

return $res;
}

1;

0 comments on commit caec909

Please sign in to comment.