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