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