Python Client Design#
The internal design of the Python client. This page builds on the shared client design and the client specification. Usage is in
the Python guide. Paths are relative to client/python/.
Services and Declarations#
Every service is built at connect from GetServices, by create_service. The client then has
the members of the server it connects to, including those another mod adds to a shipped class.
Each client has its own classes, in its Types, so a static method is a closure over its client.
A connect registers the types of every service, then builds the services. The types come first as a procedure can use a type from any service. A parameter’s default value can also be an enumeration value, which cannot be decoded until that enumeration is registered.
The client clears the type identifiers from the
Typemessages inGetServices. It names a type by its service and name, and keys its types on theTypemessages it builds from them.clientgenandpython.tmplinkrpctoolsgenerate a module per service. Its enumerations, structures and exceptions are real classes, and its classes and services are declarations whose members raiseTypeError.clientgenruns the client without the modules.The modules of the core’s services are in
krpc/services/, and those of the KSP services inkrpc/ksp/. The paths match the planned split into a base package and a package per game, so the split changes no import.import krpcimports no module.A module registers its enumerations, structures and exceptions in
krpc/declarations.pyon import. A later registration replaces an earlier one.At connect, a client uses a generated class where the server’s definition matches: an enumeration on its names and values, a structure on its field names in order, an exception on its name and the builtin it derives from. These classes hold no client, so every client shares them. A generated class is never changed to fit a server, as every client shares it.
The connection type picks the module of each service it declares, from the
<Service>Connectionbases in its MRO, and the first wins. Any other service takes the registered classes. A module generated for a newer server then applies only to the connections typed with it.Otherwise the client builds its own class. A value of the module’s enumeration converts to the built one by its number, as the other clients send it, since a client and a server of different releases are not supported. A structure decodes using the field types the server declares in either case.
exceptcompares exception classes by identity, so only a shared exception class catches a server error.A built class does not derive from its declaration, which would show members a server lacks.
DeclaredClass, the metaclass of a declaration, compares the service and class names forisinstanceandissubclass.Python has no declaration merging, so a module cannot add its service to
Connection. It declares<Service>Connection, a subclass ofConnectionwith the service as an attribute. A program combines them, andconnect[T]builds the connection asT.krpc.ksp.KSPConnectioncombines the core and KSP services.Connectiondeclares no service, only a__getattr__returningAnyfor type checkers. The core services,KRPCandStdLib, have connection types like the others, so a module generated for a newer server replaces them the same way. A program with a connection type that lacks a service then type checks, and a misspelled service is not reported.The client’s own calls to
KRPCgo throughConnection._krpc, a property typed with the shipped declaration.connectwith no connection type connects withKSPConnection, so a program written for KSP type checks with no connection type. It importskrpc.kspon the first connect, which keepsimport krpcfree of generated modules.
Server Side Functions#
compile, run, add_stream and add_event take a Python function.
krpc/functioncompiler.py and krpc/functionstatements.py compile its source, read with
inspect and ast, into a KRPC.Expression.
A function passed directly to run or add_stream compiles on every call, as a cached function
would keep the values it first captured.
Deprecated Members#
A warning fires where a program reads a member, which keeps the cost off other members and off the values the client decodes:
A deprecated enumeration value or structure field is a descriptor on the class, in place of the member or the
namedtuplefield getter. The client’s encoder and decoder read neither by name, so a value from the server gives no warning. A generated module sets these on its own classes.A deprecated class, enumeration, structure or exception is a descriptor on the service class, in place of the type.
A read is the use that warns for a structure field, as the decoder and a program build a structure through one constructor.
The generated modules take the deprecated decorator from krpc.types. A type checker sees the
one in typing_extensions. At run time it only records the message, as the built service warns,
and the client depends on no typing package.
Ownership#
Services, objects and streams hold the Connection strongly. Letting go of them closes nothing:
def active_vessel():
conn = krpc.connect()
return conn.space_center.active_vessel
# The connection stays open after conn is dropped
References#
The client holds its Transport, Session, StreamManager, Types registry and
services.
The objects the program keeps also hold the client. A Service, Object or StreamImpl
holds the Connection, and a Stream holds its StreamImpl.
The threads keep the connection alive. The reader and dispatcher threads hold the Session, which
holds the StreamManager, which holds the Connection. An unclosed connection is therefore
never collected. The threads end on a close or a connection failure.
The stream manager holds each open StreamImpl strongly, so a stream outlives its handles and its
callbacks keep running. It holds every registered StreamImpl weakly, which keeps nothing alive.
Each StreamImpl also holds the StreamManager.
The collector frees these cycles once the threads end. A callback holding its own stream or the client needs no special handling.
Lifetime#
The connection closes on
close(), at the end of awithblock, when the server or the socket fails, or at process exit. Process exit sends nodisconnect, as the operating system closes the socket.After
close(), the client and its objects stay valid. Calls raiseConnectionError, and streams and events end. A secondclose()has no further effect.Lifetime is explicit.
Connection, objects,StreamandEventhave no finalizer. An object is an id and a client, and sends no release to the server.StreamandEventare handles to oneStreamImpl, which runs until aremove()through any handle, a server ending or the close. Both are context managers, whose exit callsremove(). An exception fromremove()is dropped when the block raised one.
Threads#
The threads follow the shared design, and are named
krpc-reader and krpc-dispatcher.
Calls and waits block the calling thread.
A
KeyboardInterruptin a call abandons its slot.A value is decoded once, and every read and callback shares that object.
A
BaseExceptionfrom an end callback, such asKeyboardInterrupt, is raised once the close finishes.On the dispatcher thread, every callback exception goes to
threading.excepthook.During a close, another thread can hold a stream’s condition. A
krpc-wakerthread then wakes the threads waiting on it, once the condition is free.
Transports#
Transport holds the socket and the message framing. TCPIPTransport and
LocalTransport, a unix domain socket, derive from it and differ only in _open. There are no
WebSockets or serial transports. Windows CPython has no
socket.AF_UNIX, so krpc/winsock.py opens that socket through Winsock directly.
timeout bounds a TCP/IP connect only. handshake_timeout covers the whole handshake response.
stall_timeout runs from the last byte received, while a message is part way through arriving.
Mapping the Spec to Python#
Spec |
Python |
|---|---|
Closing a connection |
|
Remote error, and the connection, stream and encoding errors |
|
Server error with no mapped type |
|
Server exception with a mapped type |
A class on the service, whose only base is the builtin in |
Argument error |
|
Null object, nullable value |
|
Member names |
|
Waiting |
|
Interrupting a blocked thread |
Unsupported, as only the main thread can be interrupted, by |
Flags enumeration |
A |