File: JSONRPC.pm

package info (click to toggle)
libpoe-component-server-jsonrpc-perl 0.06-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 244 kB
  • sloc: perl: 2,026; makefile: 4
file content (279 lines) | stat: -rw-r--r-- 6,275 bytes parent folder | download
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
package POE::Component::Server::JSONRPC;
use strict;
use warnings;
use base qw/Class::Accessor::Fast/;

our $VERSION = '0.06';

use POE qw/
    Filter::Line
    /;
use JSON;

=encoding utf8 

=head1 NAME

POE::Component::Server::JSONRPC - POE tcp or http based JSON-RPC server

=head1 SYNOPSIS

    #http version:
    POE::Component::Server::JSONRPC::Http->new(
        # consider using something like JSON::MaybeXS for better performance
        json    => JSON::MaybeXS->new->utf8->allow_nonref,
        Port    => 3000,
        Handler => {
            'echo' => 'echo',
            'sum'  => 'sum',
        },
        SslKey  => '/path/to/the/server.key',
        SslCert => '/path/to/the/server.crt',
        Authenticate => \&authentication_handler,
        # authentication_handler must be a function that takes two parameters login and password,
        # and returns true if connection is successful, false otherwise
    );

    #tcp version:
    POE::Component::Server::JSONRPC::Tcp->new(
        Port    => 3000,
        Handler => {
            'echo' => 'echo',
            'sum'  => 'sum',
        },
    );

    sub echo {
        my ($kernel, $jsonrpc, $id, @params) = @_[KERNEL, ARG0..$#_ ];

        $kernel->post( $jsonrpc => 'result' => $id, @params );
    }

    sub sum {
        my ($kernel, $jsonrpc, $id, @params) = @_[KERNEL, ARG0..$#_ ];

        $kernel->post( $jsonrpc => 'result' => $id, $params[0] + $params[1] );
    }

=head1 DESCRIPTION

This module is a POE component for tcp or http based JSON-RPC Server.

The specification is defined on http://json-rpc.org/ and this module use JSON-RPC 1.0 spec (1.1 does not cover tcp streams)

=head1 METHODS

=head2 new

Create JSONRPC component session and return the session id.

Parameters:

=over

=item Port

Port number for listen.

=item Handler

Hash variable contains handler name as key, handler poe state name as value.

Handler name (key) is used as JSON-RPC method name.

So if you send {"method":"echo"}, this module call the poe state named "echo".

=back

=cut

sub new {
    my $self = shift->SUPER::new( @_ > 1 ? {@_} : $_[0] );

    $self->{parent} = $poe_kernel->get_active_session->ID;
    $self->{json} ||= JSON->new;

    my $session = POE::Session->create(
        object_states => [
            $self => {
                map { ( $_ => "poe_$_", ) }
                    qw/_start init_server input_handler result error send/
            },
        ],
    );

    $session->ID;
}

=head1 HANDLER PARAMETERS

=over

=item ARG0

A session id of PoCo::Server::JSONRPC itself.

=item ARG1

The id of the client you're treating, send that back in result/error.

=item ARG2 .. ARGN

JSONRPC argguments

=back

ex) If you send following request

    {"method":"echo", "params":["foo", "bar"]}

then, "echo" handler is called and parameters is that ARG0 is component session id, ARG1 is client id, ARG2 "foo", ARG3 "bar".

=head1 HANDLER RESPONSE

You must call either "result" or "error" state in your handlers to response result or error.

ex:

   $kernel->post( $component_session_id => "result" => $client_id, "result value" )

$component_session_id is ARG0 in handler. If you do above, response is:

   {"result":"result value", "error":""}


=head1 POE METHODS

Inner method for POE states.

=head2 poe__start

=cut

sub poe__start {
    my ($self, $kernel, $session, $heap) = @_[OBJECT, KERNEL, SESSION, HEAP];

    $heap->{clients} = {};
    $heap->{id} = 0;

    $kernel->yield('init_server');
}

=head2 poe_init_server

Should be defined in Http or Tcp
=cut

sub poe_init_server { print "error init_server\n"; }

=head2 poe_input_handler

=cut

sub poe_input_handler {
    my ($self, $kernel, $session, $heap, $request, $response, $dirmatch) = @_[OBJECT, KERNEL, SESSION, HEAP, ARG0..$#_ ];

    $heap->{clients}->{$heap->{id}} = {json_id => undef, response => $response};

    my $json;
    eval {
        $json = $self->{json}->decode( $request->content );
    };
    if ($@) {
        $kernel->yield('error', $heap->{id}, q{invalid json request});
        return;
    }

    $heap->{clients}->{$heap->{id}} = {json_id => $json->{id}, response => $response};

    unless ($json and $json->{method}) {
        $kernel->yield('error', $heap->{id}, q{parameter "method" is required});
        return;
    }

    unless ($self->{Handler}{ $json->{method} }) {
        $kernel->yield('error', $heap->{id}, qq{no such method "$json->{method}"});
        return;
    }

    my $handler = $self->{Handler}{ $json->{method} };
    my @params = @{ $json->{params} || [] };

    $kernel->post($self->{parent}, $handler, $session->ID, $heap->{id}, @params);

    $heap->{id}++;
    if ($heap->{id}>=65535) { # limit to 2 bytes
        $heap->{id} = 0;
    }
}

=head2 poe_result

=cut

sub poe_result {
    my ($self, $kernel, $heap, $id, @results) = @_[OBJECT, KERNEL, HEAP, ARG0..$#_ ];

    #~ print "answering to ".$id."\n";

    my $client = $heap->{clients}->{$id};

    my $json_content = $self->{json}->encode(
            {   id => $client->{json_id} || undef,
                error  => undef,
                result => (@results > 1 ? \@results : $results[0]),
            }
        );

    #~ print "json content : ".$json_content."\n";

    $kernel->yield('send',$client->{response},$json_content);
    delete $heap->{clients}->{$id};
}

=head2 poe_error

=cut

sub poe_error {
    my ($self, $kernel, $heap, $id, $error) = @_[OBJECT, KERNEL, HEAP, ARG0..$#_];

    my $client = $heap->{clients}->{$id};

    my $json_error_content = $self->{json}->encode(
        {   id => $client->{json_id} || undef,
            error  => $error,
            result => undef,
        }
    );

    #~ print "json content : ".$json_error_content."\n";

    $kernel->yield('send',$client->{response},$json_error_content);
    delete $heap->{clients}->{$id};
}

=head2 poe_send

Should be defined in Http or Tcp
=cut

sub poe_send { print "error poe_send\n"; }

=encoding UTF-8
=head1 AUTHOR

Côme Chilliet <mcmic@cpan.org>
Daisuke Murase <typester@cpan.org>

=head1 COPYRIGHT

This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the
LICENSE file included with this module.

=cut

1;