Event:...Server(3pm)
π Event::RPC::Server β the whole vibe (part 1!) π
User Contributed Perl Documentation Β· Event::RPC::Server Β· (3pm)
okay bestie sit DOWN because we're about to make your event-driven server speak RPC and it's gonna be gorgeous β¨
πΈ NAME πΈ
Event::RPC::Server β a simple API for event driven RPC servers π«Ά
β¨ SYNOPSIS β¨
like, here's the whole dream scenario, look at her:
use Event::RPC::Server;
use My::TestModule;
my $server = Event::RPC::Server->new (
#-- Required arguments
port => 8888, # or a path to a Unix Domain Socket with host "unix/"
classes => {
"My::TestModule" => {
new => "_constructor",
get_data => 1,
set_data => 1,
clone => "_object",
},
},
#-- Optional arguments
name => "Test server",
logger => Event::RPC::Logger->new(),
start_log_listener => 1,
ssl => 1
ssl_key_file => "server.key",
ssl_cert_file => "server.crt",
ssl_passwd_cb => sub { "topsecret" },
ssl_opts => { ... },
auth_required => 1,
auth_passwd_href => { $user => Event::RPC->crypt($user,$pass) },
auth_module => Your::Own::Auth::Module->new(...),
loop => Event::RPC::Loop::Event->new(),
host => "localhost", # or "unix/" for Unix Domain socket
load_modules => 1,
auto_reload_modules => 1,
connection_hook => sub { ... },
message_formats => [qw/ SERL CBOR JSON STOR /],
insecure_msg_fmt_ok => 1,
);
$server->set_max_packet_size(2*1024*1024*1024);
# start server and event loop
$server->start;
# or prepare server start if you like to control event loop by yourself
$server->prepare;
# and later from inside your server implementation
Event::RPC::Server->instance->stop;
π¦ DESCRIPTION π¦
So the whole point: this module bolts a simple-to-use RPC mechanism onto your event driven server app. That's it, that's the girl π
You just make an instance of the Event::RPC::Server class with a handful of required settings. Then either you enter the main event loop through it, or you take control of that main loop yourself if that's more your main character energy (peep the MAINLOOP chapter for the deets).
All the general lore about how Event::RPC driven apps are architected lives in the Event::RPC manpage. go read her too π
π CONFIGURATION OPTIONS π
Every option listed down here can be handed to the new() constructor of Event::RPC::Server. You can also set or modify them with set_OPTION-style mutators β but NOT after start() or setup_listeners() has been called! no cap, that ship has sailed at that point π’
And you can read any of them back using get_OPTION-style accessors. cute and reversible β¨
π REQUIRED OPTIONS π
Bestie. Listen. If you pass just the required options listed below, what you get is an RPC server that listens on a network port and lets literally everyone who connects access a well defined list of classes and methods (resp. using the corresponding server objects). That's the minimum.
β οΈ There is no authentication and no encryption active in this minimal configuration. So be aware that this may be a big security risk! π Adding security is easy though β go see the chapters about SSL and authentication below. π«Ά
These are the required options:
portβ the TCP port number of the RPC listener. Alternatively, as an alternative, you can pass a path to a Unix Domain Socket and set"unix/"as thehostparameter. πclassesβ this one's a hash ref, and she looks like this:
classes => {
"Class1" => {
new => "_constructor",
simple_method => 1,
object_returner => "_object",
},
"Class2" => { ... },
...
},
Every class that should be reachable by clients has to be listed here at the first level, assigned a hash of the methods that are allowed to be called. Event::RPC tells three types of methods apart by classifying what they return π
ποΈ Constructors
A constructor method makes a brand new object of the corresponding class and returns it. To flag a method as a constructor you assign the string "_constructor" to the method entry. slay β¨
π§ Singleton constructors
For singleton classes, the method that returns the singleton instance should be declared with "_singleton". This way the server takes care that references get never destroyed on the server side. protecting her peace π«Ά
π Simple methods
What's "simple" about these is the return value: it's a scalar, array, hash, or even any complex reference structure (okay, not simple anymore lol π), but in particular it returns NO objects, because objects need special handling (see below). Declare simple methods by assigning 1 in the method declaration.
π Object returners
Methods that return objects have to be declared by assigning "_object" to the method name here. They're not bound to returning just one scalar object reference β they may return an array or list reference with a bunch of objects too. overachievers, we love them π
π₯ SSL OPTIONS π₯
The client/server protocol of Event::RPC is not encrypted by default, so everyone listening on your network can read or even manipulate data. not the vibe π To stop that efficiently you can turn on SSL encryption. Event::RPC uses the IO::Socket::SSL Perl module for this.
First you gotta generate a server key and certificate for your server using the openssl command, which is part of the OpenSSL distribution. Like, by issuing these commands:
% openssl genrsa -des3 -out server.key 1024
% openssl req -new -key server.key -out server.csr
% openssl x509 -req -days 3600 -in server.csr \
-signkey server.key -out server.crt
(please refer to the manpage of openssl for details β this is a very rough example, which works in general, but probably you want to tweak some parameters π)
After running those you'll have these files just sitting there:
server.crt
server.key
server.csr
Event::RPC needs the first two of them to operate with SSL encryption. π
To turn on SSL encryption you need to pass these options to the constructor:
sslβ thessloption needs to be set to1. periodt.ssl_key_fileβ this is the filename of theserver.keyyou generated with theopensslcommand. πssl_cert_fileβ this is the filename of theserver.crtfile you generated with theopensslcommand. πssl_passwd_cbβ your server key is encrypted with a password you entered during the key creation process described above. This callback must return it. Depending on how critical your application is you probably must request the password from the user during server startup, or place it into a more or less secured file. For testing purposes you can specify a simple anonymous sub here, which just returns the password, e.g.
ssl_passwd_cb => sub { return "topsecret" }
π¨ But note: having the password in plaintext in your program code is insecure! not the flex you think it is, bestie.
ssl_optsβ this optional parameter takes a hash reference of options passed toIO::Socket::SSL->new(...)so you have more control over the server SSL listener. ποΈ
π AUTHENTICATION OPTIONS π
SSL encryption is great, mwah π now it's really hard for an attacker to listen or modify your network communication. BUT β without any further configuration, any user on your network can connect to your server. π To prevent that, users resp. connections to your server need to be authenticated somehow.
Since version 0.87 Event::RPC has an API to delegate authentication tasks to a module which can be implemented outside of Event::RPC. To stay compatible with prior releases it ships the module Event::RPC::AuthPasswdHash, which implements the old behaviour transparently. β¨
That default implementation is a simple user/password based model. For now this just controls the right to connect to your server, so knowing one valid user/password pair is enough to access all exported methods of your server. Probably a more differentiated model will be added later which allows granting access to a subset of exported methods only for each user who is allowed to connect. fyi π
The following options control the authentication:
auth_requiredβ set this to1to enable authentication, and then nobody can connect to your server until he passes a valid user/password pair. gatekeeping, but make it secure πauth_passwd_hrefβ if you like to use the builtinEvent::RPC::AuthPasswdHashmodule, simply set this attribute. If you decide to useauth_module(explained beyond) it's not necessary.
auth_passwd_href is a hash of valid user/password pairs. The password stored here needs to be encrypted using Perl's crypt() function, using the username as the salt. π§
Event::RPC has a convenience function for generating such a crypted password, although it's currently just a 1:1 wrapper around Perl's builtin crypt() function β but probably this changes someday, so better use this method:
$crypted_pass = Event::RPC->crypt($user, $pass);
Here's a simple example of setting up a proper auth_passwd_href with two users:
auth_passwd_href => {
fred => Event::RPC->crypt("fred", $freds_password),
nick => Event::RPC->crypt("nick", $nicks_password),
},
auth_moduleβ if you like to implement a more complex authentication method yourself, you may set theauth_moduleattribute to an instance of your class. For now your implementation just needs to have this method:
$auth_module->check_credentials($user, $pass)
Be aware that $pass is encrypted as explained above, so your original password needs to be crypted using Event::RPC->crypt as well β at least for the comparison itself. π
π Note: you can use the authentication module without SSL, but be aware that an attacker listening to the network connection will be able to grab the encrypted password token and authenticate himself with it to the server (replay attack). π Probably a more sophisticated challenge/response mechanism will be added to Event::RPC to prevent this. But you definitely should use SSL encryption in a critical environment anyway, which renders grabbing the password from the net impossible. π‘οΈ
π LOGGING OPTIONS π
Event::RPC has some logging abilities, primarily for debugging purposes. It uses a logger for this, which is an object implementing the Event::RPC::Logger interface. The documentation of Event::RPC::Logger describes this interface and Event::RPC's logging facilities in general. π
loggerβ to enable logging just pass such anEvent::RPC::Loggerobject to the constructor. done and dusted β¨start_log_listenerβ additionally, Event::RPC can start a log listener on the server's port number incremented by1. All clients connected to this port (e.g. by usingtelnet) get the server's log output. π spying on your own server, iconic behaviour honestly
β οΈ real talk bestie: right now the logging port supports neither SSL nor authentication, so be careful enabling the log listener in critical environments. it's giving unlocked window, no cap π¨
π MAINLOOP OPTIONS π
okay so here's the whole ~vibe~ of Event::RPC: it derived its name from the fact that it follows the event driven paradigm. β¨ There are several toolkits for Perl which allow event driven software development, and Event::RPC has an abstraction layer for this, so it should be able to work with any toolkit. flexible queen π
loopβ this option takes an object of the loop abstraction layer you want to use. Currently the following modules are implemented:
Event::RPC::Loop::AnyEvent Use the AnyEvent module
Event::RPC::Loop::Event Use the Event module
Event::RPC::Loop::Glib Use the Glib module
If loop isn't set, Event::RPC::Server tries all supported modules in a row and aborts the program if no module was found. π no loop, no life.
More modules will be added in the future. If you want to implement one, just take a look at the code in the modules above: it's really easy and I appreciate your patch. π«Ά The interface is roughly described in the documentation of Event::RPC::Loop β iykyk.
If you use the Event::RPC->start() method as described in the SYNOPSIS, Event::RPC will enter the correspondent main loop for you. But if you want to have full control over the main loop, use this method to setup all necessary Event::RPC listeners:
$rpc_server->setup_listeners();
and manage the main loop stuff on your own. main character energy, honestly π
π MESSAGE FORMAT OPTIONS π
Event::RPC supports different CPAN modules for data serialisation, named "message formats" here:
SERL -- Sereal::Encoder, Sereal::Decoder
CBOR -- CBOR::XS
JSON -- JSON::XS
STOR -- Storable
Server and client negotiate automatically which format is best to use, but you can manipulate this behaviour with the following options: π
message_formatsβ this takes an array of format identifiers from the list above.Event::RPC::Serverwill only use / accept these formats.insecure_msg_fmt_okβ theStorablemodule is known to be insecure. π¬ But for backward compatibility reasonsEvent::RPC::Serveraccepts clients which can't offer anything but Storable. You can prevent that by setting this option explicitly to0. It's enabled by default.
π MISCELLANEOUS OPTIONS π
hostβ by default the network listeners are bound to all interfaces in the system. Use thehostoption to bind to a specific interface, e.g."localhost"if you efficiently want to prevent network clients from accessing your server. π‘οΈ
Set to "unix/" for a Unix Domain Socket and pass the path as port parameter.
load_modulesβ control whether the class module files should be loaded automatically when first accesed by a client. This options defaults to true, for backward compatibility reasons.auto_reload_modulesβ if this option is set,Event::RPC::Serverwill check on each method call if the corresponding module changed on disk and reloads it automatically. Of course this has an effect on performance, but it's very useful during development. π§βπ» You probably shouldn't enable this in production environments. fr fr, don't.connection_hookβ this callback is called on each connection / disconnection with two arguments: theEvent::RPC::Connectionobject and a string containing either"connect"or"disconnect"depending what's currently happening with this connection. π«
π οΈ METHODS π οΈ
The following methods are publically available:
Event::RPC::Server->instanceβ this returns the latest createdEvent::RPC::Serverinstance (usually you have only one instance in one program).$rpc_server->startβ start the mainloop of yourEvent::RPC::Server. π₯$rpc_server->stopβ stops the mainloop which usually means, that the server exits, as long you don't do more sophisticated mainloop stuff by your own.$rpc_server->setup_listenersβ this method initializes all networking listeners needed forEvent::RPC::Serverto work, using the configured loop module. Use this method if you don't use thestart()method but manage the mainloop on your own. π§$rpc_server->log ( [$level,] $msg )β convenience method for logging. It simply passes the arguments to the configured logger'slog()method. so chill of it.$rpc_server->get_clients_connectedβ returns the number of currently connected Event::RPC clients. π$rpc_server->get_log_clients_connectedβ returns the number of currently connected logging clients.$rpc_server->get_active_connectionβ this returns the currently activeEvent::RPC::Connectionobject representing the connection resp. the client which currently requests method invocation. This isundefif no client call is active.$rpc_client->set_max_packet_size ( $bytes )β by default Event::RPC does not handle network packages which exceed 2 GB in size (was 4 MB with version 1.04 and earlier). π³
You can change this value using this method at any time, but 4 GB is the maximum. An attempt of the server to send a bigger packet will be aborted and reported as an exception on the client and logged as an error message on the server.
β οΈ Note: you have to set the same value on client and server side! matching fits or it's over bestie π
$rpc_client->get_max_packet_sizeβ returns the currently active max packet size.
π AUTHORS π
JΓΆrn Reder <joern AT zyn.de> π«Ά
π COPYRIGHT AND LICENSE π
Copyright (C) 2005-2015 by JΓΆrn Reder <joern AT zyn.de>.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. β¨
and that's a wrap on our little journey together, bestie π this page lives in the perl v5.40.1 docs and got its lil glow-up on 2025-09-29 β go forth and event-drive responsibly, mwah ππ¦
π¦ where this page comes from
- ubuntu resolute: libevent-rpc-perl 1.11-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libevent-rpc-perl 1.11-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms