C++ Client Design#

The internal design of the C++ client. This page builds on the shared client design and the client specification. Usage is in the C++ guide. Paths are relative to client/cpp/.

Generated Stubs#

clientgen writes one header per service from cpp.tmpl in krpctools. The header names every library and standard type from the global namespace, such as ::std::string, and the types of every service in full, so a class of the service cannot shadow them. A class with static methods has a static bind and a nested class Bound, so a member named bind is bind_ and a type named Bound is Bound_.

The _stream, _call and _call_template functions of a member foo take __ in place of _ where the scope has a member of that name, as in foo__stream beside a method foo_stream. Server names hold only letters and digits, so no member name contains __. Renaming the member in place of the helper would rename a member such as add_stream, which has no clash. The cost is that adding a member foo_stream to a service renames the existing foo_stream helper of foo. Such a pair is rare, and the rename is confined to C++ helpers.

Class Hierarchies#

A generated class derives from its base class, so RemoteObject<T> takes the root class of a hierarchy as T.

  • Equality, ordering and hashing then work within one hierarchy, and a comparison across two does not compile.

  • A generated class sets the ids of its class in its constructor.

  • is_remote_object_v tells a class of a service from a structure, as std::is_base_of names the root class.

  • An object is a value of its declared class, so a decoded object keeps the ids of its own class in _service_id and _class_id. Each generated header registers its classes, with their bases, as the program starts. krpc::is_a walks up the bases from the object’s ids, and krpc::cast builds an object of the target class with the same id. operator<< prints the name of the object’s own class.

  • Registration rests on the dynamic initialization of an inline variable, which the standard lets an implementation defer to its first use. A class’s constructors use it, so a class registers before its first object. GCC, Clang and MSVC register every class as the program starts.

  • A helper beside a member is named apart from the members of the class’s bases and of the classes of its service derived from it. A class derived from it in another service can still hide a helper.

Ownership#

krpc::Connection is a handle to one shared state. Copies, services, objects, streams and events each hold the connection, so each keeps it open:

SpaceCenter::Vessel active_vessel() {
  auto conn = krpc::connect();
  SpaceCenter sc(conn);
  return sc.active_vessel();
  // Holds the connection after conn and sc are destroyed
}

References#

The connection state holds the StreamManager, which holds the Session.

The program keeps the connection open through what it holds. A Connection, RemoteService or RemoteObject holds the Connection::State. A Stream or Event holds its StreamImpl, which holds the Connection::State.

These references are strong. With a non-owning pointer, a returned object would dangle when its connection is destroyed, moved or reallocated. A weak handle would need a non-owning Connection for each call, which can dangle or be copied out by a caller.

Reader and dispatcher work holds a StreamImpl, so the reader never runs the last release. Work left in the session is released by the close.

The handles of a stream share one pointer to its StreamImpl, apart from the pointers this work holds. Its release stops the callbacks and removes the stream from the server, whatever is queued. Otherwise a callback slower than its updates would keep the stream, and the connection, alive indefinitely.

The stream manager holds each StreamImpl weakly, and holds no client, so these references form no cycle. It holds the exception throwers directly, as the reader throws stream errors. A stream the reader registers holds no client until a handle claims it, so the manager holds it strongly until then.

Lifetime#

  • The connection closes on close(), or when the last holder is released and the dispatcher thread has run the queue down.

  • A callback in progress carries on after the last handle is released. close() waits for it.

  • After close(), the state stays valid. Calls through any holder throw ConnectionError, and streams and events end. A second close() does nothing.

Connection Handles#

  • Moves are the defaults. A moved-from connection is empty, and its holders are unaffected.

  • An empty connection is not connected, and its calls throw ConnectionError.

  • A default-constructed object identifies nothing. Encoding one throws std::invalid_argument, so a call through it or with it as an argument fails before it is sent. An object the server returns with id 0 is a valid object.

  • Service and object constructors take const Connection&, as they copy the connection. Stream and event constructors and static methods take Connection&, as they call through it. Decoders take Connection*, where null means no connection.

Callback Cycles#

User callbacks can add a cycle, as C++ has no garbage collector:

A callback holding

Effect

An object, in a stream or event callback

None. It is released once the stream’s last handle is gone

Its own stream or event

Keeps the connection open until the stream ends

An object, in an update callback

Keeps the connection open until the connection ends

A stream that ends destroys its value callbacks, and the end of the connection destroys the update callbacks, which breaks these cycles. A program that keeps such a callback calls close(). A callback added after the end is destroyed by the add.

Threads#

The threads and the close follow the shared design. The last release can run on any thread, including the dispatcher thread from a callback:

  • The close skips joining the thread it runs on. ~Session detaches that thread.

  • A thread holding a condition skips joining the dispatcher thread, which can be waiting for that condition. The dispatcher thread holds the manager, and releases it as it ends.

  • StreamManager::update moves its records to the dispatcher, so the reader holds no stream once it lets go of the update lock.

  • Callbacks are destroyed with no lock held, as one can hold the last copy of the client.

During a close, another thread can hold a stream’s condition. The condition then wakes the threads waiting on it, once its mutex is free.

An exception from a callback goes to standard error.

Mapping the Spec to C++#

Spec

C++

Closing a connection

Connection::close(), or the last release

Remote error

krpc::RemoteError, a std::runtime_error

Connection error

krpc::ConnectionError

Stream error

krpc::StreamError, also for KRPC.StreamRemovedException, whose generated name is an alias of it

Server error with no mapped type

krpc::ServerError, the base of each exception class a service declares

Server exception with a mapped type

The standard exception itself. The generated name is a using alias of it, so the server’s message tells apart the exceptions that share a type

Nullable value

std::optional, checked by the compiler where a parameter is not nullable

Null object

An empty std::optional. A default-constructed object is refused as an argument

Interrupting a blocked thread

Unsupported, as a C++ thread cannot be interrupted

Scoped stream or event

A block holding the last copy. A copy kept past the block keeps the stream running

Flags enumeration

An enum struct with generated operators, as hidden friends of the service class that declares it. ~ keeps to the declared values, so a complement holds no undeclared bit

A stream value is decoded when it is read, and for each callback.