Skip to main content

Custom Codecs

Custom codecs let an application bring its own serialization format to KeySquare.

Raw Messages can be used when an application wants to publish and subscribe to arbitrary bytes directly. A custom codec builds on that by supporting the ability to plug a custom encoder and decoder into the API, allowing applications to work directly with Java types while the codec handles conversion to and from bytes.

How Custom Messages Work

A custom codec is installed on KeySessionContext before the session is used:

KeySessionContext context = new KeySessionContext();
context.setCustomCodec(new MyCustomCodec());

Messages on the platform contain data type information in the form of a schemaId and templateId (see Message Structure). The schema id uniquely identifies a group of related data types and the template id identifies a single data type within a schema. Therefore a tuple of (schema id, template id) can uniquely identify a data type on the platform.

The platform owner should allocate unique schema ids to a team or application that wishes to publish data to the platform. This ensures that schema ids remain unique and allow teams to operate independently within their own schema space when they need to create new data types.

Codec MethodPurpose
resolveType(Class<?>)Returns a tuple of schemaId and templateId for a Java class type.
encoder(Class<?>)Returns an independent encoder instance for publishing that Java class type.
decoder(Class<?>)Returns an independent decoder instance for receiving that Java class type.

Codec Behaviour

Each call to encoder(...) and decoder(...) must return an independent instance. The API will then safely use those encoders and decoders for publishing, routing and edit processing.

Using Custom Messages

Once a codec is configured, Custom messages use the same API flow as the other message types:

AreaCustom APIMore Detail
Routingsession.routing().custom(...)Subscription
Topic creationTopics.create(schemaId, templateId, source, group, id)Topics
PublicationMessages.custom(...)Publication
Editingedit().custom(...) and editRouting().custom(...)Editing

The codec-specific part is the conversion between Java type and bytes. The rest of the API continues to work in the usual way: topics identify data, routing provides the callback, publication sends a message, and editing uses the configured codec to encode and decode the custom payload.

Message lifetime rules are covered in Subscription.