Overview / Networking

rpc

RPC with a fixed 24-byte binary frame protected by CRC, dispatch by method number negotiated once per connection, windowed streams, multiplexing and a topic bus. A per-request identifier keeps a late response from becoming the answer to the next call.

Always compiled: part of the core build.Include #include <ethereal/cpp/rpc/rpc_inc.hpp>C layer

rpc_inc.hpp

#include <ethereal/cpp/rpc/rpc_inc.hpp>

Aggregate entry point of the Rpc module.

Remote procedure call and a topic bus over Network, over the local channel of the Process module, or inside one process. Including this header brings the whole module.

The most expensive rule, and so the first one in rpc.hpp: every request has an identifier, and the response carries the same one. Without it, the late response of a call that timed out arrives while the next call is waiting and is delivered as its response. It is not an error, it is a plausible value of the wrong method, with success, and the program goes on with it.

The other rules: a method error is distinct from a transport error. An unknown method is an error, never silence. A timeout does not cancel the work on the other side, and claiming it would is false. A notification has no confirmation. The announced size has a limit.

Three transports, and the protocol does not know which one is below it:

  • Ethereal::Rpc::CTcpTransport, between machines.
  • Ethereal::Rpc::CLocalTransport, between processes on the same machine.
  • Ethereal::Rpc::CLoopbackTransport, inside one process. Embedded mode, and also a test double. The code path is the same as in the distributed case, which avoids the bug that only shows up in production.

bus.hpp

#include <ethereal/cpp/rpc/bus.hpp>

Topic bus of the Rpc module.

Publish and subscribe by topic, local to the process. Four requirements of the spec shape it:

"Topic matching by a compiled prefix trie with wildcard segments, not per-message string comparison." With a hundred subscriptions and one string comparison each, publishing costs a hundred comparisons, and the cost grows with the number of subscribers. The trie is walked by the topic, so the cost grows with the segments of the topic (three or four).

"At-most-once and at-least-once delivery, selected explicitly. Exactly-once is not offered." Exactly once needs the delivery and the effect in the same transaction, and this module knows nothing about the effect. Whoever needs it needs idempotent operations on the receiving side, and then at least once is enough.

"Bounded queues with an explicit overflow policy: drop oldest, drop newest, or reject." An unbounded queue only delays the problem until memory runs out, far from the cause. With a bound, someone has to choose what is lost, and that choice belongs to the publisher, who knows whether the old or the new message matters.

"Dead letter destination after a configurable retry count." A message nobody acknowledges cannot retry forever, nor vanish silently. After N attempts it goes to the dead letter handler, where someone can see it.

The bus is local to the process. Carrying it between processes means connecting it to a transport: what is published on one side goes out as a notification, and what arrives as a notification is published on the other. Reliable delivery between machines belongs to the transport, not to this object.

enum

EDelivery

Ethereal::Rpc#
C++
enum class   EDelivery : ETL_UINT8
{
    /// @brief  Deliver and forget. If the subscriber did not see it, nobody notices.
    eAtMostOnce = 0,

    /// @brief  Deliver until acknowledged, or give up and send it to the dead letter.
    eAtLeastOnce
};

How a message is delivered.

enum

EOverflow

Ethereal::Rpc#
C++
enum class   EOverflow : ETL_UINT8
{
    /// @brief  Drops the oldest. For whoever wants the latest state.
    eDropOldest = 0,

    /// @brief  Drops the arriving one. For whoever wants the order from the start.
    eDropNewest,

    /// @brief  Rejects the publish and says so. For whoever cannot lose anything.
    eReject
};

What happens when a subscriber queue is full.

enum

EBusError

Ethereal::Rpc#
C++
enum class   EBusError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  Empty topic, or a topic with an empty segment.
    eBadTopic,

    /// @brief  A pattern that cannot be parsed.
    eBadPattern,

    /// @brief  A subscriber queue is full and the policy was to reject.
    eFull,

    /// @brief  Nobody receives this.
    eNoSubscribers
};

Bus errors.

alias

SMessageId

Ethereal::Rpc#
using SMessageId = ETL_UINT64;

Identifies a delivery, so it can be acknowledged.

alias

SSubscription

Ethereal::Rpc#
using SSubscription = ETL_UINT64;

Identifies a subscription, so it can be cancelled.

alias

void

Ethereal::Rpc#
using MessageFn = std::function< void( const SMessageId uId, const std::string_view sTopic, std::span< const std::uint8_t > Payload ) >;

Handler of a delivered message.

The bytes point inside the bus and do not survive the return. Whoever needs them later copies them.

struct

SPublishOptions

Ethereal::Rpc#
C++
struct   SPublishOptions   final
{
    /// @brief  Delivery guarantee.
    EDelivery    eDelivery = EDelivery::eAtMostOnce;

    /// @brief  Policy when a subscriber queue is full.
    EOverflow    eOverflow = EOverflow::eDropOldest;
};

Extra options of a publish.

const

kDefaultQueueDepth

Ethereal::Rpc#
inline constexpr std::size_t kDefaultQueueDepth = 64u;

Default number of messages in a subscriber queue.

const

kDefaultMaxRetries

Ethereal::Rpc#
inline constexpr ETL_UINT32 kDefaultMaxRetries = 3u;

Default number of delivery attempts before the dead letter.

class

CMessageBus

Ethereal::Rpc#

Publish and subscribe by topic.

class CMessageBus final
Not thread safe.
constructor

CMessageBus

#
CMessageBus();

Constructor.

function

Subscribe

#
EBusError Subscribe( const std::string_view sPattern, MessageFn Fn, SSubscription & OutId, const std::size_t uQueueDepth = kDefaultQueueDepth );

Subscribes to a topic pattern.

'sensor.*.temperature' matches 'sensor.a.temperature' and not 'sensor.a.b.temperature'. 'sensor.#' matches both.

sPattern
Segments separated by dots. '*' matches one segment, '#' matches the rest and can only be the last one.
Fn
Message handler.
OutId
Receives the subscription id.
uQueueDepth
Queue size. Zero uses the default.
eNone, or eBadPattern.
function

Unsubscribe

#
bool Unsubscribe( const SSubscription uId );

Cancels a subscription. Whatever is in its queue is lost.

uId
Subscription id.
false when the subscription does not exist.
function

SubscriberCount

#
std::size_t SubscriberCount() const noexcept;

Number of live subscriptions.

function

Publish

#
EBusError Publish( const std::string_view sTopic, std::span< const std::uint8_t > Payload, const SPublishOptions & Options = SPublishOptions() );

Puts a message in the queue of each subscriber.

Publishing does not deliver. Delivering is Pump. The split keeps the publisher from paying the time of the consumers, and it is what makes the bounded queue a real bound.

sTopic
Topic. No '*' or '#'.
Payload
Message bytes. Copied once.
Options
Delivery and overflow policy.
eNone, eBadTopic, eNoSubscribers, or eFull when a queue rejected it.
function

Pump

#
std::size_t Pump( const std::size_t uMax = 0 );

Delivers what is queued.

uMax
Maximum number of deliveries. Zero is all.
Number of messages delivered.
function

Ack

#
bool Ack( const SMessageId uId );

Acknowledges an EDelivery::eAtLeastOnce delivery.

uId
Delivery id received by the handler.
false when that id is not waiting for an acknowledgement.
function

RetryPending

#
std::size_t RetryPending();

Queues again what was not acknowledged, and sends to the dead letter what is over the retry limit.

Number of messages sent to the dead letter.
function

SetDeadLetter

#
void SetDeadLetter( MessageFn Fn );

Sets the handler of the messages that ran out of retries.

Fn
Handler. Empty discards them.
function

SetMaxRetries

#
void SetMaxRetries( const ETL_UINT32 uMax ) noexcept;

Sets how many attempts a message gets before the dead letter.

uMax
Number of attempts.
function

Published

#
ETL_UINT64 Published() const noexcept;

Number of messages published.

function

Delivered

#
ETL_UINT64 Delivered() const noexcept;

Number of deliveries made.

function

Dropped

#
ETL_UINT64 Dropped() const noexcept;

Number of messages lost because a queue was full.

function

DeadLettered

#
ETL_UINT64 DeadLettered() const noexcept;

Number of messages sent to the dead letter.

function

Pending

#
std::size_t Pending() const noexcept;

Number of deliveries waiting for an acknowledgement.

context.hpp

#include <ethereal/cpp/rpc/context.hpp>

Call metadata, call context and interceptors of the Rpc module.

Metadata are key and value pairs that travel next to the body of a message, opaque to the module: trace identifier, credential, language, deadline. The call context is what a method knows besides its arguments: metadata, deadline and cancellation, in one object so the method signature does not change again for each of them. Interceptors see each call going in and out, never the bytes.

const

kMaxMetadataPairs

Ethereal::Rpc#
inline constexpr std::size_t kMaxMetadataPairs = 32u;

Maximum number of pairs in a message.

const

kMaxMetadataBytes

Ethereal::Rpc#
inline constexpr std::size_t kMaxMetadataBytes = 4096u;

Maximum size of the encoded block, in bytes.

const

kReservedPrefix

Ethereal::Rpc#
inline constexpr std::string_view kReservedPrefix = "etl.";

Key prefix reserved for the module.

An application key with this prefix would collide with a module key the day the module needed it, and the collision would show up as a deadline nobody asked for or a lost trace. CMetadata::Set rejects them. The module itself uses CMetadata::SetReserved.

const

kDeadlineKey

Ethereal::Rpc#
inline constexpr std::string_view kDeadlineKey = "etl.deadline";

Reserved key that carries the deadline, in milliseconds still left.

class

CMetadata

Ethereal::Rpc#

Key and value pairs that travel next to a message.

class CMetadata final
Not thread safe.
enum

EResult

#
C++
enum class   EResult : ETL_UINT8
{
    /// @brief  Stored.
    eOk = 0,

    /// @brief  The key is empty.
    eEmptyKey,

    /// @brief  The key starts with @ref kReservedPrefix.
    eReserved,

    /// @brief  There are already @ref kMaxMetadataPairs pairs.
    eTooMany,

    /// @brief  The block would go over @ref kMaxMetadataBytes bytes.
    eTooBig
};

Why a pair was not stored.

function

Set

#
EResult Set( const std::string_view sKey, const std::string_view sValue );

Adds or replaces a pair.

sKey
Key. Must not start with 'etl.'.
sValue
Value.
eOk, or the reason the pair was not stored. EResult::eReserved for a key that starts with 'etl.'.
function

SetReserved

#
EResult SetReserved( const std::string_view sKey, const std::string_view sValue );

Same as Set, and accepts the reserved keys. For use inside the module.

sKey
Key.
sValue
Value.
eOk, or the reason the pair was not stored.
function

Clear

#
void Clear() noexcept;

Removes all pairs.

function

Count

#
std::size_t Count() const noexcept;

Number of pairs.

function

Has

#
bool Has( const std::string_view sKey ) const;

Tells whether a key is present.

sKey
Key.
true when the key is present.
function

Get

#
std::string_view Get( const std::string_view sKey ) const;

Value of a key.

The view points inside this object and does not survive a Set or a Clear.

sKey
Key.
The value, or an empty view when the key is not present.
function

At

#
const std::pair< std::string, std::string > & At( const std::size_t uIndex ) const;

Pair at a position, in insertion order.

uIndex
Position, below Count.
The key and the value.
function

EncodedSize

#
std::size_t EncodedSize() const noexcept;

Size of the block once encoded, in bytes.

class

SCallContext

Ethereal::Rpc#
class SCallContext final
constructor

SCallContext

#
SCallContext( const ETL_UINT32 uCorrelationId, const ETL_UINT32 uMethodId, const std::string & sMethodName, const CMetadata & In, CMetadata & Out, const std::atomic< bool > * const pCancelled, const bool bHasDeadline, const ETL_UINT64 uDeadlineMs ) noexcept : m_uCorrelationId( uCorrelationId ) , m_uMethodId( uMethodId ) , m_pName( &sMethodName ) , m_pIn( &In ) , m_pOut( &Out ) , m_pCancelled( pCancelled ) , m_bHasDeadline( bHasDeadline ) , m_uDeadlineMs( uDeadlineMs )

Built by the module. A method receives it ready.

uCorrelationId
Identifier of the call.
uMethodId
Method number, as it travels.
sMethodName
Method name. Must outlive the context.
In
Metadata received with the request.
Out
Metadata to send with the response.
pCancelled
Cancellation flag. May be null.
bHasDeadline
true when a deadline came with the call.
uDeadlineMs
Milliseconds left when the request arrived.
function

CorrelationId

#
ETL_UINT32 CorrelationId() const noexcept

Identifier of the call.

function

MethodId

#
ETL_UINT32 MethodId() const noexcept

Method number, as it travels.

function

MethodName

#
const std::string & MethodName() const noexcept

Method name.

function

Incoming

#
const CMetadata & Incoming() const noexcept

Metadata that came with the request.

function

Outgoing

#
CMetadata & Outgoing() noexcept

Metadata that will go back with the response.

function

IsCancelled

#
bool IsCancelled() const noexcept

Tells whether the caller already gave up.

With a single thread server this is only true when the cancel arrived before the method started, which happens when frames pile up. While the method runs nobody reads the transport, so nothing that arrives meanwhile is seen.

Reading while the method runs needs an I/O thread, the same piece multiplexing needs. Until then, cancellation guarantees that the response of a cancelled call is not sent. See CRpcServer::CancelledResponses.

function

HasDeadline

#
bool HasDeadline() const noexcept

Tells whether a deadline came with this call.

function

DeadlineMs

#
ETL_UINT64 DeadlineMs() const noexcept

Milliseconds that were left when the request arrived.

Zero when no deadline came. The wire carries what is left, not an instant: an instant would need both clocks to agree, and they do not. See rpc.hpp.

const

kMaxInterceptors

Ethereal::Rpc#
inline constexpr std::size_t kMaxInterceptors = 8u;
class

IInterceptor

Ethereal::Rpc#

Sees the calls going in and out, without seeing the data.

class IInterceptor
Not thread safe. The server calls it on the thread that is serving.
destructor

~IInterceptor

#
virtual ~IInterceptor() = default;

Destructor.

function

OnRequest

#
virtual bool OnRequest( SCallContext & Ctx, std::string & sError ) = 0;

The call is about to go in.

The metadata are already read (SCallContext::Incoming), which is why a credential can be checked here instead of at the start of every method.

Ctx
Call context.
sError
Receives the error message when the call is rejected.
false rejects the call: the method does not run, and the caller receives the error written in sError.
function

OnResponse

#
virtual void OnResponse( SCallContext & Ctx, const bool bOk ) = 0;

The call is about to go out.

Runs even when an earlier interceptor rejected the call, but only for the ones that already went in. An interceptor that opened something on the way in must be able to close it, and one that never went in has nothing to close.

The order is the reverse of the way in: the last one in goes out first. It is the order any nesting needs, and the only one in which an open and close pair makes sense.

Ctx
Call context.
bOk
true when the method succeeded.

frame.hpp

#include <ethereal/cpp/rpc/frame.hpp>

Wire format of the Rpc module.

Defines the 24 byte frame header, its fields and flags, and the functions that write and read it byte by byte.

The spec asks for this exact format, versioned: "Define it explicitly and version it. This is a product surface." A format that is only "what the code does" cannot be versioned or documented, and it changes without anyone noticing. This one is written down here, has a version number and a test that checks it byte by byte.

const

kFrameHeaderSize

Ethereal::Rpc#
inline constexpr std::size_t kFrameHeaderSize = 24u;

Size of the header, in bytes. Fixed.

const

kFrameMagic

Ethereal::Rpc#
inline constexpr ETL_UINT32 kFrameMagic = 0x524C5445u;

'ETLR', little endian.

const

kProtocolVersion

Ethereal::Rpc#
inline constexpr ETL_UINT8 kProtocolVersion = 1u;

Protocol version spoken by this code.

const

kDefaultMaxPayload

Ethereal::Rpc#
inline constexpr ETL_UINT32 kDefaultMaxPayload = 4u * 1024u * 1024u;

Default maximum body size. Configurable per connection.

Exists so that four bytes coming from the peer do not decide how much memory is reserved. See DecodeHeader.

enum

EFrameType

Ethereal::Rpc#
C++
enum class   EFrameType : ETL_UINT8
{
    /// @brief  Request that expects a response.
    eRequest        = 1,

    /// @brief  Successful response.
    eResponse        = 2,

    /// @brief  Failure response. Not the same as the connection dropping.
    eError            = 3,

    /// @brief  A piece of a stream.
    eStreamData        = 4,

    /// @brief  End of a stream.
    eStreamEnd        = 5,

    /// @brief  Gives up on this call.
    eCancel            = 6,

    /// @brief  Liveness probe.
    ePing            = 7,

    /// @brief  Answer to a ping.
    ePong            = 8,

    /// @brief  The sender is about to close, and says why.
    eGoAway            = 9,

    /// @brief  Opening handshake: version, limits and the method table.
    eSettings        = 10,

    /// @brief  The window of a stream opened further. See the flow control.
    eWindowUpdate    = 11
};

Kind of a frame.

const

kMaxFrameType

Ethereal::Rpc#
inline constexpr ETL_UINT8 kMaxFrameType = static_cast< ETL_UINT8 >( EFrameType::eWindowUpdate );

Largest EFrameType value known to this code.

enum

EFrameFlag

Ethereal::Rpc#
C++
enum class   EFrameFlag : ETL_UINT16
{
    /// @brief  No flag.
    eNone            = 0,

    /// @brief  The body is compressed.
    eCompressed        = 1u << 0,

    /// @brief  There is a metadata block at the end of the body.
    eHasMetadata    = 1u << 1,

    /// @brief  This is the last frame of the stream.
    eEndOfStream    = 1u << 2,

    /// @brief  The body carries a deadline.
    eHasDeadline    = 1u << 3
};

Header flags. Combine with @c |.

const

kPriorityShift

Ethereal::Rpc#
inline constexpr ETL_UINT16 kPriorityShift = 8u;

Shift of the three priority bits in the flags.

The priority is a three bit value, not a flag, so it has a mask and a shift. Mixing both in the same field is what usually makes priority "2" read as two flags set.

const

kPriorityMask

Ethereal::Rpc#
inline constexpr ETL_UINT16 kPriorityMask = 0x0700u;

Mask of the three priority bits in the flags.

const

kReservedFlagMask

Ethereal::Rpc#
inline constexpr ETL_UINT16 kReservedFlagMask = static_cast< ETL_UINT16 >( ~( 0x000Fu | kPriorityMask ) );

Bits that belong to nobody. A frame with any of them set is rejected.

operator

operator|

Ethereal::Rpc#
inline EFrameFlag operator|( const EFrameFlag A, const EFrameFlag B ) noexcept

Combines two flags.

A
First flag.
B
Second flag.
The union of both.
function

Has

Ethereal::Rpc#
inline bool Has( const ETL_UINT16 uFlags, const EFrameFlag One ) noexcept

Tests one flag in a raw flags field.

uFlags
Flags field of a header.
One
Flag to test.
true when the flag is set.
struct

SFrameHeader

Ethereal::Rpc#
C++
struct   SFrameHeader   final
{
    /// @brief  Magic number, @ref kFrameMagic.
    ETL_UINT32    uMagic          = kFrameMagic;

    /// @brief  Protocol version.
    ETL_UINT8    uVersion        = kProtocolVersion;

    /// @brief  Frame type, an @ref EFrameType.
    ETL_UINT8    uType           = static_cast< ETL_UINT8 >( EFrameType::eRequest );

    /// @brief  Flags (@ref EFrameFlag) and the priority bits.
    ETL_UINT16    uFlags          = 0u;

    /// @brief  Identifier that pairs a response with its request.
    ETL_UINT32    uCorrelationId  = 0u;

    /// @brief  Method identifier.
    ETL_UINT32    uMethodId       = 0u;

    /// @brief  Body size, in bytes.
    ETL_UINT32    uPayloadLength  = 0u;

    /// @brief  CRC of the first 20 bytes.
    ETL_UINT32    uHeaderCrc      = 0u;


    /// @brief  Frame type as the enum.
    ///
    ETL_API_NOIGN    EFrameType Type() const ETL_NOEXCEPT
    {
        return static_cast< EFrameType >( uType );
    }


    /// @brief  Priority, 0 to 7.
    ///
    ETL_API_NOIGN    ETL_UINT8 Priority() const ETL_NOEXCEPT
    {
        return static_cast< ETL_UINT8 >( ( uFlags & kPriorityMask ) >> kPriorityShift );
    }


    ///
    /// SetPriority
    ///
    /// @brief  Sets the priority bits and keeps the flags.
    ///
    /// @param uPrio        Priority. Only the low three bits are used.
    ///
    ETL_API        void SetPriority( const ETL_UINT8 uPrio ) ETL_NOEXCEPT
    {
        uFlags = static_cast< ETL_UINT16 >(
            ( uFlags & static_cast< ETL_UINT16 >( ~kPriorityMask ) )
          | ( static_cast< ETL_UINT16 >( uPrio & 0x07u ) << kPriorityShift ) );
    }
};

The header, already decoded.

This is not what goes on the wire. The wire carries the 24 bytes written by EncodeHeader. This struct is only a convenient view of them, and its size in memory does not matter.

enum

EFrameError

Ethereal::Rpc#
C++
enum class   EFrameError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  Does not start with 'ETLR'. Not our protocol, or the stream lost sync.
    eBadMagic,

    /// @brief  Version this code does not speak.
    eBadVersion,

    /// @brief  Frame type that does not exist.
    eBadType,

    /// @brief  Reserved bits set. See @ref kReservedFlagMask.
    eBadFlags,

    /// @brief  The header is corrupt. Nothing inside it can be trusted.
    eBadCrc,

    /// @brief  The announced body is over the limit.
    eTooLarge,

    /// @brief  Fewer than 24 bytes arrived.
    eShort,

    /// @brief  The body that arrived does not have the size the header announces.
    ///
    /// @details  @ref DecodeHeader never returns this. The decoder sees 24 bytes and
    ///            does not know how many came after them. The layer that joins header
    ///            and body knows, and with a message transport it has the whole
    ///            message to check.
    ///
    ///            It applies both ways: a short body is a truncated message, a long
    ///            one is garbage at the end. Both mean the two sides disagree on where
    ///            the message ends, and going on would read what is not there.
    ///
    eLengthMismatch
};

Why a header was rejected.

The reasons are separate on purpose. A plain failure is not enough to decide between closing the connection, answering with an error or ignoring the frame, and those are three different reactions.

function

FrameErrorName

Ethereal::Rpc#
const ETL_CHAR * FrameErrorName( EFrameError eError ) noexcept;

Name of a reason, for messages.

eError
Reason.
A static string. Never null.
function

HeaderCrc

Ethereal::Rpc#
ETL_UINT32 HeaderCrc( const ETL_UINT8 * pBytes ) noexcept;

CRC of the header: the first 20 bytes.

This module has its own CRC. There is a 'Cryptography::CRC32' in this tree, and it is better than this one. But section 2 of the conventions says "a module never includes another module's headers directly to get functionality", and spec 09 promises "Depends on: nothing at link time". Using the other module would break both: whoever only wanted the RPC would have to take the cryptography along. A small table of our own costs less than a link dependency.

pBytes
The header bytes. At least 20 readable.
The CRC32 of the first 20 bytes.
function

EncodeHeader

Ethereal::Rpc#
void EncodeHeader( const SFrameHeader & Header, ETL_UINT8 * pOut ) noexcept;

Writes the 24 bytes, little endian, byte by byte.

Computes and fills the CRC. The uHeaderCrc field of Header is ignored.

Header
Header to write.
pOut
Destination. Needs kFrameHeaderSize bytes.
function

DecodeHeader

Ethereal::Rpc#
EFrameError DecodeHeader( const ETL_UINT8 * pIn, std::size_t uAvailable, ETL_UINT32 uMaxPayload, SFrameHeader & OutHeader ) noexcept;

Reads the 24 bytes and checks everything that can be checked.

The order of the checks matters. Magic, version and type come first because they are cheap, and because a stream that lost sync should be reported as such, not as a bad CRC.

The CRC comes before the size. In a corrupt header the size field is worthless, and rejecting it as too large sends the caller the wrong way (raise the limit) instead of the right one (the connection is corrupting bytes).

The size is checked before anything is reserved. The spec says "A payload length beyond the limit closes the connection with GoAway. It never allocates the requested size first."

pIn
The bytes. At least uAvailable of them readable.
uAvailable
How many there are. Fewer than 24 gives EFrameError::eShort.
uMaxPayload
Body size limit.
OutHeader
Destination. Only written when the result is eNone.
eNone, or the reason the header was rejected.

rpc.hpp

#include <ethereal/cpp/rpc/rpc.hpp>

Protocol of the Rpc module: errors, server, client and streams.

Request and response over any message transport, with method numbers negotiated once per connection, metadata, deadlines, cancellation, streams with flow control, a multiplexed client mode and keep alive.

The rules of the protocol are listed below. The first one is the most expensive to get wrong.

enum

ERpcError

Ethereal::Rpc#
C++
enum class ERpcError : ETL_UINT8
{
    /// @brief  No error.
    eNone = 0,

    /// @brief  The transport is not connected.
    eNotConnected,

    /// @brief  Sending failed.
    eSendFailed,

    /// @brief  The connection dropped, or the other side closed.
    eDisconnected,

    /// @brief  The response did not arrive in time. Says nothing about whether the
    ///          method ran (see rule 4).
    eTimeout,

    /// @brief  The server does not know this method. See rule 3.
    eUnknownMethod,

    /// @brief  The method failed. Different from everything above (see rule 2).
    eMethodFailed,

    /// @brief  The message that arrived does not have the expected format.
    eMalformed,

    /// @brief  Over the limit. See rule 6.
    eTooLarge,

    /// @brief  The method name is empty, or already registered.
    eInvalidMethod,

    /// @brief  The method number came from another table. See @ref MakeMethodId.
    ///
    /// @details  The caller rarely sees this: the client handles it alone, forgets
    ///            what it learned, negotiates again and repeats the call once. It
    ///            only comes out when the second attempt also gets it, which means
    ///            the other side is changing tables on every message.
    ///
    eStaleMethodId,

    /// @brief  The two sides have no protocol version in common.
    eVersionMismatch,

    /// @brief  The other side said it is closing, and said why.
    ///
    /// @details  Different from @ref eDisconnected, and the difference is the why. A
    ///            dropped connection leaves no message: it may have been the network,
    ///            the process, the cable. An @ref EFrameType::eGoAway is the other side
    ///            closing on purpose and giving the reason (see @ref EGoAwayReason and
    ///            @ref CRpcClient::GoAwayReason).
    ///
    ///            Reacting the same way to both is the classic bug: reconnecting in a
    ///            loop against a server that is rejecting what it gets.
    ///
    eGoAway,

    /// @brief  The deadline of the call ran out before the response was ready.
    ///
    /// @details  Comes from the server side, and is the other half of @ref eTimeout:
    ///            the client says "it did not arrive in time", the server says "it was
    ///            ready, and no longer counts". The caller rarely sees it (it already
    ///            gave up), but the server counts it, and that is how one finds that
    ///            the deadlines are too tight for the work asked.
    ///
    eDeadlineExceeded,

    /// @brief  The caller gave up, and said so. See @ref EFrameType::eCancel.
    eCancelled,

    /// @brief  Refused: no license was accepted and the evaluation of this machine
    ///          has ended, or the license passed was refused (see
    ///          Bundle::UnlockBundle). Local only, never sent on the wire.
    eNotLicensed
};

What can go wrong.

These values cross the wire. The first byte of an EFrameType::eError body is one of them (see the format above). Reordering the enum changes the protocol, not only the code: an old peer would read "method failed" where the new one wrote something else. Adding at the end is safe, changing what exists is not.

enum

EGoAwayReason

Ethereal::Rpc#
C++
enum class   EGoAwayReason : ETL_UINT8
{
    /// @brief  Closes and says nothing else. Also used by a reader for a code it does not know.
    eUnspecified = 0,

    /// @brief  What arrived was not a frame of this protocol.
    ///
    /// @details  Wrong magic, unknown version, bad CRC, size mismatch. There is no
    ///            way to go on: what comes next comes from the same place. The exact
    ///            reason goes in the message.
    ///
    eProtocolError,

    /// @brief  The announced body is over the limit.
    ///
    /// @details  Has its own code because the reaction is different: here the caller
    ///            may want to raise the limit, and in the other cases that fixes
    ///            nothing.
    ///
    eTooLarge,

    /// @brief  This side is closing, and it is nobody's fault.
    eShutdown,

    /// @brief  There is no protocol version in common.
    eVersionMismatch
};

Why a side is about to close the connection.

These values cross the wire, in the first byte of an EFrameType::eGoAway body. Same rule as ERpcError: adding at the end is safe, changing what exists is not.

function

GoAwayReasonName

Ethereal::Rpc#
const ETL_CHAR * GoAwayReasonName( EGoAwayReason eReason ) noexcept;

Name of a reason, for messages.

eReason
Reason.
A static string. Never null.
const

kMethodSlotMask

Ethereal::Rpc#
inline constexpr ETL_UINT32 kMethodSlotMask = 0x0000FFFFu;

Mask of the slot bits in a method number.

const

kMethodGenerationShift

Ethereal::Rpc#
inline constexpr ETL_UINT32 kMethodGenerationShift = 16u;

Shift of the generation bits in a method number.

const

kMaxMethods

Ethereal::Rpc#
inline constexpr std::size_t kMaxMethods = 0xFFFFu;

Maximum number of methods a server can register.

function

MethodSlot

Ethereal::Rpc#
inline ETL_UINT16 MethodSlot( const ETL_UINT32 uId ) noexcept

Slot part of a method number.

uId
Method number, as it travels.
The slot, 1 based. Zero means no method.
function

MethodGeneration

Ethereal::Rpc#
inline ETL_UINT16 MethodGeneration( const ETL_UINT32 uId ) noexcept

Generation part of a method number.

uId
Method number, as it travels.
The table generation.
function

MakeMethodId

Ethereal::Rpc#
inline ETL_UINT32 MakeMethodId( const ETL_UINT16 uGeneration, const ETL_UINT16 uSlot ) noexcept

Builds a method number from a generation and a slot.

uGeneration
Table generation.
uSlot
Slot, 1 based.
The number as it travels.
struct

SPeerSettings

Ethereal::Rpc#
C++
struct   SPeerSettings   final
{
    /// @brief  Agreed version: the lower of what both sides say they speak.
    ETL_UINT8        uVersion = 0;

    /// @brief  Limit of the other side: how much it accepts to receive.
    ///
    /// @details  Honored: the client does not send a frame larger than this. It is
    ///            the only path where the limit of one side rules the other.
    ///
    ETL_UINT32        uMaxPayload = 0;

    /// @brief  Concurrent streams the other side can take. Stored, not used: this
    ///          field is zero for now.
    ETL_UINT16        uMaxStreams = 0;

    /// @brief  Mask of the compression algorithms the other side understands.
    ///          Stored, not used: zero today on both sides.
    ETL_UINT8        uCompression = 0;

    /// @brief  Generation of the server method table. See @ref MakeMethodId.
    ETL_UINT16        uTableGeneration = 0;

    /// @brief  Number of methods that came in the table.
    ETL_UINT32        uMethodCount = 0;
};

What the other side said about itself in the EFrameType::eSettings frame.

Fields this code does not use yet are here anyway, on purpose. They travel on the wire already, with their meaning written down, so the side that starts using them does not need to change the format to ask for them. Each one says below whether it is honored today or only stored.

struct

SRpcResult

Ethereal::Rpc#
C++
struct   SRpcResult   final
{
    /// @brief  Error code. eNone on success.
    ERpcError        eError = ERpcError::eNone;

    /// @brief  Message the method returned when it failed, if any.
    std::string        sMessage;


    /// @brief  true on success.
    ///
    ETL_API_NOIGN    bool IsOk() const ETL_NOEXCEPT        { return eError == ERpcError::eNone; }


    /// @brief  Tells whether the failure came from the method and not from the channel.
    ///
    /// @details  The question that decides between handling and reconnecting (see
    ///            rule 2).
    ///
    ETL_API_NOIGN    bool IsMethodFailure() const ETL_NOEXCEPT
    {
        return ( eError == ERpcError::eMethodFailed ) || ( eError == ERpcError::eUnknownMethod );
    }
};

Result of a call.

const

kDefaultWindow

Ethereal::Rpc#
inline constexpr ETL_UINT32 kDefaultWindow = 64u * 1024u;

Default window: how much a reader accepts to have unread.

const

kWindowKey

Ethereal::Rpc#
inline constexpr std::string_view kWindowKey = "etl.window";

Reserved metadata key that carries the initial window.

class

CStreamWriter

Ethereal::Rpc#

What a stream method uses to send chunks.

class CStreamWriter final

Writes to the wire as it is called. There is no buffer growing behind it: when the window credit runs out, Write waits. That is how back pressure reaches the producer.

constructor

CStreamWriter

#
explicit CStreamWriter( void * const pImpl ) noexcept : m_pImpl( pImpl )

Built by the module.

pImpl
Internal stream state.
function

Write

#
bool Write( std::span< const std::uint8_t > Chunk );

Sends a chunk.

Chunk
Chunk bytes. Split only by the frame limit, never by the window.
false when sending is no longer possible: the window did not open within the deadline, the connection dropped, or the caller gave up. A method that ignores this false keeps producing into nothing.
function

BytesWritten

#
std::size_t BytesWritten() const noexcept;

Number of bytes sent so far.

function

Stalls

#
std::size_t Stalls() const noexcept;

Number of times it waited for the window.

Zero means the consumer kept up. A growing number means back pressure is happening, which is the system working, not a bug, but worth knowing.

class

CStreamReader

Ethereal::Rpc#
class CStreamReader final
constructor

CStreamReader

#
explicit CStreamReader( void * const pImpl ) noexcept : m_pImpl( pImpl )

Built by the module.

pImpl
Internal stream state.
function

Read

#
bool Read( std::span< const std::uint8_t > & OutChunk );

Pulls the next chunk.

OutChunk
Receives a view of the chunk, valid until the next Read.
false when the stream ended or broke. Use Failed to tell them apart. A method that does not tells a truncated stream from a complete one, the most expensive bug a stream can have.
function

Failed

#
bool Failed() const noexcept;

true when the stream broke (deadline, connection, cancel) instead of ending.

function

BytesRead

#
std::size_t BytesRead() const noexcept;

Number of bytes received so far.

class

CStreamSender

Ethereal::Rpc#
class CStreamSender final
constructor

CStreamSender

#
explicit CStreamSender( void * const pImpl ) noexcept : m_pImpl( pImpl )

Built by the module.

pImpl
Internal stream state.
function

Write

#
bool Write( std::span< const std::uint8_t > Chunk );

Sends a chunk.

Chunk
Chunk bytes.
false when sending is no longer possible. See CStreamWriter::Write.
function

BytesWritten

#
std::size_t BytesWritten() const noexcept;

Number of bytes sent so far.

function

Stalls

#
std::size_t Stalls() const noexcept;

Number of times it waited for the window.

struct

SCallOptions

Ethereal::Rpc#
C++
ETL_END_INTENDED_PADDING


///=============================================================================
///  Call options
///=============================================================================


/// @brief  Extra options of a call.
///
/// @details  The timeout and the deadline are the same number, on purpose.
///
///            Two ways to say how long a call has (one to wait here, another to send
///            to the other side) end up as two different numbers, and a pair like
///            "I wait 100 ms but give you 5 s" means nothing useful: at 100 ms the
///            caller gives up, and the server keeps working for the trash.
///
///            So there is one number. It rules the wait and travels as the
///            deadline, unless @ref bSendDeadline says no.
///
struct   SCallOptions   final
{
    /// @brief  Total time this call has. Zero waits with no limit.
    ETL_UINT32            uTimeoutMs = 0;

    /// @brief  Priority, 0 to 7, carried in the frame flags.
    ETL_UINT8            uPriority = 0;

    /// @brief  How much this side accepts to have unread in a stream. Zero uses the default.
    ///
    /// @details  A small window makes the producer wait more often, a large one uses
    ///            more memory per stream. See @ref kDefaultWindow.
    ///
    ETL_UINT32            uWindow = 0;

    /// @brief  Metadata to send with the request. Null is none.
    const CMetadata *    pSend = nullptr;

    /// @brief  Receives the metadata that come with the response. Null discards them.
    CMetadata *            pReceive = nullptr;

    /// @brief  true sends the deadline with the request.
    ///
    /// @details  Turning it off means "I wait this long, but I do not want the other
    ///            side to know". Useful to talk to a peer that does not understand
    ///            the deadline, and little else.
    ///
    bool                bSendDeadline = true;

    /// @brief  true tells the other side when the call gives up.
    ///
    /// @details  When on, a call that times out sends an @ref EFrameType::eCancel
    ///            after itself. This notice almost always arrives first, before the
    ///            server finds out alone, through the deadline, that answering is no
    ///            longer worth it. Both paths exist because the notice may get lost,
    ///            and the deadline is what remains when that happens.
    ///
    bool                bSendCancel = true;
};
const

DEFAULT_MAX_MESSAGE

Ethereal::Rpc#
constexpr ETL_UINT32 DEFAULT_MAX_MESSAGE = kDefaultMaxPayload;

Default limit of a message.

The same limit as the frame, not a second number. There used to be two: this one was 16 MB and kDefaultMaxPayload is 4 MB. Two limits for the same thing are a disagreement waiting to happen: what passes one is rejected by the other, and whoever reads the header does not know which one ruled. Now there is one, and this name stays for code that already uses it.

class

IMessageTransport

Ethereal::Rpc#

Where the messages go through.

class IMessageTransport

An interface, not a concrete socket, because the same protocol works over TCP (Ethereal::Network::CTcpSocket), over the local channel (Ethereal::Process::CLocalChannel) and over anything that delivers whole messages.

An implementation must deliver messages, not bytes. The two transports of this library already frame. One that does not would have to frame before reaching here.

destructor

~IMessageTransport

#
virtual ~IMessageTransport() = default;

Destructor.

function

SendMessage

#
virtual bool SendMessage( std::span< const std::uint8_t > Data ) = 0;

Sends a whole message.

Data
Message bytes.
true when the message was handed to the transport.
function

ReceiveMessage

#
virtual int ReceiveMessage( std::vector< std::uint8_t > & Out, const ETL_UINT32 uTimeoutMs ) = 0;

Receives a whole message.

Out
Receives the message.
uTimeoutMs
Zero waits with no limit.
0 received, 1 timed out, 2 the connection ended or failed.
function

IsConnected

#
virtual bool IsConnected() const = 0;

Tells whether the transport is connected.

function

Close

#
virtual void Close() = 0;

Closes the transport.

class

CRpcServer

Ethereal::Rpc#
class CRpcServer final
alias

bool

#
using Handler = std::function< bool( SCallContext & Ctx, Serialization::CReader & In, Serialization::CWriter & Out, std::string & sError ) >;

What a method does.

The context comes first, always, even for methods that do not use it. The alternative was two ways to register (with and without context), and two ways to register become two dispatch paths that one day disagree. A method that does not care about the context ignores the parameter, at no cost.

Parameters: Ctx (metadata, deadline and cancellation, see SCallContext), In (the arguments, already past the header), Out (where to write the response), sError (the failure reason, delivered to SRpcResult::sMessage on the other side). Returns false when the method failed.

alias

void

#
using NotifyHandler = std::function< void( const std::string & sName, Serialization::CReader & In ) >;

What is done with a received notification.

alias

bool

#
using StreamHandler = std::function< bool( SCallContext & Ctx, Serialization::CReader & In, CStreamWriter & Out, std::string & sError ) >;

What a stream method does.

Instead of writing one response, it writes chunks to Out, as many as it wants, and returns. The end of the stream is the return, there is no 'End()' to forget.

Returning false ends the stream with a failure, and the reason reaches the caller. The chunks already sent are gone: the consumer has seen them.

alias

bool

#
using UploadHandler = std::function< bool( SCallContext & Ctx, CStreamReader & In, Serialization::CWriter & Out, std::string & sError ) >;

What a method that receives a stream does.

Pulls chunks from In while there are any, and at the end writes one response to Out. The opposite direction of StreamHandler.

constructor

CRpcServer

#
CRpcServer();

Constructor. Draws the table generation.

function

Register

#
bool Register( const std::string & sMethod, Handler Fn );

Registers a method.

The registration order is the method number, starting at 1 (see MethodId and the wire format above). Registering in another order gives other numbers, which is why they hold per connection.

sMethod
Method name.
Fn
What the method does.
false when the name is empty or already exists. A repeated name is a programming error, so it shows up here and not on the first call.
function

RegisterStream

#
bool RegisterStream( const std::string & sMethod, StreamHandler Fn );

Registers a method that answers with a stream.

Shares the numbering and the table with the plain methods. For the caller, the difference is in what comes back, not in how it is called.

sMethod
Method name.
Fn
What the method does.
false when the name is empty or already exists.
function

RegisterUpload

#
bool RegisterUpload( const std::string & sMethod, UploadHandler Fn );

Registers a method that receives a stream and answers once.

sMethod
Method name.
Fn
What the method does.
false when the name is empty or already exists.
function

IsStream

#
bool IsStream( const std::string & sMethod ) const;

Tells whether a method answers with a stream.

sMethod
Method name.
true for a stream method.
function

IsUpload

#
bool IsUpload( const std::string & sMethod ) const;

Tells whether a method receives a stream.

sMethod
Method name.
true for an upload method.
function

MethodId

#
ETL_UINT32 MethodId( const std::string & sMethod ) const;

Number that Register gave to a method.

The number as it travels: generation on top, slot below. For the position in the table alone, see MethodSlot.

sMethod
Method name.
The number, or zero when the method does not exist.
function

TableGeneration

#
ETL_UINT16 TableGeneration() const noexcept;

Generation of this server method table.

Drawn once, at construction. Two different servers have different generations, which is what allows catching a number that came from another server table (see MakeMethodId).

function

SetNotifyHandler

#
void SetNotifyHandler( NotifyHandler Fn );

Sets what is done with incoming notifications.

Fn
Handler. Empty ignores them.
function

AddInterceptor

#
bool AddInterceptor( IInterceptor * const pInterceptor );

Adds an interceptor. Does not take ownership.

Like method registration, before serving. Adding one while serving would change the list the dispatch is walking.

pInterceptor
Interceptor. Must outlive the server.
false when there are already kMaxInterceptors, or the pointer is null.
function

InterceptorCount

#
std::size_t InterceptorCount() const noexcept;

Number of interceptors.

function

InterceptorRejections

#
ETL_UINT64 InterceptorRejections() const noexcept;

Number of calls an interceptor rejected on the way in.

function

HasMethod

#
bool HasMethod( const std::string & sMethod ) const;

Tells whether a method is registered.

sMethod
Method name.
true when it is registered.
function

MethodCount

#
std::size_t MethodCount() const noexcept;

Number of registered methods.

function

ServeOne

#
SRpcResult ServeOne( IMessageTransport & Transport, const ETL_UINT32 uTimeoutMs = 0 );

Serves one message.

Transport
Connection to serve.
uTimeoutMs
Zero waits with no limit.
ERpcError::eDisconnected when the connection ended, which is how a conversation ends, not a failure.
function

Serve

#
std::size_t Serve( IMessageTransport & Transport );

Serves until the connection ends.

Transport
Connection to serve.
Number of messages served. Zero when the library is not licensed.
function

Notify

#
bool Notify( IMessageTransport & Transport, const std::string & sName, const Serialization::CWriter & Payload );

Sends a notification through the transport. See rule 5.

Transport
Connection.
sName
Notification name.
Payload
Notification body.
true when it left here. Not that it arrived.
function

Ping

#
bool Ping( IMessageTransport & Transport );

Sends an EFrameType::ePing and does not wait for anything.

A server cannot wait for the pong, so it does not. It is inside ServeOne when it wants to ask, and waiting for an answer there would stop serving whoever already sent a request.

The pong arrives in a later pass through ServeOne, which counts it in PongsReceived. Whoever wants to know if the other side answered compares that number before and after. It is asynchronous, and the API says so instead of pretending otherwise.

Transport
Connection.
false when the frame did not go out.
function

GoAway

#
bool GoAway( IMessageTransport & Transport, const EGoAwayReason eReason, const std::string & sMessage );

Tells the other side this connection is closing, and closes it.

ServeOne sends this on its own when it rejects a frame. This method is for the other case, a side disconnecting on purpose (EGoAwayReason::eShutdown) that wants the other side to know it was not the cable.

Transport
Connection.
eReason
Reason.
sMessage
Text sent with the reason.
false when the frame did not go out. The connection closes anyway: a connection already given up is not left open just because the message did not get through.
function

RequestsHandled

#
ETL_UINT64 RequestsHandled() const noexcept;

Number of requests answered with success.

function

MethodFailures

#
ETL_UINT64 MethodFailures() const noexcept;

Number of requests whose method failed or was rejected.

function

UnknownMethods

#
ETL_UINT64 UnknownMethods() const noexcept;

Number of requests for an unknown method.

function

MalformedMessages

#
ETL_UINT64 MalformedMessages() const noexcept;

Number of messages that were not valid.

function

SettingsServed

#
ETL_UINT64 SettingsServed() const noexcept;

Number of negotiations this server answered.

One per connection, in steady state. Not counted as a request handled, since it is not a call to any method.

function

CancelledResponses

#
ETL_UINT64 CancelledResponses() const noexcept;

Number of responses not sent because the call was cancelled.

The work was done and thrown away. It measures the cost of having no way to stop a method midway (see SCallContext::IsCancelled).

function

DeadlinesExceeded

#
ETL_UINT64 DeadlinesExceeded() const noexcept;

Number of responses not sent because the deadline had passed.

A growing number means the incoming deadlines are too tight for the work asked. It is a number about load, not about a bug.

function

CancelsReceived

#
ETL_UINT64 CancelsReceived() const noexcept;

Number of EFrameType::eCancel frames received.

function

PingsAnswered

#
ETL_UINT64 PingsAnswered() const noexcept;

Number of pings this server answered.

function

PongsReceived

#
ETL_UINT64 PongsReceived() const noexcept;

Number of pongs this server received.

They answer the Ping calls it made. They are not paired with anything: the server keeps no state per connection, so it counts them instead of matching them. Whoever wants to know if a ping was answered compares this number before and after.

function

GoAwaysSent

#
ETL_UINT64 GoAwaysSent() const noexcept;

Number of connections this server closed with an EFrameType::eGoAway.

Zero in steady state. Each one is a connection lost because the other side sent something that is not a frame of this protocol (see rule 7).

function

StaleMethodIds

#
ETL_UINT64 StaleMethodIds() const noexcept;

Number of requests that came with a number from another table.

Zero in steady state. A growing number means someone is talking to this server with numbers that are not its own, almost always a client whose transport reconnected internally. See MakeMethodId.

function

NamedLookups

#
ETL_UINT64 NamedLookups() const noexcept;

Number of requests that came through the slow path: no number, name in the body.

In steady state this stops growing: it is one per method name and per connection, the call where the client did not know the number yet. Growing call after call means the client is not learning, and the cost of the name and the text comparison is paid on every call again.

class

CRpcClient

Ethereal::Rpc#
class CRpcClient final
constructor

CRpcClient

#
CRpcClient();

Constructor. Call Attach before use.

function

Attach

#
void Attach( IMessageTransport * pTransport ) noexcept;

Points the client at a transport. Does not take ownership.

Forgets all learned method numbers. They hold per connection (see the wire format above), and attaching is what marks a new connection. Whoever reconnects the same transport object internally, without going through here, keeps the numbers of the previous one.

pTransport
Transport. Must outlive its use by the client.
function

IsConnected

#
bool IsConnected() const;

Tells whether there is a transport and it is connected.

function

Handshake

#
SRpcResult Handshake( const ETL_UINT32 uTimeoutMs = 0 );

Exchanges the EFrameType::eSettings frame with the other side.

Calling this is not required. The first Call does it alone, and that is where it usually happens. It exists for whoever wants to pay the round trip at a place of their choice (when connecting, not in the middle of the first call), or wants to know what was agreed before calling anything.

Calling twice does not repeat the exchange: the second call returns what is already agreed.

A failed negotiation does not stop the module. If the other side rejects the frame, the client goes on through the slow path (name in the body), which is exactly how it worked before negotiation existed. What is not tolerated is no answer: then the channel is not good, and that comes back as ERpcError::eTimeout or ERpcError::eDisconnected.

uTimeoutMs
Zero waits with no limit.
The result of the exchange. ERpcError::eNotLicensed when the library is not licensed.
function

IsNegotiated

#
bool IsNegotiated() const noexcept;

Tells whether the negotiation happened on this connection.

function

PeerSettings

#
const SPeerSettings & PeerSettings() const noexcept;

What the other side said about itself. Only valid after IsNegotiated.

function

StartMultiplexing

#
bool StartMultiplexing();

Turns on the multiplexed mode, and with it the I/O thread.

Negotiates before starting the thread, because negotiating reads from the transport, and from the start on the thread is the reader. A rejected negotiation does not stop the mode: calls carry the name, as always.

false when already on, when there is no transport, when the thread did not start, or when the library is not licensed.
function

StopMultiplexing

#
void StopMultiplexing();

Stops the thread and goes back to the single thread mode.

Calls still waiting wake up with ERpcError::eDisconnected. Leaving them hanging would be worse than telling them so.

function

IsMultiplexed

#
bool IsMultiplexed() const noexcept;

Tells whether the multiplexed mode is on.

alias

void

#
using CompletionFn = std::function< void( const SRpcResult & Result, std::span< const std::uint8_t > Reply ) >;

What is done when an asynchronous call ends.

This runs on the I/O thread. It must be said loud, because it is the classic mistake: putting application work here stops reading the transport while it lasts, and the responses of all other calls wait. Do the minimum in here: copy, wake someone, push to a queue.

function

CallAsync

#
SRpcResult CallAsync( const std::string & sMethod, const Serialization::CWriter & Args, CompletionFn OnDone, const SCallOptions & Options );

Calls without waiting. Multiplexed mode only.

sMethod
Method name.
Args
Arguments.
OnDone
Receives the result, on the I/O thread.
Options
Call options.
The error of failing to start. The result of the call goes to OnDone.
function

CallAsync

#
SRpcResult CallAsync( const std::string & sMethod, const Serialization::CWriter & Args, CompletionFn OnDone, const ETL_UINT32 uTimeoutMs = 0 )

Short form: only the time, which is also the deadline.

sMethod
Method name.
Args
Arguments.
OnDone
Receives the result, on the I/O thread.
uTimeoutMs
Zero waits with no limit.
The error of failing to start.
function

InFlight

#
std::size_t InFlight() const;

Number of calls waiting for a response right now.

function

Ping

#
SRpcResult Ping( const ETL_UINT32 uTimeoutMs = 0, ETL_UINT64 * const pOutRoundTripUs = nullptr );

Sends an EFrameType::ePing and waits for the pong.

This measures the channel, not the application. A pong says the bytes go and come back and that the other side is running its loop. It does not say that the methods answer, that the database is up, or that the process is not about to run out of memory. A service that answers pings and fails at everything else is a common case, and a ping does not catch it.

It does not negotiate. A keep alive must work before and independently of the negotiation: a round trip of 'eSettings' to ask whether the other side is alive would make the cheapest question the most expensive one.

The body carries a token, and the pong must return it intact. A pong with another body comes back as ERpcError::eMalformed: a side that answers without reading does not count as answering.

uTimeoutMs
Zero waits with no limit.
pOutRoundTripUs
Receives the round trip, in microseconds. Optional.
The result of the exchange.
function

SetKeepAlive

#
void SetKeepAlive( const ETL_UINT32 uIntervalMs, const ETL_UINT32 uMaxFailures = 3u );

Sends a ping on its own when the connection goes idle.

Only works in the multiplexed mode, and that is not an arbitrary limit: asking on its own needs someone running when nobody called, and in the single thread mode there is no one. The client only exists while it is inside a call.

This is what makes the ping useful on an idle connection. A ping that someone must remember to send does not find a dead connection: the next call finds it, and by then it is late.

After uMaxFailures pings without answer the connection is declared dead: whoever is waiting wakes up with ERpcError::eDisconnected, and the transport closes. Closing is the part that matters: a connection that only looks alive is worse than one known to be dead.

uIntervalMs
Time with no traffic before asking. Zero turns it off.
uMaxFailures
Pings without answer before declaring the connection dead.
function

KeepAlivePings

#
ETL_UINT64 KeepAlivePings() const noexcept;

Number of automatic pings sent.

function

KeepAliveMisses

#
ETL_UINT64 KeepAliveMisses() const noexcept;

Number of connections declared dead for lack of answers.

function

PingsAnswered

#
ETL_UINT64 PingsAnswered() const noexcept;

Number of pings this client answered.

It answers them on its own, inside any wait: a Call, a Pump or a negotiation. There is nothing to turn on or call: a side that only answers pings when it feels like it is no keep alive at all.

function

Call

#
SRpcResult Call( const std::string & sMethod, const Serialization::CWriter & Args, std::vector< std::uint8_t > & Reply, const SCallOptions & Options );

Calls sMethod and waits for the response.

The time is the time of the whole operation, not of each wait. If the negotiation has not happened yet it runs here, and what it spends comes out of the same budget. The same goes for notifications that arrive during the wait: they do not stretch the deadline.

A response that already arrived wins over a deadline that already passed. If the calling thread is starved of CPU, it may wake up with both true: the deadline gone and the response in the channel. Then this method returns the response, not ERpcError::eTimeout. Throwing away work that is already done to honor a clock helps nobody.

The deadline is still respected in time, and that was measured. On a machine with eight tests competing for it, with a 5 ms deadline against a method that sleeps 20: of sixty calls, the four that came back with a result took 21.7 ms or more, and none came back with a result below the 20 the method takes. Above that one or the other comes out, depending on the order in which the client notices them.

Whoever needs the opposite must enforce it on the other side: with SCallOptions::bSendDeadline the server finds out at the end that the time has passed, and the response never goes out.

sMethod
Method name.
Args
Arguments.
Reply
Receives the response body.
Options
Call options. Read rule 4 before choosing the timeout.
The result of the call.
alias

bool

#
using StreamSink = std::function< bool( std::span< const std::uint8_t > Chunk ) >;

What is done with each arriving chunk of a stream.

Returning false stops the stream: the client gives up and tells the other side. It is how the tap is closed on a producer faster than the consumer.

function

CallStream

#
SRpcResult CallStream( const std::string & sMethod, const Serialization::CWriter & Args, StreamSink OnChunk, const SCallOptions & Options );

Calls a stream method and consumes the chunks as they arrive.

The chunks are not gathered in a list. Gathering would undo the point of the stream: a stream is asked for because the whole does not fit, or to start working before it ends.

The window is managed here: as OnChunk consumes, credit goes back to the other side. A slow OnChunk makes the producer wait, which is what is wanted.

sMethod
Method name.
Args
Arguments.
OnChunk
Receives each chunk.
Options
Call options.
The result of the stream.
function

CallStream

#
SRpcResult CallStream( const std::string & sMethod, const Serialization::CWriter & Args, StreamSink OnChunk, const ETL_UINT32 uTimeoutMs = 0 )

Short form: only the time, which is also the deadline.

sMethod
Method name.
Args
Arguments.
OnChunk
Receives each chunk.
uTimeoutMs
Zero waits with no limit.
The result of the stream.
alias

bool

#
using UploadSource = std::function< bool( CStreamSender & Out ) >;

What produces the chunks of an upload.

Returning false aborts the upload. What already went out is gone.

function

CallUpload

#
SRpcResult CallUpload( const std::string & sMethod, const Serialization::CWriter & Args, UploadSource Producer, std::vector< std::uint8_t > & Reply, const SCallOptions & Options );

Sends a stream and receives one response.

The window in this direction is not announced anywhere: it starts at kDefaultWindow by convention, and the other side returns credit as it consumes. It is an asymmetry, written down here: in the other direction the window travels in the request, because there is a request to put it in. Here the first frame already is the request.

sMethod
Method name.
Args
Arguments.
Producer
Produces the chunks.
Reply
Receives the response body.
Options
Call options.
The result of the call.
function

CallUpload

#
SRpcResult CallUpload( const std::string & sMethod, const Serialization::CWriter & Args, UploadSource Producer, std::vector< std::uint8_t > & Reply, const ETL_UINT32 uTimeoutMs = 0 )

Short form: only the time, which is also the deadline.

sMethod
Method name.
Args
Arguments.
Producer
Produces the chunks.
Reply
Receives the response body.
uTimeoutMs
Zero waits with no limit.
The result of the call.
function

Call

#
SRpcResult Call( const std::string & sMethod, const Serialization::CWriter & Args, std::vector< std::uint8_t > & Reply, const ETL_UINT32 uTimeoutMs = 0 )

Short form: only the time, which is also the deadline.

sMethod
Method name.
Args
Arguments.
Reply
Receives the response body.
uTimeoutMs
Zero waits with no limit.
The result of the call.
function

Notify

#
bool Notify( const std::string & sName, const Serialization::CWriter & Payload );

Sends a one way notice. See rule 5.

sName
Notification name.
Payload
Notification body.
true when it left here. Not that it arrived.
function

SetNotifyHandler

#
void SetNotifyHandler( CRpcServer::NotifyHandler Fn );

Sets what is done with notifications from the other side.

They arrive mixed with the responses and are delivered here during a Call. That is what makes this channel a two way bus, not only an RPC.

Fn
Handler. Empty ignores them.
function

Pump

#
SRpcResult Pump( const ETL_UINT32 uTimeoutMs );

Receives whatever arrives with no call in progress.

For whoever only wants to listen to notifications.

uTimeoutMs
Zero waits with no limit.
ERpcError::eTimeout when nothing arrived.
function

CallsMade

#
ETL_UINT64 CallsMade() const noexcept;

Number of calls made.

function

StaleResponses

#
ETL_UINT64 StaleResponses() const noexcept;

Number of responses that arrived with the wrong identifier and were discarded.

Zero on a healthy channel. A growing number means some call timed out and its response arrived later, and is the difference between discarding and delivering the wrong response. See rule 1.

function

NotificationsReceived

#
ETL_UINT64 NotificationsReceived() const noexcept;

Number of notifications received.

function

KnownMethodId

#
ETL_UINT32 KnownMethodId( const std::string & sMethod ) const;

Number this client already learned for a method.

Zero does not mean the method does not exist: it means the next call to it goes through the slow path, with the name in the body. See the wire format above.

sMethod
Method name.
The number, or zero when not learned yet.
function

Handshakes

#
ETL_UINT64 Handshakes() const noexcept;

Number of times this client negotiated.

One per connection, and that is what is measured. Two on the same connection means something invalidated it, almost always a number rejected for coming from another table, which is the fix working.

function

GoAwayReason

#
EGoAwayReason GoAwayReason() const noexcept;

Reason of the last EFrameType::eGoAway received.

Only meaningful after an operation returned ERpcError::eGoAway. The text that came with it is in the SRpcResult::sMessage of that operation.

function

Retries

#
ETL_UINT64 Retries() const noexcept;

Number of calls repeated because the method number was stale.

Zero in steady state. Each one is a call that did not fail for the caller: the client forgot the table, negotiated again and repeated. See MakeMethodId.

transport.hpp

#include <ethereal/cpp/rpc/transport.hpp>

Message transports of the Rpc module.

The protocol in rpc.hpp does not know where the messages go, on purpose: the same control channel runs between two processes on one machine, between two machines, and inside one process. The three transports are here.

None of them takes ownership of what it wraps: the socket, the channel and the peer stay with whoever created them, and must outlive the transport.

class

CTcpTransport

Ethereal::Rpc#

The protocol over a TCP socket.

class CTcpTransport final : public IMessageTransport

Uses Ethereal::Network::CTcpSocket::SendFrame, which already frames the messages.

The receive timeout comes from the socket, not from the argument. The time given to ReceiveMessage is ignored, and the one that applies is the Ethereal::Network::STcpConfig::uReceiveTimeoutMs the socket was connected with. Pretending to honor both would be worse: it would suggest that a short time in the call has an effect when it has none.
constructor

CTcpTransport

#
explicit CTcpTransport( Network::CTcpSocket & Socket ) noexcept;

Wraps a socket. Does not take ownership.

Socket
Connected socket. Must outlive the transport.
function

SendMessage

#
bool SendMessage( std::span< const std::uint8_t > Data ) override;

Sends a whole message as one TCP frame.

Data
Message bytes.
true when the frame was sent.
function

ReceiveMessage

#
int ReceiveMessage( std::vector< std::uint8_t > & Out, const ETL_UINT32 uTimeoutMs ) override;

Receives a whole message.

Out
Receives the message.
uTimeoutMs
Ignored. The socket timeout applies.
0 received, 1 timed out, 2 the connection ended or failed.
function

IsConnected

#
bool IsConnected() const override;

Tells whether the socket is open.

function

Close

#
void Close() override;

Closes the socket.

class

CLocalTransport

Ethereal::Rpc#

The protocol over the local channel of the Process module.

class CLocalTransport final : public IMessageTransport

The path for an agent and a service on the same machine: no port, no firewall, and the system permissions really apply.

ReceiveMessage blocks. The time given to it is ignored, for the same reason as in the TCP transport.
constructor

CLocalTransport

#
explicit CLocalTransport( Process::CLocalChannel & Channel ) noexcept;

Wraps a channel. Does not take ownership.

Channel
Open channel. Must outlive the transport.
function

SendMessage

#
bool SendMessage( std::span< const std::uint8_t > Data ) override;

Sends a whole message on the channel.

Data
Message bytes.
true when the message was sent.
function

ReceiveMessage

#
int ReceiveMessage( std::vector< std::uint8_t > & Out, const ETL_UINT32 uTimeoutMs ) override;

Receives a whole message.

Out
Receives the message.
uTimeoutMs
Ignored. The call blocks.
0 received, 1 timed out, 2 the connection ended or failed.
function

IsConnected

#
bool IsConnected() const override;

Tells whether the channel is open.

function

Close

#
void Close() override;

Closes the channel.

class

CLoopbackTransport

Ethereal::Rpc#

Two transports connected to each other, inside one process.

class CLoopbackTransport final : public IMessageTransport

Not only a test double, although it serves well as one. A product that runs client and server in the same executable (embedded mode, single player mode, a tool that hosts its own service) uses exactly this, so the code path exercised is the same as in the distributed case. Two different paths for the same work is how the bug that only shows up in production is made.

The queue is locked and the wait uses a condition variable, so the two sides can be on different threads.

constructor

CLoopbackTransport

#
CLoopbackTransport();

Constructor. Call Pair before use.

function

Pair

#
static void Pair( CLoopbackTransport & A, CLoopbackTransport & B ) noexcept;

Connects A and B to each other.

After this, what A sends B receives, and the other way around. Both must live while the pair exists.

A
One side.
B
The other side.
function

SendMessage

#
bool SendMessage( std::span< const std::uint8_t > Data ) override;

Queues a copy of the message for the other side.

Data
Message bytes.
false when this side or the other side is closed.
function

ReceiveMessage

#
int ReceiveMessage( std::vector< std::uint8_t > & Out, const ETL_UINT32 uTimeoutMs ) override;

Takes the next message sent by the other side.

Out
Receives the message.
uTimeoutMs
Zero waits with no limit.
0 received, 1 timed out, 2 the connection ended.
function

IsConnected

#
bool IsConnected() const override;

Tells whether both sides are still open.

function

Close

#
void Close() override;

Closes both directions and wakes whoever is waiting.

function

Pending

#
std::size_t Pending() const;

Number of messages waiting on this side.