import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Iterator;

public class ReactorFrameServer {
    private static final int MAX_FRAME = 64 * 1024;
    private static final int MAX_CONNECTIONS = 128;
    private static final int MAX_PENDING = 256 * 1024;
    private static final int MAX_PENDING_FRAMES = 2048;
    private static final int MAX_GLOBAL_PENDING = 8 * 1024 * 1024;
    private static final int WRITE_BUDGET = 64 * 1024;
    private int globalPending;
    private int connections;

    private static final class Connection {
        final ByteBuffer input = ByteBuffer.allocate(MAX_FRAME + Integer.BYTES);
        final ArrayDeque<ByteBuffer> output = new ArrayDeque<>();
        int pending;
        boolean eof;
        boolean closed;
        long lastProgress = System.nanoTime();
    }

    public static void main(String[] args) throws Exception {
        int port = args.length > 0 ? Integer.parseInt(args[0]) : 9000;
        int seconds = args.length > 1 ? Integer.parseInt(args[1]) : 60;
        if (seconds < 1 || seconds > 3600) throw new IllegalArgumentException("invalid runtime");
        new ReactorFrameServer().run(port, seconds);
    }

    private void run(int port, int seconds) throws IOException {
        long deadline = System.nanoTime() + seconds * 1_000_000_000L;
        try (Selector selector = Selector.open();
             ServerSocketChannel server = ServerSocketChannel.open()) {
            server.configureBlocking(false);
            server.bind(new InetSocketAddress("127.0.0.1", port));
            server.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("listening=" + server.getLocalAddress());
            try {
                while (System.nanoTime() - deadline < 0) {
                    selector.select(1000);
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (!key.isValid()) continue;
                        if (key.isAcceptable()) {
                            accept(server, selector);
                            continue;
                        }
                        try {
                            if (key.isReadable()) read(key);
                            if (key.isValid() && key.isWritable()) write(key);
                        } catch (IOException | RuntimeException failure) {
                            System.err.println("connection rejected=" + failure.getMessage());
                            close(key);
                        }
                    }
                    for (SelectionKey key : new ArrayList<>(selector.keys())) {
                        if (key.attachment() instanceof Connection connection
                                && System.nanoTime() - connection.lastProgress > 30_000_000_000L) {
                            close(key);
                        }
                    }
                }
            } finally {
                for (SelectionKey key : new ArrayList<>(selector.keys())) {
                    if (key.attachment() instanceof Connection) close(key);
                }
            }
        }
    }

    private void accept(ServerSocketChannel server, Selector selector) throws IOException {
        for (int accepted = 0; accepted < 16; accepted++) {
            SocketChannel client = server.accept();
            if (client == null) return;
            if (connections >= MAX_CONNECTIONS) {
                client.close();
                continue;
            }
            try {
                client.configureBlocking(false);
                client.register(selector, SelectionKey.OP_READ, new Connection());
                connections++;
            } catch (IOException | RuntimeException failure) {
                client.close();
                System.err.println("accept rejected=" + failure.getMessage());
            }
        }
    }

    private void read(SelectionKey key) throws IOException {
        Connection connection = (Connection) key.attachment();
        SocketChannel client = (SocketChannel) key.channel();
        int count = client.read(connection.input);
        if (count == 0) return;
        if (count == -1) {
            if (connection.input.position() != 0) throw new IOException("truncated frame at EOF");
            connection.eof = true;
            refresh(key, connection);
            return;
        }
        connection.lastProgress = System.nanoTime();
        ByteBuffer input = connection.input;
        input.flip();
        while (input.remaining() >= Integer.BYTES) {
            input.mark();
            int length = input.getInt();
            if (length < 0 || length > MAX_FRAME) throw new IOException("invalid length=" + length);
            if (input.remaining() < length) {
                input.reset();
                break;
            }
            int frameBytes = Integer.BYTES + length;
            if (connection.output.size() >= MAX_PENDING_FRAMES
                    || connection.pending + frameBytes > MAX_PENDING
                    || globalPending + frameBytes > MAX_GLOBAL_PENDING) {
                throw new IOException("pending byte limit exceeded");
            }
            ByteBuffer response = ByteBuffer.allocate(frameBytes);
            response.putInt(length);
            for (int index = 0; index < length; index++) response.put(input.get());
            response.flip();
            connection.output.add(response);
            connection.pending += frameBytes;
            globalPending += frameBytes;
        }
        input.compact();
        refresh(key, connection);
    }

    private void write(SelectionKey key) throws IOException {
        Connection connection = (Connection) key.attachment();
        SocketChannel client = (SocketChannel) key.channel();
        int budget = WRITE_BUDGET;
        while (budget > 0 && !connection.output.isEmpty()) {
            ByteBuffer response = connection.output.peek();
            int previousLimit = response.limit();
            response.limit(response.position() + Math.min(response.remaining(), budget));
            int count;
            try {
                count = client.write(response);
            } finally {
                response.limit(previousLimit);
            }
            if (count == 0) break;
            connection.pending -= count;
            globalPending -= count;
            budget -= count;
            connection.lastProgress = System.nanoTime();
            if (!response.hasRemaining()) connection.output.remove();
        }
        refresh(key, connection);
    }

    private void refresh(SelectionKey key, Connection connection) {
        if (connection.eof && connection.output.isEmpty()) {
            close(key);
        } else {
            int interest = connection.eof ? 0 : SelectionKey.OP_READ;
            if (!connection.output.isEmpty()) interest |= SelectionKey.OP_WRITE;
            key.interestOps(interest);
        }
    }

    private void close(SelectionKey key) {
        Connection connection = (Connection) key.attachment();
        if (connection.closed) return;
        connection.closed = true;
        globalPending -= connection.pending;
        connection.pending = 0;
        connection.output.clear();
        connections--;
        key.cancel();
        try {
            key.channel().close();
        } catch (IOException failure) {
            System.err.println("close failed=" + failure.getMessage());
        }
    }
}
