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