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 the host parameter. 🌈
  • 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 β€” the ssl option needs to be set to 1. periodt.
  • ssl_key_file β€” this is the filename of the server.key you generated with the openssl command. πŸ”‘
  • ssl_cert_file β€” this is the filename of the server.crt file you generated with the openssl command. πŸ“œ
  • 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 to IO::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 to 1 to 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 builtin Event::RPC::AuthPasswdHash module, simply set this attribute. If you decide to use auth_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 the auth_module attribute 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 an Event::RPC::Logger object to the constructor. done and dusted ✨
  • start_log_listener β€” additionally, Event::RPC can start a log listener on the server's port number incremented by 1. All clients connected to this port (e.g. by using telnet) 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::Server will only use / accept these formats.
  • insecure_msg_fmt_ok β€” the Storable module is known to be insecure. 😬 But for backward compatibility reasons Event::RPC::Server accepts clients which can't offer anything but Storable. You can prevent that by setting this option explicitly to 0. It's enabled by default.

πŸ“ MISCELLANEOUS OPTIONS πŸ“

  • host β€” by default the network listeners are bound to all interfaces in the system. Use the host option 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::Server will 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: the Event::RPC::Connection object 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 created Event::RPC::Server instance (usually you have only one instance in one program).
  • $rpc_server->start β€” start the mainloop of your Event::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 for Event::RPC::Server to work, using the configured loop module. Use this method if you don't use the start() 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's log() 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 active Event::RPC::Connection object representing the connection resp. the client which currently requests method invocation. This is undef if 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 (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