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