JSTAPd/Server.pm untested

filter: Statementstmt 0.0% 0 / 288 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 48 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 532 CC 50 SCAR 36.6
CC
50
Cov
0%
handler
90.0
api_handler
90.0
get_next
90.0
CRAP 38.8
1 package JSTAPd::Server;
2 use strict;
3 use warnings;
4 use AE;
5 use Data::Dumper;
6 use File::ShareDir;
7 use File::Spec;
8 use JSON::XS;
9 use HTTP::Request;
10 use LWP::UserAgent;
11 use Path::Class;
12 use Time::HiRes;
13  
14 use Plack::App::Directory;
15 use Plack::Builder;
16 use Plack::Request;
17 use Plack::Response;
18 use Plack::Runner;
19  
20 use JSTAPd;
21 use JSTAPd::ContentsBag;
22 use JSTAPd::Server::Contents;
23 use JSTAPd::TAP;
24  
25 sub contents { $_[0]->{contents} }
26 sub conf { $_[0]->{conf} }
27 sub jstapd_prefix { $_[0]->{conf}->{jstapd_prefix} }
28 sub run_once { !!$_[0]->{run_file} }
29 sub auto_open { !!$_[0]->{conf}->{auto_open_command} }
30  
31 sub new {
32 my($class, %opts) = @_;
33  
34 my $self = bless {
35 dir => '.',
36 port => 1978,
37 host => '127.0.0.1',
38 session_tap => +{},
39 stdout => *STDOUT,
40 %opts,
41 }, $class;
42 $self->{dir} = Path::Class::Dir->new( $self->{dir} );
43 $self->{contents} = JSTAPd::ContentsBag->new( dir => $self->{dir}, run_file => $self->{run_file} );
44 $self->{contents}->load;
45 $self->load_config;
46 $self;
47 }
48  
49 sub load_config {
50 my $self = shift;
51 my $path = $self->{dir}->file('conf.pl');
52 my $hash = do $path;
53 if (defined $hash && ref($hash) ne 'HASH') {
54 die "$path return data is not HASHref";
55 }
56 $hash ||= +{};
57  
58 $hash->{auto_open_command} = $ENV{JSTAP_AUTO_OPEN_COMMAND} if $ENV{JSTAP_AUTO_OPEN_COMMAND};
59  
60 $self->{conf} = {
61 jstapd_prefix => '____jstapd',
62 urlmap => +[],
63 apiurl => undef,
64 %{ $hash },
65 };
66 }
67  
68 sub run {
69 my $self = shift;
70  
71 my $uri = sprintf 'http://%s:%s/%s/', $self->{host}, $self->{port}, $self->{conf}->{jstapd_prefix};
72 if ($self->auto_open) {
73 if (my $pid = fork) {
74 # running to server
75 } elsif (defined $pid) {
76 # waiting http server startup
77 while (1) {
78 sleep 0.01;
79 my $res = LWP::UserAgent->new->request(
80 HTTP::Request->new( GET => $uri )
81 );
82 last if $res->code == 200;
83 }
84  
85 # open the browser
86 my $cmd = sprintf($self->conf->{auto_open_command}, $uri);
87 `$cmd`;
88 exit;
89 } else {
90 die 'browser auto open mode is fork error';
91 }
92 }
93  
94 my $env = 'development';
95 $env = 'jstapd_auto_open' if $self->auto_open;
96 my $runner = Plack::Runner->new(
97 env => $env,
98 server => 'Twiggy',
99 options => [
100 host => $self->{host},
101 port => $self->{port},
102 ],
103 );
104 print STDERR "starting: $uri\n" unless $self->auto_open;
105  
106 my $contents_htroot = sprintf '/%s/contents', $self->jstapd_prefix;
107 my $share_htroot = sprintf '/%s/share', $self->jstapd_prefix;
108 my $share_root = eval { File::ShareDir::dist_dir('JSTAPd') } || do {
109 my @dirs = File::Spec->splitdir($INC{'JSTAPd.pm'});
110 pop @dirs; pop @dirs;
111 File::Spec->catfile(@dirs, 'share');
112 };
113  
114 my $jstapd_app = $self->psgi_app;
115 my $contents_dir = Plack::App::Directory->new( root => $self->{dir} )->to_app;
116 my $contents_app = sub {
117 my $path_info = $_[0]->{PATH_INFO};
118 return $contents_dir->(@_) unless $path_info =~ /\.t\z/;
119 $jstapd_app->(@_);
120 };
121  
122 my $app = builder {
123 mount "$share_htroot" => Plack::App::Directory->new( root => $share_root )->to_app;
124 mount "$contents_htroot" => $contents_app,
125 mount "/" => $jstapd_app;
126 };
127 $runner->run( $app->to_app );
128 }
129  
130 sub psgi_app {
131 my $self = shift;
132 return sub {
133 my $res = $self->handler(@_);
134 return $res unless ref $res eq 'Plack::Response';
135 return $res->finalize();
136 };
137 }
138  
139 sub setup_session_tap {
140 my($self, $session, $path) = @_;
141 $self->{session_tap}->{$session} ||= +{
142 current_path => undef,
143 path => +{},
144 };
145 if ($path) {
146 return $self->{session_tap}->{$session}->{path}->{$path} ||= +{
147 is_end => 0,
148 tap => JSTAPd::TAP->new,
149 ajax_request_stack => +[],
150 };
151 } else {
152 return $self->{session_tap}->{$session};
153 }
154 }
155 sub get_session {
156 $_[0]->setup_session_tap($_[1]);
157 }
158 sub get_path {
159 $_[0]->setup_session_tap($_[1], $_[2]);
160 }
161 sub get_tap {
162 $_[0]->get_path($_[1], $_[2])->{tap};
163 }
164  
165 sub decode_urlmap {
166 my($self, $path) = @_;
167 my $urlmap = $self->{conf}->{urlmap};
168 for my $conf (@{ $urlmap }) {
169 my($re, $new) = %{ $conf };
170 last if $path =~ s/$re/$new/;
171 }
172 $path;
173 }
174  
175 sub handler {
176 my($self, $env) = @_;
177  
178 my $req = Plack::Request->new($env);
179  
180 my $session = $req->param('session') || Data::UUID->new->create_hex;
181  
182 my $jstapd_prefix = $self->{conf}->{jstapd_prefix};
183 my $apiurl = $self->{conf}->{apiurl};
184 my $res;
185 if ($req->uri->path eq '/favicon.ico') {
186 } elsif (my($path) = $req->uri->path =~ m!^/$jstapd_prefix/(.+)?$!) {
187 # serve jstapd contents
188 $path = 'index' unless $path;
189 $path .= 'index' if $path =~ m!/$! || !$path;
190 $self->get_session($session)->{current_path} ||= do {
191 my $p = $path;
192 $p =~ s{^contents/}{};
193 $p;
194 };
195 $res = JSTAPd::Server::Contents->handler($path, $self, $req, $session);
196  
197 # no-cache
198 $res->header( 'Pragma' => 'no-cache' );
199 $res->header( 'Cache-Control' => 'no-cache' );
200  
201 # set test session cookie
202 if ($path eq 'index' || $path =~ /\.t$/) {
203 $res->cookies->{$jstapd_prefix} = {
204 value => $session,
205 path => '/',
206 };
207 }
208 } elsif (($path) = $req->uri->path =~ m!^/${jstapd_prefix}__api/(.+)?$!) {
209 # ajax request for jstapd
210 $res = $self->api_handler($path, $req, $session);
211 $res ||= Plack::Response->new( 200, [ 'Content-Type' => 'application/json' ], '{msg:"ok"}' );
212  
213 } elsif ($apiurl && $req->uri->path =~ /$apiurl/) {
214 # ajax request for appication
215 $session = $req->cookies->{$jstapd_prefix};
216 my $current_path = $self->get_session($session)->{current_path};
217 $res = JSTAPd::Server::Contents->handler("contents/$current_path", $self, $req, $session, { path => $current_path, is_api => 1 });
218  
219 # push request
220 my $param = $req->parameters->as_hashref_mixed;
221 my $current = $self->get_path($session, $current_path);
222 push @{ $current->{ajax_request_stack} }, +{
223 method => $req->method,
224 path => $req->uri->path,
225 query => $req->uri->query,
226 param => $param,
227 };
228 if ($current->{pop_tap_request}) {
229 # send waiting request
230 my $stack = $current->{ajax_request_stack} || +[];
231 $stack = [ splice @{ $stack }, 0, $current->{pop_tap_request}->{requests} ];
232 $current->{pop_tap_request}->{cv}->send(
233 $self->json_response($stack)
234 );
235 }
236 } else {
237 # ajax request?
238 my $path = $self->decode_urlmap($req->uri->path);
239 # XXX Content-Type?
240 $res = Plack::Response->new( 200, [], $self->{dir}->file($path)->slurp.'' );
241 }
242  
243 return $res || Plack::Response->new( 404, [ 'Content-Type' => 'text/plain' ], 'Not Found' );
244 }
245  
246 sub api_handler {
247 my($self, $type, $req, $session) = @_;
248  
249 # for main index
250 my $current_path = $self->get_session($session)->{current_path};
251 if (my $code = JSTAPd::Server::controller->can($type)) {
252 my $ret = $code->($self, $session, $req, $current_path);
253 return $ret if $ret;
254 }
255  
256 # for tap test
257 my $path = $req->param('path');
258 my @session_path = ($session, $path);
259  
260 my $tap = $self->get_tap(@session_path);
261 my $current = $self->get_path(@session_path);
262 if ($type eq 'tests') {
263 $tap->tests($req->param('num'));
264 } elsif ($type eq 'tap') {
265 $tap->push_tap($req->parameters);
266 } elsif ($type eq 'tap_done') {
267 if (my $error = $req->param('error')) {
268 $tap->error($error);
269 }
270 if ($current->{end_cv}) {
271 $current->{end_cv}->send();
272 }
273 $self->get_path(@session_path)->{is_end} = 1;
274 return Plack::Response->new( 200, [ 'Content-Type' => 'text/plain' ], $tap->as_string );
275 } elsif ($type eq 'dump') {
276 warn Dumper($tap);
277 }
278 return;
279 }
280  
281 sub json_response {
282 my $res;
283 eval {
284 $res = Plack::Response->new( 200, ['Content-Type' => 'application/json' ], JSON::XS->new->ascii->encode($_[1]) );
285 };
286 if ($@) {
287 warn Dumper($_[1]);
288 warn $@;
289 }
290 $res;
291 }
292  
293  
294 sub set_tests {
295 my($self, $session, $path) = @_;
296 my $tap = $self->get_tap($session, $path);
297 $self->{contents}->visitor(sub{
298 my $obj = shift;
299 my $child = $obj->{child};
300 return unless ref $child eq 'JSTAPd::Contents';
301 next unless $child->can('suite');
302 my $suite = $child->suite;
303 return unless $suite;
304 return unless $path eq $obj->{path};
305 $tap->tests($suite->tests) unless $tap->tests;
306 });
307 }
308  
309 package JSTAPd::Server::controller;
310  
311 sub get_test_plans {
312 my($c, $session, $req, $current_path) = @_;
313 return $c->json_response($c->contents->test_plans);
314 }
315  
316 sub get_next {
317 my($c, $session, $req, $current_path) = @_;
318 my $next_path = -1;
319 if ($c->run_once) {
320 # for prove -vl jstap/foor/01_test.t
321 # or prove -vlr jstap
322 $next_path = $c->get_session($session)->{current_path} = $c->{run_file}.'' unless $current_path;
323 $c->set_tests($session, $next_path);
324 return $c->json_response(+{
325 session => $session,
326 path => $next_path,
327 });
328 }
329  
330 my $is_next = $current_path ? 0 : 1;
331 my $is_last = 0;
332 $c->{contents}->visitor(sub{
333 return if $is_last;
334 my $args = shift;
335 return if $args->{is_dir};
336 return unless $args->{name} =~ /\.t$/;
337 if ($is_next) {
338 $next_path = $args->{path};
339 $is_last++;
340 return;
341 }
342 if ($current_path eq $args->{path}) {
343 $is_next++;
344 }
345 });
346 $c->set_tests($session, $next_path);
347 $c->get_session($session)->{current_path} = $current_path = $next_path;
348 return $c->json_response(+{
349 session => $session,
350 path => "$current_path",
351 });
352 }
353  
354 sub watch_finish {
355 my($c, $session, $req, $current_path) = @_;
356  
357 my @session_path = ($session, $current_path);
358 my $current = $c->get_path(@session_path);
359 if ($current_path && $current) {
360 # 終了までまってるなり
361 if ($current->{is_end}) {
362 # もうおわってた
363 my $tap = $c->get_tap(@session_path);
364 return $c->json_response({
365 session => $session,
366 path => $current_path,
367 tap => $tap->as_hash,
368 });
369 } elsif ($current->{end_cv}) {
370 } else {
371 $current->{end_cv} = AE::cv;
372 return sub {
373 my $start_response = shift;
374 $current->{end_cv}->cb(
375 sub {
376 shift->recv;
377 my $tap = $c->get_tap(@session_path);
378 $start_response->( $c->json_response({
379 session => $session,
380 path => $current_path,
381 tap => $tap->as_hash,
382 })->finalize );
383 }
384 );
385 }
386 }
387 }
388 }
389  
390 sub pop_tap_request {
391 my($c, $session, $req, $current_path) = @_;
392  
393 my $current = $c->get_path($session, $current_path);
394 my $stack = $current->{ajax_request_stack} || +[];
395 if (my $requests = $req->param('requests')) {
396 if (scalar(@{ $stack }) >= $requests) {
397 $stack = [ splice @{ $stack }, 0, $requests ];
398 } else {
399 # waiting
400 if ($current->{pop_tap_request}) {
401 # XXX error handling
402 return Plack::Response->new( 500, [ 'Content-Type' => 'text/plain' ], 'over fllow pop_tap_request request' );
403 }
404 $current->{pop_tap_request} = {
405 cv => AE::cv,
406 requests => $requests,
407 };
408 return sub {
409 my $start_response = shift;
410 $current->{pop_tap_request}->{cv}->cb(
411 sub {
412 my $tmp = delete $current->{pop_tap_request};
413 $start_response->( shift->recv->finalize );
414 }
415 );
416 }
417 }
418 } else {
419 $current->{ajax_request_stack} = +[];
420 }
421 return $c->json_response($stack);
422 }
423  
424 sub exit {
425 my($c, $session, $req, $current_path) = @_;
426 return unless $c->run_once && ref($c->{destroy}) eq 'CODE';
427 my $tap = $c->get_tap($session, $current_path);
428 $c->{destroy}->($c->{stdout}, $tap);
429 }
430  
431 package JSTAPd::Server;
432 1;