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