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