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