Repository navigation
Expand file tree
/
Copy pathRoom.ts
More file actions
683 lines (630 loc) · 19.1 KB
/
Copy pathRoom.ts
File metadata and controls
683 lines (630 loc) · 19.1 KB
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
import { Array, Option, pipe } from 'effect'
import {
type ClientFrame,
type ClosedReason,
NEUTRAL_INPUT,
PROTOCOL_VERSION,
type PlayerInput,
ServerFrame,
} from './Protocol'
import { repeat, writeAll } from './Wire'
import type { PlayerTick, World } from './World'
// NOTE: the GameRoom's game, as pure functions over plain data, apart from
// the Durable Object that runs them (infra/worker/gameRoom.ts) so tests
// can drive every rule with a fake clock. Each function takes the room and
// the time and returns the next room and what to send, close, or record.
//
// - The tick is a fixed 60 Hz, counted from the start time: `advance` runs
// as many ticks as the clock owes, at most MAX_CATCH_UP_TICKS at once, so
// a stalled loop loses time instead of spinning to catch up.
// - Inputs land by tick: each sample becomes a change point, and a player's
// input on tick T is the newest change point at or before T. A late one
// takes effect on the next tick, for that player only.
// - About 20 times a second (every TICKS_PER_SEND ticks) every linked
// player gets a Delta from the world it was last sent, with the newest
// Input seq the room applied for it. One diff is written and shared.
// - A player who links gets Welcome and a Snapshot of the last world sent,
// so the next shared Delta applies to it.
// - No word from a linked player for AWAY_AFTER_MS, or its socket closing,
// makes it Away. Away for FREE_SEAT_AFTER_MS frees its seat.
export const TICK_HZ = 60
export const TICK_MS = 1000 / TICK_HZ
export const TICKS_PER_SEND = 3
export const SEND_MS = TICK_MS * TICKS_PER_SEND
export const AWAY_AFTER_MS = 3000
export const FREE_SEAT_AFTER_MS = 2 * 60 * 1000
export const MAX_CATCH_UP_TICKS = 30
export const MAX_INPUT_LEAD_TICKS = 60
export const MAX_QUEUED_CHANGES = 240
export const MAX_RECEIPTS = 64
export type SocketId = string
export type SeatPresence =
| { readonly _tag: 'Here' }
| { readonly _tag: 'Away'; readonly sinceMs: number }
const HERE: SeatPresence = { _tag: 'Here' }
const awaySince = (sinceMs: number): SeatPresence => ({ _tag: 'Away', sinceMs })
export interface Change {
readonly tick: number
readonly input: PlayerInput
}
export interface Receipt {
readonly seq: number
readonly lastTick: number
}
export interface Seat {
readonly slot: number
readonly playerId: string
readonly socket: Option.Option<SocketId>
readonly presence: SeatPresence
readonly lastHeardMs: number
readonly input: PlayerInput
readonly queued: ReadonlyArray<Change>
readonly receipts: ReadonlyArray<Receipt>
readonly ack: number
readonly rttMs: number
}
export interface Room<W> {
readonly seats: ReadonlyArray<Seat>
readonly world: W
readonly tick: number
readonly startedMs: number
readonly sentWorld: W
readonly sentTick: number
}
export interface Scored {
readonly slot: number
readonly playerId: string
readonly score: number
}
export type Out =
| {
readonly _tag: 'Send'
readonly socket: SocketId
readonly frame: ServerFrame
}
| { readonly _tag: 'Close'; readonly socket: SocketId }
| { readonly _tag: 'FreedSeat'; readonly playerId: string }
| {
readonly _tag: 'Ended'
readonly reason: ClosedReason
readonly tick: number
readonly scores: ReadonlyArray<Scored>
}
export interface Stepped<W> {
readonly room: Room<W>
readonly out: ReadonlyArray<Out>
}
export interface Member {
readonly slot: number
readonly playerId: string
readonly socket: Option.Option<SocketId>
}
const send = (socket: SocketId, frame: ServerFrame): Out => ({
_tag: 'Send',
socket,
frame,
})
const close = (socket: SocketId): Out => ({ _tag: 'Close', socket })
const sendToLinked = (
seats: ReadonlyArray<Seat>,
frameFor: (seat: Seat) => ServerFrame,
): ReadonlyArray<Out> =>
Array.getSomes(
Array.map(seats, seat =>
Option.map(seat.socket, socket => send(socket, frameFor(seat))),
),
)
const updateSeat = (
seats: ReadonlyArray<Seat>,
slot: number,
update: (seat: Seat) => Seat,
): ReadonlyArray<Seat> =>
Array.map(seats, seat => (seat.slot === slot ? update(seat) : seat))
const seatOfSocket = (room: Room<unknown>, socket: SocketId) =>
Array.findFirst(room.seats, seat =>
Option.exists(seat.socket, linked => linked === socket),
)
export const seatOfPlayer = <W>(room: Room<W>, playerId: string) =>
Array.findFirst(room.seats, seat => seat.playerId === playerId)
const welcome = (seat: Seat, tick: number): ServerFrame =>
ServerFrame.cases.Welcome.make({
version: PROTOCOL_VERSION,
slot: seat.slot,
state: 'Playing',
tick,
})
const snapshotFrame = <W, Own>(
world: World<W, Own>,
room: Room<W>,
seat: Seat,
): ServerFrame =>
ServerFrame.cases.Snapshot.make({
tick: room.sentTick,
ack: seat.ack,
world: writeAll(writer => world.snapshot(writer, room.sentWorld)),
})
// START
export const startRoom = <W, Own>(
world: World<W, Own>,
members: ReadonlyArray<Member>,
seed: number,
nowMs: number,
): Stepped<W> => {
const first = world.start(
Array.map(members, member => member.slot),
seed,
)
const seats = Array.map(members, (member): Seat => ({
slot: member.slot,
playerId: member.playerId,
socket: member.socket,
presence: Option.isSome(member.socket) ? HERE : awaySince(nowMs),
lastHeardMs: nowMs,
input: NEUTRAL_INPUT,
queued: [],
receipts: [],
ack: 0,
rttMs: 0,
}))
const room: Room<W> = {
seats,
world: first,
tick: 0,
startedMs: nowMs,
sentWorld: first,
sentTick: 0,
}
return {
room,
out: Array.flatMap(seats, seat =>
Option.match(seat.socket, {
onNone: () => [],
onSome: socket => [
send(socket, welcome(seat, 0)),
send(socket, snapshotFrame(world, room, seat)),
],
}),
),
}
}
// LINKS
// NOTE: a player's game socket said Hello. A newer socket replaces an older
// one (a reload, or a second tab), which is closed. The input queue and the
// seq count start over, since a new socket starts its seqs from 1.
export const link = <W, Own>(
world: World<W, Own>,
room: Room<W>,
playerId: string,
socket: SocketId,
nowMs: number,
): Option.Option<Stepped<W>> =>
Option.map(seatOfPlayer(room, playerId), seat => {
const replaced = Option.filter(seat.socket, old => old !== socket)
const linked: Seat = {
...seat,
socket: Option.some(socket),
presence: HERE,
lastHeardMs: nowMs,
input: NEUTRAL_INPUT,
queued: [],
receipts: [],
ack: 0,
}
const seats = updateSeat(room.seats, seat.slot, () => linked)
const next = { ...room, seats }
const back =
seat.presence._tag === 'Away'
? sendToLinked(
Array.filter(seats, other => other.slot !== seat.slot),
() => ServerFrame.cases.Back.make({ slot: seat.slot }),
)
: []
return {
room: next,
out: [
...Option.match(replaced, {
onNone: () => [],
onSome: old => [close(old)],
}),
send(socket, welcome(linked, room.tick)),
send(socket, snapshotFrame(world, next, linked)),
...back,
],
}
})
const awayOut = (
seats: ReadonlyArray<Seat>,
slot: number,
): ReadonlyArray<Out> =>
sendToLinked(
Array.filter(seats, other => other.slot !== slot),
() => ServerFrame.cases.Away.make({ slot }),
)
// NOTE: a socket closed. Its player is Away at once.
export const unlink = <W>(
room: Room<W>,
socket: SocketId,
nowMs: number,
): Stepped<W> =>
Option.match(seatOfSocket(room, socket), {
onNone: () => ({ room, out: [] }),
onSome: seat => {
const seats = updateSeat(room.seats, seat.slot, current => ({
...current,
socket: Option.none(),
presence:
current.presence._tag === 'Away'
? current.presence
: awaySince(nowMs),
queued: [],
receipts: [],
input: NEUTRAL_INPUT,
}))
return {
room: { ...room, seats },
out: seat.presence._tag === 'Here' ? awayOut(seats, seat.slot) : [],
}
},
})
// SEATS
const removeSeat = <W, Own>(
world: World<W, Own>,
room: Room<W>,
seat: Seat,
): Room<W> => ({
...room,
seats: Array.filter(room.seats, other => other.slot !== seat.slot),
world: world.removePlayer(room.world, seat.slot),
})
// NOTE: the host kicked a player, or they left the room from the lobby.
export const dropPlayer = <W, Own>(
world: World<W, Own>,
room: Room<W>,
playerId: string,
kicked: boolean,
): Stepped<W> =>
Option.match(seatOfPlayer(room, playerId), {
onNone: () => ({ room, out: [] }),
onSome: seat => ({
room: removeSeat(world, room, seat),
out: Option.match(seat.socket, {
onNone: () => [],
onSome: socket =>
kicked
? [send(socket, ServerFrame.cases.Kicked.make({})), close(socket)]
: [close(socket)],
}),
}),
})
// INPUTS
const changesOf = (
frame: Extract<ClientFrame, { readonly _tag: 'Input' }>,
firstTick: number,
): readonly [ReadonlyArray<Change>, number] => {
const none: readonly [ReadonlyArray<Change>, number] = [[], firstTick]
return Array.reduce(frame.samples, none, ([changes, tick], sample) => {
const next: readonly [ReadonlyArray<Change>, number] = [
Array.append(changes, { tick, input: sample.input }),
tick + sample.ticks,
]
return next
})
}
// NOTE: each sample keeps its own tick. Samples for ticks the room already
// ran are late: the newest of them takes effect on the next tick and the
// rest are dropped, so one slow message never shifts the ticks of the ones
// on time. A message claiming ticks too far ahead is pulled back whole.
// The new change points replace queued ones at or after their first tick:
// they are newer word about the same ticks.
const pointsOf = (
frame: Extract<ClientFrame, { readonly _tag: 'Input' }>,
tick: number,
): ReadonlyArray<Change> => {
const pulledBack = Math.max(0, frame.tick - (tick + MAX_INPUT_LEAD_TICKS))
const [points] = changesOf(frame, frame.tick - pulledBack)
const late = Array.filter(points, point => point.tick <= tick)
const onTime = Array.filter(points, point => point.tick > tick)
return Option.match(Array.last(late), {
onNone: () => onTime,
onSome: newestLate =>
Option.exists(Array.head(onTime), first => first.tick === tick + 1)
? onTime
: Array.prepend(onTime, { tick: tick + 1, input: newestLate.input }),
})
}
const enqueue = (
seat: Seat,
frame: Extract<ClientFrame, { readonly _tag: 'Input' }>,
tick: number,
): Seat => {
const changes = pointsOf(frame, tick)
const firstTick = Option.match(Array.head(changes), {
onNone: () => tick + 1,
onSome: change => change.tick,
})
const lastTick = Option.match(Array.last(changes), {
onNone: () => tick + 1,
onSome: change => change.tick,
})
const kept = Array.filter(seat.queued, change => change.tick < firstTick)
return {
...seat,
queued: Array.takeRight(Array.appendAll(kept, changes), MAX_QUEUED_CHANGES),
receipts: Array.takeRight(
Array.append(seat.receipts, { seq: frame.seq, lastTick }),
MAX_RECEIPTS,
),
}
}
// NOTE: any frame from a linked player is word from them, and brings an
// Away player back.
const heard = <W>(room: Room<W>, seat: Seat, nowMs: number): Stepped<W> => {
const seats = updateSeat(room.seats, seat.slot, current => ({
...current,
lastHeardMs: nowMs,
presence: HERE,
}))
return {
room: { ...room, seats },
out:
seat.presence._tag === 'Away'
? sendToLinked(
Array.filter(seats, other => other.slot !== seat.slot),
() => ServerFrame.cases.Back.make({ slot: seat.slot }),
)
: [],
}
}
export const receive = <W, Own>(
world: World<W, Own>,
room: Room<W>,
socket: SocketId,
frame: ClientFrame,
nowMs: number,
): Stepped<W> =>
Option.match(seatOfSocket(room, socket), {
onNone: () => ({ room, out: [] }),
onSome: seat => {
const woke = heard(room, seat, nowMs)
const current = Option.getOrElse(
seatOfSocket(woke.room, socket),
() => seat,
)
if (frame._tag === 'Input') {
return {
room: {
...woke.room,
seats: updateSeat(woke.room.seats, seat.slot, () =>
enqueue(current, frame, woke.room.tick),
),
},
out: woke.out,
}
}
if (frame._tag === 'Ping') {
return {
room: {
...woke.room,
seats: updateSeat(woke.room.seats, seat.slot, () => ({
...current,
rttMs: frame.rttMs,
})),
},
out: [
...woke.out,
send(
socket,
ServerFrame.cases.Pong.make({
nonce: frame.nonce,
tick: woke.room.tick,
}),
),
],
}
}
if (frame._tag === 'Leave') {
return {
room: removeSeat(world, woke.room, current),
out: [
close(socket),
{ _tag: 'FreedSeat', playerId: current.playerId },
],
}
}
return woke
},
})
// TICKS
const inputAt = (seat: Seat, tick: number): Seat => {
const due = Array.filter(seat.queued, change => change.tick <= tick)
return Option.match(Array.last(due), {
onNone: () => seat,
onSome: change => ({
...seat,
input: change.input,
queued: Array.filter(seat.queued, queued => queued.tick > tick),
}),
})
}
const acked = (seat: Seat, tick: number): Seat => {
const done = Array.filter(seat.receipts, receipt => receipt.lastTick <= tick)
return Option.match(Array.last(done), {
onNone: () => seat,
onSome: receipt => ({
...seat,
ack: Math.max(seat.ack, receipt.seq),
receipts: Array.filter(seat.receipts, other => other.lastTick > tick),
}),
})
}
const tickOf = (seat: Seat): PlayerTick => ({
slot: seat.slot,
input: seat.presence._tag === 'Here' ? seat.input : NEUTRAL_INPUT,
presence: seat.presence._tag,
})
const runTick = <W, Own>(world: World<W, Own>, room: Room<W>): Room<W> => {
const tick = room.tick + 1
const seats = Array.map(room.seats, seat => inputAt(seat, tick))
return {
...room,
tick,
world: world.step(room.world, Array.map(seats, tickOf)),
seats: Array.map(seats, seat => acked(seat, tick)),
}
}
const broadcast = <W, Own>(world: World<W, Own>, room: Room<W>): Stepped<W> => {
const diff = writeAll(writer =>
world.diff(writer, room.sentWorld, room.world),
)
return {
room: { ...room, sentWorld: room.world, sentTick: room.tick },
out: sendToLinked(room.seats, seat =>
ServerFrame.cases.Delta.make({
tick: room.tick,
base: room.sentTick,
ack: seat.ack,
diff,
}),
),
}
}
const isSendTick = (room: Room<unknown>): boolean =>
Math.floor(room.tick / TICKS_PER_SEND) >
Math.floor(room.sentTick / TICKS_PER_SEND)
const checkPresence = <W, Own>(
world: World<W, Own>,
room: Room<W>,
nowMs: number,
): Stepped<W> => {
const none: Stepped<W> = { room, out: [] }
return Array.reduce(room.seats, none, (stepped, seat): Stepped<W> => {
if (
seat.presence._tag === 'Here' &&
nowMs - seat.lastHeardMs > AWAY_AFTER_MS
) {
const seats = updateSeat(stepped.room.seats, seat.slot, current => ({
...current,
presence: awaySince(nowMs),
}))
return {
room: { ...stepped.room, seats },
out: [...stepped.out, ...awayOut(seats, seat.slot)],
}
}
if (
seat.presence._tag === 'Away' &&
nowMs - seat.presence.sinceMs > FREE_SEAT_AFTER_MS
) {
return {
room: removeSeat(world, stepped.room, seat),
out: [
...stepped.out,
...Option.match(seat.socket, {
onNone: () => [],
onSome: socket => [close(socket)],
}),
{ _tag: 'FreedSeat', playerId: seat.playerId },
],
}
}
return stepped
})
}
// NOTE: the game is over. Everyone linked hears why; `Ended` carries the
// scores by player for the room's result. Sockets stay open for the next
// game in the same room.
export const endRoom = <W, Own>(
world: World<W, Own>,
room: Room<W>,
reason: ClosedReason,
): ReadonlyArray<Out> => [
...sendToLinked(room.seats, () =>
ServerFrame.cases.RoomClosed.make({ reason }),
),
{
_tag: 'Ended',
reason,
tick: room.tick,
scores: Array.getSomes(
Array.map(world.scores(room.world), score =>
Option.map(
Array.findFirst(room.seats, seat => seat.slot === score.slot),
seat => ({
slot: score.slot,
playerId: seat.playerId,
score: score.score,
}),
),
),
),
},
]
export const isEnded = (out: ReadonlyArray<Out>): boolean =>
Array.some(out, item => item._tag === 'Ended')
// NOTE: a hair of slack, so 1000 ms is 60 ticks and not 59.999.
const TICK_SLACK = 1e-6
export const ticksDue = (room: Room<unknown>, nowMs: number): number =>
Math.max(
0,
Math.floor((nowMs - room.startedMs) / TICK_MS + TICK_SLACK) - room.tick,
)
// NOTE: one wake of the room's loop: the ticks the clock owes, one message
// to everyone if a send tick passed, then presence, then the end of the
// game, which first sends the last world if it is not out yet, so every
// player sees how the run ended. After an `Ended` out the room is done.
export const advance = <W, Own>(
world: World<W, Own>,
room: Room<W>,
nowMs: number,
): Stepped<W> => {
const owed = ticksDue(room, nowMs)
const slipped =
owed > MAX_CATCH_UP_TICKS
? {
...room,
startedMs: nowMs - (room.tick + MAX_CATCH_UP_TICKS) * TICK_MS,
}
: room
const ticked = Array.reduce(
repeat(Math.min(owed, MAX_CATCH_UP_TICKS), () => 0),
slipped,
current => runTick(world, current),
)
const sent = isSendTick(ticked)
? broadcast(world, ticked)
: { room: ticked, out: [] }
const present = checkPresence(world, sent.room, nowMs)
const out = [...sent.out, ...present.out]
if (world.isOver(present.room.world)) {
const last =
present.room.sentTick === present.room.tick
? { room: present.room, out: [] }
: broadcast(world, present.room)
return {
room: last.room,
out: [...out, ...last.out, ...endRoom(world, last.room, 'GameOver')],
}
}
if (Array.isReadonlyArrayEmpty(present.room.seats)) {
return {
room: present.room,
out: [...out, ...endRoom(world, present.room, 'Abandoned')],
}
}
return { room: present.room, out }
}
// NOTE: when the loop should wake next: the next send tick.
export const nextWakeMs = (room: Room<unknown>): number => {
const nextSendTick =
(Math.floor(room.tick / TICKS_PER_SEND) + 1) * TICKS_PER_SEND
return room.startedMs + nextSendTick * TICK_MS
}
export const linkedSockets = (room: Room<unknown>): ReadonlyArray<SocketId> =>
Array.getSomes(Array.map(room.seats, seat => seat.socket))
export const rttsOf = (
room: Room<unknown>,
): ReadonlyArray<{ readonly slot: number; readonly rttMs: number }> =>
pipe(
room.seats,
Array.map(seat => ({ slot: seat.slot, rttMs: seat.rttMs })),
)