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