WebSocket connection delayed in Mojolicious

Viewed 271

I suppose I'm doing something dumb in my Mojolicious WebSocket and there is an easy solution.

I have a form that when POSTed initiates a WebSocket for receiving progress text. The problem is that the connection doesn't complete until after I issue the finish() command. At that point, my browser actually opens the the socket and receives all of the messages.

I assume that I'm doing something wrong on the server-side, but I can't rule out the javascript as the problem.

javascript

$(document).ready(function() {
  $("form.report_form").submit(function(event) {
    event.preventDefault();

/* do the POSTy things */

    var ws = new WebSocket($('#progress_url').val());
    ws.onopen = function(){ alert('websocket is ready for business')};
    ws.onmessage = function (event) {
      console.log(event.data);
    }           
  });

/* stuff to configure the form */

});

Mojolicious Controller

package WebLOC::Controller::Progress;
use Mojo::Base 'Mojolicious::Controller';

sub tail {
    my $self = shift;

    my ($guid)
        = $self->url_for
        =~ /([0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12})/;

    my $filename = "/tmp/$guid.out";

    my $fh;
    my $is_open = open( $fh, '<', $filename );
    unless ($is_open) {    # try one more time
        sleep 1; 
        $is_open = open( $fh, '<', $filename );
    }

    if ($is_open) {
        $self->inactivity_timeout( 5 * 60 );

        # shouldn't need a subscription, but...
        $self->on( finish => sub { } );

        while ( my $msg = <$fh> ) {
            chomp $msg;

            $self->send(
                $msg => sub { $self->app->log->debug('I am drained') } );

            $self->app->log->debug("read: $msg");
        }
    }
    else {
        $self->app->log->error("Can't open file $filename: $!");

        return; 
    }

    $self->finish;

    return 0;
}

1;

Sample Application

select STDOUT;
$|=1;

say "1 of 3";
sleep 3;
say "2 of 3";
sleep 3;
say "3 of 3";
sleep 3;
exit;

Mojolicious Log

[Wed Nov 22 14:35:31 2017] [debug] GET "/progress/53898C2E-CFC8-11E7-B15D-BCDD6A63D34C"
[Wed Nov 22 14:35:31 2017] [debug] Routing to controller "WebLOC::Controller::Auth" and action "check"
[Wed Nov 22 14:35:31 2017] [debug] Routing to controller "WebLOC::Controller::Progress" and action "tail"
[Wed Nov 22 14:35:31 2017] [debug] 101 Switching Protocols (0.008343s, 119.861/s)
[Wed Nov 22 14:35:33 2017] [debug] read: 1 of 3
[Wed Nov 22 14:35:36 2017] [debug] read: 2 of 3
[Wed Nov 22 14:35:39 2017] [debug] read: 3 of 3
[Wed Nov 22 14:35:42 2017] [debug] I am drained
[Wed Nov 22 14:35:42 2017] [debug] I am drained
[Wed Nov 22 14:35:42 2017] [debug] I am drained

The log shows that the file reads (and WS sends) are happening in real-time, but the sends aren't drained until the end. I can also see that the WebSocket is not showing established(). On the client side, I don't get the onopen alert(), nor the onmessage console logs, until after the connection is closed on the server.

SOLVED The best I can tell a WebSocket is not ready to be used until after your controller exits. I assume there is a way to force it to work prior to this, but I sure couldn't figure it out.

I changed my design. Rather than trying to immediately send data to the socket, I store the tx() object in a stash hash. I then have the script's output do the the sends to that transaction.

Mojolicious Application

$self->defaults( layout => 'default', websockets => {}, );
...
$auth->websocket('/progress/:guid')->to('progress#websocket');

WebSocket Controller

sub websocket {
    my $self = shift;

    my $guid = $self->stash('guid');

    $self->on( finish => sub { delete $self->stash->{websockets}{$guid} } );

    $self->stash->{websockets}{$guid} = $self->tx;
}           

Report Controller

my $fork = Mojo::IOLoop::ReadWriteFork->new;

$fork->on(
    read => sub {
        my ( undef, $msg ) = @_;

        chomp $msg;

        my $websocket = $self->stash->{websockets}{$key};

        $websocket->send($msg) if $websocket;
    }
);

$fork->on(
    close => sub {
        my ( undef, $err ) = @_;

        my $websocket = $self->stash->{websockets}{$key};

        $websocket->finish if $websocket;

    }
);
0 Answers
Related