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