NAME

Class::Shared::Backend - load a class once and serve objects made from it

SYNOPSIS

Each example is a different real-world pattern. Most people never write this code: a frontend starts a backend for you, and class-shared start starts one from the shell.

use Class::Shared::Backend;

# 1. In the foreground, on the default unix socket.  run() does not return
#    until the backend is told to stop (Ctrl-C, SIGTERM or "class-shared stop").
Class::Shared::Backend->new()->run;

# 2. An explicit unix socket path (at most 100 characters).
Class::Shared::Backend->new(
    socket => '/run/user/1000/class-shared/class-shared.sock',
)->run;

# 3. In the background.  The process that calls run() EXITS (status 0) once
#    the background copy has been started, so run() never returns there.
Class::Shared::Backend->new(daemonize => 1, log => '/tmp/cs.log')->run;

# 4. Serve other machines, over TLS with client certificates and a token.
my $secret = 'the secret its clients were given too';
Class::Shared::Backend->new(
    host     => '0.0.0.0',
    port     => 7000,
    tls_cert => '/etc/class-shared/server.pem',
    tls_key  => '/etc/class-shared/server-key.pem',
    tls_ca   => '/etc/class-shared/clients-ca.pem',
    token    => $secret,
)->run;

# 5. Limit what the backend will hold.
Class::Shared::Backend->new(
    max_clients => 20,
    max_objects => 200,
)->run;

# 6. Take site settings from a file or the environment, with no change to
#    the program.  See "CONFIGURATION".
#      export Class__Shared__Backend__max_clients=50
Class::Shared::Backend->new(config_file => '/etc/class-shared/backend.yml')->run;

DESCRIPTION

A client names the class it wants in its first message, the handshake, and the backend loads that module then -- require for the file, import for its exports -- once per class however many clients ask for it. Each object lives until the connection that asked for it goes away.

one backend  --  Class::Simple (code, loaded when first asked for)
             |--  Class::Other  (code, loaded when first asked for)
             `--  object #1 (client A), object #2 (client B), ...

It answers one request at a time in a select loop, because all the objects share one interpreter.

There is no class option: which classes are loaded is decided by the clients, not by the command line.

OPTIONS

Every option may also be given as a site default; see "CONFIGURATION". An option you pass with the value undef counts as not given. A name that is not listed here makes new die.

socket

Unix socket path. Defaults to "socket_path" in Class::Shared. Use this or host/port, not both. It must be at most 100 characters; a longer path makes new die, because the operating system would otherwise cut it short without saying so.

dir

The directory for the default socket, when socket is not given. Defaults to "default_dir" in Class::Shared. The lock file, the pid file and the log are kept next to the socket.

host, port

Listen on TCP instead of a unix socket, over TLS. host may be 127.0.0.1 for local use or an address of this machine to accept remote clients. A TCP listener needs tls_cert, tls_key, tls_ca and a token; see "TLS".

tls_cert, tls_key

The certificate and private key this listener presents to clients. The certificate has to name the address clients use, because they check the name as well as the chain.

tls_ca

PEM file of the CA, or CAs, that clients' certificates must chain to. Client certificates are mandatory: a client that presents none, or one signed by another CA, is dropped during the handshake.

token

The shared secret for a TCP listener, which refuses to start without one and refuses to accept a frame it cannot authenticate. It is kept even though the connection is already TLS: the token checks each frame, the certificate checks the connection, and neither replaces the other. A unix socket takes no token: its mode 0600 file already decides who may connect, so its frames carry no digest at all. See "SECURITY".

log

Log file. Defaults to the control path with .log appended, when you give none. Every client the backend drops is written there with the reason it was dropped. A relative name is taken from the directory the backend is in when it first writes. See "LOG".

daemonize

Fork into the background, detach from the terminal and send output to the log. Off by default, so a failure to load the class or bind the socket is reported by die to whoever started it.

max_clients

How many connections to accept before refusing more, including connections still handshaking. Default 128. A unix client over the limit is sent a signed busy reply; a TCP client has no TLS session yet to sign one for, so it is closed and its frontend reports a failed connection.

max_objects

How many objects to hold before refusing to construct more. Default 4096.

max_queued

How many bytes may be waiting to be written to one client before it is dropped. Default one maximum-size frame (64 MiB) plus a little, so no reply the protocol allows is refused for being large. Lower it to cap what a client that asks and does not read can hold; a reply larger than the setting is then dropped rather than queued. The bound is per client, so all of them together may hold max_clients times this, which is more than any machine has; max_queued_total is what stops that from being reachable. A queued reply is also dropped if the socket takes none of it for write_timeout seconds, so this bounds what one client may have waiting, not how long it may wait.

max_queued_total

How many bytes may be waiting to be written to all clients together before the reply that would pass it is refused. Default four times max_queued: enough that a few clients may each be holding a maximum-size reply, small enough that a few hundred cannot each be holding one. A reply that would pass it is not queued and its client is dropped, with a log line giving the total, and its objects go with it; the alternative is a backend whose memory depends on how many clients decide to stop reading at once.

write_timeout

Seconds a queued reply may go without the socket taking any of it before the connection is dropped. Default 30. max_queued bounds how much one client may have waiting; without this, a client that has stopped reading could leave a reply there for ever within that allowance. Progress is what counts, so a slow client that keeps taking bytes is not dropped, however long the whole reply takes; one that takes nothing at all loses its connection, its queued reply and its objects.

max_buffered_total

The most bytes of half-received requests the backend holds, over all clients. Default four times the largest frame (about 256 MiB). A request that has only partly arrived is kept until the rest does; when these add up to more than this, the connection whose request has been arriving the longest is dropped, and its objects with it, until they fit. Set it no lower than the largest request you expect.

read_timeout

Seconds a half-received request may go without another byte arriving before the connection is dropped. Default 30. A client that is idle between requests is not affected, however long it waits.

start_timeout

Seconds to wait for another backend that is shutting down to release its lock. Default 2.

handshake_timeout

Seconds a TCP connection may spend on its TLS handshake before it is dropped and its slot freed, and then seconds any new connection may take to send a hello that is accepted. Default 5. So a connection that says nothing cannot hold one of the max_clients places.

idle_timeout

Seconds a client that has said hello may send nothing before it is dropped, and its objects with it. Default 0, which means for ever, because a program that uses its object rarely is normal. Set it if programs you do not trust to leave can connect: without it they can occupy all max_clients places.

max_log_size

When the log grows past this many bytes it is copied to LOG.1, replacing any earlier one, and emptied. Default 10485760 (10 MiB); 0 means never. A log that is a symbolic link or not a plain file is left alone. The size is looked at when the backend logs a line or has served a request.

call_timeout

Seconds one call to a target (a method, or the target's new) may run before the backend stops it and answers with the timeout kind. Default 60. 0 means no limit. The backend serves one request at a time, so a call that never returns would hold every client; this bound is what ends it. The call is stopped with an exception raised at the next point where Perl can run it, which is between two operations: a call that is inside one long operation (a system call, a long regular expression, an XS function) is stopped when that operation ends. The target's object is not repaired or removed: it may have been left half changed, and a later call on it sees it so. A target that sets its own alarm or $SIG{ALRM}, or that catches the exception and carries on, defeats the limit; the call is still reported as timed out when it returns.

config_file

The path of a configuration file to read site settings from. It is not an option of the backend itself and is not kept. See "CONFIGURATION".

config_dirs

An array reference of directories to search for the configuration file when config_file is a bare file name. Not kept either.

METHODS

The schemas in each API SPECIFICATION follow the conventions of Params::Validate::Strict (for input) and Return::Set (for output). They describe the method for people and for tools. The code does not call those modules, and this distribution does not depend on them.

new

my $backend = Class::Shared::Backend->new(%options);

Checks the options and returns a backend that is ready to run. It does not open a socket, take a lock or start anything: that happens in "run". Every option is described in "OPTIONS". You may pass the options as a list of pairs or as one hash reference.

The options come from three places. What you pass always wins. What you do not pass is taken from the environment, and then from a configuration file, as "CONFIGURATION" describes. Whatever the source, each value is checked the same way.

Choose one transport. With neither host nor port you get a unix socket (socket, or the default path). With host and port you get TCP over TLS, which also needs tls_cert, tls_key, tls_ca and token. A unix socket refuses a token and TLS files, because its permissions already decide who may connect.

Side effects: reads the environment and, if there is one, a configuration file. It builds the object and nothing else.

Dies if an option name is not known or a value has the wrong type or is out of range (for example a port that is not a whole number from 1 to 65535). The message says whether the bad value was an argument or a configured value, and names the option. It also dies if the options are inconsistent: only one of host and port; socket together with host/port; a TCP listener without a token or without all three TLS files; a unix socket with a token or TLS files; or an over-long socket path. (A perl without unix sockets is reported by run, or by new when it has to work out the default socket path.)

DECISION TABLE

The rules are checked in this order, and the first one that applies is the one you read. A value that is empty counts as not set, so token => '' is no token, and an empty TLS file name is a missing one.

host or port given?   rule                                     refused with
-------------------   --------------------------------------   ----------------------------
one of them only      a TCP listener needs both                needs both host and port
both, and a socket    use host/port or a socket, not both      either socket or host/port
both, no token        a TCP listener needs a token             needs a token
both, TLS files < 3   a TCP listener needs all three           needs tls_cert, tls_key ...
both, all of it       accepted as a TCP listener
neither, path too     the socket must fit in an address        more than the N allowed
  long
neither, a token      a unix socket needs no token             a unix socket needs no token
neither, a TLS file   a unix socket needs no TLS               a unix socket needs no TLS
neither               accepted as a unix listener

Three plain-English steps show why the table is complete. A listener is TCP if it has a host or a port, and unix if it has neither, so every input is in exactly one half. In the TCP half a token and all three TLS files are required and a socket is not allowed, so each missing or extra thing has one rule that refuses it. In the unix half a token and every TLS file are forbidden, so each extra thing has one rule that refuses it.

An option that you do not give gets its default. An option that you do give keeps its value even when that value is false, so write_timeout => 0 is a timeout of 0 and not the default, and log => '0' is a log file called 0. The defaults are read when you call new, so a program may set a package variable such as $Class::Shared::Backend::WRITE_TIMEOUT before it does.

API SPECIFICATION

Input

{
    socket            => { type => 'string',  optional => 1, min => 1, max => 100 },
    dir               => { type => 'string',  optional => 1, min => 1 },
    host              => { type => 'string',  optional => 1, min => 1 },
    port              => { type => 'integer', optional => 1, min => 1, max => 65535 },
    tls_cert          => { type => 'string',  optional => 1, min => 1 },
    tls_key           => { type => 'string',  optional => 1, min => 1 },
    tls_ca            => { type => 'string',  optional => 1, min => 1 },
    token             => { type => 'string',  optional => 1, matches => qr/\A[\x20-\x7E]*\z/ },
    log               => { type => 'string',  optional => 1, min => 1 },
    daemonize         => { type => 'boolean', optional => 1 },
    max_clients       => { type => 'integer', optional => 1, min => 1 },
    max_objects       => { type => 'integer', optional => 1, min => 1 },
    max_queued        => { type => 'integer', optional => 1, min => 1 },
    max_queued_total  => { type => 'integer', optional => 1, min => 1 },
    write_timeout     => { type => 'number',  optional => 1, min => 0 },
    handshake_timeout => { type => 'number',  optional => 1, min => 0 },
    start_timeout     => { type => 'number',  optional => 1, min => 0 },
    call_timeout      => { type => 'number',  optional => 1, min => 0 },
    read_timeout      => { type => 'number',  optional => 1, min => 0 },
    max_buffered_total => { type => 'integer', optional => 1, min => 1 },
    idle_timeout      => { type => 'number',  optional => 1, min => 0 },
    max_log_size      => { type => 'integer', optional => 1, min => 0 },
    config_file       => { type => 'string',   optional => 1, min => 1 },
    config_dirs       => { type => 'arrayref', optional => 1 },
}

Output

{ type => 'object', isa => 'Class::Shared::Backend' }

run

my $status = $backend->run;

Starts serving. In order, it

  1. goes into the background, if daemonize is true (see below);

  2. makes sure the socket directory exists and is safe;

  3. takes the lock that makes the backend a singleton (waiting up to start_timeout seconds for a backend that is shutting down);

  4. opens the listening socket (removing a leftover one that nobody answers on) and writes the pid file;

  5. serves clients until it is told to stop; and

  6. closes everything, destroys every object, removes the socket and pid file, and releases the lock.

It stops when it receives SIGTERM or SIGINT, or when a client sends the shutdown request (for example class-shared stop). SIGHUP and SIGPIPE are ignored.

Returns 0 after a normal stop. A backend object is one life: calling run again after it has stopped dies with this backend has already run and stopped. Make a new object to serve again.

Background mode. When daemonize is true, run forks twice. The process that called it exits with status 0 as soon as the first fork has finished, so run does not return there. Only the background copy goes on. The calling process does not wait for the background copy to be ready, so the socket may not exist yet when it exits. If starting fails in the background copy, the reason is written to the log and the copy exits with status 1.

Side effects: creates the socket directory, a lock file (.owner), a pid file (.pid) and a log file (.log) next to the socket; opens the listening socket; loads each class a client asks for; writes to the log. The socket and the pid file are removed at a normal stop. The lock file and the log are left in place.

Dies (when not in the background) with the reason if it cannot start: another backend is serving, the directory is unsafe, this perl has no unix sockets, the socket cannot be bound, or TLS cannot be set up. The same reason is written to the log first.

API SPECIFICATION

Input

{ }

Output

{ type => 'integer', memberof => [0] }

DESTROY

Called by Perl when the backend object goes away. It removes the socket file, but only if this object created it. A backend that failed to start because another one was already serving never owned the socket, so it leaves the other backend's socket alone. You do not call it yourself.

LOG

The backend writes its log with Log::Abstraction. Each message is one line:

[4242] 2026-11-25 10:44:55 serving on /run/user/1000/class-shared/class-shared.sock (pid 4242)

That is the process id of the process that wrote it, the local date and time, and the message. The pid is there because the process that starts a backend and the backend itself can write to the same file. A line is written as soon as the event happens, so you can follow the log with tail -f.

A message that has more than one line has a tab put at the start of each line after the first, so that nothing in a message can look like the start of a new entry. Percent signs in a message are written as they are.

Normal events (starting, stopping, a shutdown request) are logged at info. Clients that are dropped or refused are logged at warn. Failures of the backend itself (a file that cannot be removed, a reply that cannot be encoded, an internal error) are logged at error. All three are always written: there is no option to turn them down.

If the log cannot be opened or written (for example its directory does not exist), the backend carries on without it. The log is the place where failures are reported, so there is nowhere else to report this one.

CONFIGURATION

A backend can take its options from outside the program, so that whoever runs it can change them without editing code. This is done with Object::Configure. The same option can come from three places. The first one that has a value wins:

  1. what you passed to new;

  2. an environment variable named Class__Shared__Backend__OPTION, for example Class__Shared__Backend__max_clients=50;

  3. a configuration file, but only if the program that makes the backend names one with config_file. Nothing is searched for. See "Where the settings can come from".

This is the opposite of Object::Configure's own default, in which the program's values have the lowest priority. It is reversed here on purpose. The backend holds a secret (token) and the names of the certificates it trusts, and a stray variable in the environment must not be able to replace what the program chose. A value you do not pass is the place where a site default is welcome.

The file is named after the class, in lower case, with :: turned into -: class-shared-backend.yml. JSON works too (class-shared-backend.json); the kind of file is taken from its name. You give config_file either as a full path, or as a bare file name together with config_dirs, a list of directories to look in. No directory is searched unless you ask: a file in ~/.conf, for example, is not read. A config_file that has a .. in it is refused. Inside, the settings sit under a key that has __ where the class name has :::

---
Class__Shared__Backend:
    max_clients: 50
    max_objects: 1000
    log: /var/log/class-shared.log

Only the options listed in "OPTIONS" are taken from the file or the environment. Other keys are ignored, because the same file may hold settings for other classes. Each value is checked as strictly as an argument would be, and a bad one is reported as "a configured value is not valid". The rules between options still apply: a token in the environment is refused for a unix socket, just as one passed in code is.

A file called universal.yml in the same directory is read as well, and its UNIVERSAL: section applies to this backend and to every other class that uses Object::Configure. Keep the backend's file in a directory of its own so that no such file is picked up by accident.

Treat these places as you would treat the program. A token or a certificate path set in a file or in the environment can be read by anybody who can read that file or that process's environment. Keep the file mode 0600 and prefer --token-file in class-shared to putting a secret in a variable.

A backend that a frontend starts for you inherits the environment of that frontend, so these variables apply to it too.

RUNNING AS A SERVICE

You do not have to do any of this. The first frontend that cannot find a backend starts one for you. Run the backend as a service when you want it to be running before the first request, to be started again if it stops, or to run with settings that you choose in one place.

Examples marked (tested) were run, on systemd 257 with Perl 5.40. Those marked (not run) were written from the manual of that system and have not been run, so try them before you rely on them.

Decide where it lives

A unix socket is mode 0600 in a directory that only its owner can write to. This has three results.

  • Only the user who runs the backend can connect to it. Sites that run as different users cannot share one unix socket backend. Run them as one user, run one backend for each user, or use TCP with TLS (see "TLS").

  • Every client must look in the same directory as the backend. The directory is the first of these that is set: --dir or dir, the CLASS_SHARED_DIR environment variable, $XDG_RUNTIME_DIR/class-shared, /run/user/UID/class-shared, and last the system temporary directory. The most common fault is a backend that was started with --dir while the clients use the default. Run class-shared path in the same environment as a client to see where it will look.

  • The backend makes these files next to the socket: the socket itself, a lock file (.owner), a pid file (.pid) and the log (.log). If you use RuntimeDirectory with systemd, all of them are deleted when the service stops. See "Where the log goes".

Where the settings can come from

There are three places, and not all of them work with the class-shared command.

Command line options

--dir, --socket, --log, --listen, the TLS options and --token-file. Nothing else, so there is no option for max_clients.

Environment variables

Any option, as Class__Shared__Backend__NAME. This works with the class-shared command (tested): with Class__Shared__Backend__max_clients=1 set, a second client was refused. A service manager can set them for you.

A configuration file

Any option, but only when the program that makes the backend passes config_file. The class-shared command has no option for that, and a Class__Shared__Backend__config_file variable is ignored (tested). To use a file you need a launcher, which is three lines of Perl.

A value in the environment beats one in a file, and a value on the command line or in code beats both.

A configuration file and a launcher (tested)

The file, /etc/class-shared/class-shared-backend.yml:

---
Class__Shared__Backend:
    dir: /run/class-shared
    log: /var/log/class-shared/backend.log
    max_clients: 50
    max_objects: 1000

The launcher, /usr/local/bin/class-shared-backend:

#!/usr/bin/perl
use strict;
use warnings;
use Class::Shared::Backend;

Class::Shared::Backend->new(
    config_file => '/etc/class-shared/class-shared-backend.yml',
)->run;

Run it from a service manager like any other program. With this file it used the directory and log the file named, enforced max_clients, and stopped cleanly on SIGTERM (tested). The file is read once, when the backend starts, so a change needs a restart. Do not set daemonize in a file that a service manager runs: the manager would lose track of the process.

systemd, for one user (tested)

This is the usual choice for a web site that runs as an ordinary user. Save it as ~/.config/systemd/user/class-shared.service:

[Unit]
Description=Class::Shared backend

[Service]
Type=simple
StateDirectory=class-shared
EnvironmentFile=-%h/.config/class-shared/backend.env
ExecStart=/usr/local/bin/class-shared start --foreground --log %S/class-shared/backend.log
Restart=on-failure
RestartSec=2

[Install]
WantedBy=default.target

Then:

systemctl --user daemon-reload
systemctl --user enable --now class-shared
systemctl --user status class-shared
class-shared status

To start it at boot and not when you log in, run loginctl enable-linger $USER once.

The settings go in ~/.config/class-shared/backend.env, one NAME=value a line. The - after EnvironmentFile= means that the file may be missing:

Class__Shared__Backend__max_clients=50
Class__Shared__Backend__max_objects=1000
TZ=UTC

--foreground keeps the backend in the process that systemd started. Without it the command goes into the background and systemd thinks the service has ended. The socket is in the default directory, /run/user/UID/class-shared, because systemd sets XDG_RUNTIME_DIR for a user service, so clients need no setting.

What was checked: the service starts and reports active; the environment file is applied; after kill -9 the service came back after the delay set by RestartSec and a client could reach it, because a backend removes a socket that nobody answers on; and systemctl --user stop ends it cleanly and removes the socket. Stop needs no ExecStop: the backend stops on SIGTERM.

Two things to know. First, systemd does not read your shell's startup files. Its PATH is short, and PERL5LIB and perlbrew are not set. Give ExecStart the full path of the script. If you use perlbrew or a local library, name the perl that installed it as well, as in ExecStart=/home/you/perl5/perlbrew/perls/perl-5.40.0/bin/perl /home/you/perl5/perlbrew/perls/perl-5.40.0/bin/class-shared start --foreground, or add Environment=PERL5LIB=/home/you/perl5/lib/perl5 for your classes. Second, Restart=on-failure does not restart a backend that class-shared stop ended, because that is a normal exit. Use Restart=always if you want it back even then.

systemd, a system service (not run)

Use this when the backend should start with the machine, for the user that the web server runs as. Save it as /etc/systemd/system/class-shared.service:

[Unit]
Description=Class::Shared backend
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
RuntimeDirectory=class-shared
RuntimeDirectoryMode=0700
LogsDirectory=class-shared
EnvironmentFile=-/etc/class-shared/backend.env
Environment=CLASS_SHARED_DIR=/run/class-shared
ExecStart=/usr/local/bin/class-shared start --foreground --dir /run/class-shared --log /var/log/class-shared/backend.log
Restart=on-failure
RestartSec=2

[Install]
WantedBy=multi-user.target

Then systemctl daemon-reload and systemctl enable --now class-shared. RuntimeDirectoryMode=0700 matters: the backend refuses a directory that other users can write to. The clients must run as the same user and must be told the directory, with CLASS_SHARED_DIR=/run/class-shared in their environment or dir => '/run/class-shared' in their code.

To use a configuration file, replace ExecStart with the launcher from the section above.

macOS, launchd (not run)

Save this as ~/Library/LaunchAgents/org.cpan.class-shared.plist. macOS has no XDG_RUNTIME_DIR, and the temporary directory that a launchd job sees may not be the one that your shell sees, so give the directory explicitly here and to every client:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>org.cpan.class-shared</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/bin/class-shared</string>
    <string>start</string>
    <string>--foreground</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>CLASS_SHARED_DIR</key><string>/Users/you/Library/Caches/class-shared</string>
  </dict>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key>
  <dict><key>SuccessfulExit</key><false/></dict>
</dict>
</plist>

Load it with launchctl load ~/Library/LaunchAgents/org.cpan.class-shared.plist. SuccessfulExit false means "restart it only if it failed", like systemd's on-failure. With a plain KeepAlive set to true, launchd would start the backend again after class-shared stop.

FreeBSD, rc.d (not run)

Save this as /usr/local/etc/rc.d/class_shared and make it executable. It uses the command's own background mode and its stop command, so no daemon(8) is needed:

#!/bin/sh
# PROVIDE: class_shared
# REQUIRE: LOGIN
# KEYWORD: shutdown

. /etc/rc.subr

name="class_shared"
rcvar="class_shared_enable"
start_cmd="class_shared_start"
stop_cmd="class_shared_stop"
status_cmd="class_shared_status"

: ${class_shared_user:="www"}
: ${class_shared_dir:="/var/run/class-shared"}

class_shared_start() {
    su -m "${class_shared_user}" -c \
        "/usr/local/bin/class-shared start --dir ${class_shared_dir}"
}
class_shared_stop() {
    su -m "${class_shared_user}" -c \
        "/usr/local/bin/class-shared stop --dir ${class_shared_dir}"
}
class_shared_status() {
    su -m "${class_shared_user}" -c \
        "/usr/local/bin/class-shared status --dir ${class_shared_dir}"
}

load_rc_config $name
run_rc_command "$1"

Enable it with sysrc class_shared_enable=YES. Create the directory first, owned by that user and mode 0700. The command in the background mode returns before the backend is ready (see "run"), so a script that needs it at once should run class-shared status in a short loop. OpenBSD's rc.d works in the same way, with rc_start and rc_stop running the same two commands.

runit and s6 (not run)

These want a program that stays in the foreground, which is what --foreground is. A runit run file:

#!/bin/sh
exec 2>&1
exec chpst -u www /usr/local/bin/class-shared start --foreground \
    --dir /var/run/class-shared --log /var/log/class-shared/backend.log

For s6, use s6-setuidgid www in place of chpst -u www.

Containers (not run)

Run one backend in a container, in the foreground, and share the socket directory with the containers that have the clients:

docker run -d --name class-shared --user 33:33 \
    -v class-shared-run:/run/class-shared \
    myimage class-shared start --foreground --dir /run/class-shared

Every client container mounts the same volume at the same place and runs with the same user id (33 here), because the socket is mode 0600.

Without a service manager

The command starts the backend in the background, and stop ends it:

class-shared start
class-shared status
class-shared stop

To start it when the machine does, put @reboot /usr/local/bin/class-shared start in your crontab. Nothing starts it again if it stops, which is the difference from the examples above.

Windows

Not supported. A backend needs unix sockets and owner-only directories (see "SECURITY").

Where the log goes

The backend writes its log to a file (see "LOG"), also in the foreground. It does not write it to the journal or to standard output, so journalctl shows only what the service manager says (tested). Use --log to put the file somewhere that lasts. The default, next to the socket, is wrong for a service that has a RuntimeDirectory: systemd deletes the directory when the service stops, and the log with it (seen in testing). StateDirectory and LogsDirectory are kept (tested for StateDirectory).

The backend has its own environment

A service does not get your shell's environment, and a backend started by a frontend gets the frontend's. Anything that a class reads from the environment must be set for the backend. The one that shows up first is TZ: Date::Manip complains and refuses to work without a time zone, so a class that uses it needs TZ=UTC (or your zone) in the unit or the environment file. A class that reads the request's own variables, such as REMOTE_ADDR, gets the backend's, not the client's. Pass those values as arguments instead.

Objects live in memory. When the backend restarts, the objects that it held are gone.

SINGLETON

Two guards keep it to one backend per directory:

  • An exclusive flock on a control file in the socket directory, held for the life of the process. A second backend there exits with an explanation, whatever transport it was asked to use.

  • A unix socket in the way is probed: if something answers, the backend is already running; if not, the socket is a leftover and is removed. A TCP port that is in use fails to bind.

OBJECT LIFETIME

An object belongs to the connection that created it. When that connection closes -- because the frontend was destroyed, the client exited, or the client process died -- the backend destroys the object. A client cannot call, or even see, another client's object: ids are checked against the connection that owns them.

PROTOCOL

Every request and reply is a hash reference in a length-prefixed Storable frame; see Class::Shared::Protocol. Clients must start with hello.

hello

{ op => 'hello', proto => 2, class => 'Class::Simple' }. proto must be the backend's own protocol version. class is optional: a client that names none can still use ping and shutdown, which is how class-shared status works. A name is checked (see "ENCODING") and the class is loaded, once for the whole backend. The reply carries the backend's pid and version.

new

{ op => 'new', args => [...] }. Constructs a new object with those arguments and replies with its id. A constructor that dies is reported and no object is created.

call

{ op => 'call', id => $id, method => 'name', args => [...], want => 'list' | 'scalar' | 'void' }. Replies with result => [ ... ], or ok => 0 with the text of the exception. new, DESTROY and AUTOLOAD may not be called, and the id must belong to this connection.

ping

{ op => 'ping' }. Counters and identity, for class-shared status: objects, calls, clients, classes, uptime, queued (the bytes waiting to be written to all clients together) and max_queued_total, the ceiling those bytes are held against, so the one number can be read as a fraction of the other.

shutdown

{ op => 'shutdown' }. Replies first, then destroys every object and exits.

A reply that says ok => 0 also has a kind, which tells a program what went wrong, and an error, which tells a person. The kinds are:

protocol

The request was malformed, came out of order, or spoke another protocol version.

unknown_class

The class could not be loaded.

busy

The backend is full: too many clients or too many objects.

die

The target's new or method died; error is its message.

unknown_object

No such object (it may have been released).

timeout

The call ran for longer than call_timeout and was stopped; error says which call. The object is still there.

unknown_method

The target class has no such method.

forbidden

The object belongs to another connection, or the method may not be called.

internal

The backend itself failed while handling the request.

SECURITY

A unix socket is created mode 0600 in a directory only the owner can write to. That is the whole of its authentication, so it takes neither a token nor TLS, and its frames carry no digest.

The class is the client's choice. The handshake loads whatever module is named, so anybody who can connect can make the backend require any module it can find, running that module's load-time code. That is the same power they would have running perl themselves as the backend's user, which is what a unix socket's owner-only permissions and a TCP listener's certificate and token are there to confine: keep them to people you would let run code here.

A TCP listener is a TLS endpoint with client certificates: it needs tls_cert/tls_key to prove which backend it is, and tls_ca to decide which clients are welcome. Verification of the client is mandatory (SSL_VERIFY_FAIL_IF_NO_PEER_CERT), so a client that presents no certificate, or one signed by another CA, is dropped inside accept and never becomes a connection with a buffer or an object. The rejection is logged; there is nobody to send an explanation to, because they have not been authenticated.

It also needs a token. With one, every frame carries an HMAC-SHA-256 of its body, keyed with the token, and the digest is verified before Storable::thaw is given any of the frame. That order is what makes the token a guard rather than a comment: thaw runs code of the sender's choosing, so a peer without the secret is stopped before deserialisation, not after it. A wrong or missing digest ends that connection. The refusal is signed like any other frame, so a peer that does not hold the secret cannot read it either.

So the two checks answer different questions. TLS says which machine is calling and keeps what it sends private; the token says whether the frame in front of us was built by somebody who knows the secret. A stolen certificate is not a stolen secret, and a leaked secret does not let anybody read the traffic.

A unix socket needs no token, and takes none: it is created mode 0600 in a directory only the owner can write to, so the kernel has already decided who may connect and its frames carry no digest.

TLS

TCP is TLS; there is no unencrypted TCP mode. new refuses a host/port listener without tls_cert, tls_key and tls_ca, the same way it refuses one without a token, so a port cannot be opened in the clear by forgetting an argument.

The certificate has to name the address clients connect to: a frontend given a tls_ca checks the name as well as the chain, so an address- or hostname-based certificate for classhost.example.com is the one to issue for a backend reached at that name. A frontend given a tls_fingerprint instead pins this exact certificate by digest, in which case the name and the signer (a private CA, or none at all) do not have to satisfy anybody.

The commands that produce the four files, with the subjectAltName the certificate needs and a working frontend to match, are in "TRANSPORT SECURITY" in Class::Shared; t/certs/make-certs.sh in the distribution generates the same set, with a second CA and impostor certificates, for the tests.

Frame reads are non-blocking too. A connection that stops halfway through a frame, or halfway through the TLS record carrying it, keeps what has arrived in its own buffer; the loop goes on serving everyone else and resumes that connection when the rest arrives.

Replies are queued per connection and written as the socket takes them, so a client that asks for an answer and then stops reading holds its own reply, not the loop. What it may hold is bounded by max_queued: once more than that is waiting to be written to it, the client is dropped, since the alternative is holding the backend's memory for as long as it chooses to stay connected. For the same reason a queued reply that makes no progress for write_timeout seconds is dropped too: the bound caps how much a client may hold, the timeout caps how long it may hold it. max_queued_total caps what all of them together may hold, so the memory a few hundred clients that all stop reading can pin is a number, not the product of two other numbers.

The handshake is not done in accept. An accepted socket starts its TLS layer without a handshake and then finishes it, a little at a time, from the select loop as that socket becomes readable or writable. A peer that connects and then says nothing therefore costs one pending handshake for at most handshake_timeout seconds (five by default), after which it is dropped and its slot freed, while every client already connected keeps being served in the meantime. Doing the handshake in accept would let anyone who can reach the port freeze the backend for the length of the timeout, and the loop is single-threaded, so that would be every client.

Data nested many thousands of levels deep cannot be read by Storable without crashing the process. The backend therefore first reads any request over 4096 bytes in a child process, and refuses the request, and drops its connection, if the child dies. This costs one fork for each large request, and a class with a STORABLE_thaw hook sees that hook run in the child as well.

ENCODING

Arguments, results and error text: full Unicode.

Everything a client sends or receives is a Storable image, which keeps strings exactly as they are. Accented letters, any alphabet and emoji pass through the backend unchanged. The backend does not look inside them.

Class names: ASCII only.

A class name is checked in the handshake. Only the letters A to Z, digits and underscores, with :: between words, are accepted.

The token: ASCII only.

The digest is worked out by Digest::SHA on bytes. A character above code point 255 stops it from working, and a character from 128 to 255 gives a different answer as a Perl string than as the bytes of a file. So new accepts only printable ASCII (space to ~) in a token and refuses anything else.

Paths: ASCII is safest.

socket, dir, log and the tls_* files go to the operating system as they are. The 100 character limit on a socket path counts characters.

The log: not one encoding.

The log has no encoding layer. A message with only characters up to code point 255 is written as one byte per character (so caf\x{e9} is the Latin-1 byte, not UTF-8). A message with a higher character, such as an emoji, is written as UTF-8, and Perl prints a Wide character warning. Most log lines are the backend's own English text; other text can only come from an error in your own class (for example internal error while handling a request: ...). Read the log as bytes, and expect that a line may be in either form.

COMMON PITFALLS

With daemonize, run does not return in your program.

The process that calls it exits with status 0 once the background copy is started. Put nothing after the call that you need to run. Also, the process exits before the background copy is ready, so the socket may not exist at that moment.

Without daemonize, run does not return until the backend stops.

It runs the server loop for as long as the backend lives.

Which classes are loaded is decided by the clients.

There is no class option. The class must be findable in the @INC that the backend was started with, so start it with the right -I or PERL5LIB.

A misspelt option is an error.

new dies on a name it does not know, as Class::Shared::Frontend does. This includes class, which was never an option: the clients choose the class.

Environment variables and files can change what you did not pass.

If your program leaves max_clients out, Class__Shared__Backend__max_clients in the environment sets it. To be sure of a value, pass it. A bad value in the environment stops the backend from starting, and the message says it came from configuration.

The configuration file is looked up once per process.

Object::Configure remembers where it found the file for a class. Changing config_file later in the same process may not be noticed.

Log::Abstraction is not told where to log by your configuration.

Object::Configure would also accept a logger setting, but the backend ignores it and always logs to log, so that the file the clients and the CLI are told about is the file that is used.

Loading the configuration modules costs a little start-up time.

Roughly 0.1 seconds, which matters only if you start a backend very often.

The backend keeps the environment it was started with.

Its %ENV and its current directory are those of whoever started it. A client cannot change them.

One request at a time.

A slow method makes every other client wait, whatever class they use.

A TCP listener needs four things.

tls_cert, tls_key, tls_ca and a token. A unix socket accepts none of them, on purpose.

Only one backend per directory.

A second backend in the same directory exits with "another backend is already serving". That failure does not touch the first backend's socket.

A killed backend leaves files behind.

After kill -9 the socket file and the pid file stay. The next backend starts normally: it finds that nothing answers on the socket and removes it. The lock file (.owner) and the log are never removed.

Old log lines are thrown away.

It keeps only one earlier copy: see max_log_size. To keep more, give log a symbolic link to a file that something else rotates.

The limits drop clients, not requests.

A client that goes over max_queued, max_queued_total or write_timeout loses its connection and, with it, its objects.

max_clients counts connections that are still shaking hands.

A client over the limit is told "busy" on a unix socket. On TCP it is simply closed, because the TLS handshake has not happened.

The class's package variables are shared.

All objects of a class live in one process, so all clients see the same package variables. Keep state in the object.

SEE ALSO

Class::Shared, Class::Shared::Frontend, Class::Shared::Protocol, class-shared, Log::Abstraction, Object::Configure, Params::Get, Params::Validate::Strict.

AUTHOR

Nigel Horne

FORMAL SPECIFICATION

This section describes what the backend does in the Z notation, a way of writing exactly what a program promises using sets and logic. You do not need it to use the module. Read the plain text above first.

Z uses mathematical symbols, so this is the only part of the file that is not plain ASCII. A short key:

x? input      x! output      x' the value of x after the operation
=>  implies   /\  and        \/  or        ~  not
⊥  undef      ⊕  update a function      ⩤  remove from a function (domain subtraction)
↦  maps to    ⇸  partial function       #  size of a set

State

┌─ Backend ───────────────────────────────────────────────
│ classes     : ℙ CLASSNAME               loaded, each once
│ clients     : FD ⇸ CLIENT               open connections
│ objects     : ℕ₁ ⇸ (OBJECT × SERIAL)    object id to its object and owner
│ queued      : ℕ                         bytes waiting to be written, all clients
│ stop        : 𝔹
│ owns_socket : 𝔹
├─────────────────────────────────────────────────────────
│ #clients ≤ max_clients ∧ #objects ≤ max_objects
│ queued = Σ { #c.outbuf | c ∈ ran clients } ∧ queued ≤ max_queued_total
│ ∀ c ∈ ran clients • ∀ id ∈ c.objects • id ∈ dom objects ∧ owner(objects id) = c.serial
│ ∀ id ∈ dom objects • ∃ c ∈ ran clients • owner(objects id) = c.serial
│                                  an object never outlives its connection
└─────────────────────────────────────────────────────────

and each CLIENT has class (a class name or ⊥), greeted (𝔹), serial, objects (the ids it made), buffer and outbuf (bytes), and closed.

new

┌─ New ───────────────────────────────────────────────────
│ args?, env, file : NAME ⇸ VALUE ; out! : RESULT[Backend]
│ opts == (file ⊕ env) ⊕ args?            the caller's arguments win, then env, then file
├─────────────────────────────────────────────────────────
│ dom args? ⊄ OPTIONS ∨ ¬ valid(args?)    ⇒ ∃ m • out! = dies(m)
│ ¬ valid(opts ∖ dom args?)               ⇒ ∃ m • out! = dies(m)   a configured value
│ otherwise, with opts as below:
│ host? = ⊥ ∧ port? = ⊥ ∧ no token ∧ no tls_*  ∧ #socket ≤ 100  ⇒ out! = value(b) ∧ b is idle
│ host? ≠ ⊥ ∧ port? ≠ ⊥ ∧ socket? = ⊥ ∧ token ≠ ⊥ ∧ tls_cert, tls_key, tls_ca ≠ ⊥
│                                                    ⇒ out! = value(b) ∧ b is idle
│ any other combination ⇒ ∃ m • out! = dies(m)
└─────────────────────────────────────────────────────────

where an option whose value is ⊥ counts as absent from args?, and valid means every named option exists and its value has the right type and range.

run

┌─ Run ───────────────────────────────────────────────────
│ ΔBackend ; out! : RESULT[{0}]
├─────────────────────────────────────────────────────────
│ setup succeeds ⇒ owns_socket' = (transport = unix)
│                  ∧ (the loop runs until stop = true)
│                  ∧ at the end: clients' = ∅ ∧ objects' = ∅ ∧ owns_socket' = false ∧ out! = value(0)
│ setup fails ∧ ¬ daemonize ⇒ out! = dies(e) ∧ owns_socket' = false
│ setup fails ∧ daemonize   ⇒ the background process exits 1
│ daemonize ⇒ the calling process exits 0 and out! is never seen
└─────────────────────────────────────────────────────────

hello

┌─ Hello ─────────────────────────────────────────────────
│ ΔBackend ; c : CLIENT ; proto? : ℕ ; class? : STRING⊥ ; out! : REPLY
├─────────────────────────────────────────────────────────
│ proto? ≠ PROTOCOL_VERSION ⇒ out! = failure(protocol) ∧ ΞBackend
│ class? ¬in; CLASSNAME ∧ class? ≠ ⊥ ⇒ out! = failure(protocol)
│ class? ∈ CLASSNAME ∧ load fails ⇒ out! = failure(unknown_class)
│ otherwise ⇒ c.greeted' = true ∧ c.class' = class?
│             ∧ classes' = classes ∪ {class? | class? ≠ ⊥} ∧ out!.ok = true
└─────────────────────────────────────────────────────────

new (the request)

┌─ NewObject ─────────────────────────────────────────────
│ ΔBackend ; c : CLIENT ; args? : seq DATA ; out! : REPLY
├─────────────────────────────────────────────────────────
│ ¬ c.greeted ⇒ failure(protocol)            c.class = ⊥ ⇒ failure(protocol)
│ #objects ≥ max_objects ⇒ failure(busy)
│ c.class->new(args?) dies ⇒ failure(die)
│ c.class->new(args?) = o ∧ o is a reference
│     ⇒ ∃ id ¬in; dom objects • objects' = objects ⊕ {id ↦ (o, c.serial)}
│           ∧ c.objects' = c.objects ∪ {id} ∧ out! = (ok, id)
└─────────────────────────────────────────────────────────

call

┌─ Call ──────────────────────────────────────────────────
│ ΔBackend ; c : CLIENT ; id?, m? : ... ; args? : seq DATA ; want? : {list, scalar, void}
├─────────────────────────────────────────────────────────
│ id? ¬in; dom objects ⇒ failure(unknown_object)
│ id? ∈ dom objects ∧ owner(objects id?) ≠ c.serial ⇒ failure(forbidden)
│ m? ∈ {"new", "DESTROY", "AUTOLOAD"} ⇒ failure(forbidden)
│ the class has no method m? ⇒ failure(unknown_method)
│ the method dies with e ⇒ failure(die)               objects' = objects
│ the method returns r ⇒ out! = (ok, shape(want?, r))   calls' = calls + 1
└─────────────────────────────────────────────────────────

ping and shutdown

┌─ Ping ──────────────────────────────────────────────────
│ ΞBackend ; c.greeted = true ; out! = (ok, counters of the state above)
└─────────────────────────────────────────────────────────

┌─ Shutdown ──────────────────────────────────────────────
│ ΔBackend ; c.greeted = true
├─────────────────────────────────────────────────────────
│ stop' = true ∧ out! = (ok, "shutting down")     the reply is sent first
└─────────────────────────────────────────────────────────

drop a client

┌─ Drop ──────────────────────────────────────────────────
│ ΔBackend ; c : CLIENT ; reason? : STRING
├─────────────────────────────────────────────────────────
│ c ∈ ran clients
│ objects' = c.objects ⩤ objects                      its objects are destroyed
│ clients' = clients \ {c's descriptor}               the connection is closed
│ queued' = queued - #c.outbuf                        its queued reply is discarded
│ a log line records reason?
└─────────────────────────────────────────────────────────

STATE DIAGRAM

First, the life of the backend process. Then, the life of one client connection inside it.

The backend

+------+  run()  +----------+  lock taken, socket bound  +---------+
| IDLE | ------> | STARTING | -------------------------> | SERVING | <-+
+------+         +----------+                            +---------+   | requests keep
                      |                                       |      --+ it SERVING
         something    |                       SIGTERM, SIGINT |
         fails        v                       or "shutdown"   v
                 +----------+                            +----------+
                 |  FAILED  |                            | STOPPING |
                 +----------+                            +----------+
                                                               |
                                                cleanup done   v
                                                          +---------+
                                                          | STOPPED |
                                                          +---------+
IDLE to STARTING

Trigger: run. Action: if daemonize, fork twice (the caller exits 0); then check the directory, take the lock, and open the socket.

STARTING to SERVING

Trigger: the socket is open. Action: the pid file is written and serving on ... is logged. A unix backend now owns its socket.

STARTING to FAILED

Trigger: another backend holds the lock or the socket, the directory is unsafe, TLS cannot be set up, or the bind fails. Action: the reason is logged. The foreground run dies; a background copy exits with status 1. The other backend's socket is not touched.

SERVING to SERVING

Trigger: a client connects, sends a request, or goes away. Action: see the client diagram below.

SERVING to STOPPING

Trigger: SIGTERM, SIGINT or a shutdown request. Action: the loop ends.

STOPPING to STOPPED

Trigger: cleanup finishes. Action: queued replies get one last try to be sent, all connections are closed, every object is destroyed (so each DESTROY runs, here), the socket and pid file are removed, the lock is released, stopped is logged and run returns 0.

One client connection

+----------+  TCP: start TLS   +-------------+
| ACCEPTED | ----------------> | HANDSHAKING |
+----------+                   +-------------+
     |                           |         |
     | unix: no TLS              | done    | fails, or takes longer
     |                           |         | than handshake_timeout
     v                           v         |
+----------------+ <-------------+         |
| AWAITING HELLO | <-+  a failed hello      |
+----------------+ --+  changes nothing     |
     | good hello                           |
     v                                      |
+---------+  new, call, ping:               |
| GREETED | <-+  stays GREETED              |
+---------+ --+  (new adds an object)       |
     |                                      |
     | error, end of file, bad frame,       |
     | or over a limit                      |
     v                                      v
+----------------------------------------------+
|  DROPPED: objects destroyed, socket closed,  |
|  reason logged                               |
+----------------------------------------------+
ACCEPTED to HANDSHAKING

Trigger: a TCP client connects (and the backend is not full). Action: start TLS without waiting. The handshake finishes a little at a time from the loop.

ACCEPTED to AWAITING HELLO

Trigger: a unix client connects. Action: none; its socket is already trusted by its file permissions.

ACCEPTED to DROPPED

Trigger: the backend already has max_clients connections. Action: a unix client gets a signed busy reply first; a TCP client is just closed.

HANDSHAKING to AWAITING HELLO

Trigger: the TLS handshake finishes. Action: none.

HANDSHAKING to DROPPED

Trigger: the handshake fails (for example no client certificate, or one signed by another CA) or takes longer than handshake_timeout. Action: logged and closed; no object was ever made.

AWAITING HELLO to GREETED

Trigger: a hello with the right protocol version and a valid, loadable class (or no class). Action: the class is loaded once (if new) and the connection is marked greeted. A further hello on a greeted connection is refused with a protocol failure and changes nothing.

GREETED to GREETED

Trigger: new, call, ping. Action: new adds an object owned by this connection. call runs a method. An exception from the target is sent back as a reply and does not change the state.

any state to DROPPED

Trigger: end of file, a read or write error, a frame that is too large or fails its digest, a reply that would pass max_queued or max_queued_total, a queued reply that makes no progress for write_timeout seconds. Action: the connection's objects are destroyed, its queued data is discarded, the socket is closed, and the reason is logged. (When the backend itself stops, it closes every connection during its cleanup; that is not logged as a drop.)

LICENSE

This module is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation.

This module is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LICENSE file for the full text.