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