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