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