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