Advertisement
cng

EventSource Proxy

cng
Mar 20th, 2017
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.46 KB | None | 0 0
  1. sub get_enquiry_events {
  2.     my $self = shift;
  3.     my $enq_id = $self->stash->{enq_id};
  4.  
  5.     # Increase inactivity timeout for connection a bit
  6.     $self->inactivity_timeout( 60 * 20 );    # seconds * minutes
  7.  
  8.     # Change content type and finalize response headers
  9.     $self->res->headers->content_type('text/event-stream');
  10.     $self->write;
  11.  
  12.     $self->write("event:enquiry\ndata: {\"status\":\"Start\",\"component\":\"trim\",\"action\":\"update\"}\n\n");
  13.  
  14.     my $loop_id = Mojo::IOLoop->recurring(
  15.         15 => sub {
  16.             my $loop = shift;
  17.             $self->write("event:enquiry\ndata: {\"status\":\"Ping\",\"component\":\"trim\"}\n\n");
  18.         }
  19.     );
  20.  
  21.     my $ua = Mojo::UserAgent->new( max_response_size => 0 )    # new UA
  22.       ->request_timeout( 60 * 180 );                           # seconds * minutes
  23.      
  24.     my $uri = sprintf('%s/%s', MyApp->config->{firewalled_url}, $enq_id);
  25.  
  26.     # Build a normal transaction
  27.     my $tx = $ua->build_tx( GET => $uri );
  28.  
  29.     $tx->res->content->unsubscribe('read')->on(
  30.         read => sub {
  31.             my ( $content, $bytes ) = @_;
  32.             MyApp->logger->info( "get_enquiry_events-bytes: " . np($bytes));
  33.             $self->write($bytes);
  34.         }
  35.     );
  36.  
  37.     $tx->on(
  38.         finish => sub {
  39.             my $tx = shift;
  40.             Mojo::IOLoop->remove($loop_id);
  41.             $self->finish();
  42.         }
  43.     );
  44.  
  45.     $ua->start($tx => sub{
  46.         my ($ua, $tx) = @_;
  47.         MetaData::Trim->logger->info( "get_enquiry_events-callback for start");
  48.         $self->finish();
  49.     });
  50.  
  51.     # Start event loop if necessary
  52.     Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
  53.  
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement