; Pelagos Jupyter Stack — compose.reml
;
; Architecture:
;
;   jupyter-net (10.89.0.0/24):  jupyterlab ←→ redis
;
; Lisp features demonstrated:
;
;   define          — all ports and resource limits named at the top
;   env             — JUPYTER_PORT read from host environment with safe default
;   on-ready        — hook fires when redis is healthy, before notebooks can cache
;   volume          — named volume persists notebooks across container restarts
;   define-service  — macro: flat keyword-style service definitions

;; ── Configuration ─────────────────────────────────────────────────
;;
;; Override the JupyterLab port without editing this file:
;;   JUPYTER_PORT=9999 sudo pelagos compose up -f compose.reml -p jupyter

(define jupyter-port
  (let ((p (env "JUPYTER_PORT")))
    (if (null? p) 8888 (string->number p))))

(define mem-redis   "64m")
(define mem-jupyter "512m")
(define cpu-jupyter "1.0")

;; ── Network ───────────────────────────────────────────────────────

(define net-jupyter (network "jupyter-net" '(subnet "10.89.0.0/24")))

;; ── Lifecycle hooks ───────────────────────────────────────────────
;;
;; on-ready fires after redis's TCP port check passes, guaranteeing the
;; redis Python client in notebooks will connect on the first attempt.

(on-ready "redis"
  (lambda ()
    (log "redis: cache layer ready — JupyterLab kernel can connect")))

;; ── Services ──────────────────────────────────────────────────────
;;
;; Flat keyword-value list.  Each :keyword introduces a new option; values
;; run until the next :keyword.  Sublists under a keyword (like :env pairs)
;; each become a separate service option.

(define-service svc-redis "redis"
  :image   "jupyter-redis:latest"
  :network "jupyter-net"
  :memory  mem-redis)

(define-service svc-jupyterlab "jupyterlab"
  :image      "jupyter-jupyterlab:latest"
  :network    "jupyter-net"
  :depends-on "redis" 6379           ; TCP health check before kernel starts
  :env        ("REDIS_HOST" . "redis") ("REDIS_PORT" . "6379")
  :port       (jupyter-port . 8888)   ; host port from env var or default 8888
  :memory     mem-jupyter
  :cpus       cpu-jupyter)

;; ── Assemble and run ──────────────────────────────────────────────

(compose-up
  (compose
    net-jupyter
    (volume "jupyter-notebooks")
    svc-redis
    svc-jupyterlab))
