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