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