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