Multiplex/Multiplexer.pm

filter: Statementstmt 98.0% 50 / 51 Branchbran 92.3% 24 / 26 Conditioncond 85.7% 6 / 7 MC/DCmcdc 75.0% 3 / 4 Subroutinesub 92.3% 12 / 13 Podpod 100% 4 / 4 totaltotal 94.2% 99 / 105 CC 17 SCAR 15.5
CC
17
Cov
95%
__ANON__
10.0
_send
3.0
send_status
3.0
CRAP 4.7
↑ Summary Multiplex.pm »
1 package Mojolicious::Plugin::Multiplex::Multiplexer;
2  
3 1 ▶use Mojo::Base 'Mojo::EventEmitter';
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 1 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 0 ▶has tx => sub { Carp::croak 'tx is required' };
Subroutine __ANON__: not called CC=1 SCAR=1.2
9  
10 1 my %map = (
11 sub => 'subscribe',
12 msg => 'message',
13 uns => 'unsubscribe',
14 err => 'error',
15 sta => 'status',
16 );
17  
18 3 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
19 3 my $self = shift->SUPER::new(@_);
20 3 my $tx = $self->tx;
21 3 ▶ return undef unless $tx->is_websocket;
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->is_websocket 0 3 3
22 3 Scalar::Util::weaken $self->{tx};
23  
24 9 ▶ $tx->on(text => sub {
Subroutine __ANON__: called CC=10 SCAR=23.0
25 9 my ($tx, $bytes) = @_;
26 9 my %message;
27 9 @message{qw/type topic payload/} = split /,/, $bytes, 3;
28  
29 9 my $e = $map{$message{type}};
30 9 my @args = ($message{topic});
31  
32 9 ▶ if (! defined $e) {
Branch: 4 branches
BranchTrueFalseTotal
if (not defined $e) { } 1 8 9
elsif ($e eq 'error') { } 1 7 8
elsif ($e eq 'message') { } 1 6 7
elsif ($e eq 'status') { } 4 2 6
33 1 $e = 'error';
34 1 push @args, {
35 error => 'Message type not understood',
36 message => \%message,
37 };
38 } elsif ($e eq 'error') {
39 1 push @args, {
40 error => 'Client error',
41 message => \%message,
42 };
43 } elsif ($e eq 'message') {
44 1 push @args, $message{payload};
45 } elsif ($e eq 'status') {
46 1 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
47 4 my $s = $message{payload};
48 4 ▶ push @args, $s eq 'true' ? 1 :
Branch: 3 branches
BranchTrueFalseTotal
$s eq 'true' ? : 1 3 4
$s eq 'false' ? : 1 2 3
!(defined $s || length $s) ? : 1 1 2
Condition66%2/3
defined $s || length $s
l!l&&r!l&&!r
101
MC/DC50%1/2
defined $s || length $s
defined $s length $s
Truth table66%2/3
A || B
A= defined $sB= length $s
ABresult
1X1
011
000
49 $s eq 'false' ? 0 :
50 ! (defined $s || length $s) ? undef :
51 {error => 'Status payload not understood', message => \%message};
52 4 ▶ $e = 'error' if ref $args[-1];
Branch: 1 branch
BranchTrueFalseTotal
if ref $args[-1] 1 3 4
53 }
54  
55 9 $self->emit($e, @args);
56 3 });
57  
58 3 ▶ $tx->on(finish => sub { $self->emit(finish => @_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
59  
60 3 return $self;
61 }
62  
63 3 ▶sub send_status {
Subroutine send_status: called CC=3 SCAR=11.0
Pod documented
64 3 my ($self, $topic, $payload, $cb) = @_;
65 3 ▶ $payload = defined($payload) ? $payload ? ',true' : ',false' : '';
Branch: 2 branches
BranchTrueFalseTotal
defined $payload ? : 2 1 3
$payload ? : 1 1 2
66 3 $self->_send("sta,$topic$payload", $cb);
67 }
68  
69 6 ▶sub send {
Subroutine send: called CC=2 SCAR=6.9
Pod documented
70 6 my ($self, $topic, $payload, $cb) = @_;
71 6 ▶ $payload //= '';
Condition100%2/2
$payload //= ""
l!l
42
MC/DC100%1/1
$payload //= ""
$payload
Truth table100%2/2
A
A= $payload
Aresult
11
00
72 6 $self->_send("msg,$topic,$payload", $cb);
73 }
74  
75 4 ▶sub send_error {
Subroutine send_error: called CC=2 SCAR=6.9
Pod documented
76 4 my ($self, $topic, $payload, $cb) = @_;
77 4 ▶ $payload //= '';
Condition100%2/2
$payload //= ""
l!l
22
MC/DC100%1/1
$payload //= ""
$payload
Truth table100%2/2
A
A= $payload
Aresult
11
00
78 4 $self->_send("err,$topic,$payload", $cb);
79 }
80  
81 13 ▶sub _send {
Subroutine _send: called CC=3 SCAR=11.0
82 13 my ($self, $msg, $cb) = @_;
83 13 ▶ return unless my $tx = $self->tx;
Branch: 1 branch
BranchTrueFalseTotal
unless my $tx = $self->tx 0 13 13
84 13 ▶ $tx->send($msg, $cb ? sub { $self->$cb() } : ());
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$cb ? : 1 12 13
85 }
86  
87 1 1;
88  
89 =head1 NAME
90  
91 Mojolicious::Plugin::Multiplex::Multiplexer - Dispatcher class for multiplexing websockets
92  
93 =head1 SYNOPSIS
94  
95 # a simple single-threaded message relay example
96  
97 use Mojolicious::Plugin::Multiplex::Multiplexer;
98 my $multiplex = Mojolicious::Plugin::Multiplex::Multiplexer->new(tx => $tx);
99  
100 my %topics;
101 $multiplex->on(message => sub {
102 my ($multiplex, $topic, $payload) = @_;
103 return unless my $cb = $topics{$topic};
104 $multiplex->$cb($topic, $payload);
105 });
106  
107 $multiplex->on(subscribe => sub {
108 my ($multiplex, $topic) = @_;
109 $topics{$topic} = sub { shift->send(@_) };
110 $multiplex->send_status($topic, 1);
111 });
112  
113 $multiplex->on(unsubscribe => sub {
114 my ($multiplex, $topic) = @_;
115 delete $topics{$topic};
116 $multiplex->send_status($topic, 0);
117 });
118  
119 =head1 DESCRIPTION
120  
121 This class sends and receives messages over a L<websocket transaction|Mojo::Transaction::WebSocket> using a variant of the sockjs websocket multiplex protocol.
122 This variant defines five message types, they are: C<subscribe>, C<message>, C<unsubscribe>, C<status>, C<error>.
123 Further each message is assigned to a topic (channel) which is used to separate messages by subscribed listener.
124 Note that though the protocol defines an error message, the event is also emitted on other errors; in the case of an error message the error string will be C<Client error>.
125  
126 =head1 PLEASE NOTE
127  
128 This class is rather low level and is useful for writing bindings to backend message services like brokers.
129 Notice that it does not store any connection state information either, which would be the responsibility of the consuming module or script.
130 An example is given in the distribution for using this class with L<Mojo::Pg::PubSub> to relay JSON messages between web-based chat clients.
131  
132 As this module is low level it does no character encoding or decoding.
133 If a topic or payload contains non ascii characters it must be manually encoded or decoded as necessary.
134 Note further that topics cannot contain a comma due to the limitations of the simple protocol.
135  
136 =head1 EVENTS
137  
138 Inherits all of the events from L<Mojo::EventEmitter> and implements the following new ones.
139  
140 =head2 subscribe / unsubscribe
141  
142 $multiplex->on(subscribe => sub { my ($multiplex, $topic) = @_; ... });
143  
144 Emitted with a topic when the client expresses an interest in subscribing to or leaving the given topic.
145  
146 A server should respond to this message event with a L</status> reply indicating the new subscription state.
147  
148 =head2 message
149  
150 $multiplex->on(message => sub { my ($multiplex, $topic, $payload) = @_; ... });
151  
152 Emitted when a message is received from the client.
153 It is passed the topic and the payload in original encoded form (bytes).
154  
155 =head2 status
156  
157 $multiplex->on(status => sub { my ($multiplex, $topic, $payload) = @_; ... });
158  
159 Emitted when a client attempts to indicate its own subscription status of a topic (rare) or else requests the subscription status for a given topic (proposed usage).
160 Emitted with a topic name and either true or false (but defined) value when indicating the state or undefined when requesting a state.
161  
162 The server may reply to these requests but none is required.
163 For agreement with an indicated state or sending the requested current state, use L</status>.
164 For disagreeing with the indicated state, an error should be sent with L</send_error>.
165  
166 =head2 error
167  
168 $multiplex->on(error => sub { my ($multiplex, $topic, $error) = @_; ... });
169  
170 Emitted when a client sends a message which is not understood or other errors.
171 Fatal if not handled
172 Passed the topic and an error data structure.
173 This structure contains an C<error> key which defines the error and a C<message> key which contains the raw parsed error.
174  
175 =head2 finish
176  
177 $multiplex->on(finish => sub { my ($multiplex, $tx, $code, $reason) = @_; ... });
178  
179 Emitted when the websocket connection is finished.
180 This event is proxied from the transaction for convenience.
181  
182 =head1 ATTRIBUTES
183  
184 Inherits all of the attributes from L<Mojo::EventEmitter> and implements the following new ones.
185  
186 =head2 tx
187  
188 The transaction associated with the websocket.
189 This should be an instance of L<Mojo::Transaction::WebSocket>.
190  
191 =head1 METHODS
192  
193 Inherits all of the methods from L<Mojo::EventEmitter> and implements the following new ones.
194  
195 =head2 send_status
196  
197 $multiplex->send_status($topic, $state, $cb);
198  
199 Send the current state of a topic subscription (as in the response from L</subscribe> and L<unsubscrive> or request the client's subscription state (rare).
200 Takes a topic, a state, and an optional drain callback.
201 The state variable will be coerced from any true, false or undefined values, where true and false values indicate subscribed or not subscribed respectively.
202 Undefined propts the client to respond with its own notion of the subscription state, which is a rare thing for a server to do; additionally the client may not implement the response to the request.
203  
204 =head2 send
205  
206 $multiplex->send($topic, $payload, $cb);
207  
208 Send a message to the client on the given topic.
209 Takes a topic, a payload, and an optional drain callback.
210 As mentioned above, neither the topic name or payload are encoded before sending, so be sure to do so manually if necessary.
211  
212 =head2 send_error
213  
214 $multiplex->send_error($topic, $payload, $cb);
215  
216 Send an error message to the client on the given topic.
217 Takes a topic, a payload, and an optional drain callback.
218  
219 =head1 PROTOCOL
220  
221 The original protocol (extended below) was proposed by SockJS, can be found at L<https://github.com/sockjs/websocket-multiplex>.
222  
223 The underlying protocol is quite simple. Each message is a string consisting of three comma separated parts: type, topic and payload. There are three valid message types:
224  
225 sub - expresses a will to subscribe to a given topic.
226 msg - a message with payload is being sent on a topic.
227 uns - a will to unsubscribe from a topic.
228 err - a message with a payload that is emitted as an error
229 sta - a status message stating whether the other party believes you are subscribed to the topic
230 the playload is either "true" or "false"
231 this message is sent as a response to sub/uns messages
232 (TODO: consider empty status message to request the status from the other party?)
233  
234  
↑ Summary Multiplex.pm »