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.

struct TransportCodec {
decoder: std::sync::Mutex<FramePump>,
encoder: FrameEncoder,
}

Defined in rust/miniproto/src/transport.rs:149-154

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

  • decoder: std::sync::Mutex<FramePump>

    Stateful native parser and encoder backing this Python object.

  • encoder: FrameEncoder

    Immutable outgoing transport framing parameters.

  • 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(&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(&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 = True

  • 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>::ImmutableChild

  • 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 FrameEncoder {
mode: TransportMode,
max_payload_size: usize,
}

Defined in rust/miniproto/src/transport.rs:257-262

Immutable inputs used to frame outgoing packets.

  • mode: TransportMode

    TCP framing mode selected for this connection.

  • max_payload_size: usize

    Upper bound for the unframed payload size.

  • 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.

  • 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:265-276

Parser 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.

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

Defined in rust/miniproto/src/transport.rs:98-105

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:129-145

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:38-42

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: std::borrow::Cow<'_, [u8]>, encrypted_packet: std::borrow::Cow<'_, [u8]>) -> PyResult<u32>

Defined in rust/miniproto/src/transport.rs:55-64

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: Complete client-to-server packet whose decrypted and padded payload determines the token.
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:54

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

Defined in rust/miniproto/src/transport.rs:72-94

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: Complete client-to-server packet whose decrypted and padded payload determines the token.
fn encode_length_prefixed(payload: &[u8], payload_length: u32, quick_ack: bool) -> PyResult<Vec<u8>>

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

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:722-749

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:759-762

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:29

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:19

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:21

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:23

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

const MAX_TRANSPORT_PADDING: usize = 15usize;

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

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:27

Largest drained receive-buffer allocation retained for later chunks.