import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class SocketFrameDeadlineDemo {
    private static final int FRAME_BYTES = 8;
    private static final int READ_TIMEOUT_MS = 500;
    private static final long FRAME_BUDGET_NANOS = TimeUnit.MILLISECONDS.toNanos(650);

    public static void main(String[] args) throws Exception {
        experiment(false);
        experiment(true);
    }

    private static void experiment(boolean overallBudget) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        try (ServerSocket listener = new ServerSocket()) {
            listener.bind(new InetSocketAddress("127.0.0.1", 0));
            listener.setSoTimeout(5000);
            Future<?> serving = executor.submit(() -> {
                try (Socket peer = listener.accept()) {
                    peer.setSoTimeout(5000);
                    if (peer.getInputStream().read() != 42) throw new IllegalStateException("start signal mismatch");
                    for (int index = 0; index < FRAME_BYTES; index++) {
                        Thread.sleep(200);
                        peer.getOutputStream().write(index);
                    }
                } catch (java.io.IOException expectedClosedPeer) {
                    System.out.println("server IO ended=" + expectedClosedPeer.getClass().getSimpleName());
                } catch (InterruptedException interrupted) {
                    Thread.currentThread().interrupt();
                    throw new IllegalStateException(interrupted);
                }
            });
            try (Socket socket = new Socket()) {
                socket.connect(new InetSocketAddress("127.0.0.1", listener.getLocalPort()), 2000);
                socket.getOutputStream().write(42);
                long started = System.nanoTime();
                int received = 0;
                boolean timedOut = false;
                InputStream input = socket.getInputStream();
                try {
                    while (received < FRAME_BYTES) {
                        long remaining = FRAME_BUDGET_NANOS - (System.nanoTime() - started);
                        if (overallBudget && remaining <= 0) throw new SocketTimeoutException("frame deadline exceeded");
                        int waitMillis = overallBudget
                                ? (int) Math.min(READ_TIMEOUT_MS, Math.max(1, (remaining + 999_999) / 1_000_000))
                                : READ_TIMEOUT_MS;
                        socket.setSoTimeout(waitMillis);
                        int value = input.read();
                        if (value == -1) throw new IllegalStateException("unexpected EOF");
                        if (value != received) throw new IllegalStateException("byte mismatch");
                        received++;
                        if (overallBudget && System.nanoTime() - started >= FRAME_BUDGET_NANOS) {
                            throw new SocketTimeoutException("frame completed after deadline");
                        }
                    }
                } catch (SocketTimeoutException timeout) {
                    timedOut = true;
                }
                long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started);
                if (overallBudget) {
                    if (!timedOut || received == FRAME_BYTES) throw new IllegalStateException("deadline not enforced");
                } else {
                    if (timedOut || received != FRAME_BYTES) throw new IllegalStateException("unexpected read timeout");
                }
                System.out.println("overall=" + overallBudget + " bytes=" + received + " elapsedMs=" + elapsedMillis
                        + " timedOut=" + timedOut + ": PASS");
            }
            serving.get(5, TimeUnit.SECONDS);
        } finally {
            executor.shutdownNow();
            if (!executor.awaitTermination(6, TimeUnit.SECONDS)) throw new IllegalStateException("server not stopped");
        }
    }
}
