Repository navigation
Expand file tree
/
Copy pathgameRoom.ts
More file actions
1018 lines (962 loc) · 31.1 KB
/
Copy pathgameRoom.ts
File metadata and controls
1018 lines (962 loc) · 31.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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as Array from 'effect/Array'
import * as Clock from 'effect/Clock'
import * as Effect from 'effect/Effect'
import * as Fiber from 'effect/Fiber'
import * as Option from 'effect/Option'
import * as Result from 'effect/Result'
import * as Schema from 'effect/Schema'
import * as Semaphore from 'effect/Semaphore'
import type {
DurableObjectNamespace,
DurableObjectState,
WebSocket as WorkersWebSocket,
} from '@cloudflare/workers-types'
import * as SqliteClient from '@effect/sql-sqlite-do/SqliteClient'
import {
type ClosedReason,
CreateRequest,
JoinRequest,
type Lobby,
ROOM_PATHS,
Room,
RoomRefusal,
type RoomTicket,
SERVER_VERSIONS,
ServerFrame,
decodeClientFrame,
encodeServerFrame,
normalizeRoomCode,
roomCodeOfScope,
roomRefusalStatus,
roomScopeId,
} from '@munch/netcode'
import {
Connection,
IDENTITY_PATHS,
OPENED,
PING_JSON,
PONG_JSON,
verifyToken,
} from '@munch/sync-engine'
import {
DEFAULT_ROOM_SETTINGS,
type RoomWorld,
roomWorldFor,
} from '../../src/roomWorld.ts'
import {
INTERNAL_PATHS,
InternalCreate,
InternalJoin,
ROOM_CODE_HEADER,
type RoomHost,
STALLED_LOOP_MS,
answerHello,
decideAlarm,
listingOf,
reactionsOf,
roomHostOnce,
} from './gameRoomCore.ts'
import {
MATCHMAKER_NAME,
createRoomIn,
joinRoomIn,
reportListing,
} from './roomCalls.ts'
import type { SyncBindings } from './sync.ts'
import {
BadSyncBody,
CORS_HEADERS,
type Socket,
SyncCallFailed,
type SyncSetupFailed,
json,
syncErrorResponse,
tryCall,
} from './syncCore.ts'
// NOTE: one co-op room per Durable Object, named `room:<code>`. It holds
// the room's lobby scope (its SQLite storage, through the sync engine) and,
// while a game runs, the game itself in memory: the pure Room from
// @munch/netcode, stepped by a timer loop about every 50 ms, which keeps
// the object awake. In the lobby there is no timer, so it hibernates with
// its sockets open. An alarm is the watchdog: it restarts a stalled loop,
// records a game the object lost to a restart as Interrupted, and deletes
// a room a day after its last change. The run starts when the lobby's last
// READY makes it Playing. A public room tells the Matchmaker (matchmaker.ts)
// whenever its lobby changes. See MULTIPLAYER.md, Phase 2 and 3.
//
// The world is the game's own (src/roomWorld.ts): `stepWorld` over the
// lobby's seats, a campaign on Normal until the lobby picks a difficulty.
export type GameRoomBindings = SyncBindings
type GameWorld = RoomWorld
const World = roomWorldFor(DEFAULT_ROOM_SETTINGS)
const SCOPE_HEADER = 'x-sync-scope'
const GAME_TAG = 'game'
const SYNC_TAG = 'sync'
const Attachment = Schema.TaggedUnion({
Sync: { scope: Schema.String, connection: Connection },
GameOpened: { scope: Schema.String, socket: Schema.String },
GameJoined: {
scope: Schema.String,
socket: Schema.String,
playerId: Schema.String,
},
})
type Attachment = typeof Attachment.Type
const decodeAttachment = Schema.decodeUnknownOption(Attachment)
const encodeAttachment = Schema.encodeSync(Attachment)
const attachmentOf = (socket: WorkersWebSocket): Option.Option<Attachment> =>
decodeAttachment(socket.deserializeAttachment())
const sqlOf = (storage: DurableObjectState['storage']) =>
SqliteClient.layer({ storage })
interface Game {
readonly room: Room.Room<GameWorld>
readonly round: number
readonly advancedMs: number
}
const sendFrame = (socket: WorkersWebSocket, frame: ServerFrame) =>
Result.match(encodeServerFrame(frame), {
onFailure: () => undefined,
onSuccess: bytes => {
socket.send(bytes)
},
})
export class GameRoom {
private readonly lock = Semaphore.makeUnsafe(1)
private host: Option.Option<Effect.Effect<RoomHost, SyncSetupFailed>> =
Option.none()
private game: Option.Option<Game> = Option.none()
private loop: Option.Option<Fiber.Fiber<void>> = Option.none()
constructor(
private readonly ctx: DurableObjectState,
private readonly env: GameRoomBindings,
) {
ctx.setWebSocketAutoResponse(
new WebSocketRequestResponsePair(PING_JSON, PONG_JSON),
)
}
// SETUP
// NOTE: the room's code is in its own table once created, so the alarm
// can find its scope with no socket open.
private storedScope(): Effect.Effect<Option.Option<string>> {
return Effect.try({
try: () =>
Option.flatMap(
Option.fromNullishOr(
this.ctx.storage.sql
.exec('SELECT code FROM room WHERE id = 1')
.toArray()[0],
),
row =>
Option.map(normalizeRoomCode(String(row['code'])), roomScopeId),
),
catch: () => Option.none<string>(),
}).pipe(Effect.catch(none => Effect.succeed(none)))
}
private hostFor(scope: string): Effect.Effect<RoomHost, SyncSetupFailed> {
return Effect.suspend(() =>
Option.getOrElse(this.host, () => {
const once = Effect.runSync(
roomHostOnce(sqlOf(this.ctx.storage), scope, this.env.SYNC_SECRET),
)
this.host = Option.some(once)
return once
}),
)
}
private isNamed(scope: string): boolean {
const rooms = this.env.GAME_ROOMS
return rooms !== undefined && this.ctx.id.equals(rooms.idFromName(scope))
}
// SOCKETS
private syncSockets(): ReadonlyArray<
Socket & {
readonly playerId: Option.Option<string>
readonly close: () => void
}
> {
return Array.getSomes(
Array.map(this.ctx.getWebSockets(SYNC_TAG), socket =>
Option.flatMap(attachmentOf(socket), attachment =>
attachment._tag === 'Sync'
? Option.some({
connection: attachment.connection,
playerId:
attachment.connection._tag === 'Joined'
? Option.some(attachment.connection.playerId)
: Option.none(),
send: (message: string) => {
socket.send(message)
},
setConnection: (connection: Connection) => {
socket.serializeAttachment(
encodeAttachment({
_tag: 'Sync',
scope: attachment.scope,
connection,
}),
)
},
close: () => socket.close(4001, 'Removed'),
})
: Option.none(),
),
),
)
}
private gameSockets(): ReadonlyArray<{
readonly socket: WorkersWebSocket
readonly id: string
readonly playerId: Option.Option<string>
}> {
return Array.getSomes(
Array.map(this.ctx.getWebSockets(GAME_TAG), socket =>
Option.flatMap(attachmentOf(socket), attachment =>
attachment._tag === 'GameOpened'
? Option.some({
socket,
id: attachment.socket,
playerId: Option.none<string>(),
})
: attachment._tag === 'GameJoined'
? Option.some({
socket,
id: attachment.socket,
playerId: Option.some(attachment.playerId),
})
: Option.none(),
),
),
)
}
private accept(tag: string, attachment: Attachment): Response {
const pair = new WebSocketPair()
const client = pair[0]
const server = pair[1]
this.ctx.acceptWebSocket(server, [tag])
server.serializeAttachment(encodeAttachment(attachment))
return new Response(null, { status: 101, webSocket: client })
}
// GAME
private apply(
out: ReadonlyArray<Room.Out>,
host: RoomHost,
): Effect.Effect<void> {
const sockets = this.gameSockets()
const byId = (id: string) =>
Array.findFirst(sockets, entry => entry.id === id)
const game = this.game
const everyone = () => this.syncSockets()
return Effect.forEach(
out,
item => {
if (item._tag === 'Send') {
return Effect.sync(() =>
Option.map(byId(item.socket), entry =>
sendFrame(entry.socket, item.frame),
),
)
}
if (item._tag === 'Close') {
return Effect.sync(() =>
Option.map(byId(item.socket), entry =>
entry.socket.close(1000, 'Done'),
),
)
}
if (item._tag === 'FreedSeat') {
return this.lock.withPermit(
host.freeSeat(
item.playerId,
Option.match(game, {
onNone: () => 0,
onSome: current => current.round,
}),
everyone(),
),
)
}
return this.finish(item, host)
},
{ discard: true },
)
}
private finish(
ended: Extract<Room.Out, { readonly _tag: 'Ended' }>,
host: RoomHost,
): Effect.Effect<void> {
const round = Option.match(this.game, {
onNone: () => 0,
onSome: game => game.round,
})
const rtts = Option.match(this.game, {
onNone: () => [],
onSome: game => Room.rttsOf(game.room),
})
this.game = Option.none()
const stopLoop = Option.match(this.loop, {
onNone: () => Effect.void,
onSome: fiber => Effect.asVoid(Fiber.interrupt(fiber)),
})
this.loop = Option.none()
const everyone = this.syncSockets()
return Effect.gen({ self: this }, function* () {
yield* Effect.logInfo(
`Room game ${round} ended (${ended.reason}) at tick ${ended.tick}; round trips ${JSON.stringify(rtts)}`,
)
yield* this.lock.withPermit(
host.recordResult(
{
round,
reason: ended.reason,
ticks: ended.tick,
scores: ended.scores,
},
everyone,
),
)
yield* this.list(host)
yield* stopLoop
})
}
private tickLoop(host: RoomHost): Effect.Effect<void> {
return Effect.gen({ self: this }, function* () {
const current = this.game
if (Option.isNone(current)) {
return
}
const nowMs = yield* Clock.currentTimeMillis
const stepped = Room.advance(World, current.value.room, nowMs)
this.game = Option.some({
room: stepped.room,
round: current.value.round,
advancedMs: nowMs,
})
yield* this.apply(stepped.out, host)
if (Option.isNone(this.game)) {
return
}
const after = yield* Clock.currentTimeMillis
yield* Effect.sleep(Math.max(1, Room.nextWakeMs(stepped.room) - after))
return yield* this.tickLoop(host)
})
}
private startLoop(host: RoomHost): void {
Option.map(this.loop, fiber => Effect.runFork(Fiber.interrupt(fiber)))
this.loop = Option.some(Effect.runFork(this.tickLoop(host)))
}
private startGame(host: RoomHost): Effect.Effect<void> {
return Effect.gen({ self: this }, function* () {
const maybeLobby = yield* host.lobby
if (
Option.isNone(maybeLobby) ||
maybeLobby.value.status !== 'Playing' ||
Option.isSome(this.game)
) {
return
}
const lobby = maybeLobby.value
const sockets = this.gameSockets()
const nowMs = yield* Clock.currentTimeMillis
const seed = crypto.getRandomValues(new Uint32Array(1))[0] ?? nowMs
const started = Room.startRoom(
World,
Array.map(lobby.members, member => ({
slot: member.slot,
playerId: member.playerId,
socket: Option.map(
Array.findLast(sockets, entry =>
Option.exists(
entry.playerId,
playerId => playerId === member.playerId,
),
),
entry => entry.id,
),
})),
seed,
nowMs,
)
this.game = Option.some({
room: started.room,
round: lobby.round,
advancedMs: nowMs,
})
yield* this.apply(started.out, host)
this.startLoop(host)
yield* tryCall('set the watchdog', () =>
this.ctx.storage.setAlarm(nowMs + 60 * 1000),
).pipe(Effect.ignore)
})
}
private endGame(host: RoomHost, reason: ClosedReason): Effect.Effect<void> {
return Option.match(this.game, {
onNone: () => Effect.void,
onSome: game => this.apply(Room.endRoom(World, game.room, reason), host),
})
}
private dropPlayer(
playerId: string,
kicked: boolean,
host: RoomHost,
): Effect.Effect<void> {
return Effect.gen({ self: this }, function* () {
yield* host.forget(playerId)
Array.forEach(this.syncSockets(), socket => {
if (Option.exists(socket.playerId, id => id === playerId)) {
socket.close()
}
})
const game = this.game
if (Option.isSome(game)) {
const dropped = Room.dropPlayer(
World,
game.value.room,
playerId,
kicked,
)
this.game = Option.some({ ...game.value, room: dropped.room })
return yield* this.apply(dropped.out, host)
}
Array.forEach(this.gameSockets(), entry => {
if (Option.exists(entry.playerId, id => id === playerId)) {
if (kicked) {
sendFrame(entry.socket, ServerFrame.cases.Kicked.make({}))
}
entry.socket.close(1000, kicked ? 'Kicked' : 'Left')
}
})
})
}
private react(
deltas: Parameters<typeof reactionsOf>[0],
host: RoomHost,
): Effect.Effect<void> {
return Effect.flatMap(reactionsOf(deltas), reactions =>
Effect.andThen(
Effect.forEach(
reactions,
reaction =>
reaction._tag === 'MaybeStart'
? this.startGame(host)
: reaction._tag === 'EndGame'
? this.endGame(host, 'EndedByHost')
: this.dropPlayer(reaction.playerId, reaction.kicked, host),
{ discard: true },
),
Array.isReadonlyArrayNonEmpty(deltas) ? this.list(host) : Effect.void,
),
)
}
// NOTE: a public room tells the Matchmaker how it stands after a change,
// without waiting: the Matchmaker may call back to seat someone.
private list(host: RoomHost): Effect.Effect<void> {
const matchmakers = this.env.MATCHMAKER
return Effect.flatMap(host.lobby, maybeLobby =>
Option.match(Option.flatMap(maybeLobby, listingOf), {
onNone: () => Effect.void,
onSome: listing =>
Effect.sync(() => {
Effect.runFork(reportListing(matchmakers, listing))
}),
}),
)
}
// HTTP
private handle(
request: Request,
): Effect.Effect<Response, SyncSetupFailed | SyncCallFailed | BadSyncBody> {
const url = new URL(request.url)
const scope =
request.headers.get(SCOPE_HEADER) ??
roomScopeId(request.headers.get(ROOM_CODE_HEADER) ?? '')
if (Option.isNone(roomCodeOfScope(scope)) || !this.isNamed(scope)) {
return Effect.succeed(
json(400, '{"_tag":"BadRequest","reason":"Wrong room"}'),
)
}
const hostFor = this.hostFor(scope)
return Effect.gen({ self: this }, function* () {
const host = yield* hostFor
if (url.pathname === IDENTITY_PATHS.socket) {
return this.accept(SYNC_TAG, {
_tag: 'Sync',
scope,
connection: OPENED,
})
}
if (url.pathname === ROOM_PATHS.socket) {
return this.accept(GAME_TAG, {
_tag: 'GameOpened',
scope,
socket: crypto.randomUUID(),
})
}
if (url.pathname === IDENTITY_PATHS.exchange) {
const body = yield* tryCall('read the body', () => request.text())
const everyone = this.syncSockets()
const result = yield* this.lock.withPermit(
Effect.suspend(() => host.scope.exchangeWith(body, everyone)),
)
yield* this.react(result.applied, host)
return result.response
}
if (url.pathname === INTERNAL_PATHS.create) {
const text = yield* tryCall('read the body', () => request.text())
const body = yield* Effect.mapError(
Schema.decodeEffect(InternalCreate)(text),
error => new BadSyncBody({ reason: error.message }),
)
const created = yield* this.lock.withPermit(
host.create(body.playerId, body.name, body.code, body.visibility),
)
if (Result.isSuccess(created)) {
const nowMs = yield* Clock.currentTimeMillis
yield* tryCall('set the cleanup alarm', () =>
this.ctx.storage.setAlarm(nowMs + 24 * 60 * 60 * 1000),
).pipe(Effect.ignore)
yield* this.list(host)
}
return ticketResponse(created)
}
if (url.pathname === INTERNAL_PATHS.join) {
const text = yield* tryCall('read the body', () => request.text())
const body = yield* Effect.mapError(
Schema.decodeEffect(InternalJoin)(text),
error => new BadSyncBody({ reason: error.message }),
)
const everyone = this.syncSockets()
const joined = yield* this.lock.withPermit(
host.join(body.playerId, body.name, everyone),
)
yield* this.list(host)
return ticketResponse(joined)
}
return json(404, '{}')
})
}
fetch(request: Request): Promise<Response> {
return Effect.runPromise(syncErrorResponse(this.handle(request)))
}
// MESSAGES
private onSync(
socket: WorkersWebSocket,
attachment: Extract<Attachment, { readonly _tag: 'Sync' }>,
message: string,
): Effect.Effect<void, SyncSetupFailed> {
return Effect.gen({ self: this }, function* () {
const host = yield* this.hostFor(attachment.scope)
const self: Socket = {
connection: attachment.connection,
send: text => {
socket.send(text)
},
setConnection: connection => {
socket.serializeAttachment(
encodeAttachment({
_tag: 'Sync',
scope: attachment.scope,
connection,
}),
)
},
}
const everyone = this.syncSockets()
const applied = yield* this.lock.withPermit(
Effect.suspend(() => host.scope.onMessage(self, message, everyone)),
)
yield* this.react(applied, host)
})
}
private onGame(
socket: WorkersWebSocket,
attachment: Extract<
Attachment,
{ readonly _tag: 'GameOpened' | 'GameJoined' }
>,
bytes: Uint8Array,
): Effect.Effect<void, SyncSetupFailed> {
return Effect.gen({ self: this }, function* () {
const host = yield* this.hostFor(attachment.scope)
const nowMs = yield* Clock.currentTimeMillis
const decoded = decodeClientFrame(bytes)
if (Result.isFailure(decoded)) {
return refuseAndClose(socket, 'BadMessage')
}
const frame = decoded.success
if (attachment._tag === 'GameOpened') {
const answer = yield* answerHello(
frame,
this.env.SYNC_SECRET,
yield* host.lobby,
nowMs,
)
if (answer._tag === 'Refuse') {
return refuseAndClose(socket, answer.reason)
}
socket.serializeAttachment(
encodeAttachment({
_tag: 'GameJoined',
scope: attachment.scope,
socket: attachment.socket,
playerId: answer.playerId,
}),
)
const game = this.game
const linked = Option.flatMap(game, current =>
Room.link(
World,
current.room,
answer.playerId,
attachment.socket,
nowMs,
),
)
if (Option.isSome(game) && Option.isSome(linked)) {
this.game = Option.some({ ...game.value, room: linked.value.room })
return yield* this.apply(linked.value.out, host)
}
sendFrame(
socket,
ServerFrame.cases.Welcome.make({
version: answer.version,
slot: answer.slot,
state: 'Waiting',
tick: 0,
}),
)
return
}
const game = this.game
if (Option.isNone(game)) {
return
}
const received = Room.receive(
World,
game.value.room,
attachment.socket,
frame,
nowMs,
)
this.game = Option.some({ ...game.value, room: received.room })
yield* this.apply(received.out, host)
})
}
// NOTE: every socket of this object belongs to its one room, and each
// attachment names its scope.
private scopeOfObject(): Effect.Effect<Option.Option<string>> {
const fromSockets = Option.map(
Array.head(
Array.getSomes(Array.map(this.ctx.getWebSockets(), attachmentOf)),
),
attachment => attachment.scope,
)
return Option.isSome(fromSockets)
? Effect.succeed(fromSockets)
: this.storedScope()
}
webSocketMessage(
socket: WorkersWebSocket,
message: string | ArrayBuffer,
): Promise<void> {
const maybeAttachment = attachmentOf(socket)
if (Option.isNone(maybeAttachment)) {
socket.close(1003, 'Unsupported')
return Promise.resolve()
}
const attachment = maybeAttachment.value
const handled: Effect.Effect<void, SyncSetupFailed> =
attachment._tag === 'Sync'
? typeof message === 'string'
? this.onSync(socket, attachment, message)
: Effect.sync(() => socket.close(1003, 'Text only'))
: typeof message === 'string'
? Effect.void
: this.onGame(socket, attachment, new Uint8Array(message))
return Effect.runPromise(
handled.pipe(
Effect.catchTag('SyncSetupFailed', error =>
Effect.logError('Room setup failed', error.cause),
),
),
)
}
webSocketClose(
socket: WorkersWebSocket,
code: number,
reason: string,
): Promise<void> {
const maybeAttachment = attachmentOf(socket)
const game = this.game
if (
Option.isSome(maybeAttachment) &&
maybeAttachment.value._tag === 'GameJoined' &&
Option.isSome(game)
) {
const socketId = maybeAttachment.value.socket
return Effect.runPromise(
Effect.gen({ self: this }, function* () {
const nowMs = yield* Clock.currentTimeMillis
const current = this.game
if (Option.isSome(current)) {
const unlinked = Room.unlink(current.value.room, socketId, nowMs)
this.game = Option.some({ ...current.value, room: unlinked.room })
Array.forEach(unlinked.out, item => {
if (item._tag === 'Send') {
Option.map(
Array.findFirst(
this.gameSockets(),
entry => entry.id === item.socket,
),
entry => sendFrame(entry.socket, item.frame),
)
}
})
}
socket.close(code, reason)
}),
)
}
socket.close(code, reason)
return Promise.resolve()
}
webSocketError(socket: WorkersWebSocket): Promise<void> {
return this.webSocketClose(socket, 1011, 'Error')
}
// ALARM
alarm(): Promise<void> {
return Effect.runPromise(
Effect.gen({ self: this }, function* () {
const maybeScope = yield* this.scopeOfObject()
const nowMs = yield* Clock.currentTimeMillis
const maybeHost = Option.isSome(maybeScope)
? Option.some(yield* this.hostFor(maybeScope.value))
: Option.none<RoomHost>()
const lobby = Option.isSome(maybeHost)
? yield* maybeHost.value.lobby
: Option.none<Lobby>()
const decision = decideAlarm({
nowMs,
gameRunning: Option.isSome(this.game),
lobby,
socketsOpen: this.ctx.getWebSockets().length,
})
if (decision._tag === 'CheckLoop') {
if (
Option.isSome(maybeHost) &&
Option.exists(
this.game,
game => nowMs - game.advancedMs > STALLED_LOOP_MS,
)
) {
yield* Effect.logWarning('The room loop stalled; restarting it')
this.startLoop(maybeHost.value)
}
return yield* setAlarm(this.ctx, decision.nextMs)
}
if (decision._tag === 'Interrupted') {
if (Option.isSome(maybeHost) && Option.isSome(lobby)) {
yield* this.lock.withPermit(
maybeHost.value.recordResult(
{
round: lobby.value.round,
reason: 'Interrupted',
ticks: 0,
scores: [],
},
this.syncSockets(),
),
)
Array.forEach(this.gameSockets(), entry =>
sendFrame(
entry.socket,
ServerFrame.cases.RoomClosed.make({ reason: 'Interrupted' }),
),
)
}
return yield* setAlarm(this.ctx, decision.nextMs)
}
if (decision._tag === 'Later') {
return yield* setAlarm(this.ctx, decision.nextMs)
}
// NOTE: only an empty, unchanged room gets here, or an object that
// never held one. A sync scope rebuilds its tables on next use.
this.host = Option.none()
yield* tryCall('delete the room', () =>
this.ctx.storage.deleteAll(),
).pipe(Effect.ignore)
}).pipe(
Effect.catchTag('SyncSetupFailed', error =>
Effect.logError('Room alarm failed', error.cause),
),
),
)
}
}
const setAlarm = (ctx: DurableObjectState, atMs: number) =>
tryCall('set the alarm', () => ctx.storage.setAlarm(atMs)).pipe(Effect.ignore)
const refuseAndClose = (
socket: WorkersWebSocket,
reason: Parameters<typeof ServerFrame.cases.Refused.make>[0]['reason'],
) => {
sendFrame(
socket,
ServerFrame.cases.Refused.make({
reason,
minVersion: SERVER_VERSIONS.minVersion,
maxVersion: SERVER_VERSIONS.maxVersion,
}),
)
socket.close(1008, reason)
}
const encodeRefusal = Schema.encodeSync(Schema.fromJsonString(RoomRefusal))
const encodeTicket = (ticket: RoomTicket) => JSON.stringify(ticket)
const refusalResponse = (refusal: RoomRefusal): Response =>
json(roomRefusalStatus(refusal), encodeRefusal(refusal))
const ticketResponse = (result: Result.Result<RoomTicket, RoomRefusal>) =>
Result.match(result, {
onSuccess: ticket => json(200, encodeTicket(ticket)),
onFailure: refusalResponse,
})
// ROUTES
const bearerOf = (request: Request): Option.Option<string> =>
Option.flatMap(
Option.fromNullishOr(request.headers.get('authorization')),
header =>
header.startsWith('Bearer ')
? Option.some(header.slice(7))
: Option.none(),
)
const isWithinRate = (env: GameRoomBindings, request: Request) => {
const address = request.headers.get('cf-connecting-ip') ?? 'unknown'
return tryCall('check the rate limit', () =>
env.SYNC_BY_ADDRESS.limit({ key: `room:${address}` }),
).pipe(
Effect.map(outcome => outcome.success),
Effect.catchTag('SyncCallFailed', () => Effect.succeed(true)),
)
}
const answer = (status: number, text: string): Response =>
new Response(text, {
status,
headers: { ...CORS_HEADERS, 'content-type': 'application/json' },
})
const routeRoomPath = (request: Request, env: GameRoomBindings, url: URL) =>
Effect.gen(function* () {
if (request.method === 'OPTIONS') {
return new Response(null, { status: 204, headers: CORS_HEADERS })
}
const rooms = env.GAME_ROOMS
if (rooms === undefined) {
return refusalResponse(RoomRefusal.cases.Unavailable.make({}))
}
if (url.pathname === ROOM_PATHS.quick) {
const matchmakers = env.MATCHMAKER
if (matchmakers === undefined) {
return refusalResponse(RoomRefusal.cases.Unavailable.make({}))
}
if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
return json(426, '{}')
}
const stub = matchmakers.get(matchmakers.idFromName(MATCHMAKER_NAME))
const response = yield* tryCall('open the quick play socket', () =>
stub.fetch(request.url, {
headers: Object.fromEntries(request.headers.entries()),
}),
)
return new Response(null, {
status: response.status,
webSocket: response.webSocket,
})
}
if (url.pathname === ROOM_PATHS.socket) {
const maybeCode = normalizeRoomCode(url.searchParams.get('code') ?? '')
if (Option.isNone(maybeCode)) {
return refusalResponse(RoomRefusal.cases.NoRoom.make({}))
}
if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') {
return json(426, '{}')
}
const stub = rooms.get(rooms.idFromName(roomScopeId(maybeCode.value)))
const response = yield* tryCall('open the room socket', () =>
stub.fetch(request.url, {
headers: {
...Object.fromEntries(request.headers.entries()),
[ROOM_CODE_HEADER]: maybeCode.value,
},
}),
)
return new Response(null, {
status: response.status,
webSocket: response.webSocket,
})
}
if (request.method !== 'POST') {
return json(405, '{}')
}
const nowMs = yield* Clock.currentTimeMillis
const claims = yield* Effect.result(
Option.match(bearerOf(request), {
onNone: () => verifyToken(env.SYNC_SECRET, '', nowMs),
onSome: token => verifyToken(env.SYNC_SECRET, token, nowMs),
}),
)
if (Result.isFailure(claims)) {
return refusalResponse(
RoomRefusal.cases.Unauthorized.make({ reason: claims.failure.reason }),
)
}
if (!(yield* isWithinRate(env, request))) {
return refusalResponse(RoomRefusal.cases.RateLimited.make({}))
}
const playerId = claims.success.playerId
const text = yield* tryCall('read the body', () => request.text())
if (url.pathname === ROOM_PATHS.create) {
const name = Option.match(
Schema.decodeOption(Schema.fromJsonString(CreateRequest))(text),
{ onNone: () => '', onSome: body => body.name },
)
const called = yield* createRoomIn(rooms, playerId, name, 'Private')
return answer(called.status, called.text)
}
if (url.pathname === ROOM_PATHS.join) {
const maybeBody = Schema.decodeOption(Schema.fromJsonString(JoinRequest))(
text,
)
const maybeCode = Option.flatMap(maybeBody, body =>
normalizeRoomCode(body.code),
)
if (Option.isNone(maybeCode) || Option.isNone(maybeBody)) {
return refusalResponse(RoomRefusal.cases.NoRoom.make({}))
}
const called = yield* joinRoomIn(
rooms,
maybeCode.value,
playerId,
maybeBody.value.name,
)
return answer(called.status, called.text)
}
return json(404, '{}')
})
// NOTE: the /room paths. Every failure is answered here.
export const routeRoom = (
request: Request,
env: GameRoomBindings,
): Effect.Effect<Option.Option<Response>> =>