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