Files
Richard Markiewicz 4982320bff perf(ffi): size PDUs from the header and add buffered, sync and cancellable Framed reads (#2289)
`Framed.ReadPdu` copied the whole buffer into a new array on every
`FindSize` call. An active-stage PDU announces its length in its first
bytes (four for TPKT, at most three for fast-path), so `Framed` now
probes only the first four buffered bytes into a reusable array;
`ReadByHint` keeps the full copy because connection-time PDUs are few
and small.

New members, alongside the existing ones:

- `ReadPdu(CancellationToken)`, and `CancellationToken` overloads of
`ReadExact` and both `ReadByHint`.
- `TryReadBufferedPdu(out (Action, byte[]))`: takes the next PDU when it
is already buffered, without reading the stream, so a consumer can flush
rendering only when nothing more is pending.
- `ReadPduSync()`: a blocking read for a dedicated read thread.

A cancelled read stops waiting but leaves the stream read in flight; the
next read, asynchronous or synchronous, finishes it first, so bytes are
neither lost nor read twice. Every read reports a stream that ends
before the PDU is complete as `IronRdpLibException(EndOfFile)`, where
`ReadExact` and `ReadByHint` threw a plain `Exception`.

`Connection.Connect`,
`RDCleanPathConnection.ConnectRDCleanPath`/`ConnectVmConnectRDCleanPath`
and `Connection.SingleSequenceStep` take an optional `CancellationToken`
and pass it to the hint reads, the TCP connect and the TLS handshake.

Consumers:

- The Avalonia example cancels the connection sequence and the read loop
through one token on window close or session end, and uses
`TryReadBufferedPdu` to present the bitmap only once no further PDU is
buffered, so a burst of updates draws once.
- `ConnectExample` uses the cancellable read with a timeout instead of
`Task.WhenAny`, which left a read pending.
- Devolutions/IronSessions `RdpSession` uses `TryReadBufferedPdu` to
flush rendering only when the socket is quiet,
`ReadPdu(CancellationToken)` for disconnect and timeout, the cancellable
`ReadByHint` during the connection sequence, and `ReadPduSync` for a
dedicated read thread on Mono (Android/iOS), where awaiting every read
hopped pool threads. `ReadPduSync` has no consumer in this repository on
purpose: the examples are async end to end.

`ffi/INTENT.md` records the probe width, the `ReadByHint` split, the EOF
policy and the read regime.

Smoke tests cover header-only sizing for TPKT and both fast-path length
encodings, several PDUs in one read, a partial PDU left buffered, the
sync read across split reads, EOF inside a PDU body on every read path,
and a cancelled read whose in-flight stream read the next read finishes.
2026-10-28 20:35:17 -04:00
..