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