NAME

Class::Shared::Frontend - a stand-in for one object that lives in a backend

SYNOPSIS

Each example is a different real-world pattern.

use Class::Shared::Frontend;

# 1. Share one class between many processes.  The object is built in the
#    shared backend, and this process runs none of the class's code.
my $simple = Class::Shared::Frontend->new('Class::Simple');

$simple->foo('hello');
print $simple->foo(), "\n";                 # prints "hello"

# 2. The same, giving the class's constructor arguments.
#    It is Class::Simple->new(verbose => 1).
my $verbose = Class::Shared::Frontend->new('Class::Simple',
    ctor => [verbose => 1],
);

# 3. A backend on another machine, reached over TLS with a client
#    certificate, and checked against a CA.
my $remote = Class::Shared::Frontend->new('Class::Simple',
    host       => 'classhost.example.com',
    port       => 7000,
    tls_ca     => '/etc/class-shared/server-ca.pem',
    tls_cert   => '/etc/class-shared/client.pem',
    tls_key    => '/etc/class-shared/client-key.pem',
    token_file => '/etc/class-shared/token',
    ctor       => [verbose => 1],
);

# 4. Trust exactly one certificate by its fingerprint instead of a CA.
my $pinned = Class::Shared::Frontend->new('Class::Simple',
    host            => '192.0.2.10',
    port            => 7000,
    tls_fingerprint => 'AB:CD:EF:...:12',
    tls_cert        => 'client.pem',
    tls_key         => 'client-key.pem',
    token_file      => '/etc/class-shared/token',
);

# 5. Do not start a backend; fail if there is none.  Catch the error.
my $maybe = eval {
    Class::Shared::Frontend->new('Class::Simple', autostart => 0)
};
warn "no backend running: $@" unless $maybe;

# 6. Ask about the connection, and call a method whose name clashes with a
#    frontend method.
print "backend pid: ", $simple->shared_pid, "\n";
my $status = $simple->shared_status;
print "objects held: $status->{objects}\n";

# Same as $simple->foo('hello'), but also works when the target's method
# has the same name as one of the frontend's own methods.
my $same = $simple->shared_call('foo', 'hello');

# 7. Let go of the object early (it is also released when $simple goes away).
$simple->shared_close;

DESCRIPTION

Each frontend stands for one object. Constructing it asks a Class::Shared::Backend to run the target's new with the arguments in ctor, and the backend returns an id. Every method call is then forwarded over the socket, applied to that object, and the result comes back.

The backend holds many such objects, all belonging to the one copy of the class it loaded. So a hundred client processes with ten objects each still cost one copy of Class/Simple.pm, while keeping a hundred processes' worth of independent objects.

The object lives as long as the connection. When the frontend is destroyed, or the process exits or dies, the socket closes and the backend destroys everything that connection created; the target's DESTROY runs there, once.

A frontend never loads the target class. If no backend is listening on a unix socket, one is started automatically (autostart => 0 forbids that, and a TCP backend is never started for you).

In this page, target means the real class that is being shared (for example Class::Simple), and backend means the process that holds the real objects. A socket is a connection point two programs use to talk; a unix socket is a file for programs on the same machine. See "Words used in this documentation" in Class::Shared for the rest.

OPTIONS

my $frontend = Class::Shared::Frontend->new('Class::Simple', %options);

The class name may be the first argument or class => 'Class::Simple'.

ctor

Array reference of arguments for the target's new, passed as a list in the order given: ctor => [verbose => 1] is Class::Simple->new(verbose => 1), and ctor => [{verbose => 1}] is Class::Simple->new({verbose => 1}). Defaults to none, which is Class::Simple->new().

They are used once, when the frontend connects and the backend constructs the object, and they are serialised to get there, so they must be plain data: a code reference, or anything else Storable cannot freeze, is reported when the frontend is constructed rather than silently dropped. A constructor that dies makes new die with Class::Shared: could not construct Class::Simple: and the error the backend reported.

dir

Directory for the unix socket. Defaults to "default_dir" in Class::Shared.

socket

An explicit unix socket path, overriding dir and the derived name. 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.

host, port

Talk to a TCP backend on another machine, over TLS. Both are required together, and neither may be combined with socket. Autostarting does not apply. tls_cert and tls_key are required with them, and so is one of tls_ca or tls_fingerprint.

tls_ca, tls_fingerprint

How the backend is verified. One of the two is required for TCP and there is no way to switch verification off: a backend that does not verify is not a backend.

tls_ca is a PEM file of the CA that signed the backend's certificate, and the certificate must also name host. tls_fingerprint is the SHA-256 digest of that one certificate, as openssl x509 -in server.pem -noout -fingerprint -sha256 prints it (colons and all, with or without a sha256$ prefix); a pinned backend is accepted for its digest alone, whatever it is called and whoever signed it, so a self-signed certificate and an address that does not match its name are both fine.

Give one or the other, not both: a CA and a pin are alternatives.

tls_cert, tls_key

The certificate and private key this client presents. The backend verifies clients, so a connection without one is refused during the handshake and this frontend gets no object; the error says the backend refused the certificate and names these options.

token, token_file

The shared secret, needed only for a TCP backend, which will not start without one and refuses a frame it cannot authenticate; a frontend whose token is wrong is refused at the handshake and gets no object. It is a second check on top of TLS, not a replacement for it. A unix socket takes none -- its mode 0600 file already decides who may connect -- and new dies if one is given. Prefer token_file; a secret passed as token is visible to anything that can read this process's memory or command line. Give one or the other: new dies if both are given.

autostart

True by default. When false, a missing unix backend is an error.

timeout

Seconds to wait for a backend that is being started, for a TCP connect, and for the backend's answer to the first two requests (the handshake and the request for an object). The backend serves one request at a time, so a backend that is busy running another client's method answers late; when it takes longer than this, new dies with the reason instead of waiting without end. Default 10. It does not limit how long a later method call may take.

log

Where a backend started by this frontend should write. Defaults to the socket path with .log appended.

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 $frontend = Class::Shared::Frontend->new('Class::Simple', %options);
my $frontend = Class::Shared::Frontend->new('Class::Simple', \%options);
my $frontend = Class::Shared::Frontend->new(class => 'Class::Simple', %options);

Connects to a backend (starting one for a unix socket if there is none and autostart is true), and asks it to build one object. Returns the frontend. Every option is described in "OPTIONS".

The class name may be the first argument or the class option. The options may be a list of pairs or one hash reference.

Side effects: opens a connection. It may fork and start a backend process. It may create the socket directory (mode 0700) and a lock file, and it may write the backend's log.

Dies (with the reason) if an option is unknown or wrong, if no backend can be reached or started, if the handshake is refused, or if the target's new dies. No object is returned in these cases.

It also refuses to connect to a unix socket that is not the user's own: one whose directory is owned by someone else or can be written to by group or others, or that is not a socket or is owned by someone else. Such a socket could answer every call with whatever it liked, and would be told every argument. The reason begins "will not connect to". The same rule applies to class-shared status and class-shared stop.

API SPECIFICATION

Input

{
    class           => { type => 'string', position => 0, optional => 0,
                         matches => qr/\A[A-Za-z_][A-Za-z0-9_]*(?:::[A-Za-z_][A-Za-z0-9_]*)*\z/ },
    ctor            => { type => 'arrayref', optional => 1 },
    dir             => { type => 'string',   optional => 1, min => 1 },
    socket          => { type => 'string',   optional => 1, min => 1, max => 100 },
    host            => { type => 'string',   optional => 1, min => 1 },
    port            => { type => 'integer',  optional => 1, min => 1, max => 65535 },
    token           => { type => 'string',   optional => 1, matches => qr/\A[\x20-\x7E]+\z/ },
    token_file      => { type => 'string',   optional => 1, min => 1 },
    autostart       => { type => 'boolean',  optional => 1 },
    timeout         => { type => 'number',   optional => 1, min => 0 },
    log             => { type => 'string',   optional => 1, min => 1 },
    tls_cert        => { type => 'string',   optional => 1, min => 1 },
    tls_key         => { type => 'string',   optional => 1, min => 1 },
    tls_ca          => { type => 'string',   optional => 1, min => 1 },
    tls_fingerprint => { type => 'string',   optional => 1 },
}

Domains

The options are checked before a connection is made, so every partition
below is refused without contacting a backend.

partition                        representative              result
-------------------------------------------------------------------------
unknown option                    bogus => 1                  dies
odd number of arguments           "odd"                       dies
no class                          ()                          dies
invalid class name                2Bad, Foo::, M + U+00FC     dies
ctor not an array reference       ctor => "x"                 dies
unix socket with a token          token => "s"                dies
unix socket with TLS              tls_ca => "ca.pem"          dies
token and token file together     token, token_file           dies
host without port                 host => "h"                 dies
port without host                 port => 1                   dies
socket with host and port         socket, host, port          dies
TCP without certificate or key    host, port                  dies
TCP with both a CA and a pin      tls_ca, tls_fingerprint     dies

Port boundary values, with a host present: 1 and 65535 are accepted and
validation passes to the next option; 0, 65536, -1, "", "80x", " 80" and
"80.0" die.  A port is a whole number, so "0080" is accepted as 80.  A
missing host or port is reported before the port is range checked.  The
class name follows L<Class::Shared/validate_class>, and ctor must be an
array reference.

A valid unix frontend needs only a class name; a valid TCP frontend needs
host, port, tls_cert, tls_key and exactly one of tls_ca and
tls_fingerprint.  Those partitions connect, so they are covered by
F<t/02-frontend.t>; the refusals above are covered by F<t/domain.t>.

Output

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

AUTOLOAD (any method of the target)

my $answer  = $frontend->any_method(@args);
my @answers = $frontend->any_method(@args);
           $frontend->any_method(@args);

Any method name that the frontend does not define itself is sent to the backend, applied to this frontend's object, and the result is returned. The calling context is kept: in list context all the values come back, in scalar context the scalar comes back, and in void context nothing does.

An exception thrown by the target is thrown again here with its original text.

Side effects: one round trip to the backend, and whatever the target method does there. The call waits for as long as the method takes; there is no time limit.

Dies if the target dies, if the target has no such method, if the object has been released, or if the connection is lost.

A method name is a plain name: letters, digits and underscores, not starting with a digit. A name with a package in it (Other::function, SUPER::new) is refused by the backend, because it would call that function with the object as its first argument instead of a method of the object's class.

API SPECIFICATION

Input

{
    method => { type => 'string', description => 'the name you called' },
    args   => { type => 'arrayref', description => 'plain data only (Storable can freeze it)' },
}

Output

{
    type        => 'any',
    description => 'whatever the target method returns, in the context you called it in',
}

shared_call

my @result = $frontend->shared_call('method_name', @args);

Calls a method of the target by name. Use it when the target's method has the same name as one of the frontend's own methods (shared_pid, can, isa, and so on), because a direct call would reach the frontend's version instead. It keeps the calling context.

The backend refuses new, DESTROY and AUTOLOAD.

Side effects: as for any forwarded method.

Dies if the method name is missing or empty, and in the same cases as a forwarded method.

API SPECIFICATION

Input

{
    method => { type => 'string', position => 0, optional => 0, min => 1 },
    args   => { type => 'arrayref', position => 1, optional => 1 },
}

Output

{ type => 'any' }

shared_class

my $class = $frontend->shared_class;

The name of the target class, such as Class::Simple. Never fails.

API SPECIFICATION

Input

{ }

Output

{ type => 'string', min => 1 }

shared_address

my $where = $frontend->shared_address;

The place this frontend connects to: the socket path for a unix backend, or host:port for a TCP backend.

API SPECIFICATION

Input

{ }

Output

{ type => 'string', min => 1 }

shared_socket_path

my $path = $frontend->shared_socket_path;

The unix socket path, or undef when the backend is on TCP.

API SPECIFICATION

Input

{ }

Output

{ type => 'string', optional => 1, description => 'undef for a TCP backend' }

shared_pid

my $pid = $frontend->shared_pid;

The process id of the backend. It is undef after the connection is closed.

API SPECIFICATION

Input

{ }

Output

{ type => 'integer', optional => 1, min => 1 }

shared_id

my $id = $frontend->shared_id;

This object's number inside the backend. It is undef after the connection is closed. The number is only meaningful to that backend.

API SPECIFICATION

Input

{ }

Output

{ type => 'integer', optional => 1, min => 1 }

shared_connected

if ($frontend->shared_connected) { ... }

Returns 1 while the connection is open and 0 after it has been closed or lost. It does not test the connection; it only reports what this frontend last knew. A backend that has died is noticed on the next call.

API SPECIFICATION

Input

{ }

Output

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

shared_last_error

my $why = $frontend->shared_last_error;

Why the last connection attempt, or the last lost connection, failed. Undef if there has been no problem. A message is kept until something replaces it.

API SPECIFICATION

Input

{ }

Output

{ type => 'string', optional => 1 }

shared_status

my $status = $frontend->shared_status;
print "$status->{objects} objects, up $status->{uptime} seconds\n";

Asks the backend how it is, and returns its answer as a hash reference. The keys are:

ok

1 when the backend answered.

classes

An array reference: the names of the classes the backend has loaded, sorted.

objects

How many objects it holds now, for all clients.

constructed

How many objects it has built since it started.

clients

How many connections it has now.

calls

How many method calls it has run.

queued, max_queued_total

The bytes waiting to be written to all clients, and the ceiling for that.

pid, version, proto

The backend's process id, the version of the distribution, and the protocol version.

address

Where it is listening.

started, uptime

When it started (seconds since the epoch) and how long it has run (seconds).

Side effects: one round trip.

Dies if the connection is closed or lost.

API SPECIFICATION

Input

{ }

Output

{
    type   => 'hashref',
    schema => {
        ok               => { type => 'integer', memberof => [1] },
        classes          => { type => 'arrayref' },
        objects          => { type => 'integer', min => 0 },
        constructed      => { type => 'integer', min => 0 },
        clients          => { type => 'integer', min => 0 },
        calls            => { type => 'integer', min => 0 },
        queued           => { type => 'integer', min => 0 },
        max_queued_total => { type => 'integer', min => 0 },
        pid              => { type => 'integer', min => 1 },
        version          => { type => 'string' },
        proto            => { type => 'integer', min => 1 },
        address          => { type => 'string' },
        started          => { type => 'integer', min => 0 },
        uptime           => { type => 'integer', min => 0 },
    },
}

shared_close

$frontend->shared_close;

Closes the connection and gives up the object. The backend then destroys the object, and the target's DESTROY runs there. Any later call on this frontend dies. It is safe to call twice.

This also happens by itself when the frontend goes out of scope or the program ends.

Returns 1 if it closed an open connection, and 0 if there was none.

Side effects: closes the socket. If the close itself fails, a warning is given with carp; the frontend is still unusable afterwards.

API SPECIFICATION

Input

{ }

Output

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

shared_shutdown

$frontend->shared_shutdown;

Asks the whole backend to stop. This destroys every object it holds, including other clients' objects, so it is for administration and for tests, not for normal use. The frontend is closed. For a unix backend it then waits (up to 5 seconds) for the socket file to go away.

Returns 1 if the backend said it would stop, 0 otherwise (including when there was no connection).

Side effects: stops the backend process.

Dies if the request cannot be completed, after closing the frontend.

API SPECIFICATION

Input

{ }

Output

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

can

my $code = $frontend->can('method_name');
$code->($frontend, @args) if $code;

Says whether the target has a method of that name. For the frontend's own methods (such as shared_call) it answers by itself. For other names it asks the backend. If the answer is yes, it returns a code reference you can call; the reference sends the call to the backend. If the answer is no, or the backend cannot be asked, it returns undef.

Called on the class name instead of an object (Class::Shared::Frontend->can(...)) it behaves as Perl's usual can.

API SPECIFICATION

Input

{ method => { type => 'string', position => 0, optional => 0, min => 1 } }

Output

{ type => 'coderef', optional => 1, description => 'undef when the method does not exist' }

isa

if ($frontend->isa('Class::Base')) { ... }

Says whether the target is, or inherits from, the named class. It is always true for Class::Shared::Frontend and UNIVERSAL. Other names are put to the backend. It returns 1 or 0.

API SPECIFICATION

Input

{ class => { type => 'string', position => 0, optional => 0, min => 1 } }

Output

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

DESTROY

Called by Perl when the frontend goes away. It closes the connection, so the backend destroys the object. You do not call it yourself.

ERRORS

A call dies if the target dies, if the method does not exist, if the object has been released, or if the connection is lost. A lost connection is never silently replaced by a new object, because that would throw away the state the caller thought it had.

The messages you are most likely to see, and what to do:

Class::Shared::Frontend->new: unknown option 'NAME'

You spelled an option wrong. Check "OPTIONS".

Class::Shared::Frontend->new: a unix socket needs no token ... (or no TLS)

You gave token, token_file or a tls_* option without host and port. Remove them: a unix socket does not use them.

Class::Shared::Frontend->new: give token or token_file, not both

Both options name the same secret. Remove one of them.

Class::Shared::Frontend->new: port must be a whole number from 1 to 65535

The port given with host is not a number in that range. Correct it.

Class::Shared: cannot reach a backend at ADDRESS: REASON

Nothing is listening and a backend was not started, because autostart is off or the backend is on TCP. Start the backend with class-shared start.

Class::Shared: could not start a backend: REASON (socket PATH, log PATH)

The automatic start failed. Read the log file named in the message.

When REASON begins a backend is running at PATH but did not answer, nothing was started or removed: the backend is there, usually busy running another client's method. Try again, or raise timeout.

Class::Shared: cannot load CLASS: ERROR

The backend could not find or compile the class. The text after the colon is Perl's own message, for example Can't locate Class/Simple.pm in @INC. Check the spelling, and check that the backend can see the directory that holds the class (see "COMMON PITFALLS").

Class::Shared: could not construct CLASS: ERROR

The class loaded, but the target's new died. The text after the colon is the target's own message.

Class::Shared: lost the backend for 'CLASS': REASON

The connection broke, or a request could not be sent. The frontend is closed. Make a new one.

Class::Shared: this frontend has no connection to a backend ...; its object is gone

You called a method after shared_close, or after the connection was lost.

Class::Shared: socket path 'PATH' is N characters, more than the 100 allowed ...

The socket (or the default directory) makes a path that is too long. Use a shorter one.

ENCODING

Arguments, constructor arguments, results and error text: full Unicode.

They are sent with Storable, which keeps strings unchanged. Accented letters, Chinese, Arabic and emoji all arrive intact, and so does the difference between a byte string and a character string. This was checked with "caf\x{e9}", "\x{1F600}" and Japanese text, including in an exception message and in ctor. Decode input before sending it, and encode it when you print it.

Class names: ASCII only.

Letters A to Z, digits and underscores, with :: between the words.

Method names: use ASCII.
token and the file named by token_file: ASCII only.

A token with an accented letter is different as a string and as the bytes of a file, and a character above code point 255 cannot be used at all. The two ends would disagree and the connection would be refused.

dir, socket, log and the tls_* files: ASCII is safest.

They are given to the operating system as they are. The 100 character limit on a socket path counts characters, not bytes.

tls_fingerprint: hexadecimal digits, with optional colons.

COMMON PITFALLS

new is the frontend's, not the target's.

To pass arguments to the target's constructor, use ctor. You cannot call the target's new through the frontend; the backend refuses.

ctor is used once.

It is read when the object is built. Changing the array afterwards does nothing. Every element must be plain data.

Only plain data can be an argument or a return value.

Strings, numbers, undef, and array and hash references of those. A code reference, a file handle or a tied object cannot be sent. If you try, the call fails with "lost the backend ... cannot serialise message", and the frontend is closed, so the object is gone. A method that returns an object also cannot be used: the object stays in the backend.

Method names that clash with the frontend's own.

new, can, isa, DESTROY and every name that starts with shared_ belong to the frontend. Reach the target's method of that name with shared_call.

timeout does not limit a method call.

It limits starting a backend, making a TCP connection, and waiting for the answers to the handshake and to the request for an object. A later call waits for as long as the target takes, and for ever if the backend hangs.

Do not use one frontend from two processes.

After a fork, the parent and the child hold the same connection, and if both use it their requests and replies can be mixed up. Make a new frontend in the child. The same goes for threads.

A lost connection means a lost object.

The frontend does not reconnect, because a new object would have none of the old state. Make a new frontend and set it up again.

The backend sees the @INC of the process that started it.

A backend started automatically searches for classes in the directories that @INC held when it was started. A later client that has added a directory (use lib) will get "cannot load ... Can't locate ..." if the target class lives only there. Start the backend yourself with the right -I, or make sure the first client has the full @INC.

The class's package variables are shared.

All clients of one class share its package variables and any class data, because the class is loaded once. Keep state in the object.

A slow method delays every client.

The backend does one thing at a time.

A list is not a count.

my $n = $frontend->items calls the method in scalar context, exactly as Perl would. A method that returns a list gives its last value there.

undef in list context is one value.

A method that returns undef in list context gives a list with one element.

shared_shutdown is not shared_close.

shared_close gives up your object. shared_shutdown stops the backend for everybody.

A unix socket takes no token and no TLS.

Giving one is an error, on purpose, so that it never looks like extra protection.

SEE ALSO

Class::Shared, Class::Shared::Backend, Class::Shared::Protocol, class-shared.

AUTHOR

Nigel Horne

FORMAL SPECIFICATION

This section describes what each method 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 (no value)          ⊕  update a function    ↦  maps to

State

┌─ Frontend ──────────────────────────────────────────────
│ class     : CLASSNAME
│ conn      : {open, closed}
│ id        : ℕ₁ ∪ {⊥}          the object's number in the backend
│ pid       : ℕ₁ ∪ {⊥}          the backend's process id
│ last_error: STRING ∪ {⊥}
├─────────────────────────────────────────────────────────
│ conn = open ⇔ id ≠ ⊥ ∧ pid ≠ ⊥        (an open frontend always has an object)
│ conn = closed ⇒ id = ⊥ ∧ pid = ⊥
└─────────────────────────────────────────────────────────

The backend is described in "FORMAL SPECIFICATION" in Class::Shared::Backend. Here objects is the backend's partial function from ids to objects.

new

┌─ New ───────────────────────────────────────────────────
│ ΔFrontend ; opts? : OPTIONS ; objects, objects' : ℕ₁ ⇸ OBJECT
├─────────────────────────────────────────────────────────
│ opts? valid ∧ backend reachable (or started, if unix and autostart) ∧ target new succeeds
│     ⇒ conn' = open ∧ id' ¬in; dom objects ∧ objects' = objects ⊕ {id' ↦ o}
│ any other case ⇒ new dies, and no Frontend exists
└─────────────────────────────────────────────────────────

AUTOLOAD (forwarded methods) and shared_call

┌─ Forward ───────────────────────────────────────────────
│ ΞFrontend ∨ ΔFrontend ; m? : STRING ; args? : seq DATA ; ctx? : {list, scalar, void}
│ out! : RESULT[seq DATA]
├─────────────────────────────────────────────────────────
│ conn = open ∧ args? serialisable ∧ target method m? exists
│     ∧ the call returns r in context ctx?
│     ⇒ out! = value(shape(ctx?, r)) ∧ conn' = open        shape: list->r, scalar->⟨r(0)⟩, void->⟨⟩
│ conn = open ∧ the target method dies with e ⇒ out! = dies(e) ∧ conn' = open
│ conn = open ∧ args? not serialisable ⇒ out! = dies(e) ∧ conn' = closed ∧ id' = ⊥
│ connection breaks ⇒ out! = dies(e) ∧ conn' = closed ∧ id' = ⊥
│ conn = closed ⇒ out! = dies("no connection ... its object is gone")
└─────────────────────────────────────────────────────────

shared_close

┌─ SharedClose ───────────────────────────────────────────
│ ΔFrontend ; objects, objects' : ℕ₁ ⇸ OBJECT ; out! : {0, 1}
├─────────────────────────────────────────────────────────
│ conn = open ⇒ conn' = closed ∧ id' = ⊥ ∧ pid' = ⊥ ∧ out! = 1
│               ∧ objects' = {id} ⩤ objects              the backend destroys it
│ conn = closed ⇒ ΞFrontend ∧ out! = 0
└─────────────────────────────────────────────────────────

shared_shutdown

┌─ SharedShutdown ────────────────────────────────────────
│ ΔFrontend ; out! : {0, 1}
├─────────────────────────────────────────────────────────
│ conn = closed ⇒ ΞFrontend ∧ out! = 0
│ conn = open ∧ backend accepts ⇒ conn' = closed ∧ out! = 1 ∧ the backend stops
│                                 ∧ objects' = ∅          every client's object
│ conn = open ∧ request fails ⇒ conn' = closed ∧ it dies
└─────────────────────────────────────────────────────────

shared_status

┌─ SharedStatus ──────────────────────────────────────────
│ ΞFrontend ; out! : RESULT[STATUS]
├─────────────────────────────────────────────────────────
│ conn = open ⇒ out! = value(s) ∧ s.objects = #objects ∧ s.classes = loaded classes
│ conn = closed ∨ connection breaks ⇒ out! = dies(e)
└─────────────────────────────────────────────────────────

can

┌─ Can ───────────────────────────────────────────────────
│ ΞFrontend ; m? : STRING ; out! : CODE ∪ {⊥}
├─────────────────────────────────────────────────────────
│ m? ∈ methods(Class::Shared::Frontend)    ⇒ out! ≠ ⊥          answered here
│ conn = open ∧ m? ∈ methods(class)        ⇒ out! ≠ ⊥          the code ref forwards the call
│ otherwise (including a broken connection) ⇒ out! = ⊥
└─────────────────────────────────────────────────────────

isa

┌─ Isa ───────────────────────────────────────────────────
│ ΞFrontend ; c? : STRING ; out! : {0, 1}
├─────────────────────────────────────────────────────────
│ c? ∈ {"Class::Shared::Frontend", "UNIVERSAL"} ⇒ out! = 1
│ conn = open ∧ class isa c?                    ⇒ out! = 1
│ otherwise                                      ⇒ out! = 0
└─────────────────────────────────────────────────────────

Accessors

┌─ Accessors ─────────────────────────────────────────────
│ ΞFrontend
├─────────────────────────────────────────────────────────
│ shared_class! = class          shared_id! = id           shared_pid! = pid
│ shared_connected! = 1 if conn = open, else 0
│ shared_last_error! = last_error
└─────────────────────────────────────────────────────────

STATE DIAGRAM

A frontend is made by new. new either returns a frontend that is already BOUND, or it dies. So the first diagram is what happens inside new, and the second is the life of the frontend you get back.

Inside new:

          +------------+  backend answers  +------------+  object built  +-------+
new() --> | CONNECTING | ----------------> | HANDSHAKEN | -------------> | BOUND |--> new() returns
          +------------+                   +------------+                +-------+
             |                                  ^    |
  nothing    |                                  |    | refused, or the
  answers    v        a backend answers         |    | target's new() dies
          +-----------+ ------------------------+    |
          | SPAWNING  |                               |
          +-----------+                               |
                |                                     |
                | no answer in time, or the           |
                | fork or the directory fails         |
                v                                     v
          +-------------------------------------------+
          | FAILED: new() dies, no object is returned |
          +-------------------------------------------+

After new returns:

    +-- forwarded call, shared_call, shared_status, can, isa,
    |   or an accessor: no change.  (A target exception also
    v   leaves the state as it is.)
+---------+   shared_close, shared_shutdown, DESTROY,    +--------+
|  BOUND  | -------------------------------------------> | CLOSED |
+---------+   connection lost, or an argument can't be   +--------+
              sent (the frontend closes itself)             |   ^
                                                            +---+
                                 any call on a closed frontend dies
CONNECTING to HANDSHAKEN

Trigger: new; the backend answers the hello message. Action: the frontend stores the backend's pid.

CONNECTING to SPAWNING

Trigger: nothing answers, the transport is a unix socket and autostart is true. Action: take a lock file, make sure the directory is safe, remove a leftover socket, fork a backend and wait. A socket is leftover only if no backend holds the lock on the file named by the socket path plus .owner. A backend that holds it but does not answer is waited for, and nothing of its is removed.

SPAWNING to HANDSHAKEN

Trigger: the new backend answers the hello message. Action: the lock is released and the frontend stores the backend's pid.

SPAWNING to FAILED

Trigger: the directory is unsafe, the fork fails, or no backend answers within timeout seconds. Action: new dies with could not start a backend.

HANDSHAKEN to BOUND

Trigger: the backend builds the object. Action: the frontend stores the object id. new returns.

HANDSHAKEN to FAILED

Trigger: the handshake is refused, or the target's new dies. Action: the connection is closed and new dies.

BOUND to BOUND

Trigger: a forwarded call, shared_call, shared_status, can, isa or an accessor. Action: a round trip, or a local answer. An exception thrown by the target does not change the state.

BOUND to CLOSED, by error

Trigger: the connection breaks, or an argument cannot be serialised. Action: the frontend closes itself, records last_error and the call dies.

BOUND to CLOSED, on purpose

Trigger: shared_close, shared_shutdown or DESTROY. Action: the socket is closed and the backend destroys the object (or, for shared_shutdown, stops and destroys every object).

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.