Registering the bend_sort handler and implemented the missing bits and pieces.
[simpleserver-moved-to-github.git] / SimpleServer.pm
1 ##
2 ##  Copyright (c) 2000-2004, Index Data.
3 ##
4 ##  Permission to use, copy, modify, distribute, and sell this software and
5 ##  its documentation, in whole or in part, for any purpose, is hereby granted,
6 ##  provided that:
7 ##
8 ##  1. This copyright and permission notice appear in all copies of the
9 ##  software and its documentation. Notices of copyright or attribution
10 ##  which appear at the beginning of any file must remain unchanged.
11 ##
12 ##  2. The name of Index Data or the individual authors may not be used to
13 ##  endorse or promote products derived from this software without specific
14 ##  prior written permission.
15 ##
16 ##  THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTY OF ANY KIND,
17 ##  EXPRESS, IMPLIED, OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
18 ##  WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
19 ##  IN NO EVENT SHALL INDEX DATA BE LIABLE FOR ANY SPECIAL, INCIDENTAL,
20 ##  INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES
21 ##  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR
22 ##  NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 ##  LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 ##  OF THIS SOFTWARE.
25 ##
26 ##
27
28 ## $Id: SimpleServer.pm,v 1.26 2006-04-19 13:17:52 sondberg Exp $
29
30 package Net::Z3950::SimpleServer;
31
32 use strict;
33 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK);
34 use Carp;
35
36 require Exporter;
37 require DynaLoader;
38 require AutoLoader;
39
40 @ISA = qw(Exporter AutoLoader DynaLoader);
41 @EXPORT = qw( );
42 $VERSION = '1.02';
43
44 bootstrap Net::Z3950::SimpleServer $VERSION;
45
46 # Preloaded methods go here.
47
48 my $count = 0;
49
50 sub new {
51         my $class = shift;
52         my %args = @_;
53         my $self = \%args;
54
55         if ($count) {
56                 carp "SimpleServer.pm: WARNING: Multithreaded server unsupported";
57         }
58         $count = 1;
59
60         croak "SimpleServer.pm: ERROR: Unspecified search handler" unless defined($self->{SEARCH});
61         croak "SimpleServer.pm: ERROR: Unspecified fetch handler" unless defined($self->{FETCH});
62
63         bless $self, $class;
64         return $self;
65 }
66
67
68 sub launch_server {
69         my $self = shift;
70         my @args = @_;
71
72         if (defined($self->{INIT})) {
73                 set_init_handler($self->{INIT});
74         }
75         set_search_handler($self->{SEARCH});
76         set_fetch_handler($self->{FETCH});
77         if (defined($self->{CLOSE})) {
78                 set_close_handler($self->{CLOSE});
79         }
80         if (defined($self->{PRESENT})) {
81                 set_present_handler($self->{PRESENT});
82         }
83         if (defined($self->{SCAN})) {
84                 set_scan_handler($self->{SCAN});
85         }
86         if (defined($self->{SORT})) {
87                 set_sort_handler($self->{SORT});
88         }
89
90         start_server(@args);
91 }
92
93
94 # Register packages that we will use in translated RPNs
95 package Net::Z3950::APDU::Query;
96 package Net::Z3950::APDU::OID;
97 package Net::Z3950::RPN::And;
98 package Net::Z3950::RPN::Or;
99 package Net::Z3950::RPN::AndNot;
100 package Net::Z3950::RPN::Term;
101 package Net::Z3950::RPN::RSID;
102 package Net::Z3950::RPN::Attributes;
103 package Net::Z3950::RPN::Attribute;
104
105 # Must revert to original package for Autoloader's benefit
106 package Net::Z3950::SimpleServer;
107
108
109 # Autoload methods go after =cut, and are processed by the autosplit program.
110
111 1;
112 __END__
113 # Below is the stub of documentation for your module. You better edit it!
114
115 =head1 NAME
116
117 Net::Z3950::SimpleServer - Simple Perl API for building Z39.50 servers. 
118
119 =head1 SYNOPSIS
120
121   use Net::Z3950::SimpleServer;
122
123   sub my_search_handler {
124         my $args = shift;
125
126         my $set_id = $args->{SETNAME};
127         my @database_list = @{ $args->{DATABASES} };
128         my $query = $args->{QUERY};
129
130         ## Perform the query on the specified set of databases
131         ## and return the number of hits:
132
133         $args->{HITS} = $hits;
134   }
135
136   sub my_fetch_handler {        # Get a record for the user
137         my $args = shift;
138
139         my $set_id = $args->{SETNAME};
140
141         my $record = fetch_a_record($args->{OFFSET});
142
143         $args->{RECORD} = $record;
144         if (number_of_hits() == $args->{OFFSET}) {      ## Last record in set?
145                 $args->{LAST} = 1;
146         } else {
147                 $args->{LAST} = 0;
148         }
149   }
150
151
152   ## Register custom event handlers:
153
154   my $z = new Net::Z3950::SimpleServer(         INIT   =>  \&my_init_handler,
155                                                 CLOSE  =>  \&my_close_handler,
156                                                 SEARCH =>  \&my_search_handler,
157                                                 FETCH  =>  \&my_fetch_handler);
158   ## Launch server:
159
160   $z->launch_server("ztest.pl", @ARGV);
161
162 =head1 DESCRIPTION
163
164 The SimpleServer module is a tool for constructing Z39.50 "Information
165 Retrieval" servers in Perl. The module is easy to use, but it
166 does help to have an understanding of the Z39.50 query
167 structure and the construction of structured retrieval records.
168
169 Z39.50 is a network protocol for searching remote databases and
170 retrieving the results in the form of structured "records". It is widely
171 used in libraries around the world, as well as in the US Federal Government.
172 In addition, it is generally useful whenever you wish to integrate a number
173 of different database systems around a shared, asbtract data model.
174
175 The model of the module is simple: It implements a "generic" Z39.50
176 server, which invokes callback functions supplied by you to search
177 for content in your database. You can use any tools available in
178 Perl to supply the content, including modules like DBI and
179 WWW::Search.
180
181 The server will take care of managing the network connections for
182 you, and it will spawn a new process (or thread, in some
183 environments) whenever a new connection is received.
184
185 The programmer can specify subroutines to take care of the following type
186 of events:
187
188   - Initialize request
189   - Search request
190   - Present request
191   - Fetching of records
192   - Scan request (browsing) 
193   - Closing down connection
194
195 Note that only the Search and Fetch handler functions are required.
196 The module can supply default responses to the other on its own.
197
198 After the launching of the server, all control is given away from
199 the Perl script to the server. The server calls the registered
200 subroutines to field incoming requests from Z39.50 clients.
201
202 A reference to an anonymous hash is passed to each handler. Some of
203 the entries of these hashes are to be considered input and others
204 output parameters.
205
206 The Perl programmer specifies the event handlers for the server by
207 means of the SimpleServer object constructor
208
209   my $z = new Net::Z3950::SimpleServer(
210                         INIT    =>      \&my_init_handler,
211                         CLOSE   =>      \&my_close_handler,
212                         SEARCH  =>      \&my_search_handler,
213                         PRESENT =>      \&my_present_handler,
214                         SCAN    =>      \&my_scan_handler,
215                         FETCH   =>      \&my_fetch_handler);
216
217 If you want your SimpleServer to start a thread (threaded mode) to
218 handle each incoming Z39.50 request instead of forking a process
219 (forking mode), you need to register the handlers by symbol rather
220 than by code reference. Thus, in threaded mode, you will need to
221 register your handlers this way:
222
223   my $z = new Net::Z3950::SimpleServer(
224                         INIT    =>      "my_package::my_init_handler",
225                         CLOSE   =>      "my_package::my_close_handler",
226                         ....
227                         ....          );
228
229 where my_package is the Perl package in which your handler is
230 located.
231
232 After the custom event handlers are declared, the server is launched
233 by means of the method
234
235   $z->launch_server("MyServer.pl", @ARGV);
236
237 Notice, the first argument should be the name of your server
238 script (for logging purposes), while the rest of the arguments
239 are documented in the YAZ toolkit manual: The section on
240 application invocation: <http://www.indexdata.dk/yaz/yaz-7.php>
241
242 In particular, you need to use the -T switch to start your SimpleServer
243 in threaded mode.
244
245 =head2 Init handler
246
247 The init handler is called whenever a Z39.50 client is attempting
248 to logon to the server. The exchange of parameters between the
249 server and the handler is carried out via an anonymous hash reached
250 by a reference, i.e.
251
252   $args = shift;
253
254 The argument hash passed to the init handler has the form
255
256   $args = {
257                                     ## Response parameters:
258
259              IMP_ID    =>  "",      ## Z39.50 Implementation ID
260              IMP_NAME  =>  "",      ## Z39.50 Implementation name
261              IMP_VER   =>  "",      ## Z39.50 Implementation version
262              ERR_CODE  =>  0,       ## Error code, cnf. Z39.50 manual
263              ERR_STR   =>  "",      ## Error string (additional info.)
264              USER      =>  "xxx"    ## If Z39.50 authentication is used,
265                                     ## this member contains user name
266              PASS      =>  "yyy"    ## Under same conditions, this member
267                                     ## contains the password in clear text
268              HANDLE    =>  undef    ## Handler of Perl data structure
269           };
270
271 The HANDLE member can be used to store any scalar value which will then
272 be provided as input to all subsequent calls (ie. for searching, record
273 retrieval, etc.). A common use of the handle is to store a reference to
274 a hash which may then be used to store session-specific parameters.
275 If you have any session-specific information (such as a list of
276 result sets or a handle to a back-end search engine of some sort),
277 it is always best to store them in a private session structure -
278 rather than leaving them in global variables in your script.
279
280 The Implementation ID, name and version are only really used by Z39.50
281 client developers to see what kind of server they're dealing with.
282 Filling these in is optional.
283
284 The ERR_CODE should be left at 0 (the default value) if you wish to
285 accept the connection. Any other value is interpreted as a failure
286 and the client will be shown the door, with the code and the
287 associated additional information, ERR_STR returned.
288
289 =head2 Search handler
290
291 Similarly, the search handler is called with a reference to an anony-
292 mous hash. The structure is the following:
293
294   $args = {
295                                     ## Request parameters:
296
297              HANDLE    =>  ref,     ## Your session reference.
298              SETNAME   =>  "id",    ## ID of the result set
299              REPL_SET  =>  0,       ## Replace set if already existing?
300              DATABASES =>  ["xxx"], ## Reference to a list of data-
301                                     ## bases to search
302              QUERY     =>  "query", ## The query expression
303              RPN       =>  $obj,    ## Reference to a Net::Z3950::APDU::Query
304
305                                     ## Response parameters:
306
307              ERR_CODE  =>  0,       ## Error code (0=Succesful search)
308              ERR_STR   =>  "",      ## Error string
309              HITS      =>  0        ## Number of matches
310           };
311
312 Note that a search which finds 0 hits is considered successful in
313 Z39.50 terms - you should only set the ERR_CODE to a non-zero value
314 if there was a problem processing the request. The Z39.50 standard
315 provides a comprehensive list of standard diagnostic codes, and you
316 should use these whenever possible.
317
318 The QUERY is a tree-structure of terms combined by operators, the
319 terms being qualified by lists of attributes. The query is presented
320 to the search function in the Prefix Query Format (PQF) which is
321 used in many applications based on the YAZ toolkit. The full grammar
322 is described in the YAZ manual.
323
324 The following are all examples of valid queries in the PQF. 
325
326         dylan
327
328         "bob dylan"
329
330         @or "dylan" "zimmerman"
331
332         @set Result-1
333
334         @or @and bob dylan @set Result-1
335
336         @and @attr 1=1 "bob dylan" @attr 1=4 "slow train coming"
337
338         @attrset @attr 4=1 @attr 1=4 "self portrait"
339
340 You will need to write a recursive function or something similar to
341 parse incoming query expressions, and this is usually where a lot of
342 the work in writing a database-backend happens. Fortunately, you don't
343 need to support anymore functionality than you want to. For instance,
344 it is perfectly legal to not accept boolean operators, but you SHOULD
345 try to return good error codes if you run into something you can't or
346 won't support.
347
348 A more convenient alternative to the QUERY member may be the RPN
349 member, which is a reference to a Net::Z3950::APDU::Query object
350 representing the RPN query tree.  The structure of that object is
351 supposed to be self-documenting, but here's a brief summary of what
352 you get:
353
354 =over 4
355
356 =item *
357
358 C<Net::Z3950::APDU::Query> is a hash with two fields:
359
360 Z<>
361
362 =over 4
363
364 =item C<attributeSet>
365
366 Optional.  If present, it is a reference to a
367 C<Net::Z3950::APDU::OID>.  This is a string of dot-separated integers
368 representing the OID of the query's top-level attribute set.
369
370 =item C<query>
371
372 Mandatory: a refererence to the RPN tree itself.
373
374 =back
375
376 =item *
377
378 Each node of the tree is an object of one of the following types:
379
380 Z<>
381
382 =over 4
383
384 =item C<Net::Z3950::RPN::And>
385
386 =item C<Net::Z3950::RPN::Or>
387
388 =item C<Net::Z3950::RPN::AndNot>
389
390 These three classes are all arrays of two elements, each of which is a
391 node of one of the above types.
392
393 =item C<Net::Z3950::RPN::Term>
394
395 See below for details.
396
397 =item C<Net::Z3950::RPN::RSID>
398
399 A reference to a result-set ID indicating a previous search.  The ID
400 of the result-set is in the C<id> element.
401
402 =back
403
404 (I guess I should make a superclass C<Net::Z3950::RPN::Node> and make
405 all of these subclasses of it.  Not done that yet, but will do one day.)
406
407 =back
408
409 =over 4
410
411 =item *
412
413 C<Net::Z3950::RPN::Term> is a hash with two fields:
414
415 Z<>
416
417 =over 4
418
419 =item C<term>
420
421 A string containing the search term itself.
422
423 =item C<attributes>
424
425 A reference to a C<Net::Z3950::RPN::Attributes> object.
426
427 =back
428
429 =item *
430
431 C<Net::Z3950::RPN::Attributes> is an array of references to
432 C<Net::Z3950::RPN::Attribute> objects.  (Note the plural/singular
433 distinction.)
434
435 =item *
436
437 C<Net::Z3950::RPN::Attribute> is a hash with three elements:
438
439 Z<>
440
441 =over 4
442
443 =item C<attributeSet>
444
445 Optional.  If present, it is dot-separated OID string, as above.
446
447 =item C<attributeType>
448
449 An integer indicating the type of the attribute - for example, under
450 the BIB-1 attribute set, type 1 indicates a ``use'' attribute, type 2
451 a ``relation'' attribute, etc.
452
453 =item C<attributeValue>
454
455 An integer indicating the value of the attribute - for example, under
456 BIB-1, if the attribute type is 1, then value 4 indictates a title
457 search and 7 indictates an ISBN search; but if the attribute type is
458 2, then value 4 indicates a ``greater than or equal'' search, and 102
459 indicates a relevance match.
460
461 =back
462
463 =back
464
465 Note that, at the moment, none of these classes have any methods at
466 all: the blessing into classes is largely just a documentation thing
467 so that, for example, if you do
468
469         { use Data::Dumper; print Dumper($args->{RPN}) }
470
471 you get something fairly human-readable.  But of course, the type
472 distinction between the three different kinds of boolean node is
473 important.
474
475 By adding your own methods to these classes (building what I call
476 ``augmented classes''), you can easily build code that walks the tree
477 of the incoming RPN.  Take a look at C<samples/render-search.pl> for a
478 sample implementation of such an augmented classes technique.
479
480
481 =head2 Present handler
482
483 The presence of a present handler in a SimpleServer front-end is optional.
484 Each time a client wishes to retrieve records, the present service is
485 called. The present service allows the origin to request a certain number
486 of records retrieved from a given result set.
487 When the present handler is called, the front-end server should prepare a
488 result set for fetching. In practice, this means to get access to the
489 data from the backend database and store the data in a temporary fashion
490 for fast and efficient fetching. The present handler does *not* fetch
491 anything. This task is taken care of by the fetch handler, which will be
492 called the correct number of times by the YAZ library. More about this
493 below.
494 If no present handler is implemented in the front-end, the YAZ toolkit
495 will take care of a minimum of preparations itself. This default present
496 handler is sufficient in many situations, where only a small amount of
497 records are expected to be retrieved. If on the other hand, large result
498 sets are likely to occur, the implementation of a reasonable present
499 handler can gain performance significantly.
500
501 The informations exchanged between client and present handle are:
502
503   $args = {
504                                     ## Client/server request:
505
506              HANDLE    =>  ref,     ## Reference to datastructure
507              SETNAME   =>  "id",    ## Result set ID
508              START     =>  xxx,     ## Start position
509              COMP      =>  "",      ## Desired record composition
510              NUMBER    =>  yyy,     ## Number of requested records
511
512
513                                     ## Respons parameters:
514
515              HITS      =>  zzz,     ## Number of returned records
516              ERR_CODE  =>  0,       ## Error code
517              ERR_STR   =>  ""       ## Error message
518           };
519
520
521 =head2 Fetch handler
522
523 The fetch handler is asked to retrieve a SINGLE record from a given
524 result set (the front-end server will automatically call the fetch
525 handler as many times as required).
526
527 The parameters exchanged between the server and the fetch handler are
528
529   $args = {
530                                     ## Client/server request:
531
532              HANDLE    =>  ref      ## Reference to data structure
533              SETNAME   =>  "id"     ## ID of the requested result set
534              OFFSET    =>  nnn      ## Record offset number
535              REQ_FORM  =>  "n.m.k.l"## Client requested format OID
536              COMP      =>  "xyz"    ## Formatting instructions
537
538                                     ## Handler response:
539
540              RECORD    =>  ""       ## Record string
541              BASENAME  =>  ""       ## Origin of returned record
542              LAST      =>  0        ## Last record in set?
543              ERR_CODE  =>  0        ## Error code
544              ERR_STR   =>  ""       ## Error string
545              SUR_FLAG  =>  0        ## Surrogate diagnostic flag
546              REP_FORM  =>  "n.m.k.l"## Provided format OID
547           };
548
549 The REP_FORM value has by default the REQ_FORM value but can be set to
550 something different if the handler desires. The BASENAME value should
551 contain the name of the database from where the returned record originates.
552 The ERR_CODE and ERR_STR works the same way they do in the search
553 handler. If there is an error condition, the SUR_FLAG is used to
554 indicate whether the error condition pertains to the record currently
555 being retrieved, or whether it pertains to the operation as a whole
556 (eg. the client has specified a result set which does not exist.)
557
558 If you need to return USMARC records, you might want to have a look at
559 the MARC module on CPAN, if you don't already have a way of generating
560 these.
561
562 NOTE: The record offset is 1-indexed - 1 is the offset of the first
563 record in the set.
564
565 =head2 Scan handler
566
567 A full featured Z39.50 server should support scan (or in some literature
568 browse). The client specifies a starting term of the scan, and the server
569 should return an ordered list of specified length consisting of terms
570 actually occurring in the data base. Each of these terms should be close
571 to or equal to the term originally specified. The quality of scan compared
572 to simple search is a guarantee of hits. It is simply like browsing through
573 an index of a book, you always find something! The parameters exchanged are
574
575   $args = {
576                                                 ## Client request
577
578                 HANDLE          => $ref         ## Reference to data structure
579                 TERM            => 'start',     ## The start term
580                 NUMBER          => xx,          ## Number of requested terms
581                 POS             => yy,          ## Position of starting point
582                                                 ## within returned list
583                 STEP            => 0,           ## Step size
584
585                                                 ## Server response
586
587                 ERR_CODE        => 0,           ## Error code
588                 ERR_STR         => '',          ## Diagnostic message
589                 NUMBER          => zz,          ## Number of returned terms
590                 STATUS          => $status,     ## ScanSuccess/ScanFailure
591                 ENTRIES         => $entries     ## Referenced list of terms
592         };
593
594 where the term list is returned by reference in the scalar $entries, which
595 should point at a data structure of this kind,
596
597   my $entries = [
598                         {       TERM            => 'energy',
599                                 OCCURRENCE      => 5            },
600
601                         {       TERM            => 'energy density',
602                                 OCCURRENCE      => 6,           },
603
604                         {       TERM            => 'energy flow',
605                                 OCCURRENCE      => 3            },
606
607                                 ...
608
609                                 ...
610         ];
611
612 The $status flag should be assigned one of two values:
613
614   Net::Z3950::SimpleServer::ScanSuccess  On success (default)
615   Net::Z3950::SimpleServer::ScanPartial  Less terms returned than requested
616
617 The STEP member contains the requested number of entries in the term-list
618 between two adjacent entries in the response.
619
620 =head2 Close handler
621
622 The argument hash recieved by the close handler has one element only:
623
624   $args = {
625                                     ## Server provides:
626              HANDLE    =>  ref      ## Reference to data structure
627           };
628
629 What ever data structure the HANDLE value points at goes out of scope
630 after this call. If you need to close down a connection to your server
631 or something similar, this is the place to do it.
632
633 =head2 Support for SRU and SRW
634
635 Since release 1.0, SimpleServer includes support for serving the SRU
636 and SRW protocols as well as Z39.50.  These ``web-friendly'' protocols
637 enable similar functionality to that of Z39.50, but by means of rich
638 URLs in the case of SRU, and a SOAP-based web-service in the case of
639 SRW.  These protocols are described at
640 http://www.loc.gov/sru
641
642 In order to serve these protocols from a SimpleServer-based
643 application, it is necessary to launch the application with a YAZ
644 Generic Frontend Server (GFS) configuration file, which can be
645 specified using the command-line argument C<-f> I<filename>.  A
646 minimal configuration file looks like this:
647
648   <yazgfs>
649     <server>
650       <cql2rpn>pqf.properties</cql2rpn>
651     </server>
652   </yazgfs>
653
654 This file specifies only that C<pqf.properties> should be used to
655 translate the CQL queries of SRU and SRW into corresponding Z39.50
656 Type-1 queries.  For more information about YAZ GFS configuration,
657 including how to specify an Explain record, see the I<Virtual Hosts>
658 section of the YAZ manual at
659 http://indexdata.com/yaz/doc/server.vhosts.tkl
660
661 The mapping of CQL queries into Z39.50 Type-1 queries is specified by
662 a file that indicates which BIB-1 attributes should be generated for
663 each CQL index, relation, modifiers, etc.  A typical section of this
664 file looks like this:
665
666   index.dc.title                        = 1=4
667   index.dc.subject                      = 1=21
668   index.dc.creator                      = 1=1003
669   relation.<                            = 2=1
670   relation.le                           = 2=2
671
672 This file specifies the BIB-1 access points (type=1) for the Dublin
673 Core indexes C<title>, C<subject> and C<creator>, and the BIB-1
674 relations (type=2) corresponding to the CQL relations C<E<lt>> and
675 C<E<lt>=>.  For more information about the format of this file, see
676 the I<CQL> section of the YAZ manual at
677 http://indexdata.com/yaz/doc/tools.tkl#tools.cql
678
679 The YAZ distribution include a sample CQL-to-PQF mapping configuration
680 file called C<pqf.properties>; this is sufficient for many
681 applications, and a good base to work from for most others.
682
683 If a SimpleServer-based application is run without this SRU-specific
684 configuration, it can still serve SRU; however, CQL queries will not
685 be translated, but passed straight through to the search-handler
686 function, as the C<CQL> member of the parameters hash.  It is then the
687 responsibility of the back-end application to parse and handle the CQL
688 query, which is most easily done using Ed Summers' fine C<CQL::Parser>
689 module, available from CPAN at
690 http://search.cpan.org/~esummers/CQL-Parser/
691
692 =head1 AUTHORS
693
694 Anders Sønderberg (sondberg@indexdata.dk),
695 Sebastian Hammer (quinn@indexdata.dk),
696 Mike Taylor (indexdata.com).
697
698 =head1 SEE ALSO
699
700 Any Perl module which is useful for accessing the database of your
701 choice.
702
703 =cut