Last active
May 22, 2023 21:12
-
-
Save jjn1056/6c8edf08c617e6d63c7cd2e1d95c31d6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
package Camel::PSGI; | |
use Camel::Syntax; | |
use Net::Async::HTTP::Server::PSGI; | |
use IO::Async::Loop; | |
use IO::Async::Process; | |
use Module::Runtime 'use_module'; | |
die "ALPACA_HOME environment variable not set" unless $ENV{ALPACA_HOME}; | |
sub run { | |
our $loop = IO::Async::Loop->new; | |
# Chat process | |
our $stdout = ''; | |
our $chat_process = IO::Async::Process->new( | |
command => [ "cd $ENV{ALPACA_HOME} && ./chat" ], | |
stdin => { via => "pipe_write" }, | |
stdout => { | |
on_read => sub { | |
print "In on_read\n"; | |
my ($stream, $buffref) = @_; | |
while( $$buffref =~ s/^(.*)\n// ) { | |
print "The process wrote a line: '$1'\n"; | |
$stdout = $1; | |
} | |
return 0; | |
}, | |
}, | |
on_finish => sub { print "The process has finished\n" }, | |
on_exception => sub { | |
my $self = shift; | |
my ( $exception, $errno, $exitcode ) = @_; | |
if( length $exception ) { | |
print STDERR "The process died with the exception $exception " . | |
"(errno was $errno)\n"; | |
} elsif( ( my $status = W_EXITSTATUS($exitcode) ) == 255 ) { | |
print STDERR "The process failed to exec() - $errno\n"; | |
} else { | |
print STDERR "The process exited with exit status $status\n"; | |
} | |
}, | |
); | |
$loop->add( $chat_process ); | |
# Webserver | |
my $httpserver = Net::Async::HTTP::Server::PSGI->new( | |
app => use_module('Camel')->to_app, | |
); | |
$loop->add( $httpserver ); | |
$httpserver->listen( | |
addr => { family => "inet6", socktype => "stream", port => 5000 }, | |
)->get; | |
$loop->run; | |
} | |
return caller(1) ? 1 : run(@ARGV); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment