/* =============================================================================
 * multiclient.c -- the test that tells a concurrent server from an iterative one
 * =============================================================================
 *
 * [Idea]
 *   You cannot see the difference between an iterative and a concurrent server
 *   with one client: both answer immediately. The difference shows only when a
 *   SLOW client and several FAST ones arrive together:
 *
 *     - an ITERATIVE server serves the slow client to completion first, so the
 *       fast clients wait for it -- they finish after the whole delay;
 *     - a CONCURRENT server serves them in parallel, so the fast clients finish
 *       in milliseconds while the slow one is still thinking.
 *
 *   This program creates exactly that situation and MEASURES each client's
 *   completion time, so the distinction is a number rather than a claim.
 *
 * [How it works]
 *   Client 0 is the slow one: it connects, then holds the connection for
 *   `slow_ms` before sending anything. It is forked first and given a head
 *   start, so it is definitely the connection the server picks up first.
 *   Clients 1..n-1 connect and send at once. Each child reports its elapsed
 *   time through a pipe; the parent collects them and prints them in index
 *   order, so the transcript is ordered even though the runs are concurrent.
 *
 * Usage:   ./multiclient [host] [port] [nclients] [slow_ms]
 *          defaults: localhost 15221 4 600
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/time.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE   8192
#define MAXCLIENTS 64

static double now_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
}

/* One client: connect, (maybe wait), send a line, read the echo, report. */
static void run_client(int idx, const char *host, const char *port,
                       int slow_ms, double t0, int reportfd)
{
    char line[MAXLINE], msg[128];

    int fd = -1;
    for (int attempt = 0; attempt < 40 && fd < 0; attempt++) {
        fd = open_clientfd(host, port);
        if (fd < 0) usleep(25 * 1000);
    }
    if (fd < 0) {
        snprintf(msg, sizeof(msg), "%d -1 connect-failed\n", idx);
        rio_writen(reportfd, msg, strlen(msg));
        _exit(1);
    }

    /* The slow client holds the connection without sending. To an iterative
       server this is indistinguishable from a client on a bad network -- and
       it is enough to stall every other client. */
    if (slow_ms > 0)
        usleep((useconds_t)slow_ms * 1000);

    snprintf(line, sizeof(line), "client %d reporting\n", idx);
    rio_writen(fd, line, strlen(line));

    rio_t rio;
    rio_readinitb(&rio, fd);
    ssize_t n = rio_readlineb(&rio, line, MAXLINE);

    double elapsed = now_ms() - t0;
    snprintf(msg, sizeof(msg), "%d %.0f %s\n", idx, elapsed,
             n > 0 ? "echoed" : "no-reply");
    rio_writen(reportfd, msg, strlen(msg));

    close(fd);
    _exit(0);
}

int main(int argc, char **argv)
{
    const char *host = (argc > 1) ? argv[1] : "localhost";
    const char *port = (argc > 2) ? argv[2] : "15221";
    int nclients     = (argc > 3) ? atoi(argv[3]) : 4;
    int slow_ms      = (argc > 4) ? atoi(argv[4]) : 600;

    if (nclients > MAXCLIENTS) nclients = MAXCLIENTS;

    int p[2];
    if (pipe(p) < 0) { perror("pipe"); return 1; }

    printf("  %d clients: client 0 holds its connection for %d ms, "
           "clients 1-%d are immediate\n", nclients, slow_ms, nclients - 1);
    fflush(stdout);

    double t0 = now_ms();

    /* Fork the SLOW client first and give it a head start, so the server
       definitely accepts it before the others arrive. */
    pid_t pid = fork();
    if (pid == 0) { close(p[0]); run_client(0, host, port, slow_ms, t0, p[1]); }
    usleep(150 * 1000);

    for (int i = 1; i < nclients; i++) {
        pid = fork();
        if (pid == 0) { close(p[0]); run_client(i, host, port, 0, t0, p[1]); }
    }

    close(p[1]);        /* the parent must close its copy or it never sees EOF */

    /* Collect every child's report. */
    double elapsed[MAXCLIENTS];
    char   status[MAXCLIENTS][16];
    for (int i = 0; i < nclients; i++) { elapsed[i] = -1; strcpy(status[i], "?"); }

    rio_t rio;
    rio_readinitb(&rio, p[0]);
    char buf[256];
    while (rio_readlineb(&rio, buf, sizeof(buf)) > 0) {
        int idx; double ms; char st[16];
        if (sscanf(buf, "%d %lf %15s", &idx, &ms, st) == 3 &&
            idx >= 0 && idx < nclients) {
            elapsed[idx] = ms;
            snprintf(status[idx], sizeof(status[idx]), "%s", st);
        }
    }
    close(p[0]);
    while (wait(NULL) > 0) ;

    /* Report in index order: concurrent runs, ordered transcript. */
    double fast_max = 0;
    for (int i = 0; i < nclients; i++) {
        printf("    client %d %-9s finished at %6.0f ms%s\n", i, status[i],
               elapsed[i], i == 0 ? "   <- the slow one" : "");
        if (i > 0 && elapsed[i] > fast_max) fast_max = elapsed[i];
    }
    printf("    slowest FAST client finished at %.0f ms "
           "(the slow client held the server for %d ms)\n", fast_max, slow_ms);
    printf("    => %s\n",
           fast_max < slow_ms * 0.6
               ? "CONCURRENT: fast clients did not wait for the slow one"
               : "ITERATIVE: fast clients were blocked until the slow one finished");
    return 0;
}
