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