stress1-server.rkt
#lang racket/base
;; For legal info, see file "info.rkt".

(require "scgi.rkt")

(define get-next-id
  (let ((next-id 0)
        (sema    (make-semaphore 1)))
    (lambda ()
      (semaphore-wait/enable-break sema)
      (begin0 next-id
        (set! next-id (+ 1 next-id))
        (semaphore-post sema)))))

(let ((sleep-seconds (string->number (or (getenv "STRESS1_SLEEP")
                                         "0"))))
  (collect-garbage)
  (collect-garbage)
  (collect-garbage)
  (display "stress1-server ready\n")
  (flush-output (current-output-port))
  (cgi #:request
       (lambda ()
         (let ((id (get-next-id)))
           (log-info (format "~S start" id))
           (with-handlers ((exn:fail?
                            (lambda (e)
                              (log-error (format "~S ERROR ~S"
                                                 id
                                                 (exn-message e))))))
             (sleep sleep-seconds)
             (display "Content-type: text/plain\r\n\r\n")
             ;; (display (expt 42 (random 424242)))
             ;; (flush-output (current-output-port))
             ;; (sleep 10)
             (printf "(cgi-content-length) ==> ~S\n"
                     (cgi-content-length))
             (display "About to read the body.\n")
             (flush-output (current-output-port))
             (let* ((buf-size 1024)
                    (buf      (make-bytes buf-size)))
               (let loop ((read-count 0))
                 (let ((x (read-bytes! buf)))
                   (if (eof-object? x)
                       (printf "Read ~S times before EOF.\n" read-count)
                       (loop (+ 1 read-count))))))

             (display "Done.\n"))
           (log-info (format "~S end" id))))
       #:scgi-portnum (string->number (or (getenv "STRESS1_SCGI_PORT")
                                          "4000"))))