chiark / gitweb /
Merge branch 'stable-3.x'
[ypp-sc-tools.main.git] / yarrg / web / query_routesearch
1 <%doc>
2
3  This is part of the YARRG website.  YARRG is a tool and website
4  for assisting players of Yohoho Puzzle Pirates.
5
6  Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
7  Copyright (C) 2009 Clare Boothby
8
9   YARRG's client code etc. is covered by the ordinary GNU GPL (v3 or later).
10   The YARRG website is covered by the GNU Affero GPL v3 or later, which
11    basically means that every installation of the website will let you
12    download the source.
13
14  This program is free software: you can redistribute it and/or modify
15  it under the terms of the GNU Affero General Public License as
16  published by the Free Software Foundation, either version 3 of the
17  License, or (at your option) any later version.
18
19  This program is distributed in the hope that it will be useful,
20  but WITHOUT ANY WARRANTY; without even the implied warranty of
21  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  GNU Affero General Public License for more details.
23
24  You should have received a copy of the GNU Affero General Public License
25  along with this program.  If not, see <http://www.gnu.org/licenses/>.
26
27  Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
28  are used without permission.  This program is not endorsed or
29  sponsored by Three Rings.
30
31
32  This Mason component generates the core of the `routesearch' query.
33
34
35 </%doc>
36 <%args>
37 $quri
38 $dbh
39 $queryqf
40 $islandstring => '';
41 $capacitystring => '';
42 $lossperleague => '';
43 $capitalstring => '';
44 $distance => '';
45 $prselector
46 $someresults
47 $emsgokorprint
48 $allargs
49 </%args>
50
51 <%perl>
52 use BSD::Resource;
53
54 my $emsg;
55 my @warningfs;
56 my @islandids;
57
58 my $maxmaxdist=35;
59 my $maxcpu=90;
60 my $concur_lim=5;
61
62 my $qa= \%ARGS;
63 my $routeparams= { EmsgRef => \$emsg, SayRequiredCapacity => 1 };
64 my $maxdist;
65 my $maxcountea=15;
66
67 </%perl>
68
69 <h1>Find most profitable routes and trades</h1>
70
71 % if ($qa->{Dropdowns}) {
72 This feature is not available from the "drop down menus" interface.
73 % } else {
74
75 % $prselector->('RouteSearchType');
76
77 <form action="<% $quri->() |h %>" method="get">
78
79 <& enter_route, qa=>$qa, dbh=>$dbh, emsg_r=>\$emsg, warningfs_r=>\@warningfs,
80         enterwhat => 'Enter starting point(s)',
81         islandids_r => \@islandids, archipelagoes_r => undef
82  &>
83
84 <&| enter_advrouteopts, qa=>$qa, dbh=>$dbh, routeparams=>$routeparams &>
85 <td>
86 &nbsp;
87 &nbsp;
88 <td>
89  Maximum distance:
90  <&| qtextstring, qa => $qa, dbh => $dbh, prefix => 'ml',
91     thingstring => 'distance', emsgstore => \$emsg,
92     onresults => sub { ($maxdist)= @_; } &>
93    size=10
94  </&>
95 </&>
96
97 <input type=submit name=submit value="Search">
98 % my $ours= sub { $_[0] =~ m/^lossperleague|^islandstring|^capitalstring|^capacitystring|^distance/; };
99 <& "lookup:formhidden", ours => $ours &>
100
101 % }
102
103 </form>
104 <%perl>
105
106 if (!$emsg && $maxdist > $maxmaxdist) {
107         $emsg= "Searching for routes of more than $maxmaxdist leagues is not".
108                 " supported, sorry.";
109 }
110
111 $emsgokorprint->($emsg) or return;
112 @islandids or return;
113 $allargs->{'submit'} or return;
114 defined $routeparams->{MaxMass} or defined $routeparams->{MaxVolume} or return;
115
116 #---------- prepare island names ----------
117
118 my $islandname_stmt= $dbh->prepare(<<END);
119         SELECT islandname, archipelago
120           FROM islands
121          WHERE islandid = ?
122 END
123
124 my $isleinfo = sub {
125         my ($id) = @_;
126         $islandname_stmt->execute($id);
127         my $row= $islandname_stmt->fetchrow_hashref();
128         local $_= $row->{'islandname'};
129         s/ Island$//;
130         return $_, $row->{'islandname'}, $row->{'archipelago'};
131 };
132
133 #---------- compute the results ----------
134
135 my @rsargs= ($concur_lim, '-DN');
136 my $concur_fail;
137
138 foreach my $k (qw(MaxMass MaxVolume MaxCapital)) {
139         my $v= $routeparams->{$k};
140         push @rsargs, (defined $v ? $v : -1);
141 }
142 push @rsargs, defined $routeparams->{LossPerLeaguePct}
143         ? $routeparams->{LossPerLeaguePct}*0.01 : 1e-9;
144 push @rsargs, '0';
145 push @rsargs, 'search',$maxdist, $maxcountea,$maxcountea;
146 push @rsargs, $ARGS{RouteSearchType} ? 'circ' : 'any';
147 push @rsargs, @islandids;
148
149 m/[^-.0-9a-zA-Z]/ and die "$_ $& ?" foreach @rsargs;
150
151 if ($qa->{'debug'}) {
152 </%perl>
153 [[ <% "@rsargs" |h %> ]]<br><pre>
154 <%perl>
155 }
156
157 unshift @rsargs,
158         'nice', sourcebasedir().'/yarrg/routesearch',
159         '-d', dbw_filename($qa->{'Ocean'}),
160         '-C', webdatadir().'/_concur.', '.lock';
161
162 # touch _concur.0{0,1,2,3,4}.lock
163 # really chgrp www-data _concur.0?.lock
164
165 my %results; # $results{$ap}{"5 6 9 10"} = { stuff }
166
167 my $fh= new IO::File;
168 my $child= $fh->open("-|"); defined $child or die $!;
169 if (!$child) {
170         my $cpu= BSD::Resource::RLIMIT_CPU;
171         my ($soft,$hard)= getrlimit($cpu);
172         setrlimit($cpu,$maxcpu,$hard) or die $! if $hard<=$maxcpu;
173         exec @rsargs;
174         die $!;
175 }
176
177 while (<$fh>) {
178         chomp;
179         if ($qa->{'debug'}) {
180 </%perl>
181 <% $_ |h %>
182 <%perl>
183         }
184         next unless m/^\s*\@/;
185         if (m/^\@\@\@ concurrency limit exceeded/) {
186                 $concur_fail= 1;
187                 last;
188         }
189         die unless m/^ \@ *\d+ ([ap])\# *\d+ \|.*\| *(\d+)lg *\| *\d+ +(\d+) +(\d+) *\| ([0-9 ]+)$/;
190         my ($ap,$isles) = (uc $1,$5);
191         next if $results{$ap} && %{$results{$ap}} >= $maxcountea;
192         my $item= { A => $3, P => $4, Leagues => $2 };
193         my (@i, @fi, @a);
194         foreach (split / /, $isles) {
195                 my ($name,$fullname,$arch)= $isleinfo->($_);
196                 push @i, $name;
197                 push @fi, $fullname;
198                 push @a, $arch unless @a && $a[-1] eq $arch;
199         }
200         $item->{Isles}= [ @i ];
201         $item->{Archs}= [ @a ];
202         $item->{Start}= $i[0];
203         $item->{Finish}= $i[-1];
204         $item->{Vias}= [ ];
205         my $i;
206         for ($i=1; $i < @i-1; $i++) {
207                 push @{ $item->{Vias} }, $i[$i];
208         }
209         my %linkqf= %$queryqf;
210         delete $linkqf{'query'};
211         $linkqf{'routestring'}= join ', ', @fi;
212         $item->{Url}= $quri->(%linkqf);
213         $item->{ArchesString}= join ', ', @a;
214         $item->{ViasString}= join ' ', map { $_.',' } @{ $item->{Vias} };
215         $item->{RouteSortString}= join ', ', @i;
216         $results{$ap}{$isles}= $item;
217 }
218
219 if ($qa->{'debug'}) {
220         print "</pre>\n";
221 }
222
223 $!=0;
224 if (!close $fh) {
225         die $! if $!;
226         die $? if $? != 24; # SIGXCPU but not in POSIX.pm :-/
227 </%perl>
228 <h2>Search took too long and was terminated</h2>
229
230 Sorry, but your query resulted in a search that took too long.
231 Searches are limited to <% $maxcpu |h %> seconds of CPU time to
232 avoid them consuming excessive resources on the server system, and to
233 make sure that shorter searches can still happen.
234
235 <p>
236 Please try a search with a smaller minimum distance, or place more
237 restrictions on the route.
238
239 <%perl>
240         return;
241 }
242
243 if ($concur_fail) {
244 </%perl>
245 <h2>Server too busy</h2>
246
247 Sorry, but there are already <% $concur_lim |h %> route searches
248 running.  We limit the number which can run at once to avoid
249 overloading the server system and to make sure that the rest of the
250 YARRG website still runs quickly.
251 <p>
252
253 If you submitted several searches and gave up on them (eg by hitting
254 `back' or `stop' in your browser), be aware that that doesn't
255 generally stop the search process at the server end.  So it's best to
256 avoid asking for large searches that you're not sure about.
257
258 <p>
259 Otherwise, please try later.  Searches are limited to <% $maxcpu |h %>
260 seconds of CPU time so more processing resources should be available soon.
261
262 <%perl>
263         return;
264 }
265
266 $someresults->();
267
268 </%perl>
269 % foreach my $ap (qw(A P)) {
270 %       if ($ap eq 'A') {
271 <h2>Best routes for total profit</h2>
272 %       } else {
273 <h2>Best routes for profit per league</h2>
274 %       }
275 <table rules=groups id="ap<% $ap %>_table">
276 <colgroup span=2>
277 <colgroup span=1>
278 <colgroup span=1>
279 <colgroup span=3>
280 <tr>
281 <th colspan=2>Profit
282 <th>Dist.
283 <th>Archipelagoes
284 <th>
285 <th>Route
286 <th>
287 <tr>
288 <th>Abs.
289 <th>Per.lg.
290 <th>
291 <th>(link to plan)
292 <th>Start
293 <th>Via
294 <th>Finish
295 <tr>
296 <tr id="ap<% $ap %>_sortrow"><th><th><th><th><th><th><th>
297 %       my $datarow=0;
298 %       my %sortkeys;
299 %       foreach my $isles (sort {
300 %                       $results{$ap}{$b}{$ap} <=>
301 %                       $results{$ap}{$a}{$ap}
302 %               } keys %{$results{$ap}}) {
303 %               my $item= $results{$ap}{$isles};
304 %               my $ci=0;
305 %               my $rowid= "r${ap}$isles"; $rowid =~ y/ /_/;
306 %               foreach my $k (qw(A P Leagues ArchesString
307 %                                 Start RouteSortString Finish)) {
308 %                       $sortkeys{$ci}{$rowid}= $item->{$k};
309 %                       $ci++;
310 %               }
311 <tr class="datarow<% $datarow %>" id="<% $rowid %>">
312 <td align=right><% $item->{A} |h %>
313 <td align=right><% $item->{P} |h %>
314 <td align=right><% $item->{Leagues} |h %>
315 <td align=left><a href="<% $item->{Url} |h %>"><%
316                   $item->{ArchesString} |h %></a>
317 <td align=left><% $item->{Start} |h %>,
318 <td align=left><% $item->{ViasString} |h %>
319 <td align=left><% $item->{Finish} |h %>
320 </td>
321 %               $datarow ^= 1;
322 %       } # $isles
323 </table>
324 <&| tabsort,    table => "ap${ap}_table", sortkeys => "ap${ap}_sortkeys",
325                 throw => "ap${ap}_sortrow", rowclass => "datarow", cols => [
326                 { DoReverse => 1, Numeric => 1 },
327                 { DoReverse => 1, Numeric => 1 },
328                 { DoReverse => 1, Numeric => 1 },
329                 { },
330                 { },
331                 { },
332                 { },
333         ] &>
334   ap<% $ap %>_sortkeys= <% to_json_protecttags(\%sortkeys) %>;
335 </&tabsort>
336 % } # $ap
337
338 <p>
339
340 <h2>Notes</h2>
341
342 Per league values count each island visited as one
343 (additional) league; the `Dist.' column is however the actual distance
344 to be sailed.  All profit figures are somewhat approximate; get a
345 complete trading plan for a route for accurate information.
346
347 <%perl>
348
349
350 </%perl>