peer-kit / src / ardegazu / peer / games / host / driver.cljs
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
;; ported-from: src/games/host/driver.ts @ v1.3.0
;;
;; Live host driver base: turns a pure sim into a real room host. Owns what the
;; browsers keep in G — the roster (nick/badge/score), the auto-start policy
;; replacing the start button, the single pending timer that executes
;; SimEmit.next, and the split-brain concede/reassert rules. Every emitted frame
;; is broadcast AND applied locally through room.injectLocal(), the browsers'
;; hostEmit contract, so the hosting bot's own client view stays correct with no
;; parallel state.
;;
;; Divergence from the browsers, by design: no roster-grace map (peer-kit's
;; peerGone already sits behind the redial ladder, and bots don't suspend), and
;; no ensureHost() election backstop — a bot only ever claims an empty room it
;; was designated to host; failover is the matchmaker's re-mint.
;;
;; TS `abstract` has no CLJS equivalent: the per-game hooks below are ordinary
;; prototype methods that throw by default, and each subclass overrides them.
;; Subclass overriding through `defclass (extends …)` is real ES-class
;; inheritance, so a base method calling `(.roundLive this)` reaches the
;; subclass's version exactly as the TS did.
(ns ardegazu.peer.games.host.driver
  (:require [shadow.cljs.modern :refer (defclass)]))

(def ^:private MAX-SEATS 16)

(declare maybe-start clear-pending clear-start-timer clear-timers driver-start
         connected-seated broadcast-roster emit-frame on-lobby)

(defclass HostDriver
  (constructor [this room opts]
    (unchecked-set this "room" room)
    (let [m (let [x (unchecked-get opts "match")]
              (if ^boolean (js* "~{} == null" x) (js-obj) x))
          min-players (js/Math.max 1 (let [x (unchecked-get m "minPlayers")]
                                       (if ^boolean (js* "~{} == null" x) 2 x)))]
      (unchecked-set
       this "policy"
       (js-obj "minPlayers" min-players
               "expectedPlayers" (js/Math.max min-players
                                              (let [x (unchecked-get m "expectedPlayers")]
                                                (if ^boolean (js* "~{} == null" x) min-players x)))
               "startTimeoutMs" (let [x (unchecked-get m "startTimeoutMs")]
                                  (if ^boolean (js* "~{} == null" x) 15000 x))
               "maxMatches" (let [x (unchecked-get m "maxMatches")]
                              (if ^boolean (js* "~{} == null" x) js/Infinity x)))))
    (unchecked-set this "roster" (js/Map.))
    (unchecked-set this "phase" "idle")
    (unchecked-set this "matches" 0)
    (unchecked-set this "_pending" nil)
    (unchecked-set this "_startTimer" nil)
    (unchecked-set this "_closed" false)
    (unchecked-set this "_matchEndListeners" #js [])
    (.on ^js room "frame"
         (fn [from f]
           (when (and (not (identical? from (unchecked-get room "myId")))
                      (unchecked-get room "hosting"))
             (.onGameFrame ^js this from f))))
    ;; bind to a ^js local first: a ^js hint on an `unchecked-get` macro form is
    ;; LOST, and externs inference then misses the call (dev/docs/CLJS.md)
    (let [^js room-peer (unchecked-get room "peer")]
      (.on room-peer "peerGone"
           (fn [id]
             (when (unchecked-get room "hosting")
               (when (.delete ^js (unchecked-get this "roster") id) (broadcast-roster this))
               (.simPeerGone ^js this id)))))))

;; ---------------- shared machinery ----------------

(defn free-badge [self]
  (let [used (js/Set.)]
    (.forEach ^js (unchecked-get self "roster") (fn [p _k] (.add used (unchecked-get p "badge"))))
    (loop [i 0]
      (cond
        (>= i MAX-SEATS) (dec MAX-SEATS)
        (not (.has used i)) i
        :else (recur (inc i))))))

(defn roster-entries
  "The wire roster entries ([id, nick, badge, score])."
  [self]
  (let [out #js []]
    (.forEach ^js (unchecked-get self "roster")
              (fn [p id] (.push out #js [id (unchecked-get p "nick")
                                         (unchecked-get p "badge") (unchecked-get p "score")])))
    out))

(defn emit-frame
  "Broadcast + local loopback, or targeted send (self-targets loop back)."
  [self e]
  (let [room (unchecked-get self "room")
        my-id (unchecked-get room "myId")
        to (unchecked-get e "to")
        f (unchecked-get e "f")]
    (cond
      (and ^boolean (js* "!!(~{})" to) (not (identical? to my-id)))
      (let [^js room-peer (unchecked-get room "peer")] (.send room-peer to f))

      (identical? to my-id)
      (.injectLocal ^js room f)

      :else (let [^js room-peer (unchecked-get room "peer")]
              (.broadcast room-peer f)
              (.injectLocal ^js room f))))
  js/undefined)

(defn broadcast-roster [self]
  (.broadcastRoster ^js self))

(defn- broadcast-roster-default [self]
  (let [f (js-obj "t" "ro"
                  "host" (unchecked-get (unchecked-get self "room") "myId")
                  "ps" (roster-entries self))]
    (when (.roundLive ^js self) (unchecked-set f "live" 1))
    (emit-frame self (js-obj "f" f)))
  js/undefined)

(defn run-emit
  "Apply a sim transition: frames out, receipts, and the next timer."
  [self emit]
  (.forEach ^js (unchecked-get emit "frames") (fn [e] (emit-frame self e)))
  (let [match-end (unchecked-get emit "matchEnd")]
    (when ^boolean (js* "!!(~{})" match-end)
      (unchecked-set self "matches" (inc (unchecked-get self "matches")))
      (let [lb (unchecked-get (unchecked-get self "room") "leaderboard")]
        (when ^boolean (js* "!!(~{})" lb) (.hostMatchEnd ^js lb match-end)))
      (.forEach ^js (unchecked-get self "_matchEndListeners") (fn [cb] (cb match-end)))))
  (let [nxt (unchecked-get emit "next")]
    ;; SimEmit.next has THREE states and the order of these tests is
    ;; load-bearing: CLJS `nil?` compiles to `== null`, which is TRUE for
    ;; `undefined` too. Testing it first would treat an ABSENT `next` (a pick, a
    ;; snapshot — anything that emits frames without rescheduling) as an explicit
    ;; cancel and silently kill the pending step, stalling the whole match after
    ;; the first bell/tick. `identical?` is `===`, so `undefined` is matched
    ;; exactly and `null` falls through.
    (cond
      (identical? nxt js/undefined) nil          ; absent ⇒ leave pending alone
      (nil? nxt) (clear-pending self)            ; explicit null ⇒ cancel
      :else (let [step (unchecked-get nxt "step")
                  in-ms (unchecked-get nxt "inMs")]
              (clear-pending self)
              (unchecked-set
               self "_pending"
               (js/setTimeout
                (fn []
                  (unchecked-set self "_pending" nil)
                  (when-not (or (unchecked-get self "_closed")
                                (not (unchecked-get (unchecked-get self "room") "hosting")))
                    (if (identical? step "lobby")
                      (do (.execStep ^js self step) (on-lobby self))
                      (.execStep ^js self step))))
                in-ms)))))
  js/undefined)

(defn on-hi
  "The \"hi\" seat/cap/snapshot handling every game shares."
  [self from m]
  (let [raw (unchecked-get m "nick")
        nick (if (string? raw) raw "")]
    (when ^boolean (js* "!!(~{})" nick)
      (let [roster (unchecked-get self "roster")
            e (.get ^js roster from)]
        (if (and (not ^boolean (js* "!!(~{})" e)) (>= (.-size ^js roster) MAX-SEATS))
          (emit-frame self (js-obj "to" from "f" (js-obj "t" "fu")))
          (do
            (if-not ^boolean (js* "!!(~{})" e)
              (let [wins (unchecked-get m "wins")
                    score (unchecked-get m "score")
                    s (cond
                        (identical? "number" (js* "typeof ~{}" wins)) wins
                        (identical? "number" (js* "typeof ~{}" score)) score
                        :else 0)]
                (.set ^js roster from (js-obj "nick" nick "badge" (free-badge self)
                                              "score" (bit-or s 0))))
              (unchecked-set e "nick" nick))
            (broadcast-roster self)
            (when (.simRunning ^js self) (.sendSnap ^js self from))
            (maybe-start self))))))
  js/undefined)

(defn on-lobby
  "Back in the lobby (a match ended or was voided) — maybe host another."
  [self]
  (unchecked-set self "phase" "lobby")
  (maybe-start self)
  js/undefined)

(defn connected-seated
  "The connected, seated players (self always counts)."
  [self]
  (let [room (unchecked-get self "room")
        my-id (unchecked-get room "myId")
        ^js net (unchecked-get (unchecked-get room "peer") "net")
        open (js/Set. (.openPeers net))
        out #js []]
    (.forEach ^js (unchecked-get self "roster")
              (fn [_p id] (when (or (identical? id my-id) (.has open id)) (.push out id))))
    out))

(defn- driver-start [self ids]
  (unchecked-set self "phase" "running")
  (.startMatch ^js self ids)
  js/undefined)

(defn- maybe-start [self]
  (when (and (identical? (unchecked-get self "phase") "lobby")
             (not (unchecked-get self "_closed"))
             (< (unchecked-get self "matches")
                (unchecked-get (unchecked-get self "policy") "maxMatches")))
    (let [policy (unchecked-get self "policy")
          seated (connected-seated self)]
      (cond
        (>= (.-length seated) (unchecked-get policy "expectedPlayers"))
        (do (clear-start-timer self) (driver-start self seated))

        (and (>= (.-length seated) (unchecked-get policy "minPlayers"))
             (not ^boolean (js* "!!(~{})" (unchecked-get self "_startTimer"))))
        (let [t (js/setTimeout
                 (fn []
                   (unchecked-set self "_startTimer" nil)
                   (when-not (or (not (identical? (unchecked-get self "phase") "lobby"))
                                 (unchecked-get self "_closed")
                                 (not (unchecked-get (unchecked-get self "room") "hosting")))
                     (let [now (connected-seated self)]
                       (when (>= (.-length now) (unchecked-get policy "minPlayers"))
                         (driver-start self now)))))
                 (unchecked-get policy "startTimeoutMs"))]
          (unchecked-set self "_startTimer" t)
          (when ^boolean (js* "!!(~{})" (unchecked-get t "unref")) (.unref ^js t)))

        :else nil)))
  js/undefined)

(defn- clear-pending [self]
  (when ^boolean (js* "!!(~{})" (unchecked-get self "_pending"))
    (js/clearTimeout (unchecked-get self "_pending")))
  (unchecked-set self "_pending" nil)
  js/undefined)

(defn- clear-start-timer [self]
  (when ^boolean (js* "!!(~{})" (unchecked-get self "_startTimer"))
    (js/clearTimeout (unchecked-get self "_startTimer")))
  (unchecked-set self "_startTimer" nil)
  js/undefined)

(defn- clear-timers [self]
  (clear-pending self)
  (clear-start-timer self))

;; ---------------- the public / HostDriverLike surface ----------------

(let [proto (.-prototype HostDriver)
      thrower (fn [name] (fn [] (throw (js/Error. (str "HostDriver." name " is abstract")))))]
  ;; per-game hooks — every subclass overrides these (TS `abstract`)
  (doseq [name ["concedeRule" "startMatch" "onGameFrame" "execStep" "simPeerGone"
                "sendSnap" "roundLive" "simRunning" "abortSim"]]
    (unchecked-set proto name (thrower name)))

  ;; shared machinery, overridable (valley-blocks replaces broadcastRoster)
  (unchecked-set proto "broadcastRoster" (fn [] (this-as self (broadcast-roster-default self))))
  (unchecked-set proto "rosterEntries" (fn [] (this-as self (roster-entries self))))
  (unchecked-set proto "freeBadge" (fn [] (this-as self (free-badge self))))
  (unchecked-set proto "emitFrame" (fn [e] (this-as self (emit-frame self e))))
  (unchecked-set proto "runEmit" (fn [e] (this-as self (run-emit self e))))
  (unchecked-set proto "onHi" (fn [from m] (this-as self (on-hi self from m))))
  (unchecked-set proto "onLobby" (fn [] (this-as self (on-lobby self))))
  (unchecked-set proto "connectedSeated" (fn [] (this-as self (connected-seated self))))

  (unchecked-set proto "onMatchEnd"
                 (fn [cb] (this-as self
                            (.push ^js (unchecked-get self "_matchEndListeners") cb)
                            js/undefined)))

  ;; Manual start from the lobby (the auto-start policy normally does this).
  (unchecked-set
   proto "startNow"
   (fn []
     (this-as self
       (if (or (not (identical? (unchecked-get self "phase") "lobby"))
               (unchecked-get self "_closed")
               (not (unchecked-get (unchecked-get self "room") "hosting")))
         false
         (let [seated (connected-seated self)]
           (if (zero? (.-length seated))
             false
             (do (clear-start-timer self) (driver-start self seated) true)))))))

  ;; ---- HostDriverLike ----

  (unchecked-set
   proto "onClaimed"
   (fn []
     (this-as self
       (when-not (unchecked-get self "_closed")
         (let [room (unchecked-get self "room")
               my-id (unchecked-get room "myId")
               roster (unchecked-get self "roster")]
           (when-not (.has ^js roster my-id)
             (.set ^js roster my-id (js-obj "nick" (unchecked-get room "nick")
                                            "badge" (free-badge self)
                                            "score" 0)))
           (unchecked-set self "phase" "lobby")
           (broadcast-roster self)
           (maybe-start self)))
       js/undefined)))

  (unchecked-set
   proto "onSelfFrame"
   (fn [frame]
     (this-as self
       (when (and (some? frame)
                  (not (identical? frame js/undefined))
                  (string? (unchecked-get frame "t")))
         (.onGameFrame ^js self (unchecked-get (unchecked-get self "room") "myId") frame))
       js/undefined)))

  (unchecked-set
   proto "onForeignClaim"
   (fn [from m]
     (this-as self
       (if (.concedeRule ^js self from m)
         (do (clear-timers self)
             (.abortSim ^js self)
             (unchecked-set self "phase" "idle")
             (.clear ^js (unchecked-get self "roster"))
             true) ; the room base adopts their roster; our hi follows from it
         (do (broadcast-roster self) false))))) ; reassert

  (unchecked-set
   proto "close"
   (fn []
     (this-as self
       (unchecked-set self "_closed" true)
       (clear-timers self)
       (.abortSim ^js self)
       js/undefined))))

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/peer-kit.git