9a72b07f637de22fbade229d240d802d98cd003f
[irspy-moved-to-github.git] / lib / ZOOM / Pod.pm
1 # $Id: Pod.pm,v 1.3 2006-05-09 16:31:05 mike Exp $
2
3 package ZOOM::Pod;
4
5 use strict;
6 use warnings;
7
8 use ZOOM;
9
10 =head1 SYNOPSIS
11
12  use ZOOM::Pod;
13
14  $pod = new ZOOM::Pod("bagel.indexdata.com/gils",
15                       "bagel.indexdata.com/marc");
16  $pod->callback(ZOOM::Event::RECV_SEARCH, \&completed_search);
17  $pod->callback(ZOOM::Event::RECV_RECORD, \&got_record);
18  $pod->search_pqf("the");
19  $err = $pod->wait();
20  die "$pod->wait() failed with error $err" if $err;
21
22  sub completed_search {
23      ($conn, $rs) = @_;
24      print $conn->option("host"), ": found ", $rs->size(), " records\n";
25      $rs->record(0); # Queues a request for the record
26      return 0;
27  }
28
29  sub got_record {
30      ($conn, $rs) = @_;
31      $rec = $rs->record(0);
32      print $conn->option("host"), ": got $rec = '", $rec->render(), "'\n";
33      return 0;
34  }
35
36 =cut
37
38 BEGIN {
39     # Just register the name
40     ZOOM::Log::mask_str("pod");
41 }
42
43 sub new {
44     my $class = shift();
45     my(@conn) = @_;
46
47     my @state; # Hashrefs with application state associated with connections
48     foreach my $conn (@conn) {
49         if (!ref $conn) {
50             $conn = new ZOOM::Connection($conn, 0, async => 1);
51         }
52         push @state, {};
53     }
54
55     return bless {
56         conn => \@conn,
57         state => \@state,
58         rs => [],
59         callback => {},
60     }, $class;
61 }
62
63 sub option {
64     my $this = shift();
65     my($key, $value) = @_;
66
67     foreach my $conn (@{ $this->{conn} }) {
68         $conn->option($key, $value);
69     }
70 }
71
72 sub callback {
73     my $this = shift();
74     my($event, $sub) = @_;
75
76     my $old = $this->{callback}->{$event};
77     $this->{callback}->{$event} = $sub
78         if defined $sub;
79
80     return $old;
81 }
82
83 sub search_pqf {
84     my $this = shift();
85     my($pqf) = @_;
86
87     foreach my $i (0..@{ $this->{conn} }-1) {
88         $this->{rs}->[$i] = $this->{conn}->[$i]->search_pqf($pqf);
89     }
90 }
91
92 sub wait {
93     my $this = shift();
94     my $res = 0;
95
96     while ((my $i = ZOOM::event($this->{conn})) != 0) {
97         my $conn = $this->{conn}->[$i-1];
98         my $ev = $conn->last_event();
99         ZOOM::Log::log("pod", "connection ", $i-1, ": ", ZOOM::event_str($ev));
100         my $sub = $this->{callback}->{$ev};
101         if (defined $sub) {
102             $res = &$sub($conn, $this->{state}->[$i-1],
103                          $this->{rs}->[$i-1], $ev);
104             last if $res != 0;
105         }
106     }
107
108     return $res;
109 }
110
111
112 1;