UNTESTED allow for query of outstanding Stemweb processes and return of results. #29
[scpubgit/stemmaweb.git] / lib / stemmaweb / Controller / Stemweb.pm
1 package stemmaweb::Controller::Stemweb;
2 use Moose;
3 use namespace::autoclean;
4 use Encode qw/ decode_utf8 /;
5 use JSON;
6 use LWP::UserAgent;
7 use Safe::Isa;
8 use TryCatch;
9 use URI;
10
11 BEGIN { extends 'Catalyst::Controller' }
12
13 ## TODO Move the /algorithms/available function to the Stemweb module
14 my $STEMWEB_BASE_URL = 'http://slinkola.users.cs.helsinki.fi';
15
16 =head1 NAME
17
18 stemmaweb::Controller::Stemweb - Client listener for Stemweb results
19
20 =head1 DESCRIPTION
21
22 This is a client listener for the Stemweb API as implemented by the protocol defined at
23 L<https://docs.google.com/document/d/1aNYGAo1v1WPDZi6LXZ30FJSMJwF8RQPYbOkKqHdCZEc/pub>.
24
25 =head1 METHODS
26
27 =head2 result
28
29  POST stemweb/result
30  Content-Type: application/json
31  (On success):
32  { job_id: <ID number>
33    status: 0
34    format: <format>
35    result: <data> }
36  (On failure):
37  { jobid: <ID number>
38    status: >1
39    result: <error message> }
40    
41 Used by the Stemweb server to notify us that one or more stemma graphs
42 has been calculated in response to an earlier request.
43
44 =cut
45
46 sub result :Local :Args(0) {
47         my( $self, $c ) = @_;
48         if( $c->request->method eq 'POST' ) {
49                 # TODO: Verify the sender!
50                 my $answer;
51                 if( ref( $c->request->body ) eq 'File::Temp' ) {
52                         # Read in the file and parse that.
53                         open( POSTDATA, $c->request->body ) or die "Failed to open post data file";
54                         binmode( POSTDATA, ':utf8' );
55                         # JSON should be all one line
56                         my $pdata = <POSTDATA>;
57                         chomp $pdata;
58                         close POSTDATA;
59                         try {
60                                 $answer = from_json( $pdata );
61                         } catch {
62                                 return _json_error( $c, 400, 
63                                         "Could not parse POST request '' $pdata '' as JSON: $@" );
64                         }
65                 } else {
66                         $answer = from_json( $c->request->body );
67                 }
68                 return _process_stemweb_result( $c, $answer );
69         } else {
70                 return _json_error( $c, 403, 'Please use POST!' );
71         }
72 }
73
74 =head2 query
75
76  GET stemweb/query/<jobid>
77
78 A backup method to query the stemweb server to check a particular job status.
79 Returns a result as in /stemweb/result above, but status can also be -1 to 
80 indicate that the job is still running.
81
82 =cut
83
84 sub query :Local :Args(1) {
85         my( $self, $c, $jobid ) = @_;
86         my $ua = LWP::UserAgent->new();
87         my $resp = $ua->get( $STEMWEB_BASE_URL . "/jobstatus/$jobid" );
88         if( $resp->is_success ) {
89                 # Process it
90                 my $response = decode_utf8( $resp->content );
91                 $c->log->debug( "Got a response from the server: $response" );
92                 my $answer;
93                 try {
94                         $answer = from_json( $response );
95                 } catch {
96                         return _json_error( $c, 500, 
97                                 "Could not parse stemweb response '' $response '' as JSON: $@" );
98                 }
99                 return _process_stemweb_result( $c, $answer );
100         } elsif( $resp->code == 500 && $resp->header('Client-Warning')
101                 && $resp->header('Client-Warning') eq 'Internal response' ) {
102                 # The server was unavailable.
103                 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
104         } else {
105                 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
106                         . $resp->content );
107         }
108 }
109
110
111 ## Helper function for parsing Stemweb result data either by push or by pull
112 sub _process_stemweb_result {
113         my( $c, $answer ) = @_;
114         # Find a tradition with the defined Stemweb job ID.
115         # TODO: Maybe get Stemweb to pass back the tradition ID...
116         my $m = $c->model('Directory');
117         my @traditions;
118         $m->scan( sub{ push( @traditions, $_[0] )
119                                         if $_[0]->$_isa('Text::Tradition')
120                                         && $_[0]->has_stemweb_jobid 
121                                         && $_[0]->stemweb_jobid eq $answer->{job_id}; 
122                                 } );
123         if( @traditions == 1 ) {
124                 my $tradition = shift @traditions;
125                 if( $answer->{status} == 0 ) {
126                         my $stemmata;
127                         try {
128                                 $stemmata = $tradition->record_stemweb_result( $answer );
129                                 $m->save( $tradition );
130                         } catch( Text::Tradition::Error $e ) {
131                                 return _json_error( $c, 500, $e->message );
132                         } catch {
133                                 return _json_error( $c, 500, $@ );
134                         }
135                         # If we got here, success!
136                         my @steminfo = map { { 
137                                         name => $_->identifier, 
138                                         directed => _json_bool( !$_->is_undirected ),
139                                         svg => $_->as_svg() } } 
140                                 $stemmata;
141                         $c->stash->{'result'} = { 
142                                 'status' => 'success',
143                                 'stemmata' => \@steminfo };
144                 } elsif( $answer->{status} < 1 ) {
145                         $c->stash->{'result'} = { 'status' => 'running' };
146                 } else {
147                         return _json_error( $c, 500,
148                                 "Stemweb failure not handled: " . $answer->{result} );
149                 }
150         } elsif( @traditions ) {
151                 return _json_error( $c, 500, 
152                         "Multiple traditions with Stemweb job ID " . $answer->{job_id} . "!" );
153         } else {
154                 # Possible that the tradition got updated in the meantime...
155                 if( $answer->{status} == 0 ) {
156                         $c->stash->{'result'} = { 'status' => 'notfound' };
157                 } else {
158                         return _json_error( $c, 400, 
159                                 "No tradition found with Stemweb job ID " . $answer->{job_id} );
160                 }
161         }
162         $c->forward('View::JSON');
163 }
164
165 =head2 request
166
167  GET stemweb/request/?
168         tradition=<tradition ID> &
169         algorithm=<algorithm ID> &
170         [<algorithm parameters>]
171    
172 Send a request for the given tradition with the given parameters to Stemweb.
173 Processes and returns the JSON response given by the Stemweb server.
174
175 =cut
176
177 sub request :Local :Args(0) {
178         my( $self, $c ) = @_;
179         # Look up the relevant tradition and check permissions.
180         my $reqparams = $c->req->params;
181         my $tid = delete $reqparams->{tradition};
182         my $t = $c->model('Directory')->tradition( $tid );
183         my $ok = _check_permission( $c, $t );
184         return unless $ok;
185         return( _json_error( $c, 403, 
186                         'You do not have permission to update stemmata for this tradition' ) )
187                 unless $ok eq 'full';
188         
189         # Form the request for Stemweb.
190         my $algorithm = delete $reqparams->{algorithm};
191         my $return_uri = URI->new( $c->uri_for( '/stemweb/result' ) );
192         my $stemweb_request = {
193                 return_path => $return_uri->path,
194                 return_host => $return_uri->host_port,
195                 data => $t->collation->as_tsv,
196                 userid => $c->user->get_object->email,
197                 parameters => $reqparams };
198                 
199         # Call to the appropriate URL with the request parameters.
200         my $ua = LWP::UserAgent->new();
201         $c->log->debug( 'Sending request to Stemweb: ' . to_json( $stemweb_request ) ); 
202         my $resp = $ua->post( $STEMWEB_BASE_URL . "/algorithms/process/$algorithm/",
203                 'Content-Type' => 'application/json; charset=utf-8', 
204                 'Content' => encode_json( $stemweb_request ) ); 
205         if( $resp->is_success ) {
206                 # Process it
207                 $c->log->debug( 'Got a response from the server: '
208                         . decode_utf8( $resp->content ) );
209                 my $stemweb_response = decode_json( $resp->content );
210                 try {
211                         $t->set_stemweb_jobid( $stemweb_response->{jobid} );
212                 } catch( Text::Tradition::Error $e ) {
213                         return _json_error( $c, 429, $e->message );
214                 }
215                 $c->model('Directory')->save( $t );
216                 $c->stash->{'result'} = $stemweb_response;
217                 $c->forward('View::JSON');
218         } elsif( $resp->code == 500 && $resp->header('Client-Warning')
219                 && $resp->header('Client-Warning') eq 'Internal response' ) {
220                 # The server was unavailable.
221                 return _json_error( $c, 503, "The Stemweb server is currently unreachable." );
222         } else {
223                 return _json_error( $c, 500, "Stemweb error: " . $resp->code . " / "
224                         . $resp->content );
225         }
226 }
227
228 # Helper to check what permission, if any, the active user has for
229 # the given tradition
230 sub _check_permission {
231         my( $c, $tradition ) = @_;
232     my $user = $c->user_exists ? $c->user->get_object : undef;
233     if( $user ) {
234         return 'full' if ( $user->is_admin || 
235                 ( $tradition->has_user && $tradition->user->id eq $user->id ) );
236     }
237         # Text doesn't belong to us, so maybe it's public?
238         return 'readonly' if $tradition->public;
239
240         # ...nope. Forbidden!
241         return _json_error( $c, 403, 'You do not have permission to view this tradition.' );
242 }
243
244 # Helper to throw a JSON exception
245 sub _json_error {
246         my( $c, $code, $errmsg ) = @_;
247         $c->response->status( $code );
248         $c->stash->{'result'} = { 'error' => $errmsg };
249         $c->forward('View::JSON');
250         return 0;
251 }
252
253 sub _json_bool {
254         return $_[0] ? JSON::true : JSON::false;
255 }
256
257
258 1;