Skip to content

miniproto_native::transport

miniproto_native / transport


Registers TCP transport framing callables and the stateful codec class. Stateful native codecs for Telegram TCP abridged, intermediate and padded-intermediate frames.

miniproto._native.TransportCodec accepts fragmented input and emits payload, quick-ACK and transport-error events. Its framing validation raises ValueError, which the Python adapter converts to ProtocolValidationError on receive and TransportError on encode. PyO3 conversion errors propagate unchanged. FramePump uses no Python objects. Its Python wrappers remain attached during parsing, encoding and result conversion, holding the GIL on GIL-enabled builds. Quick-ACK hashing can detach for large packets.

Item Kind Description
TransportCodec struct Python-visible incremental TCP framing codec, exported as miniproto._native.TransportCodec.
FramePump struct Parser/encoder retaining incomplete input without accessing Python objects
TransportMode enum Supported Telegram TCP framing modes selected by their Python wire-name strings.
FrameEvent enum One native frame-pump result before it is converted to a Python return shape.
register fn Registers Python TransportCodec and quick_ack_token on miniproto._native.
quick_ack_token fn Computes the flagged quick-ACK token for Python quick_ack_token.
__pyfunction_quick_ack_token fn
quick_ack_token_raw fn Computes a quick-ACK token without Python argument conversion or GIL interaction.
encode_length_prefixed fn Encodes a four-byte little-endian length prefix and payload, optionally setting quick-ACK bit.
padded_packet_length fn Determines the embedded MTProto packet length within a padded-intermediate payload.
to_fixed fn Converts a slice to an exact fixed-width array for frame header decoding.
PythonFrameEvent type Python feed_data event tuple: kind, payload, numeric detail, quick-ACK request flag.
ABRIDGED_LONG_MARKER const Abridged header byte that introduces its three-byte word-length form.
QUICK_ACK_MASK const Wire bit that asks the peer to return a quick-ACK token.
PADDED_QUICK_ACK_MARKER const Padded-intermediate payload marker identifying a quick-ACK response.
MAX_TRANSPORT_PADDING const Maximum random padding bytes allowed by padded-intermediate TCP framing.
RETAINED_BUFFER_LIMIT const Largest drained receive-buffer allocation retained for later chunks.
struct TransportCodec {
pump: FramePump,
}

Defined in rust/miniproto/src/transport.rs:133-136

Python-visible incremental TCP framing codec, exported as miniproto._native.TransportCodec.

  • pump: FramePump

    Stateful native parser and encoder backing this Python object.

  • fn new(mode: &str, max_payload_size: usize, server_side: bool) -> PyResult<Self>

    Creates TransportCodec(mode, max_payload_size, server_side=False).

    An unsupported mode or zero payload bound raises ValueError. A negative bound or one larger than usize raises OverflowError during PyO3 conversion.

    • mode: One of the supported Python TCP mode names.

    • max_payload_size: Positive upper bound for decoded application payload bytes.

    • server_side: Whether inbound quick-ACK request bits remain payload metadata instead of

      being interpreted as quick-ACK response frames.

  • fn encode_packet(&self, payload: &[u8], quick_ack: bool) -> PyResult<Vec<u8>>

    Encodes Python encode_packet(payload, quick_ack=False) into a single TCP frame.

    Returns ValueError for oversized payloads, invalid abridged alignment, length overflow,

    or operating-system randomness failure in padded mode.

    • payload: Complete MTProto payload to frame.

    • quick_ack: Whether to set the outbound quick-ACK request bit where the mode supports it.

  • fn feed_data(&mut self, data: &[u8]) -> PyResult<Vec<(u8, Vec<u8>, i64, bool)>>

    Feeds Python feed_data(data) and returns tagged native event tuples.

    Tuple kinds are 0 payload, 1 quick ACK and 2 negative transport error. It preserves

    incomplete trailing bytes for the next call and raises Python errors for invalid framing.

    • data: Newly received TCP bytes to append to this codec’s buffered stream.
  • fn feed_transport_data(&mut self, py: Python<'_>, data: &[u8]) -> PyResult<Vec<Py<PyAny>>>

    Feeds compatibility feed_transport_data(data) and returns bytes or integer Python events.

    The GIL token is used only for object conversion after native parsing; malformed framing

    returns a Python exception.

    • py: The acquired GIL token used to build Python bytes and integer events.

    • data: Newly received TCP bytes to append to this codec’s buffered stream.

  • type Target = TransportCodec

  • type Output = Bound<'py, TransportCodec>

  • type Error = PyErr

  • fn into_pyobject(self, py: ::pyo3::Python<'py>) -> ::pyo3::PyResult<::pyo3::Bound<'py, Self>>

  • const NAME: &str

  • type Frozen = False

  • const MODULE: ::core::option::Option<&str>

  • type Layout = <<TransportCodec as PyClassImpl>::BaseNativeType as PyClassBaseType>::Layout

  • type BaseType = PyAny

  • type ThreadChecker = NoopThreadChecker

  • type PyClassMutability = <<PyAny as PyClassBaseType>::PyClassMutability as PyClassMutability>::MutableChild

  • type Dict = PyClassDummySlot

  • type WeakRef = PyClassDummySlot

  • type BaseNativeType = PyAny

  • fn items_iter() -> ::pyo3::impl_::pyclass::PyClassItemsIter

  • const RAW_DOC: &'static ::core::ffi::CStr

  • const DOC: &'static ::core::ffi::CStr

  • fn lazy_type_object() -> &'static ::pyo3::impl_::pyclass::LazyTypeObject<Self>

  • fn __traverse__(&self, visit: ::pyo3::gc::PyVisit<'_>) -> ::core::result::Result<(), ::pyo3::gc::PyTraverseError>

impl PyClassNewTextSignature for TransportCodec
Section titled “impl PyClassNewTextSignature for TransportCodec”
  • const TEXT_SIGNATURE: &'static str
  • fn arguments(self, py: Python<'_>) -> Py<PyAny>
impl PyMethods for ::pyo3::impl_::pyclass::PyClassImplCollector<TransportCodec>
Section titled “impl PyMethods for ::pyo3::impl_::pyclass::PyClassImplCollector<TransportCodec>”
  • fn py_methods(self) -> &'static ::pyo3::impl_::pyclass::PyClassItems
  • fn type_check(object: &Bound<'_, PyAny>) -> bool

  • fn classinfo_object(py: Python<'_>) -> Bound<'_, PyAny>

  • fn type_object_raw(py: ::pyo3::Python<'_>) -> *mut ::pyo3::ffi::PyTypeObject
  • type Output = T
struct FramePump {
mode: TransportMode,
max_payload_size: usize,
server_side: bool,
buffer: Vec<u8>,
offset: usize,
}

Defined in rust/miniproto/src/transport.rs:221-232

Parser/encoder retaining incomplete input without accessing Python objects

  • mode: TransportMode

    Framing variant used for every operation.

  • max_payload_size: usize

    Maximum permitted decoded MTProto payload size.

  • server_side: bool

    Whether inbound quick-ACK request bits represent payload frames rather than ACK responses.

  • buffer: Vec<u8>

    Accumulated unconsumed receive bytes.

  • offset: usize

    Leading consumed byte count within buffer.

  • fn new(mode: TransportMode, max_payload_size: usize, server_side: bool) -> PyResult<Self> — TransportMode

    Creates a framed-stream pump after validating its positive payload limit.

    Returns ValueError for zero max_payload_size.

    • mode: Internal TCP framing strategy for this pump.

    • max_payload_size: Positive upper bound for decoded application payload bytes.

    • server_side: Whether quick-ACK request bits are decoded as payload metadata.

  • fn encode_packet(&self, payload: &[u8], quick_ack: bool) -> PyResult<Vec<u8>>

    Encodes one payload using the pump’s configured TCP transport mode.

    Returns ValueError for size/alignment violations or downstream frame construction errors.

    • payload: Complete MTProto payload to frame.

    • quick_ack: Whether to set the outbound quick-ACK request bit where allowed.

  • fn encode_abridged(&self, payload: &[u8], quick_ack: bool) -> PyResult<Vec<u8>>

    Encodes an abridged frame with a one- or four-byte word-count header.

    Returns ValueError unless payload is four-byte aligned and representable on the wire.

    • payload: Four-byte-aligned MTProto payload to frame.

    • quick_ack: Whether to set abridged’s quick-ACK request bit.

  • fn encode_intermediate(&self, payload: &[u8], quick_ack: bool) -> PyResult<Vec<u8>>

    Encodes an intermediate frame with a flagged four-byte byte-count header.

    Returns ValueError for unrepresentable transport lengths.

    • payload: MTProto payload to frame.

    • quick_ack: Whether to set intermediate’s quick-ACK request bit.

  • fn encode_padded_intermediate(&self, payload: &[u8], quick_ack: bool) -> PyResult<Vec<u8>>

    Encodes an intermediate frame with random zero-to-fifteen-byte padding.

    Returns ValueError for arithmetic, size or operating-system randomness failures.

    • payload: MTProto payload to frame before random transport padding.

    • quick_ack: Whether to set the intermediate quick-ACK request bit.

  • fn feed_data(&mut self, data: &[u8]) -> PyResult<Vec<FrameEvent>> — FrameEvent

    Buffers data, parses every complete frame and retains a partial suffix for later input.

    Returns parsed events or a Python exception for allocation, overflow or invalid framing.

    • data: Newly received TCP bytes to append before parsing complete frames.
  • fn parse_one(&self) -> PyResult<Option<(FrameEvent, usize)>> — FrameEvent

    Attempts to parse one complete frame without mutating the receive buffer.

    Returns None for an incomplete frame or a Python exception for malformed framing.

  • fn parse_abridged(&self) -> PyResult<Option<(FrameEvent, usize)>> — FrameEvent

    Parses one abridged frame or client-side quick-ACK response from buffered input.

    Returns None while incomplete and ValueError for oversized or overflowing frames.

  • fn parse_intermediate(&self, padded: bool) -> PyResult<Option<(FrameEvent, usize)>> — FrameEvent

    Parses one intermediate or padded-intermediate frame from buffered input.

    padded selects padded payload processing. Returns None while incomplete or ValueError

    for invalid lengths and protocol-incompatible quick-ACK forms.

    • padded: Whether the wire payload carries padded-intermediate transport suffix bytes.
  • fn payload_event(&self, payload: Vec<u8>, padded: bool, quick_ack_requested: bool) -> PyResult<FrameEvent> — FrameEvent

    Converts a complete raw transport payload to an application, ACK or error event.

    Removes padded-intermediate suffix bytes after checking the packet shape and padding length. Invalid shape or excess payload length returns ValueError. Random padding byte values are unrestricted.

    • payload: Complete raw payload after its transport frame prefix.

    • padded: Whether to classify and remove padded-intermediate suffix bytes.

    • quick_ack_requested: Whether the inbound frame header requested a quick ACK.

  • fn validate_frame_length(&self, payload_length: usize, padded: bool) -> PyResult<()>

    Validates a declared frame payload length against this pump’s configured maximum.

    Adds the allowed padded-mode suffix and returns ValueError on overflow or excess.

    • payload_length: Declared transport payload size in bytes.

    • padded: Whether the frame may include up to MAX_TRANSPORT_PADDING bytes.

  • fn read_slice(&self, offset: usize, length: usize) -> PyResult<&[u8]>

    Borrows a checked range from the accumulated receive buffer.

    Returns ValueError rather than panicking on overflow or a truncated frame.

    • offset: Absolute buffered-stream offset at which the range begins.

    • length: Number of bytes to borrow.

  • fn read_fixed<const N: usize>(&self, offset: usize) -> PyResult<[u8; N]>

    Reads an exactly N-byte receive-buffer field at offset.

    Returns ValueError for missing bytes.

    • N: Compile-time field width to read.

    • offset: Absolute buffered-stream offset at which the field begins.

  • fn compact(&mut self)

    Discards consumed bytes and releases oversized capacity when the buffer is fully drained

  • type Output = T
enum TransportMode {
Abridged,
Intermediate,
PaddedIntermediate,
}

Defined in rust/miniproto/src/transport.rs:82-89

Supported Telegram TCP framing modes selected by their Python wire-name strings.

  • Abridged

    TCP abridged framing with a word-count prefix.

  • Intermediate

    TCP intermediate framing with a four-byte byte-count prefix.

  • PaddedIntermediate

    Intermediate framing with up to 15 random padding bytes.

  • fn parse(value: &str) -> PyResult<Self>

    Parses one Python transport mode name into its internal framing strategy.

    Returns ValueError for unsupported values.

    • value: Python transport mode name to map to a framing variant.
  • fn clone(&self) -> Self
  • fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
  • fn eq(&self, other: &Self) -> bool
  • type Output = T
impl StructuralPartialEq for TransportMode
Section titled “impl StructuralPartialEq for TransportMode”
enum FrameEvent {
Payload {
payload: Vec<u8>,
quick_ack_requested: bool,
},
QuickAck(u32),
TransportError(i32),
}

Defined in rust/miniproto/src/transport.rs:113-129

One native frame-pump result before it is converted to a Python return shape.

  • Payload

    A complete MTProto payload and whether the peer requested a quick ACK.

  • QuickAck

    A quick-ACK token received from the peer.

    The contained u32 is the wire token, including its quick-ACK mask bit.

  • TransportError

    A negative MTProto transport error received in its dedicated wire form.

    The contained i32 is the peer-provided negative transport error code.

  • fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
  • fn eq(&self, other: &Self) -> bool
  • type Output = T
fn register(m: &Bound<'_, pyo3::types::PyModule>) -> PyResult<()>

Defined in rust/miniproto/src/transport.rs:35-39

Registers Python TransportCodec and quick_ack_token on miniproto._native.

Returns a PyO3 exception if either export cannot be installed.

  • m: The Python extension module receiving the transport exports.
fn quick_ack_token(py: Python<'_>, auth_key: Vec<u8>, encrypted_packet: Vec<u8>) -> PyResult<u32>

Defined in rust/miniproto/src/transport.rs:52-57

Computes the flagged quick-ACK token for Python quick_ack_token.

The 256-byte auth_key and nonempty encrypted portion of encrypted_packet are validated. Returns the token with the quick-ACK bit set or ValueError for invalid packet/key input.

  • py: Acquired Python token used to detach hashing for sufficiently large packets.
  • auth_key: 256-byte MTProto authorization key used by the quick-ACK hash schedule.
  • encrypted_packet: Full MTProto packet whose nonempty encrypted suffix is hashed.
unsafe fn __pyfunction_quick_ack_token<'py>(py: Python<'py>, _slf: *mut ffi::PyObject, _args: *const *mut ffi::PyObject, _nargs: ffi::Py_ssize_t, _kwargs: *mut ffi::PyObject) -> PyResult<*mut ffi::PyObject>

Defined in rust/miniproto/src/transport.rs:51

fn quick_ack_token_raw(auth_key: &[u8], encrypted_packet: &[u8]) -> PyResult<u32>

Defined in rust/miniproto/src/transport.rs:65-78

Computes a quick-ACK token without Python argument conversion or GIL interaction.

  • auth_key: 256-byte MTProto authorization key used by the quick-ACK hash schedule.
  • encrypted_packet: Full MTProto packet whose nonempty encrypted suffix is hashed.
fn encode_length_prefixed(payload: &[u8], payload_length: u32, quick_ack: bool) -> PyResult<Vec<u8>>

Defined in rust/miniproto/src/transport.rs:636-649

Encodes a four-byte little-endian length prefix and payload, optionally setting quick-ACK bit.

Returns ValueError if header-plus-payload length overflows usize.

  • payload: Bytes to follow the four-byte header.
  • payload_length: Already validated wire length, excluding the header.
  • quick_ack: Whether to set the intermediate quick-ACK request bit.
fn padded_packet_length(payload: &[u8]) -> PyResult<usize>

Defined in rust/miniproto/src/transport.rs:659-686

Determines the embedded MTProto packet length within a padded-intermediate payload.

Returns ValueError for malformed unencrypted or encrypted packet shapes; it deliberately does not treat arbitrary encrypted payload bytes as transport error indicators.

  • payload: Padded-intermediate contents containing an embedded MTProto packet and suffix.
fn to_fixed<const N: usize>(data: &[u8]) -> PyResult<[u8; N]>

Defined in rust/miniproto/src/transport.rs:696-699

Converts a slice to an exact fixed-width array for frame header decoding.

Returns ValueError rather than panicking on an unexpected length.

  • N: Compile-time width required by the caller.
  • data: Slice expected to contain exactly N bytes.
type PythonFrameEvent = (u8, Vec<u8>, i64, bool);

Defined in rust/miniproto/src/transport.rs:26

Python feed_data event tuple: kind, payload, numeric detail, quick-ACK request flag.

const ABRIDGED_LONG_MARKER: u8 = 127u8;

Defined in rust/miniproto/src/transport.rs:16

Abridged header byte that introduces its three-byte word-length form.

const QUICK_ACK_MASK: u32 = 2_147_483_648u32;

Defined in rust/miniproto/src/transport.rs:18

Wire bit that asks the peer to return a quick-ACK token.

const PADDED_QUICK_ACK_MARKER: [u8; 4];

Defined in rust/miniproto/src/transport.rs:20

Padded-intermediate payload marker identifying a quick-ACK response.

const MAX_TRANSPORT_PADDING: usize = 15usize;

Defined in rust/miniproto/src/transport.rs:22

Maximum random padding bytes allowed by padded-intermediate TCP framing.

const RETAINED_BUFFER_LIMIT: usize = 1_048_576usize;

Defined in rust/miniproto/src/transport.rs:24

Largest drained receive-buffer allocation retained for later chunks.