congestion-control/receiver.py
2026-10-28 11:03:44 -06:00

104 lines
4.2 KiB
Python

"""A TCP-style receiver: it keeps early packets, ACKs cumulatively and advertises its free buffer. Given.
Project 3's two receivers each did half of what TCP's does. The Go-Back-N
receiver sent cumulative ACKs ("I have everything before n") but threw away a
packet that arrived early; the Selective Repeat receiver kept early packets but
ACKed each one by its own number. This one does both: it keeps an early packet
in its buffer, and every ACK still says the next packet it needs. A packet
after a gap therefore produces a duplicate ACK, which is the signal your
congestion controller reads.
Flow control. The buffer holds `buffer` packets. The application reads
delivered data out of it `drain` packets a second (None reads it at once).
Every ACK carries the free space left, rwnd, in its payload as a 2-byte
number, so the sender can keep within it. When the buffer was full and space
opens up, the receiver sends a window update on its own, so a sender stopped by
rwnd = 0 is not left waiting forever.
References:
Peterson and Davie, section 5.2.4, flow control and the advertised window
RFC 9293, section 3.8.6, managing the window
"""
import math
import socket
import struct
import time
import packet
def rwnd_of(payload):
"""The advertised window carried in an ACK's payload, in packets."""
return struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else None
class Receiver:
def __init__(self, sock, buffer=64, drain=None, linger=0.5):
self.sock = sock
self.buffer = buffer
self.drain = drain
self.linger = linger
self._held = 0.0 # delivered packets the application has not read yet
self._last = time.monotonic()
self.early = {} # seq -> payload, kept until the gap before it fills
def room(self):
"""Buffer space, in packets, not taken by delivered data the application has not read yet."""
now = time.monotonic()
if self.drain is None:
self._held = 0.0
else:
self._held = max(0.0, self._held - self.drain * (now - self._last))
self._last = now
return max(0, self.buffer - math.ceil(self._held))
def free(self):
"""The window to advertise: room left after the early packets already kept."""
return max(0, self.room() - len(self.early))
def _ack(self, expected, peer):
space = self.free()
self.sock.sendto(packet.encode(packet.ACK, expected, struct.pack("!H", min(space, 65535))), peer)
return space
def receive(self):
"""Return every byte the sender sent, in order."""
expected, parts, peer, advertised = 0, [], None, None
self.sock.settimeout(0.05)
while True:
try:
raw, peer = self.sock.recvfrom(2048)
except socket.timeout:
if peer is not None and advertised == 0 and self.free() > 0:
advertised = self._ack(expected, peer) # window update after a full buffer
continue
got = packet.decode(raw)
if got is None:
continue
kind, seq, payload = got
if kind == packet.DATA:
# The window starts at the next packet needed, so that packet always has a place.
if expected <= seq < expected + self.room() and seq not in self.early:
self.early[seq] = payload
while expected in self.early:
parts.append(self.early.pop(expected))
self._held += 1
expected += 1
advertised = self._ack(expected, peer)
elif kind == packet.FIN and seq == expected:
self._finish(peer)
return b"".join(parts)
def _finish(self, peer):
finack = packet.encode(packet.FINACK, 0)
self.sock.sendto(finack, peer)
self.sock.settimeout(self.linger)
while True:
try:
raw, peer = self.sock.recvfrom(2048)
except socket.timeout:
return
got = packet.decode(raw)
if got and got[0] == packet.FIN:
self.sock.sendto(finack, peer)