summaryrefslogtreecommitdiff
path: root/Tanja.pm
blob: 0d1915a5d1b4fdba2f236f1bcc4921f7becf4b23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# TODO: Split into multiple files? (Or at least don't load AnyEvent::Handle and
# JSON::XS when they aren't needed.)

package Tanja;

use strict;
use warnings;

# Just make sure it's loaded. It doesn't export anything.
use AnyEvent;


# Args: [ pattern ], [ tuple ]
# Returns: a true value on match, a false value otherwise
# TODO: this match() implementation is for experimental purposes only, it
# should actually follow some established semantics to interoperate properly.
# undef is used as wildcard (in either the tuple or the pattern).
sub match {
	my($p, $t) = @_;
	return 0 if @$p > @$t;
	for my $i (keys @$p) {
		next if !defined $p->[$i] or !defined $t->[$i];
		return 0 if $p->[$i] ne $t->[$i];
	}
	return 1;
}


package Tanja::Server;

use strict;
use warnings;


# Create a new server (representing a "network")
sub new {
	return bless({
		lastid => 1,
		pat => {}, # Note: Also used directly by Tanja::Link
	}, shift);
}


# Create a new session
sub session {
	return Tanja::Session->new(shift);
}


# Link with another server via an AnyEvent::Handle stream
sub link {
	return Tanja::Link->new(@_);
}


# Send a tuple to the network.
# Arguments: [ tuple ], $return_cb->([tuple] or ())
# TODO: Some way to indicate that the session isn't interested in replies anymore?
sub send {
	my($s, $t, $cb) = @_;
	my $ret = Tanja::ReturnPath->_new($cb);
	for my $reg (grep Tanja::match($_->[0], $t), values %{$s->{pat}}) {
		AnyEvent::postpone {
			$reg->[1]->($t, $ret);
		}
	}
}


sub _register {
	my($s, $pat, $cb) = @_;
	my $id = $s->{lastid};
	# Explicitely wrap around long before 2^31, to avoid having Perl turn the ID into a float.
	++$id >= 1<<30 and $id = 1 while $s->{pat}{$id};
	$s->{pat}{$id} = [ $pat, $cb ];
	$s->{lastid} = $id;
	return $id;
}


sub _unregister {
	my($s, $id) = @_;
	delete $s->{pat}{$id};
}


package Tanja::Session;

use strict;
use warnings;


# Create a new session (usually called by $serv->session)
sub new {
	my($own, $serv) = @_;
	return bless({
		server => $serv,
		pat => {},
	}, $own);
}


# Register for a pattern
#   Args: [ pattern ], callback
#   Returns: $id, for use with unreg()
# Callback:
#   Args: [ tuple ], $return_path
sub reg {
	my($s, $pat, $cb) = @_;
	my $id;
	$id = $s->{server}->_register($pat, sub { $s->{pat}{$id} && $cb->(@_) });
	$s->{pat}{$id} = 1;
	return $id;
}


# Unregister a single pattern
sub unreg {
	my($s, $id) = @_;
	$s->{server}->_unregister($id);
	delete $s->{pat}{$id};
}


# For convenience. Same as ->reg(), but unregisters automatically after one call.
sub reg_once {
	my($s, $pat, $cb) = @_;
	my $id;
	$id = $s->reg($pat, sub { $s->unreg($id); $cb->(@_) });
	return $id;
}


sub send {
	my $s = shift;
	$s->{server}->send(@_);
}


# "Close" the session (simply unregisters all its patterns)
sub close {
	my $s = shift;
	$s->{server}->_unregister($_) for (keys %{$s->{pat}});
	$s->{pat} = {};
}


package Tanja::ReturnPath;

use strict;
use warnings;


sub _new {
	my($own, $cb) = @_;
	return bless \$cb, $own;
}


sub null {
	my $cb = shift;
	return !$$cb;
}


sub reply {
	my($cb, $t) = @_;
	$$cb && AnyEvent::postpone { $$cb->($t); };
}


sub DESTROY {
	my $cb = shift;
	my $c = $$cb;
	$c && AnyEvent::postpone { $c->() };
	undef $$cb;
}


package Tanja::Link;

use strict;
use warnings;
use AnyEvent::Handle;
use Errno 'EPIPE';


# Args: Tanja::Server, $server||!$client, AnyEvent::Handle, $error->($message)
# Automatically initiates handshake and stuff. Error callback will also be
# called when the remote side simply disconnected, $message is in that case
# undef.
sub new {
	my($own, $serv, $init, $handle, $err) = @_;
	my $s = bless {
		serv => $serv,
		hdl => $handle,
		init => $init,
		err => $err,
	}, $own;
	$handle->on_error(sub { $s->_err($! == EPIPE ? undef : $_[2]) });
	# TODO: Better to have a timeout on writes. (Although this buffer limit isn't bad either)
	$handle->wbuf_max(5*1024*1024); # This would be really bad.
	$s->_handshake;
	return $s;
}


sub _err {
	my($s, $m) = @_;
	$s->{hdl}->destroy;
	$s->{err} && $s->{err}->($m);
}


sub _handshake {
	my $s = shift;

	# If we should initiate the handshake, do so
	$s->{init} && $s->{hdl}->push_write("ver,1.0 ser,json\012");

	# Receive handshake from other party
	$s->{hdl}->push_read(line => "\012" => sub {
		my $ver = ($_[1] =~ /\bver,([^ ]+)\b/) && $1;
		my $ser = ($_[1] =~ /\bser,([^ ]+)\b/) && $1;

		# Validate
		$s->_err("Invalid handshake: $_[1]") if !$ver || !$ser
			|| ($s->{init} ? $ver ne '1.0' : !grep /^1\./, split /,/, $ver)
			|| ($s->{init} ? $ser ne 'json' : !grep $_ eq 'json', split /,/, $ser);

		# Reply with our handshake if we hadn't sent it yet.
		!$s->{init} && $s->{hdl}->push_write("ver,1.0 ser,json\012");

		# Handshake complete, send out initial register messages
		$s->{hdl}->push_write('Tanja::Link::JSON' => register => $_+0, $s->{serv}{pat}{$_}[0]) for (keys %{$s->{serv}{pat}});

		# TODO: start regular message exchange.
	});
}


sub close {
	$_[0]->{hdl}->push_shutdown;
}


# JSON serialization format
package Tanja::Link::JSON;

use strict;
use warnings;
use JSON::XS;

my @num_to_cmd = ('', qw|register unregister tuple response close|);
my %cmd_to_num = map +($num_to_cmd[$_], $_), keys @num_to_cmd;


sub anyevent_read_type {
	my $cb = $_[1];
	sub {
		$_[0]{rbuf} =~ s/^([^\012]*)\012// or return;
		my $d = eval { decode_json $1; };
		return $cb->($_[0], undef) || 1 if !$d || ref($d) ne 'ARRAY';
		my $num = shift @$d;
		return $cb->($_[0], undef) || 1 if !$num || $num !~ /^\d+$/ || $num > @num_to_cmd;
		$cb->($_[0], $num_to_cmd[$num], @$d);
		1
	}
}

sub anyevent_write_type {
	my(undef, $cmd, @args) = @_;
	encode_json([$cmd_to_num{$cmd}, @args])."\n";
}


1;

# vim:noet:sw=4:ts=4