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