/* =============================================================================
 * 02_select_server.c -- a concurrent server with ONE process and no threads
 * =============================================================================
 *
 * [Idea]
 *   The reason an iterative server blocks is that it waits on ONE descriptor at
 *   a time. select() removes that limitation: hand the kernel a SET of
 *   descriptors and it tells you which are ready to read. Then you only ever
 *   touch descriptors that will not block, so a single process can interleave
 *   many conversations.
 *
 *   The price is that YOU become the scheduler. There is no call stack per
 *   client to hold "where this conversation had got to", so that state must be
 *   stored explicitly -- here, a pool of connected descriptors plus a buffered
 *   reader for each. This is EVENT-BASED programming: a loop, a readiness test,
 *   and an explicit state machine.
 *
 * [What it answers]
 *   - How can one process serve many clients with no fork and no threads?
 *   - What does select() actually tell you, and why must the set be rebuilt?
 *   - What is the real cost of the event-based style?
 *
 * [Trade-offs]
 *   + no process/thread creation cost; total control over scheduling;
 *     no concurrency bugs, because there is only one flow of control.
 *   - the logic is inside out: every "wait" must become a stored state;
 *     one long computation in the loop stalls EVERY client (no pre-emption);
 *     it cannot use more than one core.
 *
 * Usage:   ./02_select_server [port] [max_connections]
 *          defaults: 15222, 8   (exits once that many clients have disconnected)
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/socket.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE  8192
#define MAXCLIENTS FD_SETSIZE

/* The explicit state the call stack would otherwise have held for us. */
typedef struct {
    int    maxfd;                   /* largest descriptor in use            */
    fd_set ready_set;              /* descriptors select() reported ready  */
    fd_set read_set;               /* all descriptors we care about        */
    int    nready;                 /* how many select() said are ready     */
    int    clientfd[MAXCLIENTS];   /* -1 = slot free                       */
    rio_t  clientrio[MAXCLIENTS];  /* one buffered reader per client        */
} pool_t;

static void pool_init(pool_t *p, int listenfd)
{
    for (int i = 0; i < MAXCLIENTS; i++)
        p->clientfd[i] = -1;
    /* Initially the only descriptor of interest is the listening one. */
    p->maxfd = listenfd;
    FD_ZERO(&p->read_set);
    FD_SET(listenfd, &p->read_set);
}

/* A new connection arrived: find a free slot and start tracking it. */
static void pool_add(pool_t *p, int connfd)
{
    p->nready--;
    for (int i = 0; i < MAXCLIENTS; i++) {
        if (p->clientfd[i] < 0) {
            p->clientfd[i] = connfd;
            rio_readinitb(&p->clientrio[i], connfd);   /* its own buffer */
            FD_SET(connfd, &p->read_set);              /* watch it from now on */
            if (connfd > p->maxfd)
                p->maxfd = connfd;
            return;
        }
    }
    fprintf(stderr, "pool_add: too many clients\n");
    close(connfd);
}

/* Service every client that select() said has data waiting.
 * Returns how many clients disconnected during this pass. */
static int pool_service(pool_t *p)
{
    char buf[MAXLINE];
    int  gone = 0;

    for (int i = 0; (i < MAXCLIENTS) && (p->nready > 0); i++) {
        int connfd = p->clientfd[i];
        if (connfd < 0 || !FD_ISSET(connfd, &p->ready_set))
            continue;

        p->nready--;
        /* This read will not block: select() just told us data is waiting.
           [Edge cases] It may still be a SHORT line; rio_readlineb handles
           that, but note the subtlety -- its internal buffer may already hold
           a further line, which is why each client needs its OWN rio_t. */
        ssize_t n = rio_readlineb(&p->clientrio[i], buf, MAXLINE);
        if (n > 0) {
            rio_writen(connfd, buf, (size_t)n);        /* echo it back */
        } else {
            /* n == 0: this client closed (EOF). Stop tracking it. */
            close(connfd);
            FD_CLR(connfd, &p->read_set);
            p->clientfd[i] = -1;
            gone++;
        }
    }
    return gone;
}

int main(int argc, char **argv)
{
    const char *port = (argc > 1) ? argv[1] : "15222";
    int maxconn      = (argc > 2) ? atoi(argv[2]) : 8;

    int listenfd = open_listenfd(port);
    if (listenfd < 0) { fprintf(stderr, "cannot listen on %s\n", port); return 1; }

    static pool_t pool;
    pool_init(&pool, listenfd);

    printf("[select-server] listening on 127.0.0.1:%s, one process, "
           "serving up to %d clients\n", port, maxconn);
    fflush(stdout);

    int accepted = 0, finished = 0;
    while (finished < maxconn) {
        /* [C tip] select() MODIFIES the set it is given (it turns it into the
           "ready" set), so we must copy our master set every iteration. */
        pool.ready_set = pool.read_set;
        pool.nready = select(pool.maxfd + 1, &pool.ready_set, NULL, NULL, NULL);
        if (pool.nready < 0) {
            if (errno == EINTR) continue;
            perror("select");
            break;
        }

        /* Is the LISTENING descriptor ready? Then a connection is pending. */
        if (FD_ISSET(listenfd, &pool.ready_set) && accepted < maxconn) {
            int connfd = accept(listenfd, NULL, NULL);
            if (connfd >= 0) {
                pool_add(&pool, connfd);
                accepted++;
                printf("[select-server] accepted client %d (fd %d), "
                       "now watching %d descriptor(s)\n",
                       accepted, connfd, pool.maxfd + 1);
                fflush(stdout);
            }
        }

        /* Echo for whichever connected clients have data. */
        finished += pool_service(&pool);
    }

    close(listenfd);
    printf("[select-server] done; %d client(s) served and disconnected\n", finished);

    printf("\nObservations\n------------\n");
    printf("- ONE process, no fork and no threads, yet clients were interleaved:\n");
    printf("  select() reported which descriptors were ready and we only ever\n");
    printf("  read those, so nothing blocked.\n");
    printf("- The listening descriptor is just another member of the set. When\n");
    printf("  IT is ready, a connection is pending; when a connfd is ready,\n");
    printf("  data is pending.\n");
    printf("- select() overwrites its argument with the ready set, so the master\n");
    printf("  set must be COPIED every iteration -- a classic beginner bug.\n");
    printf("- The cost is inverted logic: with no per-client call stack, the\n");
    printf("  conversation's state (its rio_t and slot) is stored by hand. One\n");
    printf("  long computation here would stall EVERY client, and this design\n");
    printf("  cannot use a second core.\n");
    return 0;
}
