@netifyjs/protocol 1.0.0-alpha.2 → 1.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/package.json +2 -2
  2. package/src/codec/index.ts +82 -157
  3. package/src/dispatch/dispatcher/index.ts +116 -33
  4. package/src/dispatch/session/index.ts +9 -3
  5. package/src/index.ts +2 -4
  6. package/src/photon/balancing/codec/index.ts +27 -53
  7. package/src/photon/balancing/format/authenticate/request/index.ts +52 -6
  8. package/src/photon/balancing/format/friends/request/index.ts +21 -5
  9. package/src/photon/balancing/format/game/create/request/index.ts +45 -8
  10. package/src/photon/balancing/format/game/debug/request/index.ts +19 -4
  11. package/src/photon/balancing/format/game/join/request/index.ts +65 -13
  12. package/src/photon/balancing/format/game/list/request/index.ts +29 -3
  13. package/src/photon/balancing/format/game/random/request/index.ts +58 -10
  14. package/src/photon/balancing/format/groups/request/index.ts +19 -3
  15. package/src/photon/balancing/format/index.ts +7 -0
  16. package/src/photon/balancing/format/leave/request/index.ts +19 -3
  17. package/src/photon/balancing/format/lobby/join/request/index.ts +23 -3
  18. package/src/photon/balancing/format/lobby/stats/request/index.ts +19 -3
  19. package/src/photon/balancing/format/once/request/index.ts +31 -8
  20. package/src/photon/balancing/format/properties/get/request/index.ts +31 -4
  21. package/src/photon/balancing/format/properties/set/request/index.ts +36 -7
  22. package/src/photon/balancing/format/raise/request/index.ts +76 -10
  23. package/src/photon/balancing/format/reader/index.ts +75 -6
  24. package/src/photon/balancing/format/regions/request/index.ts +16 -1
  25. package/src/photon/balancing/format/rpc/request/index.ts +26 -3
  26. package/src/photon/balancing/format/settings/request/index.ts +15 -2
  27. package/src/photon/balancing/format/shared/credentials/index.ts +77 -33
  28. package/src/photon/balancing/format/shared/lobby/index.ts +41 -5
  29. package/src/photon/balancing/format/shared/options/index.ts +56 -24
  30. package/src/photon/balancing/format/table/index.ts +399 -0
  31. package/src/photon/balancing/index.ts +11 -1
  32. package/src/photon/balancing/travel/index.ts +15 -12
  33. package/src/photon/binary/v18/index.ts +26 -1
  34. package/src/photon/binary/value/index.ts +52 -3
  35. package/src/photon/client/connection/index.ts +6 -6
  36. package/src/photon/cluster/back/index.ts +32 -45
  37. package/src/photon/cluster/dresser/index.ts +7 -8
  38. package/src/photon/cluster/front/index.ts +25 -49
  39. package/src/photon/cluster/grid/index.ts +1 -1
  40. package/src/photon/cluster/mover/index.ts +12 -12
  41. package/src/photon/cluster/press/index.ts +2 -18
  42. package/src/photon/cluster/route/game/index.ts +9 -11
  43. package/src/photon/cluster/route/master/index.ts +15 -34
  44. package/src/photon/cluster/route/name/index.ts +4 -21
  45. package/src/photon/cluster/seat/game/index.ts +6 -26
  46. package/src/photon/cluster/seat/master/index.ts +1 -1
  47. package/src/photon/cluster/sessions/index.ts +5 -6
  48. package/src/photon/cluster/spread/index.ts +8 -147
  49. package/src/photon/enet/client/index.ts +1 -8
  50. package/src/photon/enet/gateway/index.ts +5 -15
  51. package/src/photon/enet/index.ts +1 -1
  52. package/src/photon/enet/link/index.ts +34 -15
  53. package/src/photon/enet/outbound/index.ts +279 -0
  54. package/src/photon/enet/peer/index.ts +59 -0
  55. package/src/photon/enet/transport/index.ts +8 -24
  56. package/src/photon/game/admission/index.ts +353 -0
  57. package/src/photon/game/bag/index.ts +13 -0
  58. package/src/photon/game/broadcast/index.ts +79 -0
  59. package/src/photon/game/editor/index.ts +446 -0
  60. package/src/photon/game/gate/index.ts +9 -8
  61. package/src/photon/game/handler/index.ts +30 -3
  62. package/src/photon/game/history/index.ts +234 -0
  63. package/src/photon/game/hooked/index.ts +16 -15
  64. package/src/photon/game/index.ts +12 -1
  65. package/src/photon/game/lifecycle/index.ts +193 -0
  66. package/src/photon/game/peer/index.ts +1 -10
  67. package/src/photon/game/properties/index.ts +342 -0
  68. package/src/photon/game/room/index.ts +435 -1793
  69. package/src/photon/game/rooms/index.ts +2 -1
  70. package/src/photon/game/seats/index.ts +237 -0
  71. package/src/photon/game/server/index.ts +12 -2
  72. package/src/photon/game/services/index.ts +41 -0
  73. package/src/photon/game/settings/index.ts +22 -0
  74. package/src/photon/game/snapshot/index.ts +133 -0
  75. package/src/photon/game/throttle/index.ts +60 -0
  76. package/src/photon/game/touch/index.ts +2 -5
  77. package/src/photon/game/venue/index.ts +31 -0
  78. package/src/photon/master/application/index.ts +7 -0
  79. package/src/photon/master/gate/index.ts +12 -8
  80. package/src/photon/master/handler/index.ts +36 -748
  81. package/src/photon/master/index.ts +5 -0
  82. package/src/photon/master/list/sql/index.ts +37 -3
  83. package/src/photon/master/listing/index.ts +133 -0
  84. package/src/photon/master/lobby/index.ts +9 -0
  85. package/src/photon/master/login/index.ts +424 -0
  86. package/src/photon/master/matchmaking/index.ts +282 -0
  87. package/src/photon/master/query/index.ts +45 -0
  88. package/src/photon/master/redirect/index.ts +8 -7
  89. package/src/photon/master/services/index.ts +35 -0
  90. package/src/photon/master/settings/index.ts +44 -0
  91. package/src/photon/master/sql/cost/index.ts +263 -0
  92. package/src/photon/master/sql/index.ts +1 -0
  93. package/src/photon/message/binary/index.ts +35 -1
  94. package/src/photon/message/client/index.ts +14 -11
  95. package/src/photon/message/format/index.ts +9 -0
  96. package/src/photon/message/handler/index.ts +48 -63
  97. package/src/photon/message/pipeline/index.ts +12 -12
  98. package/src/photon/message/server/index.ts +87 -43
  99. package/src/photon/message/watch/index.ts +127 -15
  100. package/src/photon/server/config/index.ts +5 -0
  101. package/src/photon/server/deferral/index.ts +57 -0
  102. package/src/photon/server/host/index.ts +36 -10
  103. package/src/photon/server/index.ts +1 -0
  104. package/src/photon/server/listeners/index.ts +11 -0
  105. package/src/photon/tcp/client/index.ts +1 -1
  106. package/src/photon/tcp/codec/index.ts +41 -38
  107. package/src/photon/tcp/framing/index.ts +24 -4
  108. package/src/photon/tcp/server/index.ts +4 -4
  109. package/src/photon/websocket/bridge/index.ts +16 -20
  110. package/src/photon/websocket/message/index.ts +27 -39
  111. package/src/photon/websocket/path/index.ts +2 -5
  112. package/src/scale/batch/index.ts +14 -6
  113. package/src/scale/fanout/index.ts +6 -6
  114. package/src/scale/index.ts +2 -4
  115. package/src/scale/outbound/index.ts +192 -0
  116. package/src/scale/relay/index.ts +24 -16
  117. package/src/scale/sink/index.ts +6 -11
  118. package/src/scale/transport/index.ts +27 -44
  119. package/src/scale/tunnel/index.ts +56 -86
  120. package/src/smartfox/common/bluebox/gateway/index.ts +401 -0
  121. package/src/smartfox/common/bluebox/index.ts +4 -0
  122. package/src/smartfox/{x2 → common}/bluebox/transport/index.ts +36 -23
  123. package/src/smartfox/common/index.ts +5 -0
  124. package/src/smartfox/common/strikes/index.ts +74 -0
  125. package/src/smartfox/pro/bluebox/index.ts +176 -4
  126. package/src/smartfox/pro/codec/index.ts +8 -7
  127. package/src/smartfox/pro/escalation/index.ts +28 -20
  128. package/src/smartfox/pro/flood/index.ts +2 -2
  129. package/src/smartfox/pro/format/extension/raw/index.ts +12 -2
  130. package/src/smartfox/pro/handler/chat/index.ts +11 -8
  131. package/src/smartfox/pro/handler/login/index.ts +2 -25
  132. package/src/smartfox/pro/handler/shared/index.ts +4 -3
  133. package/src/smartfox/pro/index.ts +11 -5
  134. package/src/smartfox/pro/login/gate/index.ts +166 -0
  135. package/src/smartfox/pro/login/index.ts +1 -0
  136. package/src/smartfox/pro/moderation/index.ts +220 -0
  137. package/src/smartfox/pro/options/index.ts +5 -5
  138. package/src/smartfox/pro/protocol/index.ts +62 -8
  139. package/src/smartfox/pro/web/index.ts +33 -26
  140. package/src/smartfox/pro/zone/index.ts +59 -282
  141. package/src/smartfox/pro/zones/index.ts +3 -3
  142. package/src/smartfox/x2/bluebox/index.ts +149 -4
  143. package/src/smartfox/x2/chat/index.ts +9 -19
  144. package/src/smartfox/x2/codec/index.ts +34 -40
  145. package/src/smartfox/x2/config/index.ts +6 -1
  146. package/src/smartfox/x2/data/array/index.ts +96 -60
  147. package/src/smartfox/x2/data/object/index.ts +144 -82
  148. package/src/smartfox/x2/data/serializer/index.ts +41 -23
  149. package/src/smartfox/x2/flood/gate/index.ts +19 -13
  150. package/src/smartfox/x2/format/buddy/init/response/index.ts +4 -3
  151. package/src/smartfox/x2/format/find/rooms/response/index.ts +4 -3
  152. package/src/smartfox/x2/format/find/users/response/index.ts +4 -3
  153. package/src/smartfox/x2/format/group/subscribe/response/index.ts +4 -3
  154. package/src/smartfox/x2/format/login/response/index.ts +4 -3
  155. package/src/smartfox/x2/format/mmo/position/response/index.ts +8 -6
  156. package/src/smartfox/x2/format/room/join/response/index.ts +4 -3
  157. package/src/smartfox/x2/games/index.ts +35 -8
  158. package/src/smartfox/x2/hall/index.ts +0 -6
  159. package/src/smartfox/x2/handler/session/index.ts +1 -1
  160. package/src/smartfox/x2/index.ts +8 -3
  161. package/src/smartfox/x2/member/index.ts +10 -3
  162. package/src/smartfox/x2/packet/login/response/index.ts +12 -0
  163. package/src/smartfox/x2/protocol/index.ts +11 -1
  164. package/src/smartfox/x2/rooms/index.ts +1 -2
  165. package/src/smartfox/x2/sessions/index.ts +6 -0
  166. package/src/smartfox/x2/udp/index.ts +61 -24
  167. package/src/smartfox/x2/web/index.ts +35 -17
  168. package/src/smartfox/x2/websocket/index.ts +18 -36
  169. package/src/smartfox/x2/zone/index.ts +77 -28
  170. package/src/smartfox/x2/zones/index.ts +17 -5
  171. package/src/photon/enet/handler/index.ts +0 -65
  172. package/src/scale/hosted/index.ts +0 -68
  173. package/src/scale/outlet/index.ts +0 -121
  174. package/src/smartfox/pro/bluebox/gateway/index.ts +0 -310
  175. package/src/smartfox/pro/bluebox/session/index.ts +0 -63
  176. package/src/smartfox/pro/bluebox/transport/index.ts +0 -104
  177. package/src/smartfox/x2/bluebox/gateway/index.ts +0 -315
  178. /package/src/smartfox/{x2 → common}/bluebox/session/index.ts +0 -0
  179. /package/src/smartfox/{pro → common}/counters/index.ts +0 -0
  180. /package/src/smartfox/{pro → common}/counters/memory/index.ts +0 -0
  181. /package/src/smartfox/{pro → common}/counters/offender/index.ts +0 -0
  182. /package/src/smartfox/{pro → common}/counters/store/index.ts +0 -0
  183. /package/src/smartfox/{pro → common}/sequence/index.ts +0 -0
@@ -1,110 +1,54 @@
1
+ import type { Channel } from '@netifyjs/netify'
2
+
1
3
  import { ActorProperty } from '../../balancing/code/actor/index.ts'
2
4
  import { EventCaching } from '../../balancing/code/caching/index.ts'
3
5
  import { ErrorCode } from '../../balancing/code/error/index.ts'
4
- import { EventRange } from '../../balancing/code/event/index.ts'
5
6
  import { GameProperty } from '../../balancing/code/game/index.ts'
6
7
  import { JoinMode } from '../../balancing/code/join/index.ts'
7
8
  import { ErrorMessage } from '../../balancing/code/message/index.ts'
8
9
  import { ReceiverGroup } from '../../balancing/code/receiver/index.ts'
9
10
  import { RoomOptionFlag } from '../../balancing/code/room/index.ts'
10
- import { WebFlag } from '../../balancing/code/web/index.ts'
11
11
  import { RoomEntry } from '../../balancing/entity/entry/index.ts'
12
- import { Lobby } from '../../balancing/entity/lobby/index.ts'
12
+ import { RaiseEventRequestFormat } from '../../balancing/format/raise/request/index.ts'
13
13
  import { CustomEvent } from '../../balancing/packet/event/custom/index.ts'
14
14
  import { ErrorInfoEvent } from '../../balancing/packet/event/error/index.ts'
15
15
  import { JoinEvent } from '../../balancing/packet/event/join/index.ts'
16
16
  import { LeaveEvent } from '../../balancing/packet/event/leave/index.ts'
17
17
  import { PropertiesChangedEvent } from '../../balancing/packet/event/properties/index.ts'
18
- import { CacheSliceChangedEvent } from '../../balancing/packet/event/slice/index.ts'
19
18
  import type { ChangeGroupsRequest } from '../../balancing/packet/groups/request/index.ts'
20
19
  import type { LeaveRequest } from '../../balancing/packet/leave/request/index.ts'
21
20
  import { LeaveResponse } from '../../balancing/packet/leave/response/index.ts'
22
21
  import type { GetPropertiesRequest } from '../../balancing/packet/properties/get/request/index.ts'
23
- import { GetPropertiesResponse } from '../../balancing/packet/properties/get/response/index.ts'
24
22
  import type { SetPropertiesRequest } from '../../balancing/packet/properties/set/request/index.ts'
25
23
  import { SetPropertiesResponse } from '../../balancing/packet/properties/set/response/index.ts'
26
24
  import type { RaiseEventRequest } from '../../balancing/packet/raise/request/index.ts'
27
25
  import { RaiseEventResponse } from '../../balancing/packet/raise/response/index.ts'
28
26
  import { PhotonHashtable } from '../../binary/hashtable/index.ts'
29
- import { Kind } from '../../binary/kind/index.ts'
30
- import { Shape } from '../../binary/shape/index.ts'
31
27
  import { PhotonValue } from '../../binary/value/index.ts'
32
28
  import { LeaveReason } from '../../hooks/reason/index.ts'
33
- import type { HookSender } from '../../hooks/sender/index.ts'
34
- import { JsonKeys } from '../../message/json/keys/index.ts'
35
- import type { ExcludedUser } from '../../registry/index.ts'
36
- import { Actor } from '../actor/index.ts'
37
- import type { Authenticator } from '../authenticator/index.ts'
29
+ import type { Actor } from '../actor/index.ts'
30
+ import { Admission } from '../admission/index.ts'
38
31
  import { PropertyBag } from '../bag/index.ts'
39
- import { ActorCache, RoomCache } from '../cache/index.ts'
40
- import type { Alarm, Clock } from '../clock/index.ts'
41
- import { EntrySetup } from '../entry/index.ts'
32
+ import { PropertyEditor } from '../editor/index.ts'
33
+ import type { EntrySetup } from '../entry/index.ts'
42
34
  import { Fault } from '../fault/index.ts'
43
- import { InterestGroups } from '../groups/index.ts'
35
+ import { History } from '../history/index.ts'
36
+ import { Lifecycle } from '../lifecycle/index.ts'
44
37
  import type { GamePeer } from '../peer/index.ts'
45
- import type { GameChanges, GameSummary, Herald } from '../report/index.ts'
46
- import type { GameConfiguration } from '../settings/index.ts'
47
- import { SharedFrames } from '../shared/index.ts'
48
- import type { ActorSnapshot, RoomSnapshot } from '../snapshot/index.ts'
38
+ import { RoomProperties } from '../properties/index.ts'
39
+ import type { GameChanges, GameSummary } from '../report/index.ts'
40
+ import { Seats } from '../seats/index.ts'
41
+ import type { RoomServices } from '../services/index.ts'
42
+ import { RoomArchive } from '../snapshot/index.ts'
49
43
  import { JoinStage } from '../stage/index.ts'
50
- import { WellKnownProperties } from '../wellknown/index.ts'
51
-
52
- /**
53
- * What every room of a Game Server shares
54
- */
55
- export type RoomServices = {
56
- /**
57
- * Limits and waits
58
- */
59
- readonly configuration: GameConfiguration
60
-
61
- /**
62
- * Tells the time and runs the waits
63
- */
64
- readonly clock: Clock
65
-
66
- /**
67
- * Tells the Master what happens
68
- */
69
- readonly herald: Herald
70
-
71
- /**
72
- * Compares the tokens of two connections
73
- */
74
- readonly authenticator: Authenticator
75
-
76
- /**
77
- * Posts the WebHooks, or null
78
- */
79
- readonly hooks: HookSender | null
80
-
81
- /**
82
- * Encodes an event once for the clients that read the same bytes, or null
83
- */
84
- readonly shared: SharedFrames | null
85
- }
44
+ import { Throttle } from '../throttle/index.ts'
45
+ import type { Venue } from '../venue/index.ts'
86
46
 
87
47
  /**
88
48
  * One game on a Game Server
89
49
  * @class
90
50
  */
91
- export class Room {
92
- /**
93
- * A player time to live that never runs out
94
- */
95
- protected static readonly FOREVER: number = 2 ** 31 - 1
96
-
97
- /**
98
- * Lowest property code the server owns
99
- */
100
- private static readonly LOWEST_WELL_KNOWN: number = 235
101
-
102
- /**
103
- * How a GUID user id looks
104
- */
105
- private static readonly GUID: RegExp =
106
- /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i
107
-
51
+ export class Room implements Venue {
108
52
  /**
109
53
  * Its name
110
54
  */
@@ -120,110 +64,55 @@ export class Room {
120
64
  */
121
65
  public readonly version: string
122
66
 
123
- /**
124
- * Whether it's gone for good
125
- */
126
- public closed: boolean
127
-
128
67
  /**
129
68
  * What every room shares
130
69
  */
131
70
  protected readonly services: RoomServices
132
71
 
133
72
  /**
134
- * Takes the room off the server's list
135
- */
136
- private readonly dispose: (room: Room) => void
137
-
138
- /**
139
- * Its own properties
140
- */
141
- private readonly properties: PropertyBag
142
-
143
- /**
144
- * Connected actors in the order they came
145
- */
146
- protected readonly active: Actor[]
147
-
148
- /**
149
- * The connected actor of each connection
150
- */
151
- private readonly seats: Map<GamePeer, Actor>
152
-
153
- /**
154
- * Actors that are away, in the order they went
155
- */
156
- protected readonly inactive: Actor[]
157
-
158
- /**
159
- * Connections that keep it alive
160
- */
161
- private readonly references: Set<GamePeer>
162
-
163
- /**
164
- * Who hears which group
165
- */
166
- private readonly groups: InterestGroups
167
-
168
- /**
169
- * Events kept for the whole room
170
- */
171
- private readonly roomCache: RoomCache
172
-
173
- /**
174
- * Events actors keep about themselves
175
- */
176
- private readonly actorCache: ActorCache
177
-
178
- /**
179
- * User ids with a seat kept
73
+ * Its own properties and options
180
74
  */
181
- private expected: string[]
75
+ protected readonly properties: RoomProperties
182
76
 
183
77
  /**
184
- * Users kept out
78
+ * Who sits in it
185
79
  */
186
- private excluded: readonly ExcludedUser[]
80
+ protected readonly seats: Seats
187
81
 
188
82
  /**
189
- * Room option bits
83
+ * Events kept for later joiners
190
84
  */
191
- private flags: number
85
+ protected readonly history: History
192
86
 
193
87
  /**
194
- * Highest actor number given out
88
+ * Keeps it alive and times the empty seats
195
89
  */
196
- private counter: number
90
+ protected readonly lifecycle: Lifecycle
197
91
 
198
92
  /**
199
- * Actor number of the master client, or 0
93
+ * Saves it and brings it back
200
94
  */
201
- private master: number
95
+ protected readonly archive: RoomArchive
202
96
 
203
97
  /**
204
- * Lobby it's listed in, or null
98
+ * Decides who gets which seat
205
99
  */
206
- private lobby: Lobby | null
100
+ private readonly admission: Admission
207
101
 
208
102
  /**
209
- * Property keys lobbies show, or null
103
+ * Reads and writes properties for clients
210
104
  */
211
- private filter: readonly PhotonValue[] | null
105
+ private readonly editor: PropertyEditor
212
106
 
213
107
  /**
214
- * Closes the empty room once its time is up, or null
108
+ * Counts forwarded operations
215
109
  */
216
- private removal: Alarm | null
110
+ private readonly throttle: Throttle
217
111
 
218
112
  /**
219
- * Clock second the forward count belongs to
220
- */
221
- private forwardSecond: number
222
-
223
- /**
224
- * Forwarded operations in that second
113
+ * Takes the room off the server's list
225
114
  */
226
- private forwardCount: number
115
+ private readonly dispose: (room: Room) => void
227
116
 
228
117
  /**
229
118
  * @param name its name
@@ -240,106 +129,44 @@ export class Room {
240
129
  dispose: (room: Room) => void,
241
130
  ) {
242
131
  const configuration = services.configuration
132
+ const properties = new RoomProperties()
133
+ const seats = new Seats()
134
+ const history = new History(configuration, seats, this)
135
+ const lifecycle = new Lifecycle(seats, properties, services.clock, this)
136
+ const throttle = new Throttle(configuration, services.clock)
243
137
 
244
138
  this.name = name
245
139
  this.application = application
246
140
  this.version = version
247
- this.closed = false
248
141
  this.services = services
249
- this.dispose = dispose
250
- this.properties = PropertyBag.of()
251
- this.active = []
252
- this.seats = new Map<GamePeer, Actor>()
253
- this.inactive = []
254
- this.references = new Set<GamePeer>()
255
- this.groups = new InterestGroups()
256
- this.roomCache = new RoomCache(
257
- configuration.eventCacheLimit,
258
- configuration.sliceLimit,
259
- )
260
- this.actorCache = new ActorCache(configuration.actorEventCacheLimit)
261
- this.expected = []
262
- this.excluded = []
263
- this.flags = 0
264
- this.counter = 0
265
- this.master = 0
266
- this.lobby = null
267
- this.filter = null
268
- this.removal = null
269
- this.forwardSecond = 0
270
- this.forwardCount = 0
271
-
272
- this.properties.set(Room.key(GameProperty.MAX_PLAYERS), PhotonValue.byte(0))
273
- this.properties.set(Room.key(GameProperty.IS_OPEN), PhotonValue.bool(true))
274
- this.properties.set(
275
- Room.key(GameProperty.IS_VISIBLE),
276
- PhotonValue.bool(true),
142
+ this.properties = properties
143
+ this.seats = seats
144
+ this.history = history
145
+ this.lifecycle = lifecycle
146
+ this.archive = new RoomArchive(properties, seats, history)
147
+ this.admission = new Admission(
148
+ seats,
149
+ properties,
150
+ history,
151
+ lifecycle,
152
+ services,
277
153
  )
278
- }
279
-
280
- /**
281
- * The key of a well-known property
282
- * @param code which property
283
- */
284
- private static key(code: number): PhotonValue {
285
- return PhotonValue.byte(code)
286
- }
287
-
288
- /**
289
- * Whether a property is one a saved room keeps outside its table
290
- * @param key typed key
291
- */
292
- private static wellKnown(key: PhotonValue): boolean {
293
- const code = key.kind === Kind.BYTE ? (key.integer() ?? 0) : 0
294
-
295
- return (
296
- code >= Room.LOWEST_WELL_KNOWN &&
297
- code !== GameProperty.PROPS_LISTED_IN_LOBBY
154
+ this.editor = new PropertyEditor(
155
+ properties,
156
+ seats,
157
+ throttle,
158
+ services,
159
+ this,
298
160
  )
161
+ this.throttle = throttle
162
+ this.dispose = dispose
299
163
  }
300
164
 
301
165
  /**
302
- * The refusal for a user the room keeps out
303
- * @param ban who's kept out and why
304
- */
305
- private static banned(ban: ExcludedUser): Fault {
306
- switch (ban.reason) {
307
- case 1:
308
- return Fault.of(
309
- ErrorCode.JOIN_FAILED_FOUND_EXCLUDED_USER_ID,
310
- 'User {0} is banned in this game',
311
- ban.userId,
312
- )
313
- case 2:
314
- return Fault.of(
315
- ErrorCode.JOIN_FAILED_FOUND_EXCLUDED_USER_ID,
316
- 'User {0} is global banned',
317
- ban.userId,
318
- )
319
- default:
320
- return Fault.of(
321
- ErrorCode.JOIN_FAILED_FOUND_EXCLUDED_USER_ID,
322
- 'Unknown reason {0} for excluding ',
323
- ban.reason,
324
- )
325
- }
326
- }
327
-
328
- /**
329
- * A table with one well-known property
330
- * @param code which property
331
- * @param value what it holds
332
- */
333
- private static single(code: number, value: PhotonValue): PhotonHashtable {
334
- return PhotonHashtable.of().set(Room.key(code), value)
335
- }
336
-
337
- /**
338
- * User ids as a property value
339
- * @param users who has a seat kept
166
+ * Whether it's gone for good
340
167
  */
341
- private static names(users: readonly string[]): PhotonValue {
342
- return PhotonValue.array(Shape.string(), [...users])
168
+ public get closed(): boolean {
169
+ return this.lifecycle.closed
343
170
  }
344
171
 
345
172
  /**
@@ -348,137 +175,22 @@ export class Room {
348
175
  * @param setup the request as the room needs it
349
176
  */
350
177
  public enter(peer: GamePeer, setup: EntrySetup): void {
351
- const fresh = this.counter === 0
178
+ const fresh = this.seats.counter === 0
352
179
  if (!this.claim(peer, setup, fresh)) return
353
180
 
354
181
  this.settle(peer, setup, fresh)
355
182
  }
356
183
 
357
- /**
358
- * Holds the room for a connection and says whether its request may go on
359
- * @param peer who's asking
360
- * @param setup the request as the room needs it
361
- * @param fresh whether the request starts the room
362
- */
363
- protected claim(peer: GamePeer, setup: EntrySetup, fresh: boolean): boolean {
364
- peer.stage = JoinStage.CREATING_OR_LOADING_GAME
365
- peer.room = this
366
- this.references.add(peer)
367
-
368
- const unfit = fresh ? this.founding(setup) : null
369
- if (unfit === null) return true
370
-
371
- this.reject(peer, setup, unfit, null)
372
- return false
373
- }
374
-
375
- /**
376
- * Seats a connection that holds the room, or tells it why not
377
- * @param peer who's asking
378
- * @param setup the request as the room needs it
379
- * @param fresh whether the request starts the room
380
- */
381
- protected settle(peer: GamePeer, setup: EntrySetup, fresh: boolean): void {
382
- peer.stage = JoinStage.CONVERTING_PARAMS
383
- const unfit = fresh ? null : this.admission(peer, setup)
384
- if (unfit !== null) {
385
- this.reject(peer, setup, unfit, null)
386
- return
387
- }
388
-
389
- if (fresh) {
390
- this.lobby = setup.lobby
391
- this.list(setup.properties)
392
- }
393
-
394
- peer.stage = JoinStage.CHECKING_CACHE_SLICE
395
- const slice = setup.cacheSliceIndex
396
- if (slice !== null && !this.roomCache.has(slice)) {
397
- this.reject(
398
- peer,
399
- setup,
400
- Fault.invalid(ErrorMessage.CACHE_SLICE_NOT_AVAILABLE, slice),
401
- null,
402
- )
403
- return
404
- }
405
-
406
- peer.stage = JoinStage.ADDING_ACTOR
407
- const seat = this.seat(peer, setup)
408
- if (seat instanceof Fault) {
409
- this.reject(peer, setup, seat, null)
410
- return
411
- }
412
-
413
- const actor = seat === null ? this.add(peer) : this.reactivate(seat, peer)
414
-
415
- this.removal?.cancel()
416
- this.removal = null
417
- if (this.master === 0) this.elect()
418
-
419
- peer.stage = JoinStage.CHECK_AFTER_JOIN_PARAMS
420
- const unfurnished = fresh ? this.furnish(setup) : null
421
- const reserved =
422
- unfurnished === null ? this.reserve(setup.expectedUsers ?? []) : null
423
- if (reserved === null) {
424
- this.reject(
425
- peer,
426
- setup,
427
- unfurnished ??
428
- Fault.of(ErrorCode.SLOT_ERROR, ErrorMessage.CANT_ADD_SLOTS),
429
- actor,
430
- )
431
- return
432
- }
433
-
434
- peer.stage = JoinStage.APPLY_ACTOR_PROPERTIES
435
- actor.properties.merge(setup.actorProperties)
436
-
437
- const extended = !fresh && reserved.length > 0
438
- if (extended) {
439
- this.properties.set(
440
- Room.key(GameProperty.EXPECTED_USERS),
441
- Room.names(this.expected),
442
- )
443
- }
444
-
445
- peer.stage = JoinStage.SENDING_USER_RESPONSE
446
- peer.send(setup.accept(this.entry(actor, setup)))
447
-
448
- peer.stage = JoinStage.PUBLISHING_EVENTS
449
- this.announce(actor, setup)
450
- if (extended) {
451
- this.tell(
452
- this.active,
453
- PropertiesChangedEvent.of(
454
- actor.number,
455
- 0,
456
- Room.single(GameProperty.EXPECTED_USERS, Room.names(this.expected)),
457
- ),
458
- )
459
- }
460
-
461
- peer.stage = JoinStage.EVENTS_PUBLISHED
462
- this.replay(peer, slice ?? 0)
463
-
464
- peer.stage = JoinStage.COMPLETE
465
- const arrival: GameChanges = {
466
- newUsers: [actor.userId],
467
- expectedUsers: extended ? [...this.expected] : null,
468
- }
469
- this.report(fresh ? this.describe() : arrival)
470
- }
471
-
472
184
  /**
473
185
  * Takes a connection out because it asked
474
186
  * @param peer who's leaving
475
187
  * @param packet what the client sent
476
188
  */
477
189
  public leave(peer: GamePeer, packet: LeaveRequest): void {
478
- const actor = this.playing(peer)
190
+ const actor = this.seats.playing(peer)
479
191
 
480
192
  if (actor !== null) {
481
- if (packet.isInactive && this.playerTtl !== 0) {
193
+ if (packet.isInactive && this.properties.playerTtl !== 0) {
482
194
  this.deactivate(actor)
483
195
  } else {
484
196
  this.remove(actor, false)
@@ -495,10 +207,13 @@ export class Room {
495
207
  * @param peer who's gone
496
208
  */
497
209
  public disconnected(peer: GamePeer): void {
498
- const actor = this.playing(peer)
210
+ const actor = this.seats.playing(peer)
499
211
 
500
212
  if (actor !== null) {
501
- if (peer.stage === JoinStage.COMPLETE && this.playerTtl !== 0) {
213
+ if (
214
+ peer.stage === JoinStage.COMPLETE &&
215
+ this.properties.playerTtl !== 0
216
+ ) {
502
217
  this.deactivate(actor)
503
218
  } else {
504
219
  this.remove(actor, false)
@@ -540,44 +255,7 @@ export class Room {
540
255
  * @param packet what the client sent
541
256
  */
542
257
  public inspect(peer: GamePeer, packet: GetPropertiesRequest): void {
543
- const kinds = packet.kinds ?? 0
544
- const publish = this.has(RoomOptionFlag.PUBLISH_USER_ID)
545
- let game: PhotonHashtable | null = null
546
- let actors: PhotonHashtable | null = null
547
-
548
- if ((kinds & 0x01) !== 0) {
549
- const keys = packet.gameProperties
550
- game =
551
- keys === null
552
- ? this.properties.all()
553
- : this.properties.pick(this.keys(keys, peer.json, JsonKeys.ROOM))
554
- }
555
-
556
- if ((kinds & 0x02) !== 0) {
557
- const keys = packet.actorProperties
558
- const wanted =
559
- packet.actors === null ? null : new Set<number>(packet.actors)
560
- actors = PhotonHashtable.of()
561
-
562
- for (const actor of this.active) {
563
- if (wanted !== null && !wanted.has(actor.number)) continue
564
-
565
- const table =
566
- keys === null
567
- ? actor.properties.all()
568
- : actor.properties.pick(this.keys(keys, peer.json, JsonKeys.ACTOR))
569
- if (keys === null && publish) {
570
- table.set(
571
- Room.key(ActorProperty.USER_ID),
572
- PhotonValue.string(actor.userId),
573
- )
574
- }
575
-
576
- actors.set(PhotonValue.int(actor.number), PhotonValue.hashtable(table))
577
- }
578
- }
579
-
580
- peer.send(GetPropertiesResponse.success(actors, game).to(packet))
258
+ this.editor.inspect(peer, packet)
581
259
  }
582
260
 
583
261
  /**
@@ -586,11 +264,12 @@ export class Room {
586
264
  * @param packet what the client sent
587
265
  */
588
266
  public regroup(peer: GamePeer, packet: ChangeGroupsRequest): void {
589
- const actor = this.playing(peer)
267
+ const actor = this.seats.playing(peer)
590
268
  if (actor === null) return
591
269
 
592
- if (packet.remove !== null) this.groups.remove(actor, packet.remove)
593
- if (packet.add !== null) this.groups.add(actor, packet.add)
270
+ const groups = this.seats.groups
271
+ if (packet.remove !== null) groups.remove(actor, packet.remove)
272
+ if (packet.add !== null) groups.add(actor, packet.add)
594
273
  }
595
274
 
596
275
  /**
@@ -602,7 +281,7 @@ export class Room {
602
281
  const quiet = configuration.lastTouchLimit * 1000
603
282
  const idle = configuration.noActivityLimit * 3_600_000
604
283
 
605
- for (const actor of [...this.active]) {
284
+ for (const actor of [...this.seats.active]) {
606
285
  const peer = actor.peer
607
286
  if (peer === null) continue
608
287
  if (now - peer.touched <= quiet && now - peer.operated <= idle) continue
@@ -618,22 +297,26 @@ export class Room {
618
297
  */
619
298
  public describe(): GameChanges {
620
299
  const herald = this.services.herald
621
- const everyone = [...this.active, ...this.inactive]
300
+ const properties = this.properties
301
+ const seats = this.seats
302
+ const filter = properties.filter
622
303
 
623
304
  return {
624
305
  reinitialize: true,
625
- newUsers: everyone.map<string>((actor: Actor): string => actor.userId),
626
- inactiveUsers: this.inactive.map<string>(
306
+ newUsers: seats.everyone.map<string>(
627
307
  (actor: Actor): string => actor.userId,
628
308
  ),
629
- expectedUsers: [...this.expected],
630
- maxPlayers: this.maxPlayers,
631
- isOpen: this.isOpen,
632
- isVisible: this.isVisible,
633
- excludedUsers: [...this.excluded],
634
- checkUserIdOnJoin: this.has(RoomOptionFlag.CHECK_USER_ON_JOIN),
635
- propertyFilter: this.filter === null ? null : herald.filter(this.filter),
636
- properties: herald.properties(this.listed(this.properties.all())),
309
+ inactiveUsers: seats.inactive.map<string>(
310
+ (actor: Actor): string => actor.userId,
311
+ ),
312
+ expectedUsers: [...seats.expected],
313
+ maxPlayers: properties.maxPlayers,
314
+ isOpen: properties.isOpen,
315
+ isVisible: properties.isVisible,
316
+ excludedUsers: [...seats.excluded],
317
+ checkUserIdOnJoin: properties.has(RoomOptionFlag.CHECK_USER_ON_JOIN),
318
+ propertyFilter: filter === null ? null : herald.filter(filter),
319
+ properties: herald.properties(properties.listed(properties.bag.all())),
637
320
  }
638
321
  }
639
322
 
@@ -651,12 +334,12 @@ export class Room {
651
334
  public debug(): string {
652
335
  return (
653
336
  `Game ${this.name}: ` +
654
- `actors=${String(this.active.length)}, ` +
655
- `inactive=${String(this.inactive.length)}, ` +
656
- `master=${String(this.master)}, ` +
657
- `open=${String(this.isOpen)}, ` +
658
- `visible=${String(this.isVisible)}, ` +
659
- `cached=${String(this.roomCache.size)}`
337
+ `actors=${String(this.seats.active.length)}, ` +
338
+ `inactive=${String(this.seats.inactive.length)}, ` +
339
+ `master=${String(this.seats.master)}, ` +
340
+ `open=${String(this.properties.isOpen)}, ` +
341
+ `visible=${String(this.properties.isVisible)}, ` +
342
+ `cached=${String(this.history.size)}`
660
343
  )
661
344
  }
662
345
 
@@ -665,22 +348,10 @@ export class Room {
665
348
  * @param peer who's letting go
666
349
  */
667
350
  public release(peer: GamePeer): void {
668
- if (!this.references.delete(peer)) return
351
+ if (!this.lifecycle.forget(peer)) return
669
352
  if (peer.room === this) peer.room = null
670
- if (this.references.size > 0 || this.closed) return
671
-
672
- const wait = this.emptyRoomTtl
673
- if (wait <= 0) {
674
- this.close()
675
- return
676
- }
677
353
 
678
- this.removal?.cancel()
679
- this.removal = this.services.clock.after(wait, (): void => {
680
- this.removal = null
681
- if (this.references.size > 0 || this.active.length > 0) return
682
- this.close()
683
- })
354
+ this.lifecycle.linger()
684
355
  }
685
356
 
686
357
  /**
@@ -688,14 +359,7 @@ export class Room {
688
359
  */
689
360
  public close(): void {
690
361
  if (this.closed) return
691
- this.closed = true
692
-
693
- this.removal?.cancel()
694
- this.removal = null
695
- for (const actor of this.inactive) {
696
- actor.expiry?.cancel()
697
- actor.expiry = null
698
- }
362
+ this.lifecycle.stop()
699
363
 
700
364
  this.services.herald.remove(this.application, this.version, this.name)
701
365
  this.dispose(this)
@@ -705,382 +369,163 @@ export class Room {
705
369
  * Stops every wait without telling anyone
706
370
  */
707
371
  public halt(): void {
708
- this.closed = true
709
- this.removal?.cancel()
710
- this.removal = null
711
-
712
- for (const actor of this.inactive) {
713
- actor.expiry?.cancel()
714
- actor.expiry = null
715
- }
372
+ this.lifecycle.stop()
716
373
  }
717
374
 
718
375
  /**
719
- * Everything the room needs to come back later
376
+ * Sends one packet to several actors
377
+ * @param actors who gets it
378
+ * @param packet a typed packet
720
379
  */
721
- protected snapshot(): RoomSnapshot {
722
- const everyone = [...this.active, ...this.inactive]
723
- const properties = PhotonHashtable.of()
724
- for (const [key, value] of this.properties.all().entries()) {
725
- if (!Room.wellKnown(key)) properties.set(key, value)
726
- }
380
+ public tell(actors: readonly Actor[], packet: unknown): void {
381
+ if (actors.length === 0) return
727
382
 
728
- const groups = new Map<number, readonly number[]>()
729
- for (const id of this.groups.ids()) {
730
- groups.set(
731
- id,
732
- everyone
733
- .filter((actor: Actor): boolean => actor.groups.has(id))
734
- .map<number>((actor: Actor): number => actor.number),
735
- )
383
+ const only = actors.length === 1 ? actors[0] : undefined
384
+ if (only !== undefined) {
385
+ only.send(packet)
386
+ return
736
387
  }
737
388
 
738
- return {
739
- counter: this.counter,
740
- actors: everyone.map<ActorSnapshot>((actor: Actor): ActorSnapshot => ({
741
- number: actor.number,
742
- userId: actor.userId,
743
- active: actor.active,
744
- properties: actor.properties.all(),
745
- deactivatedAt: actor.deactivatedAt,
746
- })),
747
- properties,
748
- slices: this.roomCache.filled(),
749
- groups,
750
- emptyRoomTtl: this.emptyRoomTtl,
751
- isOpen: this.isOpen,
752
- isVisible: this.isVisible,
753
- lobbyId: this.lobby?.name ?? null,
754
- lobbyType: this.lobby?.type ?? 0,
755
- lobbyProperties: this.filter,
756
- maxPlayers: this.maxPlayers,
757
- playerTtl: this.playerTtl,
758
- slice: this.roomCache.current,
759
- flags: this.flags,
760
- excluded: this.excluded,
761
- expected: this.expected,
389
+ const channels: Channel[] = []
390
+ for (const actor of actors) {
391
+ if (actor.peer !== null) channels.push(actor.peer.channel)
762
392
  }
393
+
394
+ this.services.broadcaster.spread(channels, packet)
763
395
  }
764
396
 
765
397
  /**
766
- * Brings back a saved room with every seat empty
767
- * @param snapshot the room as it was saved
398
+ * Takes out an actor whose time away ran out
399
+ * @param actor who stayed away
768
400
  */
769
- protected restore(snapshot: RoomSnapshot): void {
770
- this.counter = snapshot.counter
771
- for (const saved of snapshot.actors ?? []) {
772
- this.inactive.push(
773
- Actor.away(
774
- saved.number,
775
- saved.userId,
776
- saved.properties,
777
- saved.deactivatedAt,
778
- ),
779
- )
780
- }
781
-
782
- if (snapshot.properties !== null) {
783
- this.properties.merge(snapshot.properties)
784
- }
401
+ public expire(actor: Actor): void {
402
+ actor.expiry = null
403
+ if (!this.lifecycle.waiting(actor)) return
785
404
 
786
- this.roomCache.load(snapshot.slices, snapshot.slice)
787
- for (const [id, numbers] of snapshot.groups ?? []) {
788
- for (const number of numbers) {
789
- this.groups.recall(this.numbered(number), id)
790
- }
791
- }
405
+ this.remove(actor, false)
406
+ }
792
407
 
793
- this.flags = snapshot.flags
794
- this.properties.deleteNull = this.has(RoomOptionFlag.DELETE_NULL_PROPS)
795
- this.revive(snapshot)
408
+ /**
409
+ * Holds the room for a connection and says whether its request may go on
410
+ * @param peer who's asking
411
+ * @param setup the request as the room needs it
412
+ * @param fresh whether the request starts the room
413
+ */
414
+ protected claim(peer: GamePeer, setup: EntrySetup, fresh: boolean): boolean {
415
+ peer.stage = JoinStage.CREATING_OR_LOADING_GAME
416
+ peer.room = this
417
+ this.lifecycle.hold(peer)
796
418
 
797
- this.lobby =
798
- snapshot.lobbyId === null
799
- ? null
800
- : Lobby.of(snapshot.lobbyId, snapshot.lobbyType)
801
- if (snapshot.lobbyProperties !== null) {
802
- this.filter = snapshot.lobbyProperties
803
- }
419
+ const unfit = fresh ? this.founding(setup) : null
420
+ if (unfit === null) return true
804
421
 
805
- this.master = 0
806
- this.excluded = [...snapshot.excluded]
807
- this.expected = [...snapshot.expected]
422
+ this.reject(peer, setup, unfit, null)
423
+ return false
808
424
  }
809
425
 
810
426
  /**
811
- * Writes the well-known properties of a saved room
812
- * @param snapshot the room as it was saved
427
+ * Seats a connection that holds the room, or tells it why not
428
+ * @param peer who's asking
429
+ * @param setup the request as the room needs it
430
+ * @param fresh whether the request starts the room
813
431
  */
814
- private revive(snapshot: RoomSnapshot): void {
815
- const properties = PhotonHashtable.of()
816
- .set(Room.key(GameProperty.IS_OPEN), PhotonValue.bool(snapshot.isOpen))
817
- .set(
818
- Room.key(GameProperty.IS_VISIBLE),
819
- PhotonValue.bool(snapshot.isVisible),
820
- )
821
- .set(Room.key(GameProperty.MASTER_CLIENT_ID), PhotonValue.int(0))
432
+ protected settle(peer: GamePeer, setup: EntrySetup, fresh: boolean): void {
433
+ const properties = this.properties
434
+ const seats = this.seats
822
435
 
823
- if (snapshot.emptyRoomTtl !== 0) {
824
- properties.set(
825
- Room.key(GameProperty.EMPTY_ROOM_TTL),
826
- PhotonValue.int(snapshot.emptyRoomTtl),
827
- )
436
+ peer.stage = JoinStage.CONVERTING_PARAMS
437
+ const unfit = fresh ? null : this.admission.refusal(peer, setup)
438
+ if (unfit !== null) {
439
+ this.reject(peer, setup, unfit, null)
440
+ return
828
441
  }
829
442
 
830
- if (snapshot.maxPlayers !== 0) {
831
- properties.set(
832
- Room.key(GameProperty.MAX_PLAYERS),
833
- PhotonValue.byte(snapshot.maxPlayers & 0xff),
834
- )
835
- }
836
-
837
- if (snapshot.playerTtl !== 0) {
838
- properties.set(
839
- Room.key(GameProperty.PLAYER_TTL),
840
- PhotonValue.int(snapshot.playerTtl),
841
- )
443
+ if (fresh) {
444
+ properties.lobby = setup.lobby
445
+ properties.list(setup.properties)
842
446
  }
843
447
 
844
- if (snapshot.expected.length > 0) {
845
- properties.set(
846
- Room.key(GameProperty.EXPECTED_USERS),
847
- Room.names(snapshot.expected),
448
+ peer.stage = JoinStage.CHECKING_CACHE_SLICE
449
+ const slice = setup.cacheSliceIndex
450
+ if (slice !== null && !this.history.has(slice)) {
451
+ this.reject(
452
+ peer,
453
+ setup,
454
+ Fault.invalid(ErrorMessage.CACHE_SLICE_NOT_AVAILABLE, slice),
455
+ null,
848
456
  )
457
+ return
849
458
  }
850
459
 
851
- this.properties.merge(properties)
852
- }
853
-
854
- /**
855
- * Starts the wait of every empty seat of a saved room
856
- */
857
- protected vacate(): void {
858
- const ttl = this.playerTtl
859
- const now = this.services.clock.now()
860
- if (ttl <= 0 || ttl >= Room.FOREVER) return
861
-
862
- for (const actor of [...this.inactive]) {
863
- const left = actor.deactivatedAt ?? now
864
- actor.deactivatedAt = left
865
-
866
- if (left + ttl <= now) {
867
- this.expire(actor)
868
- continue
869
- }
870
-
871
- actor.expiry = this.services.clock.after(left + ttl - now, (): void => {
872
- this.expire(actor)
873
- })
460
+ peer.stage = JoinStage.ADDING_ACTOR
461
+ const seat = this.admission.seat(peer, setup)
462
+ if (seat instanceof Fault) {
463
+ this.reject(peer, setup, seat, null)
464
+ return
874
465
  }
875
- }
876
-
877
- /**
878
- * Most players allowed, 0 for any number
879
- */
880
- private get maxPlayers(): number {
881
- return this.number(GameProperty.MAX_PLAYERS) ?? 0
882
- }
883
-
884
- /**
885
- * Whether players may join
886
- */
887
- private get isOpen(): boolean {
888
- return this.flag(GameProperty.IS_OPEN) ?? true
889
- }
890
-
891
- /**
892
- * Whether lobbies list it
893
- */
894
- private get isVisible(): boolean {
895
- return this.flag(GameProperty.IS_VISIBLE) ?? true
896
- }
897
-
898
- /**
899
- * How long a player's seat is kept in ms
900
- */
901
- protected get playerTtl(): number {
902
- return this.number(GameProperty.PLAYER_TTL) ?? 0
903
- }
904
-
905
- /**
906
- * How long the empty room stays in ms
907
- */
908
- private get emptyRoomTtl(): number {
909
- return this.number(GameProperty.EMPTY_ROOM_TTL) ?? 0
910
- }
911
-
912
- /**
913
- * Whether a cache passed its limit
914
- */
915
- private get discarded(): boolean {
916
- return this.roomCache.discarded || this.actorCache.discarded
917
- }
918
-
919
- /**
920
- * Whether players hear nothing about each other
921
- */
922
- private get quiet(): boolean {
923
- return this.has(RoomOptionFlag.SUPPRESS_PLAYER_INFO)
924
- }
925
-
926
- /**
927
- * Whether join and leave events stay unsent
928
- */
929
- private get suppressed(): boolean {
930
- return this.quiet || this.has(RoomOptionFlag.SUPPRESS_ROOM_EVENTS)
931
- }
932
-
933
- /**
934
- * User ids with a seat kept that never showed up
935
- */
936
- private get awaited(): number {
937
- return this.pending(this.expected)
938
- }
939
-
940
- /**
941
- * Numbers of the connected actors in the order they came
942
- */
943
- private get numbers(): readonly number[] {
944
- return this.active.map<number>((actor: Actor): number => actor.number)
945
- }
946
-
947
- /**
948
- * Whether a room option is on
949
- * @param bit which option
950
- */
951
- private has(bit: number): boolean {
952
- return (this.flags & bit) !== 0
953
- }
954
466
 
955
- /**
956
- * A whole number property of the room, or null
957
- * @param code which property
958
- */
959
- private number(code: number): number | null {
960
- return this.properties.get(Room.key(code))?.integer() ?? null
961
- }
467
+ const actor = seat === null ? seats.add(peer) : seats.reactivate(seat, peer)
962
468
 
963
- /**
964
- * A yes or no property of the room, or null
965
- * @param code which property
966
- */
967
- private flag(code: number): boolean | null {
968
- return this.properties.get(Room.key(code))?.flag() ?? null
969
- }
469
+ this.lifecycle.occupied()
470
+ if (seats.master === 0) this.elect()
970
471
 
971
- /**
972
- * Which game this is and how full
973
- */
974
- private summary(): GameSummary {
975
- return {
976
- application: this.application,
977
- version: this.version,
978
- game: this.name,
979
- lobby: this.lobby?.name ?? null,
980
- lobbyType: this.lobby?.type ?? 0,
981
- actorCount: this.active.length,
982
- inactiveCount: this.inactive.length,
472
+ peer.stage = JoinStage.CHECK_AFTER_JOIN_PARAMS
473
+ const longest = this.services.configuration.maxEmptyRoomTtl
474
+ const unfurnished = fresh ? properties.furnish(setup, longest) : null
475
+ const reserved =
476
+ unfurnished === null
477
+ ? seats.reserve(setup.expectedUsers ?? [], properties.maxPlayers)
478
+ : null
479
+ if (reserved === null) {
480
+ this.reject(
481
+ peer,
482
+ setup,
483
+ unfurnished ??
484
+ Fault.of(ErrorCode.SLOT_ERROR, ErrorMessage.CANT_ADD_SLOTS),
485
+ actor,
486
+ )
487
+ return
983
488
  }
984
- }
985
-
986
- /**
987
- * How many of some user ids have no actor
988
- * @param users user ids to look for
989
- */
990
- private pending(users: readonly string[]): number {
991
- return users.filter((user: string): boolean => this.user(user) === null)
992
- .length
993
- }
994
-
995
- /**
996
- * The connected actor of a connection, or null
997
- * @param peer the connection
998
- */
999
- protected playing(peer: GamePeer): Actor | null {
1000
- return this.seats.get(peer) ?? null
1001
- }
1002
489
 
1003
- /**
1004
- * The actor with a number, connected or away, or null
1005
- * @param number actor number
1006
- */
1007
- private numbered(number: number): Actor | null {
1008
- for (const actor of this.active) {
1009
- if (actor.number === number) return actor
1010
- }
490
+ peer.stage = JoinStage.APPLY_ACTOR_PROPERTIES
491
+ actor.properties.merge(setup.actorProperties)
1011
492
 
1012
- for (const actor of this.inactive) {
1013
- if (actor.number === number) return actor
493
+ const extended = !fresh && reserved.length > 0
494
+ if (extended) {
495
+ properties.bag.set(
496
+ RoomProperties.key(GameProperty.EXPECTED_USERS),
497
+ RoomProperties.names(seats.expected),
498
+ )
1014
499
  }
1015
500
 
1016
- return null
1017
- }
1018
-
1019
- /**
1020
- * The actor of a user, connected or away, or null
1021
- * @param userId who to look for
1022
- */
1023
- private user(userId: string): Actor | null {
1024
- return (
1025
- [...this.active, ...this.inactive].find(
1026
- (actor: Actor): boolean => actor.userId === userId,
1027
- ) ?? null
1028
- )
1029
- }
1030
-
1031
- /**
1032
- * Sends one packet to several actors
1033
- * @param actors who gets it
1034
- * @param packet a typed packet
1035
- */
1036
- protected tell(actors: readonly Actor[], packet: unknown): void {
1037
- const shared = actors.length > 1 ? this.services.shared : null
1038
- let frame: Uint8Array | null = null
1039
- let framed = false
1040
-
1041
- for (const actor of [...actors]) {
1042
- const peer = actor.peer
1043
- if (
1044
- shared === null ||
1045
- peer === null ||
1046
- !SharedFrames.reads(peer.channel)
1047
- ) {
1048
- actor.send(packet)
1049
- continue
1050
- }
1051
-
1052
- if (!framed) {
1053
- frame = shared.frame(packet)
1054
- framed = true
1055
- }
1056
-
1057
- if (frame === null) actor.send(packet)
1058
- else peer.pass(frame)
1059
- }
1060
- }
501
+ peer.stage = JoinStage.SENDING_USER_RESPONSE
502
+ peer.send(setup.accept(this.entry(actor, setup)))
1061
503
 
1062
- /**
1063
- * Why a request can't start this room, or null
1064
- * @param setup the request as the room needs it
1065
- */
1066
- private founding(setup: EntrySetup): Fault | null {
1067
- if (!this.creatable(setup)) {
1068
- return Fault.of(
1069
- ErrorCode.GAME_DOES_NOT_EXIST,
1070
- ErrorMessage.GAME_ID_DOES_NOT_EXIST,
504
+ peer.stage = JoinStage.PUBLISHING_EVENTS
505
+ this.announce(actor, setup)
506
+ if (extended) {
507
+ this.tell(
508
+ seats.active,
509
+ PropertiesChangedEvent.of(
510
+ actor.number,
511
+ 0,
512
+ RoomProperties.single(
513
+ GameProperty.EXPECTED_USERS,
514
+ RoomProperties.names(seats.expected),
515
+ ),
516
+ ),
1071
517
  )
1072
518
  }
1073
519
 
1074
- const plugins = setup.plugins
1075
- if (plugins === null) return null
1076
- if (plugins.length > 1) {
1077
- return Fault.of(
1078
- ErrorCode.PLUGIN_MISMATCH,
1079
- 'Currently only one plugin per game supported.',
1080
- )
1081
- }
520
+ peer.stage = JoinStage.EVENTS_PUBLISHED
521
+ this.history.replay(peer, slice ?? 0)
1082
522
 
1083
- return this.mismatch(plugins[0] ?? null)
523
+ peer.stage = JoinStage.COMPLETE
524
+ const arrival: GameChanges = {
525
+ newUsers: [actor.userId],
526
+ expectedUsers: extended ? [...seats.expected] : null,
527
+ }
528
+ this.report(fresh ? this.describe() : arrival)
1084
529
  }
1085
530
 
1086
531
  /**
@@ -1108,689 +553,35 @@ export class Room {
1108
553
  : Fault.of(
1109
554
  ErrorCode.PLUGIN_MISMATCH,
1110
555
  "Plugin Mismatch requested='{0}' got ErrorPlugin with message:'{1}'",
1111
- wanted,
1112
- 'PluginManager initialization failed.',
1113
- )
1114
- }
1115
-
1116
- /**
1117
- * Why a connection can't get into this room, or null
1118
- * @param peer who's asking
1119
- * @param setup the request as the room needs it
1120
- */
1121
- private admission(peer: GamePeer, setup: EntrySetup): Fault | null {
1122
- const userId = peer.userId
1123
- const awaited = this.expected.includes(userId)
1124
-
1125
- if (setup.rejoining) {
1126
- const fault = this.rejoin(peer, setup)
1127
- if (fault !== undefined) return fault
1128
- if (awaited) {
1129
- return Fault.denied(ErrorMessage.REJOIN_OR_JOIN_WITH_EXPECTED_PLAYER)
1130
- }
1131
- }
1132
-
1133
- if (!this.isOpen) {
1134
- return Fault.of(
1135
- ErrorCode.GAME_CLOSED,
1136
- this.discarded
1137
- ? ErrorMessage.GAME_CLOSED_CACHE_DISCARDED
1138
- : ErrorMessage.GAME_CLOSED,
1139
- )
1140
- }
1141
-
1142
- const limit = this.maxPlayers
1143
- const taken = this.active.length + this.inactive.length + this.awaited
1144
- if (limit > 0 && taken >= limit && !awaited) {
1145
- return Fault.of(ErrorCode.GAME_FULL, ErrorMessage.GAME_FULL)
1146
- }
1147
-
1148
- return null
1149
- }
1150
-
1151
- /**
1152
- * How a rejoin request fares, undefined to go on as a plain join
1153
- * @param peer who's asking
1154
- * @param setup the request as the room needs it
1155
- */
1156
- private rejoin(peer: GamePeer, setup: EntrySetup): Fault | null | undefined {
1157
- if (this.discarded) {
1158
- return Fault.of(
1159
- ErrorCode.EVENT_CACHE_EXCEEDED,
1160
- ErrorMessage.REJOINING_BLOCKED_CACHE_EXCEEDED,
1161
- )
1162
- }
1163
-
1164
- const lasting = this.playerTtl !== 0
1165
- const only = setup.mode === JoinMode.REJOIN_ONLY
1166
- if (!lasting && only) {
1167
- return Fault.denied(ErrorMessage.REJOIN_NOT_SUPPORTED)
1168
- }
1169
-
1170
- const named = this.has(RoomOptionFlag.CHECK_USER_ON_JOIN)
1171
- const actor = named
1172
- ? this.user(peer.userId)
1173
- : this.numbered(setup.actorNumber)
1174
- if (actor !== null) {
1175
- return lasting || only
1176
- ? null
1177
- : Fault.denied(ErrorMessage.REJOIN_NOT_SUPPORTED)
1178
- }
1179
-
1180
- if (!only) return undefined
1181
-
1182
- return named
1183
- ? Fault.of(
1184
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1185
- ErrorMessage.USER_NOT_FOUND,
1186
- )
1187
- : Fault.of(
1188
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1189
- ErrorMessage.ACTOR_NOT_FOUND,
1190
- setup.actorNumber,
1191
- )
1192
- }
1193
-
1194
- /**
1195
- * The seat a connection comes back to, null for a new one, or why it can't sit
1196
- * @param peer who's asking
1197
- * @param setup the request as the room needs it
1198
- */
1199
- private seat(peer: GamePeer, setup: EntrySetup): Actor | Fault | null {
1200
- if (this.playing(peer) !== null) {
1201
- return Fault.of(
1202
- ErrorCode.JOIN_FAILED_PEER_ALREADY_JOINED,
1203
- 'Join failed: Peer already joined the specified game.',
1204
- )
1205
- }
1206
-
1207
- const found = this.has(RoomOptionFlag.CHECK_USER_ON_JOIN)
1208
- ? this.seatByUser(peer, setup)
1209
- : this.seatByNumber(peer, setup)
1210
- if (found !== null) return found
1211
-
1212
- return setup.mode === JoinMode.REJOIN_ONLY
1213
- ? Fault.of(
1214
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1215
- 'Rejoin failed: userid={0} not found, actor nr={1}.',
1216
- peer.userId,
1217
- setup.actorNumber,
1218
- )
1219
- : null
1220
- }
1221
-
1222
- /**
1223
- * The seat of a connection's user id, null for none, or why it can't sit
1224
- * @param peer who's asking
1225
- * @param setup the request as the room needs it
1226
- */
1227
- private seatByUser(peer: GamePeer, setup: EntrySetup): Actor | Fault | null {
1228
- const userId = peer.userId
1229
- if (userId === '') {
1230
- return Fault.invalid(
1231
- 'Join failed: UserId is not set, checkUserIdOnJoin=true expects a UserId.',
1232
- )
1233
- }
1234
-
1235
- const ban = this.excluded.find(
1236
- (user: ExcludedUser): boolean => user.userId === userId,
1237
- )
1238
- if (ban !== undefined) return Room.banned(ban)
1239
-
1240
- const actor = this.user(userId)
1241
- if (actor === null) return null
1242
-
1243
- if (actor.active) {
1244
- return this.takeover(actor, peer, setup, setup.forceRejoin)
1245
- ? actor
1246
- : Fault.of(
1247
- ErrorCode.JOIN_FAILED_FOUND_ACTIVE_JOINER,
1248
- ErrorMessage.USER_ALREADY_JOINED,
1249
- userId,
1250
- setup.mode,
1251
- )
1252
- }
1253
-
1254
- if (this.expired(actor)) {
1255
- return Fault.of(
1256
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1257
- "Join failed: UserId '{0}' is expired (JoinMode={1}).",
1258
- userId,
1259
- setup.mode,
1260
- )
1261
- }
1262
-
1263
- return setup.rejoining
1264
- ? actor
1265
- : Fault.of(
1266
- ErrorCode.JOIN_FAILED_FOUND_INACTIVE_JOINER,
1267
- "Found inactive UserId '{0}', but not rejoining (JoinMode={1}).",
1268
- userId,
1269
- setup.mode,
1270
- )
1271
- }
1272
-
1273
- /**
1274
- * The seat a request names by number, null for none, or why it can't sit
1275
- * @param peer who's asking
1276
- * @param setup the request as the room needs it
1277
- */
1278
- private seatByNumber(
1279
- peer: GamePeer,
1280
- setup: EntrySetup,
1281
- ): Actor | Fault | null {
1282
- const number = setup.actorNumber
1283
- if (number <= 0) return null
1284
-
1285
- const actor = this.numbered(number)
1286
- if (actor === null) {
1287
- return Fault.of(
1288
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1289
- 'Rejoin failed: actor nr={0} not found.',
1290
- number,
1291
- )
1292
- }
1293
-
1294
- if (actor.active) {
1295
- return this.takeover(actor, peer, setup, false)
1296
- ? actor
1297
- : Fault.of(
1298
- ErrorCode.JOIN_FAILED_FOUND_ACTIVE_JOINER,
1299
- ErrorMessage.USER_WITH_ACTOR_ID_ALREADY_JOINED,
1300
- number,
1301
- setup.mode,
1302
- )
1303
- }
1304
-
1305
- const strangers =
1306
- actor.userId !== peer.userId &&
1307
- !(Room.GUID.test(actor.userId) && Room.GUID.test(peer.userId))
1308
- if (strangers) {
1309
- return Fault.internal(
1310
- "Rejoin failed: userId of peer doesn't match userid of actor.",
1311
- )
1312
- }
1313
-
1314
- if (this.expired(actor)) {
1315
- return Fault.of(
1316
- ErrorCode.JOIN_FAILED_WITH_REJOINER_NOT_FOUND,
1317
- "Join failed: ActorNr '{0}' is expired.",
1318
- number,
1319
- )
1320
- }
1321
-
1322
- return setup.rejoining
1323
- ? actor
1324
- : Fault.internal(
1325
- "Found inactive ActorNr '{0}', but not rejoining (JoinMode={1}).",
1326
- number,
1327
- setup.mode,
1328
- )
1329
- }
1330
-
1331
- /**
1332
- * Whether a seat's time away has run out
1333
- * @param actor the seat
1334
- */
1335
- private expired(actor: Actor): boolean {
1336
- const ttl = this.playerTtl
1337
- const since = actor.deactivatedAt
1338
- if (ttl <= 0 || ttl >= Room.FOREVER || since === null) return false
1339
-
1340
- return this.services.clock.now() - since > ttl
1341
- }
1342
-
1343
- /**
1344
- * Frees a taken seat for a second connection of the same login
1345
- * @param actor the seat
1346
- * @param peer who's asking
1347
- * @param setup the request as the room needs it
1348
- * @param forced whether the request insists
1349
- */
1350
- private takeover(
1351
- actor: Actor,
1352
- peer: GamePeer,
1353
- setup: EntrySetup,
1354
- forced: boolean,
1355
- ): boolean {
1356
- const holder = actor.peer
1357
- if (holder === null || this.playerTtl === 0 || !setup.rejoining) {
1358
- return false
1359
- }
1360
-
1361
- const first = holder.token
1362
- const second = peer.token
1363
- const same =
1364
- first !== null &&
1365
- second !== null &&
1366
- this.services.authenticator.same(first, second)
1367
- if (!forced && !same) return false
1368
-
1369
- this.groups.suspend(actor)
1370
- if (actor.peer !== null) this.seats.delete(actor.peer)
1371
- actor.peer = null
1372
- actor.deactivatedAt = this.services.clock.now()
1373
- this.active.splice(this.active.indexOf(actor), 1)
1374
- this.inactive.push(actor)
1375
-
1376
- this.references.delete(holder)
1377
- holder.room = null
1378
- holder.drop()
1379
-
1380
- return true
1381
- }
1382
-
1383
- /**
1384
- * Gives a connection a new seat
1385
- * @param peer who sits down
1386
- */
1387
- private add(peer: GamePeer): Actor {
1388
- this.counter += 1
1389
-
1390
- const actor = Actor.of(this.counter, peer)
1391
- this.active.push(actor)
1392
- this.seats.set(peer, actor)
1393
-
1394
- return actor
1395
- }
1396
-
1397
- /**
1398
- * Gives a connection its old seat back
1399
- * @param actor the seat
1400
- * @param peer who sits down
1401
- */
1402
- private reactivate(actor: Actor, peer: GamePeer): Actor {
1403
- actor.expiry?.cancel()
1404
- actor.expiry = null
1405
- actor.peer = peer
1406
- actor.deactivatedAt = null
1407
-
1408
- this.inactive.splice(this.inactive.indexOf(actor), 1)
1409
- this.active.push(actor)
1410
- this.seats.set(peer, actor)
1411
- this.groups.resume(actor)
1412
-
1413
- return actor
1414
- }
1415
-
1416
- /**
1417
- * Makes the connected actor with the lowest number the master client
1418
- */
1419
- private elect(): void {
1420
- this.master = this.numbers.reduce<number>(
1421
- (lowest: number, number: number): number =>
1422
- lowest === 0 || number < lowest ? number : lowest,
1423
- 0,
1424
- )
1425
- this.properties.set(
1426
- Room.key(GameProperty.MASTER_CLIENT_ID),
1427
- PhotonValue.int(this.master),
1428
- )
1429
- }
1430
-
1431
- /**
1432
- * Takes over the options of the request that made the room, or says why not
1433
- * @param setup the request as the room needs it
1434
- */
1435
- private furnish(setup: EntrySetup): Fault | null {
1436
- const longest = this.services.configuration.maxEmptyRoomTtl
1437
-
1438
- this.flags = setup.flags
1439
- this.properties.deleteNull = this.has(RoomOptionFlag.DELETE_NULL_PROPS)
1440
- if (setup.emptyRoomTtl > longest) {
1441
- return Fault.invalid(
1442
- ErrorMessage.MAX_TTL_EXCEEDED,
1443
- setup.emptyRoomTtl,
1444
- longest,
1445
- )
1446
- }
1447
-
1448
- this.properties.merge(setup.properties)
1449
- if (setup.expectedUsers !== null) {
1450
- this.properties.set(
1451
- Room.key(GameProperty.EXPECTED_USERS),
1452
- Room.names(setup.expectedUsers),
1453
- )
1454
- }
1455
-
1456
- if (setup.emptyRoomTtl !== 0) {
1457
- this.properties.set(
1458
- Room.key(GameProperty.EMPTY_ROOM_TTL),
1459
- PhotonValue.int(setup.emptyRoomTtl),
1460
- )
1461
- }
1462
-
1463
- if (setup.playerTtl !== 0) {
1464
- this.properties.set(
1465
- Room.key(GameProperty.PLAYER_TTL),
1466
- PhotonValue.int(setup.playerTtl),
1467
- )
1468
- }
1469
-
1470
- return null
1471
- }
1472
-
1473
- /**
1474
- * Keeps seats for some users and says who's new, or null if there's no room
1475
- * @param users user ids to keep a seat for
1476
- */
1477
- private reserve(users: readonly string[]): readonly string[] | null {
1478
- const added = users.filter(
1479
- (user: string): boolean => !this.expected.includes(user),
1480
- )
1481
- const limit = this.maxPlayers
1482
- const taken = this.active.length + this.awaited + this.pending(added)
1483
- if (limit !== 0 && taken > limit) return null
1484
-
1485
- let seats = this.active.length + this.inactive.length + this.awaited
1486
- for (const user of added) {
1487
- if (this.user(user) !== null) continue
1488
- if (limit !== 0 && seats === limit) return null
1489
- seats += 1
1490
- }
1491
-
1492
- this.expected.push(...added)
1493
- return added
1494
- }
1495
-
1496
- /**
1497
- * Remembers which properties lobbies show
1498
- * @param properties room properties of a request
1499
- */
1500
- private list(properties: PhotonHashtable): void {
1501
- const key = Room.key(GameProperty.PROPS_LISTED_IN_LOBBY)
1502
- if (!properties.has(key)) return
1503
-
1504
- this.filter = WellKnownProperties.filter(properties.get(key))
1505
- }
1506
-
1507
- /**
1508
- * The properties of a table that lobbies show
1509
- * @param table properties to pick from
1510
- */
1511
- private listed(table: PhotonHashtable): PhotonHashtable {
1512
- const filter = this.filter
1513
- const shown =
1514
- filter === null
1515
- ? null
1516
- : new Set<string | null>(
1517
- filter.map<string | null>(
1518
- (key: PhotonValue): string | null => key.identity,
1519
- ),
1520
- )
1521
- const hidden = new Set<string | null>(
1522
- [
1523
- GameProperty.MAX_PLAYERS,
1524
- GameProperty.IS_OPEN,
1525
- GameProperty.IS_VISIBLE,
1526
- GameProperty.PROPS_LISTED_IN_LOBBY,
1527
- ].map<string | null>(
1528
- (code: number): string | null => Room.key(code).identity,
1529
- ),
1530
- )
1531
- const listed = PhotonHashtable.of()
1532
-
1533
- for (const [key, value] of table.entries()) {
1534
- const identity = key.identity
1535
- if (shown === null ? hidden.has(identity) : !shown.has(identity)) continue
1536
- listed.set(key, value)
1537
- }
1538
-
1539
- return listed
1540
- }
1541
-
1542
- /**
1543
- * What a joiner learns about the room
1544
- * @param joiner who got in
1545
- * @param setup the request as the room needs it
1546
- */
1547
- private entry(joiner: Actor, setup: EntrySetup): RoomEntry {
1548
- const publish = this.has(RoomOptionFlag.PUBLISH_USER_ID)
1549
- const everyone = [...this.active, ...this.inactive]
1550
- const players = PhotonHashtable.of()
1551
-
1552
- for (const actor of this.quiet ? [] : everyone) {
1553
- const self = actor === joiner && !(setup.rejoining && actor.active)
1554
- if (self || (actor.properties.size === 0 && !publish)) continue
1555
-
1556
- const table = actor.properties.all()
1557
- if (!actor.active) {
1558
- table.set(Room.key(ActorProperty.IS_INACTIVE), PhotonValue.bool(true))
1559
- }
1560
-
1561
- if (publish) {
1562
- table.set(
1563
- Room.key(ActorProperty.USER_ID),
1564
- PhotonValue.string(actor.userId),
1565
- )
1566
- }
1567
-
1568
- players.set(PhotonValue.int(actor.number), PhotonValue.hashtable(table))
1569
- }
1570
-
1571
- return RoomEntry.of(
1572
- joiner.number,
1573
- this.suppressed
1574
- ? null
1575
- : everyone.map<number>((actor: Actor): number => actor.number),
1576
- this.properties.all(),
1577
- players.size === 0 ? null : players,
1578
- this.flags,
1579
- )
1580
- }
1581
-
1582
- /**
1583
- * Tells every connected actor who got in
1584
- * @param joiner who got in
1585
- * @param setup the request as the room needs it
1586
- */
1587
- private announce(joiner: Actor, setup: EntrySetup): void {
1588
- if (this.suppressed) return
1589
-
1590
- let properties: PhotonHashtable | null = null
1591
- if (setup.broadcast) {
1592
- properties = PropertyBag.copy(setup.actorProperties)
1593
- if (this.has(RoomOptionFlag.PUBLISH_USER_ID)) {
1594
- properties.set(
1595
- Room.key(ActorProperty.USER_ID),
1596
- PhotonValue.string(joiner.userId),
1597
- )
1598
- }
1599
- }
1600
-
1601
- this.tell(
1602
- this.active,
1603
- JoinEvent.of(joiner.number, this.numbers, properties),
1604
- )
1605
- }
1606
-
1607
- /**
1608
- * Sends a joiner every cached event
1609
- * @param peer who got in
1610
- * @param from first room cache slice to send
1611
- */
1612
- private replay(peer: GamePeer, from: number): void {
1613
- for (const event of this.actorCache.replay()) {
1614
- peer.send(CustomEvent.of(event.code, event.actor, event.data))
1615
- }
1616
-
1617
- for (const slice of this.roomCache.replay(from)) {
1618
- if (slice.index !== 0) {
1619
- peer.send(CacheSliceChangedEvent.of(slice.index, 0))
1620
- }
1621
-
1622
- for (const event of slice.events) {
1623
- peer.send(CustomEvent.of(event.code, event.actor, event.data))
1624
- }
1625
- }
1626
- }
1627
-
1628
- /**
1629
- * Answers a failed join and undoes what it did
1630
- * @param peer who was refused
1631
- * @param setup the request as the room needs it
1632
- * @param fault why
1633
- * @param actor the seat it already got, or null
1634
- */
1635
- protected reject(
1636
- peer: GamePeer,
1637
- setup: EntrySetup,
1638
- fault: Fault,
1639
- actor: Actor | null,
1640
- ): void {
1641
- peer.send(setup.refuse(fault))
1642
-
1643
- if (actor === null) {
1644
- const refused: GameChanges = { failedToAdd: [peer.userId] }
1645
- this.report(refused)
1646
- } else {
1647
- this.remove(actor, true)
1648
- }
1649
-
1650
- this.release(peer)
1651
- peer.part(this.services.clock, this.services.configuration.disconnectDelay)
1652
- }
1653
-
1654
- /**
1655
- * Keeps the seat of an actor that went away
1656
- * @param actor who went away
1657
- */
1658
- private deactivate(actor: Actor): void {
1659
- const ttl = this.playerTtl
1660
- const leading = this.master === actor.number
1661
-
1662
- this.groups.suspend(actor)
1663
- if (actor.peer !== null) this.seats.delete(actor.peer)
1664
- actor.peer = null
1665
- actor.deactivatedAt = this.services.clock.now()
1666
- this.active.splice(this.active.indexOf(actor), 1)
1667
- this.inactive.push(actor)
1668
-
1669
- if (ttl > 0 && ttl < Room.FOREVER) {
1670
- actor.expiry = this.services.clock.after(ttl, (): void => {
1671
- this.expire(actor)
1672
- })
1673
- }
1674
-
1675
- if (leading) this.elect()
1676
- if (!this.suppressed && this.active.length > 0) {
1677
- this.tell(
1678
- this.active,
1679
- LeaveEvent.of(
1680
- actor.number,
1681
- this.numbers,
1682
- true,
1683
- leading ? this.master : null,
1684
- ),
1685
- )
1686
- }
1687
-
1688
- const away: GameChanges = { inactiveUsers: [actor.userId] }
1689
- this.report(away)
1690
- }
1691
-
1692
- /**
1693
- * Takes out an actor whose time away ran out
1694
- * @param actor who stayed away
1695
- */
1696
- protected expire(actor: Actor): void {
1697
- actor.expiry = null
1698
- if (this.closed || !this.inactive.includes(actor)) return
1699
-
1700
- this.remove(actor, false)
1701
- }
1702
-
1703
- /**
1704
- * Takes an actor out for good
1705
- * @param actor who's out
1706
- * @param failed whether its join never finished
1707
- */
1708
- private remove(actor: Actor, failed: boolean): void {
1709
- const peer = actor.peer
1710
- const leading = this.master === actor.number
1711
- const known = peer === null || peer.stage >= JoinStage.EVENTS_PUBLISHED
1712
- const list = actor.active ? this.active : this.inactive
1713
-
1714
- list.splice(list.indexOf(actor), 1)
1715
- if (this.has(RoomOptionFlag.DELETE_CACHE_ON_LEAVE)) {
1716
- this.actorCache.forget(actor.number)
1717
- this.roomCache.forget(actor.number)
1718
- }
1719
-
1720
- actor.expiry?.cancel()
1721
- actor.expiry = null
1722
- if (actor.peer !== null) this.seats.delete(actor.peer)
1723
- actor.peer = null
1724
- this.groups.forget(actor)
1725
-
1726
- if (leading) this.elect()
1727
- if (known && !this.suppressed && this.active.length > 0) {
1728
- this.tell(
1729
- this.active,
1730
- LeaveEvent.of(
1731
- actor.number,
1732
- this.numbers,
1733
- false,
1734
- leading ? this.master : null,
1735
- ),
1736
- )
1737
- }
1738
-
1739
- const gone: GameChanges = failed
1740
- ? { failedToAdd: [actor.userId] }
1741
- : { removedUsers: [actor.userId] }
1742
- this.report(gone)
1743
- peer?.part(this.services.clock, this.services.configuration.disconnectDelay)
1744
- }
1745
-
1746
- /**
1747
- * Whether one more forwarded operation is over the limit
1748
- * @param webFlags web flags of the request, or null
1749
- */
1750
- private throttled(webFlags: number | null): boolean {
1751
- const limit = this.services.configuration.httpForwardLimit
1752
- if (limit <= 0 || ((webFlags ?? 0) & WebFlag.HTTP_FORWARD) === 0) {
1753
- return false
1754
- }
1755
-
1756
- const second = Math.floor(this.services.clock.now() / 1000)
1757
- if (second !== this.forwardSecond) {
1758
- this.forwardSecond = second
1759
- this.forwardCount = 0
1760
- }
1761
-
1762
- this.forwardCount += 1
1763
- return this.forwardCount > limit
1764
- }
1765
-
1766
- /**
1767
- * Handles a raised event and says why it failed, or null
1768
- * @param peer who raised it
1769
- * @param packet what the client sent
1770
- */
1771
- private raised(peer: GamePeer, packet: RaiseEventRequest): Fault | null {
1772
- const everyone = this.active.length + this.inactive.length
1773
- if ((packet.actors?.length ?? 0) > 2 * everyone) {
1774
- return Fault.invalid('Actors excceds CurrentPlayers count')
1775
- }
556
+ wanted,
557
+ 'PluginManager initialization failed.',
558
+ )
559
+ }
1776
560
 
1777
- const sender = this.playing(peer)
1778
- if (sender === null) return null
1779
- if (this.throttled(packet.webFlags)) {
1780
- return Fault.of(
1781
- ErrorCode.HTTP_LIMIT_REACHED,
1782
- ErrorMessage.HTTP_FORWARDED_OPERATIONS_LIMIT_REACHED,
1783
- )
1784
- }
561
+ /**
562
+ * Answers a failed join and undoes what it did
563
+ * @param peer who was refused
564
+ * @param setup the request as the room needs it
565
+ * @param fault why
566
+ * @param actor the seat it already got, or null
567
+ */
568
+ protected reject(
569
+ peer: GamePeer,
570
+ setup: EntrySetup,
571
+ fault: Fault,
572
+ actor: Actor | null,
573
+ ): void {
574
+ peer.send(setup.refuse(fault))
1785
575
 
1786
- if (packet.eventCode > EventRange.LAST_RAISABLE) {
1787
- return Fault.invalid(
1788
- ErrorMessage.SIMULATES_PHOTON_EVENT,
1789
- EventRange.LAST_RAISABLE,
1790
- )
576
+ if (actor === null) {
577
+ const refused: GameChanges = { failedToAdd: [peer.userId] }
578
+ this.report(refused)
579
+ } else {
580
+ this.remove(actor, true)
1791
581
  }
1792
582
 
1793
- return this.spread(sender, packet)
583
+ this.release(peer)
584
+ peer.part(this.services.clock, this.services.configuration.disconnectDelay)
1794
585
  }
1795
586
 
1796
587
  /**
@@ -1799,20 +590,22 @@ export class Room {
1799
590
  * @param packet what the client sent
1800
591
  */
1801
592
  protected spread(sender: Actor, packet: RaiseEventRequest): Fault | null {
593
+ const seats = this.seats
594
+ const history = this.history
1802
595
  const targets = [...new Set<number>(packet.actors ?? [])]
1803
596
  const caching = packet.caching
1804
597
  if (caching >= EventCaching.SLICE_INCREASE_INDEX) {
1805
- return this.slice(sender, packet)
598
+ return history.slice(sender, packet)
1806
599
  }
1807
600
 
1808
601
  if (caching === EventCaching.REMOVE_FROM_ROOM_CACHE) {
1809
- this.roomCache.remove(packet.eventCode, packet.actors, packet.data)
602
+ history.remove(packet)
1810
603
  sender.send(RaiseEventResponse.success().to(packet))
1811
604
  return null
1812
605
  }
1813
606
 
1814
607
  if (caching === EventCaching.REMOVE_FROM_ROOM_CACHE_FOR_ACTORS_LEFT) {
1815
- this.roomCache.prune(new Set<number>(this.numbers))
608
+ history.prune()
1816
609
  sender.send(RaiseEventResponse.success().to(packet))
1817
610
  return null
1818
611
  }
@@ -1821,24 +614,24 @@ export class Room {
1821
614
  let cacheable = false
1822
615
 
1823
616
  if (targets.length > 0) {
1824
- recipients = this.active.filter((actor: Actor): boolean =>
617
+ recipients = seats.active.filter((actor: Actor): boolean =>
1825
618
  targets.includes(actor.number),
1826
619
  )
1827
620
  } else if (packet.group !== 0) {
1828
- recipients = [...this.groups.of(packet.group)].filter(
621
+ recipients = [...seats.groups.of(packet.group)].filter(
1829
622
  (actor: Actor): boolean => actor !== sender,
1830
623
  )
1831
624
  } else if (packet.receiverGroup === ReceiverGroup.ALL) {
1832
- recipients = [...this.active]
625
+ recipients = [...seats.active]
1833
626
  cacheable = true
1834
627
  } else if (packet.receiverGroup === ReceiverGroup.OTHERS) {
1835
- recipients = this.active.filter(
628
+ recipients = seats.active.filter(
1836
629
  (actor: Actor): boolean => actor !== sender,
1837
630
  )
1838
631
  cacheable = true
1839
632
  } else if (packet.receiverGroup === ReceiverGroup.MASTER_CLIENT) {
1840
- recipients = this.active.filter(
1841
- (actor: Actor): boolean => actor.number === this.master,
633
+ recipients = seats.active.filter(
634
+ (actor: Actor): boolean => actor.number === seats.master,
1842
635
  )
1843
636
  if (recipients.length === 0) return null
1844
637
  } else {
@@ -1848,12 +641,16 @@ export class Room {
1848
641
  )
1849
642
  }
1850
643
 
1851
- if (cacheable && caching !== EventCaching.DO_NOT_CACHE && !this.discarded) {
1852
- const fault = this.keep(sender, packet)
644
+ if (
645
+ cacheable &&
646
+ caching !== EventCaching.DO_NOT_CACHE &&
647
+ !history.discarded
648
+ ) {
649
+ const fault = history.keep(sender, packet)
1853
650
  if (fault !== null) return fault
1854
651
  }
1855
652
 
1856
- if (this.discarded) this.overflow()
653
+ if (history.discarded) this.overflow()
1857
654
 
1858
655
  this.tell(
1859
656
  recipients,
@@ -1866,406 +663,251 @@ export class Room {
1866
663
  }
1867
664
 
1868
665
  /**
1869
- * Puts a raised event in a cache, or says why not
1870
- * @param sender who raised it
666
+ * Changes properties of the room or of one actor and says why it failed, or null
667
+ * @param peer who's changing them
1871
668
  * @param packet what the client sent
1872
669
  */
1873
- private keep(sender: Actor, packet: RaiseEventRequest): Fault | null {
1874
- const code = packet.eventCode
1875
- const data = packet.data
1876
-
1877
- switch (packet.caching) {
1878
- case EventCaching.MERGE_CACHE:
1879
- if (!ActorCache.suits(data)) return Room.unsuited('MergeCache')
1880
- this.actorCache.merge(sender.number, code, data)
1881
- return null
1882
- case EventCaching.REPLACE_CACHE:
1883
- if (!ActorCache.suits(data)) return Room.unsuited('ReplaceCache')
1884
- this.actorCache.replace(sender.number, code, data)
1885
- return null
1886
- case EventCaching.REMOVE_CACHE:
1887
- if (!ActorCache.suits(data)) return Room.unsuited('RemoveCache')
1888
- this.actorCache.remove(sender.number, code)
1889
- return null
1890
- case EventCaching.ADD_TO_ROOM_CACHE:
1891
- this.roomCache.add(sender.number, code, data)
1892
- return null
1893
- case EventCaching.ADD_TO_ROOM_CACHE_GLOBAL:
1894
- this.roomCache.add(0, code, data)
1895
- return null
1896
- default:
1897
- return Fault.invalid("Unknown cache operation '{0}'.", packet.caching)
1898
- }
1899
- }
1900
-
1901
- /**
1902
- * The refusal for content an actor cache can't hold
1903
- * @param operation name of the cache operation
1904
- */
1905
- private static unsuited(operation: string): Fault {
1906
- return Fault.invalid(
1907
- "Cache operation '{0}' requires a Hashtable as event data.",
1908
- operation,
1909
- )
670
+ protected altered(
671
+ peer: GamePeer,
672
+ packet: SetPropertiesRequest,
673
+ ): Fault | null {
674
+ return this.editor.change(peer, packet)
1910
675
  }
1911
676
 
1912
677
  /**
1913
- * Closes the room after a cache passed its limit and tells everyone
678
+ * Which game this is and how full
1914
679
  */
1915
- private overflow(): void {
1916
- const closing = this.isOpen
680
+ private summary(): GameSummary {
681
+ const lobby = this.properties.lobby
1917
682
 
1918
- if (closing) {
1919
- const closed = Room.single(GameProperty.IS_OPEN, PhotonValue.bool(false))
1920
- this.properties.merge(closed)
1921
- this.tell(this.active, PropertiesChangedEvent.of(0, 0, closed))
1922
- const shut: GameChanges = { isOpen: false }
1923
- this.report(shut)
683
+ return {
684
+ application: this.application,
685
+ version: this.version,
686
+ game: this.name,
687
+ lobby: lobby?.name ?? null,
688
+ lobbyType: lobby?.type ?? 0,
689
+ actorCount: this.seats.active.length,
690
+ inactiveCount: this.seats.inactive.length,
1924
691
  }
1925
-
1926
- this.tell(
1927
- this.active,
1928
- ErrorInfoEvent.of(
1929
- closing
1930
- ? ErrorMessage.ROOM_CLOSED_CACHED_EVENTS_LIMIT_EXCEEDED
1931
- : ErrorMessage.CACHED_EVENTS_LIMIT_EXCEEDED,
1932
- ),
1933
- )
1934
692
  }
1935
693
 
1936
694
  /**
1937
- * Moves or purges cache slices, or says why not
1938
- * @param sender who asked
1939
- * @param packet what the client sent
695
+ * Why a request can't start this room, or null
696
+ * @param setup the request as the room needs it
1940
697
  */
1941
- private slice(sender: Actor, packet: RaiseEventRequest): Fault | null {
1942
- const index = packet.cacheSliceIndex
1943
- const before = this.roomCache.current
1944
- let fault: Fault | null
1945
-
1946
- switch (packet.caching) {
1947
- case EventCaching.SLICE_INCREASE_INDEX:
1948
- fault = this.roomCache.increase()
1949
- break
1950
- case EventCaching.SLICE_SET_INDEX:
1951
- fault =
1952
- index === null
1953
- ? Fault.invalid('SliceSetIndex: Missing paramter CacheSliceIndex.')
1954
- : this.roomCache.move(index)
1955
- break
1956
- case EventCaching.SLICE_PURGE_INDEX:
1957
- return index === null
1958
- ? Fault.invalid('SlicePurgeIndex: Missing paramter CacheSliceIndex.')
1959
- : this.roomCache.purge(index)
1960
- case EventCaching.SLICE_PURGE_UP_TO_INDEX:
1961
- return index === null
1962
- ? Fault.invalid(
1963
- 'SlicePurgeUpToIndex: Missing paramter CacheSliceIndex.',
1964
- )
1965
- : this.roomCache.purgeBelow(index)
1966
- default:
1967
- return Fault.invalid('Unknown cache operation={0}.', packet.caching)
698
+ private founding(setup: EntrySetup): Fault | null {
699
+ if (!this.creatable(setup)) {
700
+ return Fault.of(
701
+ ErrorCode.GAME_DOES_NOT_EXIST,
702
+ ErrorMessage.GAME_ID_DOES_NOT_EXIST,
703
+ )
1968
704
  }
1969
705
 
1970
- if (fault !== null || this.roomCache.current === before) return fault
1971
-
1972
- this.tell(
1973
- this.active,
1974
- CacheSliceChangedEvent.of(this.roomCache.current, sender.number),
1975
- )
706
+ const plugins = setup.plugins
707
+ if (plugins === null) return null
708
+ if (plugins.length > 1) {
709
+ return Fault.of(
710
+ ErrorCode.PLUGIN_MISMATCH,
711
+ 'Currently only one plugin per game supported.',
712
+ )
713
+ }
1976
714
 
1977
- return null
715
+ return this.mismatch(plugins[0] ?? null)
1978
716
  }
1979
717
 
1980
718
  /**
1981
- * Property keys as a bag knows them
1982
- * @param keys keys as the client sent them
1983
- * @param json whether the client speaks JSON
1984
- * @param codes property codes a JSON client sends as text
719
+ * Makes the connected actor with the lowest number the master client
1985
720
  */
1986
- private keys(
1987
- keys: readonly PhotonValue[],
1988
- json: boolean,
1989
- codes: readonly number[],
1990
- ): readonly PhotonValue[] {
1991
- if (!json) return keys
1992
-
1993
- return keys.map<PhotonValue>((key: PhotonValue): PhotonValue => {
1994
- const code = Number(key.text() ?? '')
1995
- return codes.includes(code) ? PhotonValue.byte(code) : key
1996
- })
721
+ private elect(): void {
722
+ this.properties.bag.set(
723
+ RoomProperties.key(GameProperty.MASTER_CLIENT_ID),
724
+ PhotonValue.int(this.seats.elect()),
725
+ )
1997
726
  }
1998
727
 
1999
728
  /**
2000
- * Who hears about a property change
2001
- * @param sender who made it
2002
- * @param packet what the client sent
2003
- * @param swapping whether expected values came along
729
+ * What a joiner learns about the room
730
+ * @param joiner who got in
731
+ * @param setup the request as the room needs it
2004
732
  */
2005
- private audience(
2006
- sender: Actor,
2007
- packet: SetPropertiesRequest,
2008
- swapping: boolean,
2009
- ): readonly Actor[] {
2010
- if (!packet.broadcast && !swapping) return []
2011
- if (swapping || this.has(RoomOptionFlag.BROADCAST_PROPS_CHANGE_TO_ALL)) {
2012
- return [...this.active]
2013
- }
733
+ private entry(joiner: Actor, setup: EntrySetup): RoomEntry {
734
+ const properties = this.properties
735
+ const publish = properties.has(RoomOptionFlag.PUBLISH_USER_ID)
736
+ const everyone = this.seats.everyone
737
+ const players = PhotonHashtable.of()
2014
738
 
2015
- return this.active.filter((actor: Actor): boolean => actor !== sender)
2016
- }
739
+ for (const actor of properties.quiet ? [] : everyone) {
740
+ const self = actor === joiner && !(setup.rejoining && actor.active)
741
+ if (self || (actor.properties.size === 0 && !publish)) continue
2017
742
 
2018
- /**
2019
- * The actor behind a property request, or why there's none
2020
- * @param peer who's changing properties
2021
- * @param packet what the client sent
2022
- */
2023
- private setter(peer: GamePeer, packet: SetPropertiesRequest): Actor | Fault {
2024
- const sender = this.playing(peer)
2025
- if (sender === null) {
2026
- return Fault.invalid(ErrorMessage.PEER_NOT_JOINED_TO_ROOM)
2027
- }
743
+ const table = actor.properties.all()
744
+ if (!actor.active) {
745
+ table.set(
746
+ RoomProperties.key(ActorProperty.IS_INACTIVE),
747
+ PhotonValue.bool(true),
748
+ )
749
+ }
2028
750
 
2029
- return this.throttled(packet.webFlags)
2030
- ? Fault.of(
2031
- ErrorCode.HTTP_LIMIT_REACHED,
2032
- ErrorMessage.HTTP_FORWARDED_OPERATIONS_LIMIT_REACHED,
751
+ if (publish) {
752
+ table.set(
753
+ RoomProperties.key(ActorProperty.USER_ID),
754
+ PhotonValue.string(actor.userId),
2033
755
  )
2034
- : sender
2035
- }
756
+ }
2036
757
 
2037
- /**
2038
- * Changes properties of the room or of one actor and says why it failed, or null
2039
- * @param peer who's changing them
2040
- * @param packet what the client sent
2041
- */
2042
- protected altered(
2043
- peer: GamePeer,
2044
- packet: SetPropertiesRequest,
2045
- ): Fault | null {
2046
- return packet.actorNumber > 0
2047
- ? this.changeActor(peer, packet)
2048
- : this.changeRoom(peer, packet)
758
+ players.set(PhotonValue.int(actor.number), PhotonValue.hashtable(table))
759
+ }
760
+
761
+ return RoomEntry.of(
762
+ joiner.number,
763
+ properties.suppressed
764
+ ? null
765
+ : everyone.map<number>((actor: Actor): number => actor.number),
766
+ properties.bag.all(),
767
+ players.size === 0 ? null : players,
768
+ properties.flags,
769
+ )
2049
770
  }
2050
771
 
2051
772
  /**
2052
- * Changes the properties of one actor and says why it failed, or null
2053
- * @param peer who's changing them
2054
- * @param packet what the client sent
773
+ * Tells every connected actor who got in
774
+ * @param joiner who got in
775
+ * @param setup the request as the room needs it
2055
776
  */
2056
- private changeActor(
2057
- peer: GamePeer,
2058
- packet: SetPropertiesRequest,
2059
- ): Fault | null {
2060
- const sender = this.setter(peer, packet)
2061
- if (sender instanceof Fault) return sender
2062
-
2063
- const target = this.numbered(packet.actorNumber)
2064
- if (target === null) {
2065
- return Fault.invalid(ErrorMessage.ACTOR_NOT_FOUND, packet.actorNumber)
2066
- }
777
+ private announce(joiner: Actor, setup: EntrySetup): void {
778
+ if (this.properties.suppressed) return
2067
779
 
2068
- const joining =
2069
- target.peer !== null && target.peer.stage !== JoinStage.COMPLETE
2070
- if (packet.broadcast && joining) {
2071
- return Fault.invalid(
2072
- ErrorMessage.ACTOR_JOINING_NOT_COMPLETE,
2073
- packet.actorNumber,
2074
- )
780
+ let properties: PhotonHashtable | null = null
781
+ if (setup.broadcast) {
782
+ properties = PropertyBag.copy(setup.actorProperties)
783
+ if (this.properties.has(RoomOptionFlag.PUBLISH_USER_ID)) {
784
+ properties.set(
785
+ RoomProperties.key(ActorProperty.USER_ID),
786
+ PhotonValue.string(joiner.userId),
787
+ )
788
+ }
2075
789
  }
2076
790
 
2077
- const expected = EntrySetup.promoted(
2078
- packet.expectedValues,
2079
- peer.json,
2080
- JsonKeys.ACTOR,
2081
- )
2082
- const properties = EntrySetup.stripped(
2083
- EntrySetup.promoted(packet.properties, peer.json, JsonKeys.ACTOR),
2084
- )
2085
- const swapping = expected !== null && expected.size > 0
2086
- const unmet = target.properties.swap(properties, swapping ? expected : null)
2087
- if (unmet !== null) return Fault.of(ErrorCode.OPERATION_INVALID, unmet)
2088
-
2089
- peer.send(SetPropertiesResponse.success().to(packet))
2090
791
  this.tell(
2091
- this.quiet ? [] : this.audience(sender, packet, swapping),
2092
- PropertiesChangedEvent.of(sender.number, target.number, properties).via(
2093
- packet.travel,
2094
- ),
792
+ this.seats.active,
793
+ JoinEvent.of(joiner.number, this.seats.numbers, properties),
2095
794
  )
2096
-
2097
- return null
2098
795
  }
2099
796
 
2100
797
  /**
2101
- * Changes the properties of the room and says why it failed, or null
2102
- * @param peer who's changing them
2103
- * @param packet what the client sent
798
+ * Keeps the seat of an actor that went away
799
+ * @param actor who went away
2104
800
  */
2105
- private changeRoom(
2106
- peer: GamePeer,
2107
- packet: SetPropertiesRequest,
2108
- ): Fault | null {
2109
- const known = WellKnownProperties.read(
2110
- EntrySetup.promoted(packet.properties, peer.json, JsonKeys.ROOM),
2111
- )
2112
- if (known.fault !== null) {
2113
- return Fault.of(ErrorCode.OPERATION_INVALID, known.fault)
2114
- }
801
+ private deactivate(actor: Actor): void {
802
+ const seats = this.seats
803
+ const leading = seats.master === actor.number
2115
804
 
2116
- const sender = this.setter(peer, packet)
2117
- if (sender instanceof Fault) return sender
805
+ seats.suspend(actor, this.services.clock.now())
806
+ this.lifecycle.away(actor)
2118
807
 
2119
- const wanted = WellKnownProperties.read(
2120
- EntrySetup.promoted(packet.expectedValues, peer.json, JsonKeys.ROOM),
2121
- )
2122
- const expected =
2123
- wanted.fault === null ? wanted.properties : packet.expectedValues
2124
- const swapping = expected !== null && expected.size > 0
2125
- const before = this.properties.all()
2126
- const seats = [...this.expected]
2127
- const state = [this.maxPlayers, this.isOpen, this.isVisible] as const
2128
-
2129
- const fault = this.revise(known, swapping ? expected : null)
2130
- if (fault !== null) {
2131
- this.properties.restore(before)
2132
- this.expected = seats
2133
- return fault
808
+ if (leading) this.elect()
809
+ if (!this.properties.suppressed && seats.active.length > 0) {
810
+ this.tell(
811
+ seats.active,
812
+ LeaveEvent.of(
813
+ actor.number,
814
+ seats.numbers,
815
+ true,
816
+ leading ? seats.master : null,
817
+ ),
818
+ )
2134
819
  }
2135
820
 
2136
- peer.send(SetPropertiesResponse.success().to(packet))
2137
- this.tell(
2138
- this.audience(sender, packet, swapping),
2139
- PropertiesChangedEvent.of(sender.number, 0, known.properties).via(
2140
- packet.travel,
2141
- ),
2142
- )
2143
- this.publish(known, state)
2144
-
2145
- return null
821
+ const away: GameChanges = { inactiveUsers: [actor.userId] }
822
+ this.report(away)
2146
823
  }
2147
824
 
2148
825
  /**
2149
- * Writes checked room properties and says why it failed, or null
2150
- * @param known the properties after their type check
2151
- * @param expected values the room must hold first, or null
826
+ * Takes an actor out for good
827
+ * @param actor who's out
828
+ * @param failed whether its join never finished
2152
829
  */
2153
- private revise(
2154
- known: WellKnownProperties,
2155
- expected: PhotonHashtable | null,
2156
- ): Fault | null {
2157
- const longest = this.services.configuration.maxEmptyRoomTtl
2158
- const stay = known.number(GameProperty.EMPTY_ROOM_TTL)
2159
- if (stay !== null && stay > longest) {
2160
- return Fault.invalid(
2161
- ErrorMessage.SET_PROPERTIES_MAX_TTL_EXCEEDED,
2162
- stay,
2163
- longest,
2164
- )
2165
- }
2166
-
2167
- const leader = known.number(GameProperty.MASTER_CLIENT_ID)
2168
- if (leader !== null && !this.numbers.includes(leader)) {
2169
- return Fault.invalid(
2170
- "MasterClientId value '{0}' is invalid. No actor with such number",
2171
- leader,
2172
- )
2173
- }
830
+ private remove(actor: Actor, failed: boolean): void {
831
+ const seats = this.seats
832
+ const peer = actor.peer
833
+ const leading = seats.master === actor.number
834
+ const known = peer === null || peer.stage >= JoinStage.EVENTS_PUBLISHED
2174
835
 
2175
- if (known.has(GameProperty.EXPECTED_USERS) && expected === null) {
2176
- return Fault.invalid('ExpectedUsers may be updated only in CAS mode')
836
+ seats.drop(actor)
837
+ if (this.properties.has(RoomOptionFlag.DELETE_CACHE_ON_LEAVE)) {
838
+ this.history.forget(actor.number)
2177
839
  }
2178
840
 
2179
- const limit = known.number(GameProperty.MAX_PLAYERS) ?? 0
2180
- if (limit !== 0 && limit < this.active.length + this.inactive.length) {
2181
- return Fault.invalid(
2182
- 'new MaxPlayer can not be less then current amount of players',
841
+ if (leading) this.elect()
842
+ if (known && !this.properties.suppressed && seats.active.length > 0) {
843
+ this.tell(
844
+ seats.active,
845
+ LeaveEvent.of(
846
+ actor.number,
847
+ seats.numbers,
848
+ false,
849
+ leading ? seats.master : null,
850
+ ),
2183
851
  )
2184
852
  }
2185
853
 
2186
- const unmet = this.properties.swap(known.properties, expected)
2187
- if (unmet !== null) return Fault.of(ErrorCode.OPERATION_INVALID, unmet)
2188
-
2189
- if (leader !== null) this.master = leader
2190
- this.list(known.properties)
2191
-
2192
- return known.has(GameProperty.EXPECTED_USERS)
2193
- ? this.reseat(known, expected)
2194
- : null
854
+ const gone: GameChanges = failed
855
+ ? { failedToAdd: [actor.userId] }
856
+ : { removedUsers: [actor.userId] }
857
+ this.report(gone)
858
+ peer?.part(this.services.clock, this.services.configuration.disconnectDelay)
2195
859
  }
2196
860
 
2197
861
  /**
2198
- * Swaps the list of kept seats and says why it failed, or null
2199
- * @param known the properties after their type check
2200
- * @param expected values the room held first, or null
862
+ * Handles a raised event and says why it failed, or null
863
+ * @param peer who raised it
864
+ * @param packet what the client sent
2201
865
  */
2202
- private reseat(
2203
- known: WellKnownProperties,
2204
- expected: PhotonHashtable | null,
2205
- ): Fault | null {
2206
- const key = Room.key(GameProperty.EXPECTED_USERS)
2207
- const old = WellKnownProperties.users(expected?.get(key) ?? null) ?? []
2208
- const users =
2209
- WellKnownProperties.users(known.value(GameProperty.EXPECTED_USERS)) ?? []
2210
- if (users.includes('')) {
2211
- return Fault.invalid(ErrorMessage.SLOT_CAN_NOT_HAVE_EMPTY_NAME)
866
+ private raised(peer: GamePeer, packet: RaiseEventRequest): Fault | null {
867
+ if ((packet.actors?.length ?? 0) > 2 * this.seats.taken) {
868
+ return Fault.invalid('Actors excceds CurrentPlayers count')
2212
869
  }
2213
870
 
2214
- const kept = this.expected.filter(
2215
- (user: string): boolean => !old.includes(user) || users.includes(user),
2216
- )
2217
- const seats = [...new Set<string>([...kept, ...users])]
2218
- const limit = this.maxPlayers
2219
- const taken =
2220
- this.active.length + this.inactive.length + this.pending(seats)
2221
- if (limit !== 0 && taken > limit) {
2222
- return Fault.invalid('Not enough places to reserve all requested slots')
871
+ const sender = this.seats.playing(peer)
872
+ if (sender === null) return null
873
+ if (this.throttle.throttled(packet.webFlags)) {
874
+ return Fault.of(
875
+ ErrorCode.HTTP_LIMIT_REACHED,
876
+ ErrorMessage.HTTP_FORWARDED_OPERATIONS_LIMIT_REACHED,
877
+ )
2223
878
  }
2224
879
 
2225
- this.expected = seats
2226
- return null
880
+ const refusal = RaiseEventRequestFormat.refusal(packet)
881
+ if (refusal !== null) return Fault.invalid(refusal)
882
+
883
+ return this.spread(sender, packet)
2227
884
  }
2228
885
 
2229
886
  /**
2230
- * Tells the Master about changed room properties if it cares
2231
- * @param known the properties that were written
2232
- * @param state player limit, open and visible as they were before
887
+ * Closes the room after a cache passed its limit and tells everyone
2233
888
  */
2234
- private publish(
2235
- known: WellKnownProperties,
2236
- state: readonly [number, boolean, boolean],
2237
- ): void {
2238
- const herald = this.services.herald
2239
- const refiltered = known.has(GameProperty.PROPS_LISTED_IN_LOBBY)
2240
- const reseated = known.has(GameProperty.EXPECTED_USERS)
2241
- const limited =
2242
- known.has(GameProperty.MAX_PLAYERS) && this.maxPlayers !== state[0]
2243
- const opened = known.has(GameProperty.IS_OPEN) && this.isOpen !== state[1]
2244
- const shown =
2245
- known.has(GameProperty.IS_VISIBLE) && this.isVisible !== state[2]
2246
- const listed = this.listed(
2247
- refiltered ? this.properties.all() : known.properties,
2248
- )
2249
- if (
2250
- !limited &&
2251
- !opened &&
2252
- !shown &&
2253
- !refiltered &&
2254
- !reseated &&
2255
- listed.size === 0
2256
- ) {
2257
- return
2258
- }
889
+ private overflow(): void {
890
+ const active = this.seats.active
891
+ const closing = this.properties.isOpen
2259
892
 
2260
- const changes: GameChanges = {
2261
- maxPlayers: limited ? this.maxPlayers : null,
2262
- isOpen: opened ? this.isOpen : null,
2263
- isVisible: shown ? this.isVisible : null,
2264
- expectedUsers: reseated ? [...this.expected] : null,
2265
- propertyFilter:
2266
- refiltered && this.filter !== null ? herald.filter(this.filter) : null,
2267
- properties: listed.size === 0 ? null : herald.properties(listed),
893
+ if (closing) {
894
+ const closed = RoomProperties.single(
895
+ GameProperty.IS_OPEN,
896
+ PhotonValue.bool(false),
897
+ )
898
+ this.properties.bag.merge(closed)
899
+ this.tell(active, PropertiesChangedEvent.of(0, 0, closed))
900
+ const shut: GameChanges = { isOpen: false }
901
+ this.report(shut)
2268
902
  }
2269
- this.report(changes)
903
+
904
+ this.tell(
905
+ active,
906
+ ErrorInfoEvent.of(
907
+ closing
908
+ ? ErrorMessage.ROOM_CLOSED_CACHED_EVENTS_LIMIT_EXCEEDED
909
+ : ErrorMessage.CACHED_EVENTS_LIMIT_EXCEEDED,
910
+ ),
911
+ )
2270
912
  }
2271
913
  }