rsocket-frames-ts
Version:
RSocket frame codec implemented with Uint8Array. Supports full spec, metadata extensions, and browser compatibility.
1,062 lines (1,046 loc) • 120 kB
text/typescript
import { ByteWriter, ByteReader } from 'bebyte';
/**
* Enumeration of all standard RSocket frame types.
*
* These frame types define the kind of protocol message being sent
* over the RSocket connection. Each frame has a unique identifier byte
* used for decoding and routing.
*/
declare enum FrameType {
/** `0x00` - Reserved for future use. */
RESERVED = 0,
/** `0x01` - Sent by the client to initiate the connection and negotiate setup parameters. */
SETUP = 1,
/** `0x02` - Sent by the responder to grant the requester permission to send requests. */
LEASE = 2,
/** `0x03` - Used to maintain liveness of the connection. */
KEEPALIVE = 3,
/** `0x04` - Request-Response interaction model (1 request, 1 response). */
REQUEST_RESPONSE = 4,
/** `0x05` - Fire-and-Forget: A one-way message with no response. */
REQUEST_FNF = 5,
/** `0x06` - Request a stream of responses (possibly infinite). */
REQUEST_STREAM = 6,
/** `0x07` - Bi-directional stream of messages between requester and responder. */
REQUEST_CHANNEL = 7,
/** `0x08` - Request N more items in a stream (backpressure mechanism). */
REQUEST_N = 8,
/** `0x09` - Cancel an ongoing request. */
CANCEL = 9,
/** `0x0A` - Used to transmit a payload on a stream. */
PAYLOAD = 10,
/** `0x0B` - Represents an application or connection-level error. */
ERROR = 11,
/** `0x0C` - Pushes metadata out-of-band to the peer. */
METADATA_PUSH = 12,
/** `0x0D` - Sent to resume a connection (if supported). */
RESUME = 13,
/** `0x0E` - Acknowledges a successful resume. */
RESUME_OK = 14,
/** `0x3F` - Reserved for protocol extensions. */
EXT = 63
}
declare namespace FrameType {
/**
* Attempts to determine the `FrameType` based on the given byte value.
*
* This performs a best-match lookup by applying bitmask matching
* in reverse order of definition, favoring the most specific match.
*
* @param {number} byte - The raw frame type byte value.
* @returns {FrameType} The corresponding `FrameType` enum value.
*/
function fromByte(byte: number): FrameType;
}
/**
* Internal enum defining individual frame-level flags used in RSocket.
* These flags modify frame behavior.
*/
declare enum _FrameFlag {
/**
* No flags are set.
*/
NONE = 0,
/**
* Indicates that the frame can be safely ignored if not understood.
*/
IGNORE = 512,
/**
* Indicates that the frame contains metadata.
*/
METADATA = 256
}
/**
* RSocket frame flags, including utility to combine multiple flags.
*/
declare const FrameFlag: {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type FrameFlag = number | _FrameFlag;
/**
* Internal enum for keepalive-specific flags.
*/
declare enum _KeepaliveFlag {
/**
* If set, the receiver must respond with a KEEPALIVE frame.
*/
RESPOND = 128
}
/**
* Flags applicable to KEEPALIVE frames.
*/
declare const KeepaliveFlag: typeof _KeepaliveFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type KeepaliveFlag = FrameFlag | _KeepaliveFlag;
/**
* Enum for custom [extension frame]{@link ExtensionFrame} flags.
*/
declare enum _ExtensionFlag {
EXT_1 = 128,
EXT_2 = 64,
EXT_3 = 32,
EXT_4 = 16,
EXT_5 = 8,
EXT_6 = 4,
EXT_7 = 2,
EXT_8 = 1
}
/**
* Flags applicable to EXT (extension) frames.
*/
declare const ExtensionFlag: typeof _ExtensionFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type ExtensionFlag = FrameFlag | _ExtensionFlag;
/**
* Internal enum for setup frame flags.
*/
declare enum _SetupFlag {
/**
* Enables session resumption support.
*/
RESUME = 128,
/**
* Enables lease-based flow control.
*/
LEASE = 64
}
/**
* Flags applicable to SETUP frames.
*/
declare const SetupFlag: typeof _SetupFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type SetupFlag = FrameFlag | _SetupFlag;
/**
* Enum for the `FOLLOWS` flag, indicating that more fragments follow.
*/
declare enum FollowsFlag {
/**
* Indicates that this frame is followed by more fragments.
*/
FOLLOWS = 128
}
/**
* Flags applicable to [FIRE_AND_FORGET]{@link RequestFireAndForgetFrame} frames.
*/
declare const FireAndForgetFlag: typeof FollowsFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type FireAndForgetFlag = FrameFlag | FollowsFlag;
/**
* Flags applicable to [REQUEST_RESPONSE]{@link RequestResponseFrame} frames (same as [FIRE_AND_FORGET]{@link RequestFireAndForgetFrame}.
*/
declare const RequestResponseFlag: typeof FollowsFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type RequestResponseFlag = FireAndForgetFlag;
/**
* Flags applicable to [REQUEST_STREAM]{@link RequestStreamFrame} frames (same as [REQUEST_RESPONSE]{@link RequestResponseFrame}).
*/
declare const RequestStreamFlag: typeof FollowsFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type RequestStreamFlag = RequestResponseFlag;
/**
* Enum representing the `COMPLETE` flag, indicating stream completion.
*/
declare enum CompleteFlag {
COMPLETE = 64
}
/**
* Enum for payload-specific flags.
*/
declare enum _PayloadFlag {
/**
* Indicates the presence of the next payload fragment.
*/
NEXT = 32
}
/**
* Flags applicable to [REQUEST_CHANNEL]{@link RequestChannelFrame} frames.
*/
declare const RequestChannelFlag: typeof FollowsFlag & typeof CompleteFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type RequestChannelFlag = FrameFlag | FollowsFlag | CompleteFlag;
/**
* Flags applicable to [PAYLOAD]{@link PayloadFrame} frames.
*/
declare const PayloadFlag: typeof _PayloadFlag & typeof FollowsFlag & typeof CompleteFlag & {
/**
* Combines multiple frame flags into a single numeric bitmask.
*
* @param flags List of frame flags to combine.
* @returns Combined numeric flag.
* @example
* ```ts
* const flags = FrameFlag.combine(FrameFlag.METADATA, FrameFlag.IGNORE);
* ```
*/
combine: (...flags: FrameFlag[]) => number;
} & typeof _FrameFlag;
type PayloadFlag = _PayloadFlag | RequestChannelFlag;
/**
* Abstract base class for writing frame content to a binary stream.
*
* Subclasses must implement the `write` method to serialize frame-specific
* data using the provided `ByteWriter`.
*
* ### Example Usage:
* ```ts
* class SetupFrameWriter extends FrameWriter {
* protected write(writer: ByteWriter): void {
* writer.i32(this.version);
* writer.write(this.payload);
* }
* }
* ```
*/
declare abstract class FrameWriter {
/**
* Writes the frame content to the provided `ByteWriter`.
* This method must be implemented by subclasses to define
* the serialization logic for the frame.
*
* @param {ByteWriter} writer - The writer used to output binary data.
*/
protected abstract write(writer: ByteWriter): void;
}
/**
* ### Frame Header Format
*
* RSocket frames begin with a RSocket Frame Header. The general layout is given below.
*
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |0| Stream ID |
* +-----------+-+-+---------------+-------------------------------+
* |Frame Type |I|M| Flags | Depends on Frame Type ...
* +-------------------------------+
* ```
*
* * __Stream ID__: (31 bits = max value 2^31-1 = 2,147,483,647) Unsigned 31-bit integer representing the stream Identifier for this frame or 0 to indicate the entire connection.
* * Transport protocols that include demultiplexing, such as HTTP/2, MAY omit the Stream ID field if all parties agree. The means of negotiation and agreement is left to the transport protocol.
* * __Frame Type__: (6 bits = max value 63) Type of Frame.
* * [__Flags__: (10 bits)]{@link FrameFlag} Any Flag bit not specifically indicated in the frame type should be set to 0 when sent and not interpreted on
* reception. Flags generally depend on Frame Type, but all frame types MUST provide space for the following flags:
* * (__I__)gnore: Ignore frame if not understood
* * (__M__)etadata: Metadata present
*
* @see [Official documentation]{@link https://github.com/rsocket/rsocket/blob/master/Protocol.md#frame-header-format}
*/
declare class Header extends FrameWriter {
readonly frameType: FrameType;
readonly streamId: number;
readonly flags: FrameFlag;
/**
* Creates a new RSocket `Header` instance.
*
* @param {FrameType} frameType - Type of the frame (6 bits).
* @param {number} streamId - Stream ID this frame is associated with (must be a 31-bit unsigned int).
* @param {FrameFlag} flags - Bitmask of frame flags (10 bits max).
*/
constructor(frameType: FrameType, // (31 bits = max value 2^31-1 = 2,147,483,647) Unsigned 31-bit integer representing the stream Identifier for this frame or 0 to indicate the entire connection.
streamId: number, // 6 bits = max value 63) Type of Frame.
flags: FrameFlag);
/**
* Deserializes a `Header` from the binary reader.
*
* @param {ByteReader} reader - Byte stream reader positioned at the start of the frame.
* @returns {Header} Parsed frame header.
*/
static from(reader: ByteReader): Header;
/**
* Checks if a specific flag is set.
*
* @param {FrameFlag} flag - Flag to check.
* @returns {boolean} True if the flag is set.
*/
isFlagSet(flag: FrameFlag): boolean;
/**
* Serializes this header to the binary writer.
*
* @param {ByteWriter} writer - Writer to serialize to.
*/
write(writer: ByteWriter): void;
}
/**
* Represents a payload frame in the RSocket protocol.
*
* @template T - The type of the payload, defaults to `Uint8Array`.
*/
declare class Payload<T = Uint8Array> extends FrameWriter {
readonly mimeType: MimeType<T>;
readonly payload: T;
/**
* Creates a new [Payload]{@link Payload} instance.
*
* @param mimeType - The MIME type indicating the format of the payload data.
* @param payload - The binary payload content.
*/
constructor(mimeType: MimeType<T>, payload: T);
/**
* Converts the payload to a [Uint8Array]{@link Uint8Array}.
*
* @returns The payload data as a [Uint8Array]{@link Uint8Array}.
*/
toUint8Array(): Uint8Array;
/**
* Serializes the payload and writes it to the given [ByteWriter]{@link ByteWriter}.
*
* @param writer - The byte writer to which the payload will be written.
*/
write(writer: ByteWriter): void;
}
/**
* Represents a MIME type and provides serialization/deserialization
* logic for metadata and payloads associated with that type.
*
* @template T The payload type, defaults to `Uint8Array`.
*/
declare class MimeType<T = Uint8Array> {
readonly mimeType: string;
readonly identifier?: number | undefined;
/**
* Internal registry of all known MIME types.
* Maps MIME type strings to their corresponding `MimeType` instances.
* @private
*/
private static _values;
/**
* Creates a new `MimeType` instance and registers it in the internal map.
*
* @param {string} mimeType - The MIME type string (e.g. "application/json").
* @param {number} [identifier] - Optional numeric identifier for well-known types.
*/
constructor(mimeType: string, identifier?: number | undefined);
/**
* Indicates whether the MIME type is well-known (has an associated identifier).
*
* @returns {boolean} `true` if the type has an identifier, otherwise `false`.
*/
get isWellKnown(): boolean;
/**
* Serializes the given payload into a `Metadata` object.
*
* @param {T} payload - The payload to wrap.
* @returns {Metadata<T>} The resulting `Metadata` instance.
* @protected
*/
protected serializeMetadata(payload: T): Metadata<T>;
/**
* Deserializes a `Metadata` object from a `ByteReader` stream.
*
* @param {ByteReader} payload - The byte stream to read from.
* @param {boolean} [hasPayload=true] - Whether a length-prefixed payload is expected.
* @returns {Metadata<T>} The deserialized metadata.
* @protected
*/
protected deserializeMetadata(payload: ByteReader, hasPayload?: boolean): Metadata<T>;
/**
* Converts a payload or byte stream into a `Metadata` object.
* Automatically chooses between serialization and deserialization based on input type.
*
* @param {ByteReader | T} payload - Either raw data or a reader to deserialize from.
* @param {boolean} [hasPayload=true] - Indicates if the reader contains a length-prefixed payload.
* @returns {Metadata<T>} A `Metadata` instance.
*/
toMetadata(payload: ByteReader | T, hasPayload?: boolean): Metadata<T>;
/**
* Serializes the given payload into a `Payload` object.
*
* @param {T} payload - The payload to wrap.
* @returns {Payload<T>} The resulting `Payload` instance.
* @protected
*/
protected serializePayload(payload: T): Payload<T>;
/**
* Deserializes a `Payload` object from a `ByteReader` stream.
*
* @param {ByteReader} payload - The byte stream to read from.
* @returns {Payload<T>} The deserialized payload.
* @protected
*/
protected deserializePayload(payload: ByteReader): Payload<T>;
/**
* Converts a payload or byte stream into a `Payload` object.
* Automatically chooses between serialization and deserialization based on input type.
*
* @param {ByteReader | T} payload - Either raw data or a reader to deserialize from.
* @returns {Payload<T>} A `Payload` instance.
*/
toPayload(payload: ByteReader | T): Payload<T>;
/**
* Retrieves a registered `MimeType` by string or identifier.
* If no match is found, returns a generic `UnknownMimeType` instance and logs a warning.
*
* @param {string | number} mimeType - MIME type string or numeric identifier.
* @returns {MimeType} A matching or unknown `MimeType` instance.
*/
static valueOf(mimeType: string | number): MimeType;
}
/**
* ## Metadata Payload for data MIME Type
* This metadata type is intended to be used per stream, and not per connection nor individual payloads and as such it **MUST** only be used in frame types used to initiate interactions.
* This includes [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, and [`REQUEST_CHANNEL`]{@link RequestChannelFrame}.
* Multiple metadata payloads with the same MIME type are allowed.
* The order of metadata payloads MUST be preserved when presented to responders. The Metadata MIME Type is `message/x.rsocket.mime-type.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |M| MIME ID/Len | Data Encoding MIME Type ...
* +---------------+-----------------------------------------------+
* ```
* * (**M**)etadata Type: Metadata type is a well known value represented by a unique integer.
* * **MIME ID/Length**: (7 bits = max value 2^7 = 128) Unsigned 7-bit integer. If M flag is set, indicates a [Well-known MIME Type ID]{@link WellKnownMimeType}. If M flag is not set, indicates the encoding MIME Type Length in bytes.
* * **Metadata Encoding MIME Type**: MIME Type for encoding of Metadata. This SHOULD be a US-ASCII string that includes the [Internet media type]{@link https://en.wikipedia.org/wiki/Internet_media_type} specified in [RFC 2045]{@link https://github.com/rsocket/rsocket/blob/master/Protocol.md#frame-fnf}.
* Many are registered with [IANA]{@link https://www.iana.org/assignments/media-types/media-types.xhtml} and others such as [Routing]{@link RSocketRouting} and [Tracing (Zipkin)]{@link} are not.
* [Suffix]{@link http://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xml} rules MAY be used for handling layout. The string MUST NOT be null terminated. (Not present if M flag is set)
*/
declare class RSocketMimeType extends MimeType<MimeType> {
/**
* Serializes a single `MimeType` to binary metadata format.
*
* @param {MimeType} payload - The MIME type to serialize.
* @returns {Metadata<MimeType>} The metadata object wrapping the MIME type.
*/
protected serializeMetadata(payload: MimeType): Metadata<MimeType>;
/**
* Deserializes metadata into a `MimeType` object.
*
* @param {ByteReader} payload - The binary reader.
* @param {boolean} [hasPayload=true] - Whether the payload has a length prefix.
* @returns {Metadata<MimeType>} The resulting metadata.
*/
protected deserializeMetadata(payload: ByteReader, hasPayload?: boolean): Metadata<MimeType>;
}
/**
* ## Metadata Payload for acceptable data MIME Types
* This metadata type is intended to be used per stream, and not per connection nor individual payloads and as such it **MUST** only be used in frame types used to initiate interactions.
* This includes [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, and [`REQUEST_CHANNEL`]{@link RequestChannelFrame}.
* Multiple metadata payloads with the same MIME type are allowed. The order of metadata payloads MUST be preserved when presented to responders. The Metadata MIME Type is `message/x.rsocket.accept-mime-types.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |M| MIME ID/Len | Data Encoding MIME Type ...
* +---------------+-----------------------------------------------+
* |M| MIME ID/Len | Data Encoding MIME Type ...
* +---------------+-----------------------------------------------+
* ...
* ```
* * (**M**)etadata Type: Metadata type is a well known value represented by a unique integer.
* * **MIME ID/Length**: (7 bits = max value 2^7 = 128) Unsigned 7-bit integer. If M flag is set, indicates a [Well-known MIME Type ID]{@link WellKnownMimeType}. If M flag is not set, indicates the encoding MIME Type Length in bytes.
* * **Metadata Encoding MIME Type**: MIME Type for encoding of Metadata. This SHOULD be a US-ASCII string that includes the [Internet media type]{@link https://en.wikipedia.org/wiki/Internet_media_type} specified in [RFC 2045]{@link https://github.com/rsocket/rsocket/blob/master/Protocol.md#frame-fnf}.
* Many are registered with [IANA]{@link https://www.iana.org/assignments/media-types/media-types.xhtml} and others such as [Routing]{@link RSocketRouting} and [Tracing (Zipkin)]{@link} are not.
* [Suffix]{@link http://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xml} rules MAY be used for handling layout. The string MUST NOT be null terminated. (Not present if M flag is set)
*/
declare class RSocketMimeTypes extends MimeType<Array<MimeType>> {
/**
* Serializes a list of MIME types into binary metadata format.
*
* @param {Array<MimeType>} payloads - MIME types to encode.
* @returns {Metadata<Array<MimeType>>} The resulting metadata.
*/
protected serializeMetadata(payloads: Array<MimeType>): Metadata<Array<MimeType>>;
/**
* Deserializes a byte stream into a list of `MimeType` objects.
*
* @param {ByteReader} reader - Source to read metadata from.
* @param {boolean} [hasPayload=true] - Whether to read a length-prefixed block.
* @returns {Metadata<Array<MimeType>>} Parsed metadata with MIME types.
*/
protected deserializeMetadata(reader: ByteReader, hasPayload?: boolean): Metadata<Array<MimeType>>;
}
/**
* # Routing Metadata Extension
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* When two system are communicating via RSocket, there are often logical divisions in the messages that are sent from the requester to the responder. These logical divisions can often be implemented by the responder as "routes" for messages to be sent to. This extension specification provides an interoperable structure for metadata payloads to contain routing information. It is designed such that an arbitrary collection of tags (strings) can be used by the responder to route messages and any individual tag (or all included tags) can be ignored.
*
* ## Metadata Payload
* This metadata type is intended to be used per stream, and not per connection nor individual payloads and as such it **MUST** only be used in frame types used to initiate interactions.
* This includes [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, and [`REQUEST_CHANNEL`]{@link RequestChannelFrame}.
* The Metadata MIME Type is `message/x.rsocket.routing.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Tag Length | Tag ...
* +---------------+-----------------------------------------------+
* | Tag Length | Tag ...
* +---------------+-----------------------------------------------+
* ...
* ```
*
* * **Tag Payload**: Any number of complete tag payloads.
* * **Tag Length**: (8 bits = max value 2^8-1 = 255) Unsigned 8-bit integer of Tag Length in bytes.
* * **Tag**: UTF-8 encoded Token used for routing. The string MUST NOT be null terminated. Examples include URI path-style routes (`/person/1`, `/address`), dot-separated convention ("person.1"), or any other format (`ios-client`, `android-client`).
*/
declare class RSocketRouting extends MimeType<Array<string>> {
/**
* Serializes an array of routing tags (UTF-8 strings) into metadata.
* Each tag is prefixed by its byte length as an 8-bit unsigned integer.
*
* @param {Array<string>} payloads - Array of routing tags to serialize.
* @returns {Metadata<Array<string>>} Serialized metadata instance.
*/
protected serializeMetadata(payloads: Array<string>): Metadata<Array<string>>;
/**
* Converts the routing tag array into a `Uint8Array` binary format.
*
* Format:
* [tag_length: u8][tag: UTF-8 bytes] repeated for each tag.
*
* @returns {Uint8Array} Serialized routing metadata.
*/
protected deserializeMetadata(payloads: ByteReader, hasPayload?: boolean): Metadata<Array<string>>;
}
/**
* # Composite Metadata Extension
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* There are a number of situations where an arbitrary collection of discrete metadata types should be attached to frame. For example, a request frame may want to include both routing metadata as well as tracing metadata. This extension specification provides an interoperable structure for metadadata payloads to contain multiple discrete metadata types. It is designed such that if a consumer of the metadata is unaware of a particular type, it can be safely skipped and the next one read.
*
* ## Metadata Payload
* This metadata type is intended to be used per stream, and not per connection nor individual payloads and as such it **MUST** only be used in frame types used to initiate interactions.
* This includes [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, and [`REQUEST_CHANNEL`]{@link RequestChannelFrame}.
* Multiple metadata payloads with the same MIME type are allowed. The order of metadata payloads MUST be preserved when presented to responders.
* The [`SETUP` Frame]{@link SetupFrame} Metadata MIME Type is `message/x.rsocket.composite-metadata.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |M| MIME ID/Len | Metadata Encoding MIME Type ...
* +---------------+---------------+---------------+---------------+
* | Metadata Length |
* +-----------------------------------------------+---------------+
* | Metadata Payload ...
* +---------------+-----------------------------------------------+
* |M| MIME ID/Len | Metadata Encoding MIME Type ...
* +---------------+-------------------------------+---------------+
* | Metadata Length |
* +-----------------------------------------------+---------------+
* | Metadata Payload ...
* +---------------------------------------------------------------+
* ...
* ```
*
* * **Metadata Payload**: Any number of complete metadata payloads.
* * (**M**)etadata Type: Metadata type is a well known value represented by a unique integer.
* * **MIME ID/Length**: (7 bits = max value 2^7 = 128) Unsigned 7-bit integer. If M flag is set, indicates a [Well-known MIME Type ID][wk]. If M flag is not set, indicates the encoding MIME Type Length in bytes.
* * **Metadata Encoding MIME Type**: MIME Type for encoding of Metadata. This SHOULD be a US-ASCII string that includes the [Internet media type](https://en.wikipedia.org/wiki/Internet_media_type) specified in [RFC 2045][rf]. Many are registered with [IANA][ia] and others such as [Routing][r] and [Tracing (Zipkin)][tz] are not. [Suffix][s] rules MAY be used for handling layout. The string MUST NOT be null terminated. (Not present if M flag is set)
* * **Metadata Length**: (24 bits = max value 16,777,215) Unsigned 24-bit integer of Metadata Length in bytes.
* * **Metadata Payload**: User configured metadata encoded as defined by the Metadata Encoding MIME Type.
*/
declare class RSocketComposite extends MimeType<Array<Metadata<any>>> {
/**
* Serializes an array of `Metadata<T>` entries into composite metadata format.
*
* @param {Array<Metadata<any>>} payloads - Metadata entries to encode.
* @returns {Metadata<Array<Metadata<any>>>} Composite metadata wrapper.
*/
protected serializeMetadata(payloads: Array<Metadata<any>>): Metadata<Array<Metadata<any>>>;
/**
* Deserializes a composite metadata block into individual `Metadata<T>` instances.
* Each metadata entry is parsed according to its MIME type.
*
* @param {ByteReader} payloads - Reader containing composite metadata.
* @param {boolean} [hasPayload=true] - Whether the payload is prefixed with a length (i24).
* @returns {Metadata<Array<Metadata<any>>>} The reconstructed composite metadata object.
*/
protected deserializeMetadata(payloads: ByteReader, hasPayload?: boolean): Metadata<Array<Metadata<any>>>;
}
/**
* Bit-level flags describing Zipkin tracing metadata behavior.
*/
type TracingZipkinFlags = {
/** Indicates if trace/span/parent IDs are present. */
idsSet: boolean;
/** Forces tracing regardless of sampling. */
debug: boolean;
/** Marks the trace as sampled (ignored if debug is true). */
sampled: boolean;
/** Explicitly marks trace as not sampled (ignored if sampled/debug is true). */
notSampled: boolean;
/** Enables 128-bit trace ID (if false, trace ID is 64-bit). */
traceId128: boolean;
/** If true, includes parent span ID in metadata. */
hasParent: boolean;
};
/**
* Represents a deserialized payload for Zipkin Tracing metadata.
*
* @property {TracingZipkinFlags} flags - Bit flags affecting encoding behavior.
* @property {bigint | [bigint, bigint]} traceId - 64- or 128-bit Trace ID.
* @property {bigint} spanId - Unique identifier for the span.
* @property {bigint=} parentSpanId - Optional parent span ID.
*/
type TracingZipkinPayload = {
flags: TracingZipkinFlags;
traceId: bigint | [bigint, bigint];
spanId: bigint;
parentSpanId?: bigint;
};
/**
* # Tracing (Zipkin) Metadata Extension
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* Observability and tracing are key requirements for robust and reliable applications. When using distributed applications connected with RSocket, it's important to propagate metadata about the current logical operations throughout the entire system.
* One of the most popular systems for doing this kind of tracing is [Zipkin]{@link https://zipkin.io}. This extension specification provides an interoperable structure for Zipkin metadata payloads to contain tracing information. It is designed such that systems can efficently communicate span and trace information to a Zipkin server and propagate that information throughout a distributed system.
*
* ## Metadata Payload
* This metadata type is intended to be used per stream, and not per connection nor individual payloads and as such it **MUST** only be used in frame types used to initiate interactions and payloads. This includes [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, [`REQUEST_CHANNEL`]{@link RequestChannelFrame}, and [`PAYLOAD`]{@link PayloadFrame}.
* The Metadata MIME Type is `message/x.rsocket.tracing-zipkin.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |I|D|S|N|T|P| |
* +-+-+---+---+---+-----------------------------------------------+
* | |
* + +
* | |
* + Trace ID +
* | |
* + +
* | |
* +---------------------------------------------------------------+
* | |
* + Span ID +
* | |
* +---------------------------------------------------------------+
* | |
* + Parent Span ID +
* | |
* +---------------------------------------------------------------+
* ```
*
* * **Flags**: (8 bits)
* * (**I**)Ds Set: When zero, the metadata only includes sampling information and no IDs
* * For example, a health check might set only the (**N**)ot Sampled flag without generating IDs
* * (**D**)ebug: Tracing payload should be force traced.
* * (**S**)ample: Tracing payload should be accepted for tracing. (Ignored when D flag is set.)
* * (**N**)ot Sampled: Tracing payload should not be sampled. (Ignored when S flag or D flag is set.)
* * (**T**)race Id Size: Unset indicates that the Trace Id is 64-bit. Set indicates that the Trace Id is 128-bit.
* * (**P**)arent Span Id: Tracing payload contains a parent span id.
* * **Trace ID**: (64 or 128 bits) Unsigned 64- or 128-bit integer ID of the trace. Every span in a trace shares this ID.
* * **Span ID**: (64 bits) Unsigned 64-bit integer ID for a particular span. This may or may not be the same as the trace id.
* * **Parent Span ID**: (64 bits) Unsigned 64-bit integer ID for a particular parent span. This is an optional ID that will only be present on child spans. That is the span without a parent id is considered the root of the trace. (Not present if P flag is not set)
*/
declare class RSocketTracingZipkin extends MimeType<TracingZipkinPayload> {
/**
* Serializes a structured tracing payload into a binary metadata block.
*
* @param {TracingZipkinPayload} payload - The tracing data to encode.
* @returns {Metadata<TracingZipkinPayload>} A Metadata object with a `toUint8Array()` method.
*/
protected serializeMetadata(payload: TracingZipkinPayload): Metadata<TracingZipkinPayload>;
/**
* Deserializes a binary tracing metadata payload into a structured object.
*
* @param {ByteReader} reader - Byte reader to extract metadata from.
* @param {boolean} [hasPayload=true] - Whether metadata is prefixed with a length (i24).
* @returns {Metadata<TracingZipkinPayload>} Parsed tracing metadata.
*/
protected deserializeMetadata(reader: ByteReader, hasPayload?: boolean): Metadata<TracingZipkinPayload>;
}
/**
* Abstract base class representing an RSocket authentication type.
*
* Subclasses define how specific authentication payloads are serialized and deserialized.
* Provides facilities for working with both well-known and custom authentication types.
*
* @template T The type of the authentication data.
*/
declare abstract class AuthType<T> {
readonly authType: string;
readonly identifier?: number | undefined;
private static _values;
/**
* Creates a new authentication type.
*
* @param authType A unique string identifier for the authentication type.
* @param identifier An optional numeric identifier for well-known authentication types.
*/
constructor(authType: string, identifier?: number | undefined);
/**
* @return `true` if this authentication type is a [well-known type]{@link WellKnownAuthType} (i.e., has a numeric identifier).
*/
get isWellKnown(): boolean;
/**
* Serializes the given authentication data into the provided writer.
*
* @param writer A [ByteWriter]{@link ByteWriter} used to serialize the data.
* @param data The authentication data to serialize.
*/
abstract write(writer: ByteWriter, data: T): void;
/**
* Deserializes authentication data from the given reader.
*
* @param reader A [ByteReader]{@link ByteReader} used to read the serialized data.
* @returns The deserialized authentication data.
*/
abstract read(reader: ByteReader): T;
/**
* Wraps the authentication data with this authentication type.
*
* @param data The authentication data.
* @returns An object pairing the authentication type with the provided data.
*/
auth(data: T): {
authType: AuthType<T>;
data: T;
};
/**
* Retrieves a registered [AuthType]{@link AuthType} by string name or numeric identifier.
*
* If the type is not recognized, returns a generic unknown type
* that reads and writes raw [Uint8Array]{@link Uint8Array} data.
*
* @param authType A string or number representing the authentication type.
* @returns The corresponding `AuthType` instance.
*/
static valueOf(authType: string | number): AuthType<any>;
}
type AuthData<D> = {
authType: AuthType<D>;
data: D;
};
/**
* # Authentication Extension
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* Authentication is a necessary component to any real world application. This extension specification provides a standardized mechanism for including both the type of credentials and the credentials in metadata payloads.
*
* ## Metadata Payload
* This metadata type can be used in a per connection or per stream, and not individual payloads and as such it **MUST** only be used in frame types used to initiate interactions and payloads.
* This includes [`SETUP`]{@link SetupFrame}, [`REQUEST_FNF`]{@link RequestFireAndForgetFrame}, [`REQUEST_RESPONSE`]{@link RequestResponseFrame}, [`REQUEST_STREAM`]{@link RequestStreamFrame}, and [`REQUEST_CHANNEL`]{@link RequestChannelFrame}.
* The Metadata MIME Type is `message/x.rsocket.authentication.v0`.
*
* ### Metadata Contents
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |A| Auth ID/Len | Authentication Type ...
* +---------------+---------------+---------------+---------------+
* | Authentication Payload ...
* +---------------+-----------------------------------------------+
* ```
*
* * (**A**)uthentication Type: Authentication type is a well known value represented by a unique integer. If A flag is set (a value of `1`), indicates a [Well-known Auth Type ID]{@link WellKnownAuthType}. If A flag is not set (a value of `0`), indicates the Authentication Type Length in bytes.
* * **Auth ID/Length**: (7 bits = max value 2^7 = 128) Unsigned 7-bit integer. If A flag is set (a value of `1`), indicates a [Well-known Auth Type ID]{@link WellKnownAuthType}. If A flag is not set (a value of `0`), indicates the Authentication Type Length in bytes.
* * **Authentication Type**: the type of authentication encoding. This SHOULD be a US-ASCII string. The string MUST NOT be null terminated. (Not present if A flag is set)
* * **Authentication Payload**: The authentication payload encoded as defined by the Authentication Encoding Type.
*/
declare class RSocketAuth<D> extends MimeType<AuthData<D>> {
/**
* Serializes authentication metadata including auth type and credentials.
*
* If the `authType` is well-known, it writes the ID.
* Otherwise, it writes the UTF-8 string name and the payload.
*
* @param {AuthData<D>} payload - Authentication data to serialize.
* @returns {Metadata<AuthData<D>>} Metadata wrapper containing the auth data.
*/
protected serializeMetadata(payload: AuthData<D>): Metadata<AuthData<D>>;
/**
* Deserializes binary metadata into authentication data.
*
* Resolves the `AuthType` based on the ID or name, then uses it to decode
* the corresponding credentials from the stream.
*
* @param {ByteReader} payload - The input binary reader.
* @param {boolean} [hasPayload=true] - Whether to expect a length-prefixed payload.
* @returns {Metadata<AuthData<D>>} Parsed authentication metadata.
*/
protected deserializeMetadata(payload: ByteReader, hasPayload?: boolean): Metadata<AuthData<D>>;
}
/**
* # Simple Authentication Type
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* Authentication is a necessary component to any real world application. The most "simple" mechanism for authenticating is leveraging a username and password for authentication. This Authentication Type provides a standardized mechanism for including a username and password in the Authentication Payload of the [Authentication Extension]{@link RSocketAuth} using the Authentication Type of `simple`.
*
* ## Authentication Payload
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Username Length |
* +-------------------------------+-------------------------------+
* | Username ...
* +-------------------------------+-------------------------------+
* | Password ...
* +-------------------------------+-------------------------------+
* ```
*
* * **Username Length**: (16 bits = max value 2^16-1 = 65535) Unsigned 16-bit integer of Username Length in bytes.
* * **Username**: The UTF-8 encoded username. The string MUST NOT be null terminated.
* * **Password**: The UTF-8 encoded password. The string MUST NOT be null terminated.
*
* ## Security Considerations
* The Simple Authentication Type transmits the username and password in cleartext. Additionally, it does not protect the authenticity or confidentiality of the payload that is transmitted along with it. This means that the [Transport]{@link https://github.com/rsocket/rsocket/blob/master/Protocol.md#transport-protocol} that is used should provide both authenticity and confidentiality to protect both the username and password and corresponding payload.
*
* The use of the UTF-8 character encoding scheme and of normalization introduces additional security considerations; see [Section 10 of RFC3629]{@link https://tools.ietf.org/html/rfc3629#section-10} and [Section 6 of RFC5198]{@link https://tools.ietf.org/html/rfc5198#section-6} for more information.
*/
declare class SimpleAuthType extends AuthType<{
username: string;
password: string;
}> {
/**
* Reads and decodes the authentication payload from the given ByteReader.
*
* @param {ByteReader} reader - The byte reader to extract the authentication data.
* @returns {{ username: string, password: string }} The decoded credentials.
*/
read(reader: ByteReader): {
username: string;
password: string;
};
/**
* Writes the authentication payload to the given ByteWriter.
*
* Encodes the username and password using UTF-8 and writes:
* - A 16-bit unsigned integer representing the byte-length of the username.
* - The UTF-8 encoded username.
* - The UTF-8 encoded password.
*
* @param {ByteWriter} writer - The byte writer to write the authentication data.
* @param {{ username: string, password: string }} data - The credentials to encode and write.
* @returns {void}
*/
write(writer: ByteWriter, data: {
username: string;
password: string;
}): void;
}
/**
* # Bearer Token Authentication Type
*
* _This extension specification is currently incubating. While incubating the version is 0._
*
* ## Introduction
* Authentication is a necessary component to any real world application. A common mechanism for authenticating is using a bearer token. A bearer token can be presented as a means of obtaining access to a resource (i.e. session ids, OAuth 2 tokens, etc).
* This Authentication Type provides a standardized mechanism for including a bearer token in the Authentication Payload of the [Authentication Extension]{@link RSocketAuth} using the Authentication Type of `bearer`.
*
* ### Authentication Payload
* ```
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Bearer Token ...
* +---------------+-----------------------------------------------+
* ```
*
* * **Bearer Token**: The UTF-8 encoded bearer token. The string MUST NOT be null terminated.
*/
declare class BearerAuthType extends AuthType<string> {
/**
* Reads a bearer token from the given byte stream.
*
* @param {ByteReader} reader - A stream from which to read the bearer token.
* @returns {string} Decoded bearer token as a UTF-8 string.
*/
read(reader: ByteReader): string;
/**
* Writes a bearer token to the output stream.
*
* @param {ByteWriter} writer - The stream to write to.
* @param {string} data - The bearer token to encode and write.
*/
write(writer: ByteWriter, data: string): void;
}
/**
* Namespace containing well-known authentication types for use in
* `RSocketAuth` metadata.
*
* These types represent commonly used credential schemes and are associated
* with numeric identifiers for efficient encoding. They are typically
* used in frames that support authentication, such as `SETUP`.
*/
declare namespace WellKnownAuthType {
/**
* Simple Authentication Type.
* Uses a UTF-8 encoded `username` and `password` pair.
* Identifier: `0`
*
* Example:
* ```ts
* {
* authType: WellKnownAuthType.SIMPLE,
* data: { username: "admin", password: "secret" }
* }
* ```
*/
const SIMPLE: SimpleAuthType;
/**
* Bearer Authentication Type.
* Uses a single UTF-8 encoded bearer token.
* Identifier: `1`
*
* Example:
* ```ts
* {
* authType: WellKnownAuthType.BEARER,
* data: "eyJhbGciOiJIUzI1NiIsInR5cCI6..."
* }
* ```
*/
const BEARER: BearerAuthType; /**
* Resolves a well-known or custom authentication type by name or numeric ID.
*
* @param {string | number} type - The authentication type name or identifier.
* @returns {AuthType<any>} Matching AuthType instance.
*/
const valueOf: typeof AuthType.valueOf;
}
/**
* Namespace containing predefined and registered well-known MIME types,
* including both standard media types and RSocket-specific types.
*/
declare namespace WellKnownMimeType {
/** AVRO encoded binary data. */
const APPLICATION_AVRO: MimeType<Uint8Array<ArrayBufferLike>>;
/** Concise Binary Object Representation (CBOR). */
const APPLICATION_CBOR: MimeType<Uint8Array<ArrayBufferLike>>;
/** GraphQL query format. */
const APPLICATION_GRAPHQL: MimeType<Uint8Array<ArrayBufferLike>>;
/** GZIP compressed data. */
const APPLICATION_GZIP: MimeType<Uint8Array<ArrayBufferLike>>;
/** JavaScript source code. */
const APPLICATION_JAVASCRIPT: MimeType<Uint8Array<ArrayBufferLike>>;
/** JSON encoded data. */
const APPLICATION_JSON: MimeType<Uint8Array<ArrayBufferLike>>;
/** Binary stream format. */
const APPLICATION_OCTET_STREAM: MimeType<Uint8Array<ArrayBufferLike>>;
/** Portable Document Format. */
const APPLICATION_PDF: MimeType<Uint8Array<ArrayBufferLike>>;
/** Apache Thrift binary protocol. */
const APPLICATION_THRIFT: MimeType<Uint8Arr