Markdown
[simpleserver-moved-to-github.git] / SimpleServer.pm
1 ## This file is part of simpleserver
2 ## Copyright (C) 2000-2015 Index Data.
3 ## All rights reserved.
4 ## Redistribution and use in source and binary forms, with or without
5 ## modification, are permitted provided that the following conditions are met:
6 ##
7 ##     * Redistributions of source code must retain the above copyright
8 ##       notice, this list of conditions and the following disclaimer.
9 ##     * Redistributions in binary form must reproduce the above copyright
10 ##       notice, this list of conditions and the following disclaimer in the
11 ##       documentation and/or other materials provided with the distribution.
12 ##     * Neither the name of Index Data nor the names of its contributors
13 ##       may be used to endorse or promote products derived from this
14 ##       software without specific prior written permission.
15 ##
16 ## THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
17 ## EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 ## WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 ## DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
20 ## DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 ## (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 ## LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 ## ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 ## THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26
27 package Net::Z3950::SimpleServer;
28
29 use strict;
30 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
31 use Carp;
32
33 require Exporter;
34 require DynaLoader;
35 require AutoLoader;
36
37 @ISA = qw(Exporter AutoLoader DynaLoader);
38 @EXPORT = qw( );
39 $VERSION = '1.20';
40
41 bootstrap Net::Z3950::SimpleServer $VERSION;
42
43 # Preloaded methods go here.
44
45 my $count = 0;
46
47 sub new {
48         my $class = shift;
49         my %args = @_;
50         my $self = \%args;
51
52         if ($count) {
53                 carp "SimpleServer.pm: WARNING: Multithreaded server unsupported";
54         }
55         $count = 1;
56
57         croak "SimpleServer.pm: ERROR: Unspecified search handler" unless defined($self->{SEARCH});
58         croak "SimpleServer.pm: ERROR: Unspecified fetch handler" unless defined($self->{FETCH});
59
60         bless $self, $class;
61         return $self;
62 }
63
64
65 sub launch_server {
66         my $self = shift;
67         my @args = @_;
68
69         ### This modal internal interface, in which we set a bunch of
70         #   globals and then call start_server(), is asking for
71         #   trouble.  Instead, we should just pass the $self object
72         #   as a parameter into start_server().
73         if (defined($self->{GHANDLE})) {
74                 set_ghandle($self->{GHANDLE});
75         }
76         if (defined($self->{INIT})) {
77                 set_init_handler($self->{INIT});
78         }
79         set_search_handler($self->{SEARCH});
80         set_fetch_handler($self->{FETCH});
81         if (defined($self->{CLOSE})) {
82                 set_close_handler($self->{CLOSE});
83         }
84         if (defined($self->{PRESENT})) {
85                 set_present_handler($self->{PRESENT});
86         }
87         if (defined($self->{SCAN})) {
88                 set_scan_handler($self->{SCAN});
89         }
90         if (defined($self->{SORT})) {
91                 set_sort_handler($self->{SORT});
92         }
93         if (defined($self->{EXPLAIN})) {
94                 set_explain_handler($self->{EXPLAIN});
95         }
96         if (defined($self->{DELETE})) {
97                 set_delete_handler($self->{DELETE});
98         }
99         if (defined($self->{START})) {
100                 set_start_handler($self->{START});
101         }
102         start_server(@args);
103 }
104
105
106 # Register packages that we will use in translated RPNs
107 package Net::Z3950::RPN::Node;
108 package Net::Z3950::APDU::Query;
109 our @ISA = qw(Net::Z3950::RPN::Node);
110 package Net::Z3950::APDU::OID;
111 package Net::Z3950::RPN::And;
112 our @ISA = qw(Net::Z3950::RPN::Node);
113 package Net::Z3950::RPN::Or;
114 our @ISA = qw(Net::Z3950::RPN::Node);
115 package Net::Z3950::RPN::AndNot;
116 our @ISA = qw(Net::Z3950::RPN::Node);
117 package Net::Z3950::RPN::Prox;
118 our @ISA = qw(Net::Z3950::RPN::Node);
119 package Net::Z3950::RPN::Term;
120 our @ISA = qw(Net::Z3950::RPN::Node);
121 package Net::Z3950::RPN::RSID;
122 our @ISA = qw(Net::Z3950::RPN::Node);
123 package Net::Z3950::RPN::Attributes;
124 package Net::Z3950::RPN::Attribute;
125 package Net::Z3950::RPN::Prox::Attributes;
126 package Net::Z3950::FacetList;
127 package Net::Z3950::FacetField;
128 package Net::Z3950::FacetTerms;
129 package Net::Z3950::FacetTerm;
130
131
132 # Utility method for re-rendering Type-1 query back down to PQF
133 package Net::Z3950::RPN::Node;
134
135 sub toPQF {
136     my $this = shift();
137     my $class = ref $this;
138
139     if ($class eq "Net::Z3950::APDU::Query") {
140         my $res = "";
141         my $set = $this->{attributeSet};
142         $res .= "\@attrset $set " if defined $set;
143         return $res . $this->{query}->toPQF();
144     } elsif ($class eq "Net::Z3950::RPN::Or") {
145         return '@or ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
146     } elsif ($class eq "Net::Z3950::RPN::And") {
147         return '@and ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
148     } elsif ($class eq "Net::Z3950::RPN::AndNot") {
149         return '@not ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
150     } elsif ($class eq "Net::Z3950::RPN::Prox") {
151     my $pattrs = $this->[3];
152         return '@prox ' . $pattrs->{exclusion} . ' ' . $pattrs->{distance} . ' ' . $pattrs->{ordered} . ' ' . $pattrs->{relationType} . (defined $pattrs->{known} ? ' k ' . $pattrs->{known} : ' p ' . $pattrs->{zprivate}) . ' ' . $this->[0]->toPQF() . ' ' . $this->[1]->toPQF();
153     } elsif ($class eq "Net::Z3950::RPN::RSID") {
154         return '@set ' . $this->{id};
155     } elsif ($class ne "Net::Z3950::RPN::Term") {
156         die "unknown PQF node-type '$class'";
157     }
158
159     my $res = "";
160     foreach my $attr (@{ $this->{attributes} }) {
161         $res .= "\@attr ";
162         my $set = $attr->{attributeSet};
163         $res .= "$set " if defined $set;
164         $res .= $attr->{attributeType} . "=" . $attr->{attributeValue} . " ";
165     }
166
167     return $res . $this->{term};
168 }
169
170
171 # Must revert to original package for Autoloader's benefit
172 package Net::Z3950::SimpleServer;
173
174
175 # Autoload methods go after =cut, and are processed by the autosplit program.
176
177 1;
178 __END__
179 # Below is the stub of documentation for your module. You better edit it!
180
181 =head1 NAME
182
183 Net::Z3950::SimpleServer - Simple Perl API for building Z39.50 servers. 
184
185 =head1 SYNOPSIS
186
187   use Net::Z3950::SimpleServer;
188
189   sub my_search_handler {
190         my $args = shift;
191
192         my $set_id = $args->{SETNAME};
193         my @database_list = @{ $args->{DATABASES} };
194         my $query = $args->{QUERY};
195
196         ## Perform the query on the specified set of databases
197         ## and return the number of hits:
198
199         $args->{HITS} = $hits;
200   }
201
202   sub my_fetch_handler {        # Get a record for the user
203         my $args = shift;
204
205         my $set_id = $args->{SETNAME};
206
207         my $record = fetch_a_record($args->{OFFSET});
208
209         $args->{RECORD} = $record;
210         if (number_of_hits() == $args->{OFFSET}) {      ## Last record in set?
211                 $args->{LAST} = 1;
212         } else {
213                 $args->{LAST} = 0;
214         }
215   }
216
217   ## Register custom event handlers:
218   my $z = new Net::Z3950::SimpleServer(GHANDLE = $someObject,
219                                        INIT   =>  \&my_init_handler,
220                                        CLOSE  =>  \&my_close_handler,
221                                        SEARCH =>  \&my_search_handler,
222                                        FETCH  =>  \&my_fetch_handler);
223
224   ## Launch server:
225   $z->launch_server("ztest.pl", @ARGV);
226
227 =head1 DESCRIPTION
228
229 The SimpleServer module is a tool for constructing Z39.50 "Information
230 Retrieval" servers in Perl. The module is easy to use, but it
231 does help to have an understanding of the Z39.50 query
232 structure and the construction of structured retrieval records.
233
234 Z39.50 is a network protocol for searching remote databases and
235 retrieving the results in the form of structured "records". It is widely
236 used in libraries around the world, as well as in the US Federal Government.
237 In addition, it is generally useful whenever you wish to integrate a number
238 of different database systems around a shared, abstract data model.
239
240 The model of the module is simple: It implements a "generic" Z39.50
241 server, which invokes callback functions supplied by you to search
242 for content in your database. You can use any tools available in
243 Perl to supply the content, including modules like DBI and
244 WWW::Search.
245
246 The server will take care of managing the network connections for
247 you, and it will spawn a new process (or thread, in some
248 environments) whenever a new connection is received.
249
250 The programmer can specify subroutines to take care of the following type
251 of events:
252
253   - Start service (called once).
254   - Initialize request
255   - Search request
256   - Present request
257   - Fetching of records
258   - Scan request (browsing) 
259   - Closing down connection
260
261 Note that only the Search and Fetch handler functions are required.
262 The module can supply default responses to the other on its own.
263
264 After the launching of the server, all control is given away from
265 the Perl script to the server. The server calls the registered
266 subroutines to field incoming requests from Z39.50 clients.
267
268 A reference to an anonymous hash is passed to each handler. Some of
269 the entries of these hashes are to be considered input and others
270 output parameters.
271
272 The Perl programmer specifies the event handlers for the server by
273 means of the SimpleServer object constructor
274
275   my $z = new Net::Z3950::SimpleServer(
276                         START   =>      \&my_start_handler,
277                         INIT    =>      \&my_init_handler,
278                         CLOSE   =>      \&my_close_handler,
279                         SEARCH  =>      \&my_search_handler,
280                         PRESENT =>      \&my_present_handler,
281                         SCAN    =>      \&my_scan_handler,
282                         FETCH   =>      \&my_fetch_handler,
283                         EXPLAIN =>      \&my_explain_handler,
284                         DELETE  =>      \&my_delete_handler,
285                         SORT    =>      \&my_sort_handler);
286
287 In addition, the arguments to the constructor may include GHANDLE, a
288 global handle which is made available to each invocation of every
289 callback function.  This is typically a reference to either a hash or
290 an object.
291
292 If you want your SimpleServer to start a thread (threaded mode) to
293 handle each incoming Z39.50 request instead of forking a process
294 (forking mode), you need to register the handlers by symbol rather
295 than by code reference. Thus, in threaded mode, you will need to
296 register your handlers this way:
297
298   my $z = new Net::Z3950::SimpleServer(
299                         INIT    =>      "my_package::my_init_handler",
300                         CLOSE   =>      "my_package::my_close_handler",
301                         ....
302                         ....          );
303
304 where my_package is the Perl package in which your handler is
305 located.
306
307 After the custom event handlers are declared, the server is launched
308 by means of the method
309
310   $z->launch_server("MyServer.pl", @ARGV);
311
312 Notice, the first argument should be the name of your server
313 script (for logging purposes), while the rest of the arguments
314 are documented in the YAZ toolkit manual: The section on
315 application invocation: <http://indexdata.com/yaz/doc/server.invocation.tkl>
316
317 In particular, you need to use the -T switch to start your SimpleServer
318 in threaded mode.
319
320 =head2 Start handler
321
322 The start handler is called when service is started. The argument hash
323 passed to the start handler has the form
324
325   $args = {
326              CONFIG =>  "default-config" ## GFS config (as given by -c)
327           };
328
329
330 The purpose of the start handler is to read the configuration file
331 for the Generic Frontend Server . This is specified by option -c.
332 If -c is omitted, the configuration file is set to "default-config".
333
334 The start handler is optional. It is supported in Simpleserver 1.16 and
335 later.
336
337 =head2 Init handler
338
339 The init handler is called whenever a Z39.50 client is attempting
340 to logon to the server. The exchange of parameters between the
341 server and the handler is carried out via an anonymous hash reached
342 by a reference, i.e.
343
344   $args = shift;
345
346 The argument hash passed to the init handler has the form
347
348   $args = {
349                                     ## Response parameters:
350
351              PEER_NAME =>  "",      ## Name or IP address of connecting client
352              IMP_ID    =>  "",      ## Z39.50 Implementation ID
353              IMP_NAME  =>  "",      ## Z39.50 Implementation name
354              IMP_VER   =>  "",      ## Z39.50 Implementation version
355              ERR_CODE  =>  0,       ## Error code, cnf. Z39.50 manual
356              ERR_STR   =>  "",      ## Error string (additional info.)
357              USER      =>  "xxx"    ## If Z39.50 authentication is used,
358                                     ## this member contains user name
359              PASS      =>  "yyy"    ## Under same conditions, this member
360                                     ## contains the password in clear text
361              GHANDLE   =>  $obj     ## Global handler specified at creation
362              HANDLE    =>  undef    ## Handler of Perl data structure
363           };
364
365 The HANDLE member can be used to store any scalar value which will then
366 be provided as input to all subsequent calls (ie. for searching, record
367 retrieval, etc.). A common use of the handle is to store a reference to
368 a hash which may then be used to store session-specific parameters.
369 If you have any session-specific information (such as a list of
370 result sets or a handle to a back-end search engine of some sort),
371 it is always best to store them in a private session structure -
372 rather than leaving them in global variables in your script.
373
374 The Implementation ID, name and version are only really used by Z39.50
375 client developers to see what kind of server they're dealing with.
376 Filling these in is optional.
377
378 The ERR_CODE should be left at 0 (the default value) if you wish to
379 accept the connection. Any other value is interpreted as a failure
380 and the client will be shown the door, with the code and the
381 associated additional information, ERR_STR returned.
382
383 =head2 Search handler
384
385 Similarly, the search handler is called with a reference to an anony-
386 mous hash. The structure is the following:
387
388   $args = {
389                                     ## Request parameters:
390
391              GHANDLE   =>  $obj     ## Global handler specified at creation
392              HANDLE    =>  ref,     ## Your session reference.
393              SETNAME   =>  "id",    ## ID of the result set
394              REPL_SET  =>  0,       ## Replace set if already existing?
395              DATABASES =>  ["xxx"], ## Reference to a list of data-
396                                     ## bases to search
397              QUERY     =>  "query", ## The query expression
398              RPN       =>  $obj,    ## Reference to a Net::Z3950::APDU::Query
399
400                                     ## Response parameters:
401
402              ERR_CODE  =>  0,       ## Error code (0=Successful search)
403              ERR_STR   =>  "",      ## Error string
404              HITS      =>  0        ## Number of matches
405           };
406
407 Note that a search which finds 0 hits is considered successful in
408 Z39.50 terms - you should only set the ERR_CODE to a non-zero value
409 if there was a problem processing the request. The Z39.50 standard
410 provides a comprehensive list of standard diagnostic codes, and you
411 should use these whenever possible.
412
413 The QUERY is a tree-structure of terms combined by operators, the
414 terms being qualified by lists of attributes. The query is presented
415 to the search function in the Prefix Query Format (PQF) which is
416 used in many applications based on the YAZ toolkit. The full grammar
417 is described in the YAZ manual.
418
419 The following are all examples of valid queries in the PQF. 
420
421         dylan
422
423         "bob dylan"
424
425         @or "dylan" "zimmerman"
426
427         @set Result-1
428
429         @or @and bob dylan @set Result-1
430
431         @and @attr 1=1 "bob dylan" @attr 1=4 "slow train coming"
432
433         @attrset @attr 4=1 @attr 1=4 "self portrait"
434
435 You will need to write a recursive function or something similar to
436 parse incoming query expressions, and this is usually where a lot of
437 the work in writing a database-backend happens. Fortunately, you don't
438 need to support anymore functionality than you want to. For instance,
439 it is perfectly legal to not accept boolean operators, but you SHOULD
440 try to return good error codes if you run into something you can't or
441 won't support.
442
443 A more convenient alternative to the QUERY member may be the RPN
444 member, which is a reference to a Net::Z3950::APDU::Query object
445 representing the RPN query tree.  The structure of that object is
446 supposed to be self-documenting, but here's a brief summary of what
447 you get:
448
449 =over 4
450
451 =item *
452
453 C<Net::Z3950::APDU::Query> is a hash with two fields:
454
455 Z<>
456
457 =over 4
458
459 =item C<attributeSet>
460
461 Optional.  If present, it is a reference to a
462 C<Net::Z3950::APDU::OID>.  This is a string of dot-separated integers
463 representing the OID of the query's top-level attribute set.
464
465 =item C<query>
466
467 Mandatory: a reference to the RPN tree itself.
468
469 =back
470
471 =item *
472
473 Each node of the tree is an object of one of the following types:
474
475 Z<>
476
477 =over 4
478
479 =item C<Net::Z3950::RPN::And>
480
481 =item C<Net::Z3950::RPN::Or>
482
483 =item C<Net::Z3950::RPN::AndNot>
484
485 These three classes are all arrays of two elements, each of which is a
486 node of one of the above types.
487
488 =item C<Net::Z3950::RPN::Term>
489
490 See below for details.
491
492 =item C<Net::Z3950::RPN::RSID>
493
494 A reference to a result-set ID indicating a previous search.  The ID
495 of the result-set is in the C<id> element.
496
497 =back
498
499 =back
500
501 =over 4
502
503 =item *
504
505 C<Net::Z3950::RPN::Term> is a hash with two fields:
506
507 Z<>
508
509 =over 4
510
511 =item C<term>
512
513 A string containing the search term itself.
514
515 =item C<attributes>
516
517 A reference to a C<Net::Z3950::RPN::Attributes> object.
518
519 =back
520
521 =item *
522
523 C<Net::Z3950::RPN::Attributes> is an array of references to
524 C<Net::Z3950::RPN::Attribute> objects.  (Note the plural/singular
525 distinction.)
526
527 =item *
528
529 C<Net::Z3950::RPN::Attribute> is a hash with three elements:
530
531 Z<>
532
533 =over 4
534
535 =item C<attributeSet>
536
537 Optional.  If present, it is dot-separated OID string, as above.
538
539 =item C<attributeType>
540
541 An integer indicating the type of the attribute - for example, under
542 the BIB-1 attribute set, type 1 indicates a ``use'' attribute, type 2
543 a ``relation'' attribute, etc.
544
545 =item C<attributeValue>
546
547 An integer or string indicating the value of the attribute - for example, under
548 BIB-1, if the attribute type is 1, then value 4 indicates a title
549 search and 7 indicates an ISBN search; but if the attribute type is
550 2, then value 4 indicates a ``greater than or equal'' search, and 102
551 indicates a relevance match.
552
553 =back
554
555 =back
556
557 All of these classes except C<Attributes> and C<Attribute> are
558 subclasses of the abstract class C<Net::Z3950::RPN::Node>.  That class
559 has a single method, C<toPQF()>, which may be used to turn an RPN
560 tree, or part of one, back into a textual prefix query.
561
562 Note that, apart to C<toPQF()>, none of these classes have any methods at
563 all: the blessing into classes is largely just a documentation thing
564 so that, for example, if you do
565
566         { use Data::Dumper; print Dumper($args->{RPN}) }
567
568 you get something fairly human-readable.  But of course, the type
569 distinction between the three different kinds of boolean node is
570 important.
571
572 By adding your own methods to these classes (building what I call
573 ``augmented classes''), you can easily build code that walks the tree
574 of the incoming RPN.  Take a look at C<samples/render-search.pl> for a
575 sample implementation of such an augmented classes technique.
576
577
578 =head2 Present handler
579
580 The presence of a present handler in a SimpleServer front-end is optional.
581 Each time a client wishes to retrieve records, the present service is
582 called. The present service allows the origin to request a certain number
583 of records retrieved from a given result set.
584 When the present handler is called, the front-end server should prepare a
585 result set for fetching. In practice, this means to get access to the
586 data from the backend database and store the data in a temporary fashion
587 for fast and efficient fetching. The present handler does *not* fetch
588 anything. This task is taken care of by the fetch handler, which will be
589 called the correct number of times by the YAZ library. More about this
590 below.
591 If no present handler is implemented in the front-end, the YAZ toolkit
592 will take care of a minimum of preparations itself. This default present
593 handler is sufficient in many situations, where only a small amount of
594 records are expected to be retrieved. If on the other hand, large result
595 sets are likely to occur, the implementation of a reasonable present
596 handler can gain performance significantly.
597
598 The information exchanged between client and present handle is:
599
600   $args = {
601                                     ## Client/server request:
602
603              GHANDLE   =>  $obj     ## Global handler specified at creation
604              HANDLE    =>  ref,     ## Reference to datastructure
605              SETNAME   =>  "id",    ## Result set ID
606              START     =>  xxx,     ## Start position
607              COMP      =>  "",      ## Desired record composition
608              NUMBER    =>  yyy,     ## Number of requested records
609
610
611                                     ## Response parameters:
612
613              HITS      =>  zzz,     ## Number of returned records
614              ERR_CODE  =>  0,       ## Error code
615              ERR_STR   =>  ""       ## Error message
616           };
617
618
619 =head2 Fetch handler
620
621 The fetch handler is asked to retrieve a SINGLE record from a given
622 result set (the front-end server will automatically call the fetch
623 handler as many times as required).
624
625 The parameters exchanged between the server and the fetch handler are
626
627   $args = {
628                                     ## Client/server request:
629
630              GHANDLE   =>  $obj     ## Global handler specified at creation
631              HANDLE    =>  ref      ## Reference to data structure
632              SETNAME   =>  "id"     ## ID of the requested result set
633              OFFSET    =>  nnn      ## Record offset number
634              REQ_FORM  =>  "n.m.k.l"## Client requested format OID
635              COMP      =>  "xyz"    ## Formatting instructions
636              SCHEMA    =>  "abc"    ## Requested schema, if any
637
638                                     ## Handler response:
639
640              RECORD    =>  ""       ## Record string
641              BASENAME  =>  ""       ## Origin of returned record
642              LAST      =>  0        ## Last record in set?
643              ERR_CODE  =>  0        ## Error code
644              ERR_STR   =>  ""       ## Error string
645              SUR_FLAG  =>  0        ## Surrogate diagnostic flag
646              REP_FORM  =>  "n.m.k.l"## Provided format OID
647              SCHEMA    =>  "abc"    ## Provided schema, if any
648           };
649
650 The REP_FORM value has by default the REQ_FORM value but can be set to
651 something different if the handler desires. The BASENAME value should
652 contain the name of the database from where the returned record originates.
653 The ERR_CODE and ERR_STR works the same way they do in the search
654 handler. If there is an error condition, the SUR_FLAG is used to
655 indicate whether the error condition pertains to the record currently
656 being retrieved, or whether it pertains to the operation as a whole
657 (eg. the client has specified a result set which does not exist.)
658
659 If you need to return USMARC records, you might want to have a look at
660 the MARC module on CPAN, if you don't already have a way of generating
661 these.
662
663 NOTE: The record offset is 1-indexed - 1 is the offset of the first
664 record in the set.
665
666 =head2 Scan handler
667
668 A full featured Z39.50 server should support scan (or in some literature
669 browse). The client specifies a starting term of the scan, and the server
670 should return an ordered list of specified length consisting of terms
671 actually occurring in the data base. Each of these terms should be close
672 to or equal to the term originally specified. The quality of scan compared
673 to simple search is a guarantee of hits. It is simply like browsing through
674 an index of a book, you always find something! The parameters exchanged are
675
676   $args = {
677                                                 ## Client request
678
679                 GHANDLE         => $obj,        ## Global handler specified at creation
680                 HANDLE          => $ref,        ## Reference to data structure
681                 DATABASES       => ["xxx"],     ## Reference to a list of data-
682                                                 ## bases to search
683                 TERM            => 'start',     ## The start term
684                 RPN             =>  $obj,       ## Reference to a Net::Z3950::RPN::Term
685
686                 NUMBER          => xx,          ## Number of requested terms
687                 POS             => yy,          ## Position of starting point
688                                                 ## within returned list
689                 STEP            => 0,           ## Step size
690
691                                                 ## Server response
692
693                 ERR_CODE        => 0,           ## Error code
694                 ERR_STR         => '',          ## Diagnostic message
695                 NUMBER          => zz,          ## Number of returned terms
696                 STATUS          => $status,     ## ScanSuccess/ScanFailure
697                 ENTRIES         => $entries     ## Referenced list of terms
698         };
699
700 where the term list is returned by reference in the scalar $entries, which
701 should point at a data structure of this kind,
702
703   my $entries = [
704                         {       TERM            => 'energy',
705                                 OCCURRENCE      => 5            },
706
707                         {       TERM            => 'energy density',
708                                 OCCURRENCE      => 6,           },
709
710                         {       TERM            => 'energy flow',
711                                 OCCURRENCE      => 3            },
712
713                                 ...
714
715                                 ...
716         ];
717
718 The $status flag is only meaningful after a successful scan, and
719 should be assigned one of two values:
720
721   Net::Z3950::SimpleServer::ScanSuccess  Full success (default)
722   Net::Z3950::SimpleServer::ScanPartial  Fewer terms returned than requested
723
724 The STEP member contains the requested number of entries in the term-list
725 between two adjacent entries in the response.
726
727 A better alternative to the TERM member is the the RPN
728 member, which is a reference to a Net::Z3950::RPN::Term object
729 representing the scan clause.  The structure of that object is the
730 same as for Term objects included as part of the RPN tree passed to
731 search handlers.  This is more useful than the simple TERM because it
732 includes attributes (e.g. access points associated with the term),
733 which are discarded by the TERM element.
734
735 =head2 Close handler
736
737 The argument hash received by the close handler has two elements only:
738
739   $args = {
740                                     ## Server provides:
741
742              GHANDLE   =>  $obj     ## Global handler specified at creation
743              HANDLE    =>  ref      ## Reference to data structure
744           };
745
746 What ever data structure the HANDLE value points at goes out of scope
747 after this call. If you need to close down a connection to your server
748 or something similar, this is the place to do it.
749
750 =head2 Delete handler
751
752 The argument hash received by the delete handler has the following elements:
753
754   $args = {
755                                     ## Client request:
756              GHANDLE   =>  $obj,    ## Global handler specified at creation
757              HANDLE    =>  ref,     ## Reference to data structure
758              SETNAME   =>  "id",    ## Result set ID
759
760                                     ## Server response:
761              STATUS    => 0         ## Deletion status
762           };
763
764 The SETNAME element of the argument hash may or may not be defined.
765 If it is, then SETNAME is the name of a result set to be deleted; if
766 not, then all result-sets associated with the current session should
767 be deleted.  In either case, the callback function should report on
768 success or failure by setting the STATUS element either to zero, on
769 success, or to an integer from 1 to 10, to indicate one of the ten
770 possible failure codes described in section 3.2.4.1.4 of the Z39.50
771 standard -- see 
772 http://www.loc.gov/z3950/agency/markup/05.html#Delete-list-statuses1
773
774 =head2 Sort handler
775
776 The argument hash received by the sort handler has the following elements:
777
778         $args = {
779                                         ## Client request:
780                 GHANDLE => $obj,        ## Global handler specified at creation
781                 HANDLE => ref,          ## Reference to data structure
782                 INPUT => [ a, b ... ],  ## Names of result-sets to sort
783                 OUTPUT => "name",       ## Name of result-set to sort into
784                 SEQUENCE                ## Sort specification: see below
785
786                                         ## Server response:
787                 STATUS => 0,            ## Success, Partial or Failure
788                 ERR_CODE => 0,          ## Error code
789                 ERR_STR => '',          ## Diagnostic message
790
791         };
792
793 The SEQUENCE element is a reference to an array, each element of which
794 is a hash representing a sort key.  Each hash contains the following
795 elements:
796
797 =over 4
798
799 =item RELATION
800
801 0 for an ascending sort, 1 for descending, 3 for ascending by
802 frequency, or 4 for descending by frequency.
803
804 =item CASE
805
806 0 for a case-sensitive sort, 1 for case-insensitive
807
808 =item MISSING
809
810 How to respond if one or more records in the set to be sorted are
811 missing the fields indicated in the sort specification.  1 to abort
812 the sort, 2 to use a "null value", 3 if a value is provided to use in
813 place of the missing data (although in the latter case, the actual
814 value to use is currently not made available, so this is useless).
815
816 =back
817
818 And one or other of the following:
819
820 =over 4
821
822 =item SORTFIELD
823
824 A string indicating the field to be sorted, which the server may
825 interpret as it sees fit (presumably by an out-of-band agreement with
826 the client).
827
828 =item ELEMENTSPEC_TYPE and ELEMENTSPEC_VALUE
829
830 I have no idea what this is.
831
832 =item ATTRSET and SORT_ATTR
833
834 ATTRSET is the attribute set from which the attributes are taken, and
835 SORT_ATTR is a reference to an array containing the attributes
836 themselves.  Each attribute is represented by (are you following this
837 carefully?) yet another hash, this one containing the elements
838 ATTR_TYPE and ATTR_VALUE: for example, type=1 and value=4 in the BIB-1
839 attribute set would indicate access-point 4 which is title, so that a
840 sort of title is requested.
841
842 =back
843
844 Precisely why all of the above is so is not clear, but goes some way
845 to explain why, in the Z39.50 world, the developers of the standard
846 are not so much worshiped as blamed.
847
848 The backend function should set STATUS to 0 on success, 1 for "partial
849 success" (don't ask) or 2 on failure, in which case ERR_CODE and
850 ERR_STR should be set.
851
852 =head2 Support for SRU and SRW
853
854 Since release 1.0, SimpleServer includes support for serving the SRU
855 and SRW protocols as well as Z39.50.  These ``web-friendly'' protocols
856 enable similar functionality to that of Z39.50, but by means of rich
857 URLs in the case of SRU, and a SOAP-based web-service in the case of
858 SRW.  These protocols are described at
859 http://www.loc.gov/sru
860
861 In order to serve these protocols from a SimpleServer-based
862 application, it is necessary to launch the application with a YAZ
863 Generic Frontend Server (GFS) configuration file, which can be
864 specified using the command-line argument C<-f> I<filename>.  A
865 minimal configuration file looks like this:
866
867   <yazgfs>
868     <server>
869       <cql2rpn>pqf.properties</cql2rpn>
870     </server>
871   </yazgfs>
872
873 This file specifies only that C<pqf.properties> should be used to
874 translate the CQL queries of SRU and SRW into corresponding Z39.50
875 Type-1 queries.  For more information about YAZ GFS configuration,
876 including how to specify an Explain record, see the I<Virtual Hosts>
877 section of the YAZ manual at
878 http://indexdata.com/yaz/doc/server.vhosts.tkl
879
880 The mapping of CQL queries into Z39.50 Type-1 queries is specified by
881 a file that indicates which BIB-1 attributes should be generated for
882 each CQL index, relation, modifiers, etc.  A typical section of this
883 file looks like this:
884
885   index.dc.title                        = 1=4
886   index.dc.subject                      = 1=21
887   index.dc.creator                      = 1=1003
888   relation.<                            = 2=1
889   relation.le                           = 2=2
890
891 This file specifies the BIB-1 access points (type=1) for the Dublin
892 Core indexes C<title>, C<subject> and C<creator>, and the BIB-1
893 relations (type=2) corresponding to the CQL relations C<E<lt>> and
894 C<E<lt>=>.  For more information about the format of this file, see
895 the I<CQL> section of the YAZ manual at
896 http://indexdata.com/yaz/doc/tools.tkl#tools.cql
897
898 The YAZ distribution include a sample CQL-to-PQF mapping configuration
899 file called C<pqf.properties>; this is sufficient for many
900 applications, and a good base to work from for most others.
901
902 If a SimpleServer-based application is run without this SRU-specific
903 configuration, it can still serve SRU; however, CQL queries will not
904 be translated, but passed straight through to the search-handler
905 function, as the C<CQL> member of the parameters hash.  It is then the
906 responsibility of the back-end application to parse and handle the CQL
907 query, which is most easily done using Ed Summers' fine C<CQL::Parser>
908 module, available from CPAN at
909 http://search.cpan.org/~esummers/CQL-Parser/
910
911 =head1 AUTHORS
912
913 Anders Sønderberg (sondberg@indexdata.dk),
914 Sebastian Hammer (quinn@indexdata.dk),
915 Mike Taylor (indexdata.com).
916
917 =head1 COPYRIGHT AND LICENCE
918
919 Copyright (C) 2000-2015 by Index Data.
920
921 This library is free software; you can redistribute it and/or modify
922 it under the same terms as Perl itself, either Perl version 5.8.4 or,
923 at your option, any later version of Perl 5 you may have available.
924
925 =head1 SEE ALSO
926
927 Any Perl module which is useful for accessing the data source of your
928 choice.
929
930 =cut