"""Bound the lifetime of command bytes in a Linux TCP send queue. TCP acknowledgement is transport evidence only, never command confirmation. All writes on the guarded stream must pass through write(), including ACKs. """ import asyncio import fcntl import socket import struct import sys import termios import time from collections import deque MAX_DELIVERY_SECONDS = 30 def queued_bytes(sock): if sys.platform != "linux": # Production is qualified on Ubuntu only. Other platforms conservatively # retain the deadline, without claiming TCP acknowledgement evidence. return None return struct.unpack("i", fcntl.ioctl(sock, termios.TIOCOUTQ, struct.pack("i", 0)))[0] class Delivery: def __init__(self, writer): self.writer = writer self.sock = writer.get_extra_info("socket") # Also abort queued kernel data on EOF, task cancellation and shutdown. # transport.abort() alone discards only asyncio's own write buffer. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) if sys.platform == "linux": self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_USER_TIMEOUT, 30000) self.written = 0 self.pending = deque() self.timer = None def ready(self): """Do not enqueue a new command behind an unacknowledged stream prefix. This is Linux transport admission, not device execution confirmation. Non-Linux engineering tests retain their conservative expiry watchdog. """ if self.writer.is_closing() or self.writer.transport.get_write_buffer_size(): return False try: queued = queued_bytes(self.sock) return queued is None or queued == 0 except OSError: return False def write(self, data, deadline=None, observe=None): started = time.monotonic() def note(phase, reason=None): if observe is not None: observe(phase, time.time(), time.monotonic() - started, reason) if deadline is not None and deadline <= time.monotonic(): note("unconfirmed", "expired_before_write") self.abort() raise TimeoutError("command delivery expired before write") try: self.writer.write(data) except (OSError, RuntimeError): note("unconfirmed", "write_failed") raise note("written") self.written += len(data) if deadline is not None: self.pending.append((self.written, deadline, note)) self.check() def check(self): self.cancel_timer() if not self.pending: return if self.writer.is_closing(): self.abort() return try: queued = queued_bytes(self.sock) if queued is not None: acknowledged = self.written - queued - self.writer.transport.get_write_buffer_size() while self.pending and self.pending[0][0] <= acknowledged: self.pending.popleft()[2]("tcp_acknowledged") if self.pending: remaining = min(deadline for _, deadline, _ in self.pending) - time.monotonic() if remaining <= 0: self.abort("delivery_deadline") else: self.timer = asyncio.get_running_loop().call_later( min(0.25, remaining), self.check ) except OSError: self.abort("socket_error") def cancel_timer(self): if self.timer is not None: self.timer.cancel() self.timer = None def abort(self, reason="connection_closed"): self.cancel_timer() while self.pending: self.pending.popleft()[2]("unconfirmed", reason) self.writer.transport.abort()