;; canon: bot.git src/bot/worker.cljs (ported from src/worker.ts)
;;
;; Stack-B room worker: joins ONE chat or board room in its own process.
;;
;; Why a separate process: the two kits carry different libp2p generations
;; whose WebRTC transports load two different builds of the same native
;; library (libdatachannel) — two copies in one process abort it. Isolating
;; the chat/board stack keeps each native alone, and a native crash takes
;; down one room, not the bot.
;;
;; THE TWO-STACK LAW: this module graph (the :worker shadow build →
;; dist/worker.js) value-requires ONLY ardegazu-rooms-kit — never peer-kit.
;;
;; node dist/worker.js '<json job>'
(ns __NAME__.worker
(:require ["node:path" :as path]
["node:fs" :as fs]
["ardegazu-rooms-kit/chat" :refer (ChatClient)]
["ardegazu-rooms-kit/board" :refer (BoardClient)]
["ardegazu-rooms-kit" :refer (Identity)]
[__NAME__.behaviors :as behaviors]))
(defn- run []
(let [^js job (js/JSON.parse (let [a (aget js/process.argv 2)] (if (some? a) a "{}")))
log (fn [line] (js/console.log (str "[" (.-app job) "] " line)))
seed (.trim ^js (fs/readFileSync (.-seedFile job) "utf8"))]
(-> (.fromSeed Identity seed)
(.then
(fn [^js identity]
(if (identical? (.-app job) "chat")
(-> (.join ChatClient #js {:roomSecret (.-secret job)
:name (.-nick job)
:dataDir (path/join (.-dataDir job))
:identity identity
:origin (.-origin job)})
(.then (fn [chat]
(behaviors/attach-behavior
(let [b (.-behavior job)] (if (some? b) b "echo"))
#js {:kind "chat" :chat chat :log log
:self (.-publicKeyB64 identity) :nick (.-nick job)})
(log "joined"))))
(-> (.join BoardClient #js {:roomSecret (.-secret job)
:name (.-nick job)
:dataDir (path/join (.-dataDir job))
:identity identity
:origin (.-origin job)})
(.then (fn [board]
(behaviors/attach-behavior
(let [b (.-behavior job)] (if (some? b) b "sign"))
#js {:kind "board" :board board :log log :nick (.-nick job)})
(log "joined")))))))
(.then (fn [_]
(.on js/process "SIGTERM" (fn [] (js/process.exit 0))))))))
(defn init
"Run only as the process entry script (the fork from __NAME__.rooms, or
`node dist/worker.js …`) — an import must stay side-effect free."
[]
(when (identical? (some-> (aget js/process.argv 1) (path/basename)) "worker.js")
(run)))