;;; rpc-relay.lsp — transparent S-expression relay.
;;;
;;; Listens on *listen-port*, forwards every request byte-for-byte to
;;; *backend-host*:*backend-port*, returns the backend's reply. Used
;;; to demonstrate a multi-runtime chain: Python client → C relay →
;;; asm backend, where the same .lsp runs at every hop and the wire
;;; format (Scheme source) needs no translation.
;;;
;;;   python3 lumbda.py --fast examples/rpc-relay.lsp
;;;   ./c/lumbda examples/rpc-relay.lsp
;;;   ./asm/lumbda < examples/rpc-relay.lsp
;;;
;;; Override *listen-port* / *backend-port* by pre-defining before load
;;; (or edit here for a one-off demo).

(define *listen-port*  9082)
(define *backend-host* "127.0.0.1")
(define *backend-port* 9080)
(define *max-requests* 100000)

;;; Forward the raw request bytes to the backend, return the raw reply.
;;; No parsing — the relay never looks inside the sexp. Bytes in,
;;; bytes out. Which is the point: S-expressions are the envelope.

(define (forward-request req)
  (let ((back (tcp-connect *backend-host* *backend-port*)))
    (if back
        (begin
          (tcp-send back req)
          (let ((reply (tcp-recv back 8192)))
            (tcp-close back)
            (if (and reply (> (string-length reply) 0))
                reply
                "(error \"empty from backend\")\n")))
        "(error \"backend unreachable\")\n")))

(define server (tcp-listen *listen-port*))

(define (relay-loop n snap)
  (if (>= n *max-requests*)
      (begin (display "request cap reached, exiting\n") (tcp-close server))
      (begin
        (let ((client (tcp-accept server)))
          (let ((req (tcp-recv client 4096)))
            (if (and req (> (string-length req) 0))
                (tcp-send client (forward-request req))
                #f))
          (tcp-close client))
        (heap-restore snap)
        (relay-loop (+ n 1) snap))))

(display "rpc-relay on :") (display *listen-port*)
(display " -> ") (display *backend-host*) (display ":") (display *backend-port*)
(newline)
(relay-loop 0 (heap-snapshot))
