-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiplayerServicesFacade.cs
More file actions
465 lines (409 loc) · 14.8 KB
/
MultiplayerServicesFacade.cs
File metadata and controls
465 lines (409 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
using System;
using System.Threading.Tasks;
using Unity.BossRoom.Infrastructure;
using Unity.Services.Authentication;
using Unity.Services.Multiplayer;
using UnityEngine;
using VContainer;
using VContainer.Unity;
namespace Unity.BossRoom.UnityServices.Sessions
{
/// <summary>
/// An abstraction layer between the direct calls into the Multiplayer Services SDK and the outcomes you actually want.
/// </summary>
public class MultiplayerServicesFacade : IDisposable, IStartable
{
[Inject]
LifetimeScope m_ParentScope;
[Inject]
UpdateRunner m_UpdateRunner;
[Inject]
LocalSession m_LocalSession;
[Inject]
LocalSessionUser m_LocalUser;
[Inject]
IPublisher<UnityServiceErrorMessage> m_UnityServiceErrorMessagePub;
[Inject]
IPublisher<SessionListFetchedMessage> m_SessionListFetchedPub;
LifetimeScope m_ServiceScope;
MultiplayerServicesInterface m_MultiplayerServicesInterface;
RateLimitCooldown m_RateLimitQuery;
RateLimitCooldown m_RateLimitJoin;
RateLimitCooldown m_RateLimitQuickJoin;
RateLimitCooldown m_RateLimitHost;
public ISession CurrentUnitySession { get; private set; }
bool m_IsTracking;
public void Start()
{
m_ServiceScope = m_ParentScope.CreateChild(builder =>
{
builder.Register<MultiplayerServicesInterface>(Lifetime.Singleton);
});
m_MultiplayerServicesInterface = m_ServiceScope.Container.Resolve<MultiplayerServicesInterface>();
//See https://docs.unity.com/ugs/manual/lobby/manual/rate-limits
m_RateLimitQuery = new RateLimitCooldown(1f);
m_RateLimitJoin = new RateLimitCooldown(1f);
m_RateLimitQuickJoin = new RateLimitCooldown(1f);
m_RateLimitHost = new RateLimitCooldown(3f);
}
public void Dispose()
{
EndTracking();
if (m_ServiceScope != null)
{
m_ServiceScope.Dispose();
}
}
public void SetRemoteSession(ISession session)
{
CurrentUnitySession = session;
m_LocalSession.ApplyRemoteData(session);
}
/// <summary>
/// Initiates tracking of joined session's events. The host also starts sending heartbeat pings here.
/// </summary>
public void BeginTracking()
{
if (!m_IsTracking)
{
m_IsTracking = true;
SubscribeToJoinedSession();
}
}
/// <summary>
/// Ends tracking of joined session's events and leaves or deletes the session. The host also stops sending heartbeat
/// pings here.
/// </summary>
public void EndTracking()
{
if (m_IsTracking)
{
m_IsTracking = false;
}
if (CurrentUnitySession != null)
{
UnsubscribeFromJoinedSession();
if (m_LocalUser.IsHost)
{
DeleteSessionAsync();
}
else
{
LeaveSessionAsync();
}
}
}
/// <summary>
/// Attempt to create a new session and then join it.
/// </summary>
public async Task<(bool Success, ISession Session)> TryCreateSessionAsync(string sessionName, int maxPlayers, bool isPrivate)
{
if (!m_RateLimitHost.CanCall)
{
Debug.LogWarning("Create Session hit the rate limit.");
return (false, null);
}
try
{
var session = await m_MultiplayerServicesInterface.CreateSession(sessionName,
maxPlayers,
isPrivate,
m_LocalUser.GetDataForUnityServices(),
null);
return (true, session);
}
catch (Exception e)
{
PublishError(e);
}
return (false, null);
}
/// <summary>
/// Attempt to join an existing session with a join code.
/// </summary>
public async Task<(bool Success, ISession Session)> TryJoinSessionByCodeAsync(string sessionCode)
{
if (!m_RateLimitJoin.CanCall)
{
Debug.LogWarning("Join Session hit the rate limit.");
return (false, null);
}
if (string.IsNullOrEmpty(sessionCode))
{
Debug.LogWarning("Cannot join a Session without a join code.");
return (false, null);
}
Debug.Log($"Joining session with join code {sessionCode}");
try
{
var session = await m_MultiplayerServicesInterface.JoinSessionByCode(sessionCode, m_LocalUser.GetDataForUnityServices());
return (true, session);
}
catch (Exception e)
{
PublishError(e);
}
return (false, null);
}
/// <summary>
/// Attempt to join an existing session by name.
/// </summary>
public async Task<(bool Success, ISession Session)> TryJoinSessionByNameAsync(string sessionName)
{
if (!m_RateLimitJoin.CanCall)
{
Debug.LogWarning("Join Session hit the rate limit.");
return (false, null);
}
if (string.IsNullOrEmpty(sessionName))
{
Debug.LogWarning("Cannot join a Session without a session name.");
return (false, null);
}
Debug.Log($"Joining session with name {sessionName}");
try
{
var session = await m_MultiplayerServicesInterface.JoinSessionById(sessionName, m_LocalUser.GetDataForUnityServices());
return (true, session);
}
catch (Exception e)
{
PublishError(e);
}
return (false, null);
}
/// <summary>
/// Attempt to join the first session among the available sessions that match the filtered onlineMode.
/// </summary>
public async Task<(bool Success, ISession Session)> TryQuickJoinSessionAsync()
{
if (!m_RateLimitQuickJoin.CanCall)
{
Debug.LogWarning("Quick Join Session hit the rate limit.");
return (false, null);
}
try
{
var session = await m_MultiplayerServicesInterface.QuickJoinSession(m_LocalUser.GetDataForUnityServices());
return (true, session);
}
catch (Exception e)
{
PublishError(e);
}
return (false, null);
}
void ResetSession()
{
CurrentUnitySession = null;
m_LocalUser?.ResetState();
m_LocalSession?.Reset(m_LocalUser);
// no need to disconnect Netcode, it should already be handled by Netcode's callback to disconnect
}
void SubscribeToJoinedSession()
{
CurrentUnitySession.Changed += OnSessionChanged;
CurrentUnitySession.StateChanged += OnSessionStateChanged;
CurrentUnitySession.Deleted += OnSessionDeleted;
CurrentUnitySession.PlayerJoined += OnPlayerJoined;
CurrentUnitySession.PlayerHasLeft += OnPlayerHasLeft;
CurrentUnitySession.RemovedFromSession += OnRemovedFromSession;
CurrentUnitySession.PlayerPropertiesChanged += OnPlayerPropertiesChanged;
CurrentUnitySession.SessionPropertiesChanged += OnSessionPropertiesChanged;
}
void UnsubscribeFromJoinedSession()
{
CurrentUnitySession.Changed -= OnSessionChanged;
CurrentUnitySession.StateChanged -= OnSessionStateChanged;
CurrentUnitySession.Deleted -= OnSessionDeleted;
CurrentUnitySession.PlayerJoined -= OnPlayerJoined;
CurrentUnitySession.PlayerHasLeft -= OnPlayerHasLeft;
CurrentUnitySession.RemovedFromSession -= OnRemovedFromSession;
CurrentUnitySession.PlayerPropertiesChanged -= OnPlayerPropertiesChanged;
CurrentUnitySession.SessionPropertiesChanged -= OnSessionPropertiesChanged;
}
void OnSessionChanged()
{
m_LocalSession.ApplyRemoteData(CurrentUnitySession);
// as client, check if host is still in session
if (!m_LocalUser.IsHost)
{
foreach (var sessionUser in m_LocalSession.sessionUsers)
{
if (sessionUser.Value.IsHost)
{
return;
}
}
m_UnityServiceErrorMessagePub.Publish(new UnityServiceErrorMessage("Host left the session", "Disconnecting.", UnityServiceErrorMessage.Service.Session));
EndTracking();
// no need to disconnect Netcode, it should already be handled by Netcode's callback to disconnect
}
}
void OnSessionStateChanged(SessionState sessionState)
{
switch (sessionState)
{
case SessionState.None:
break;
case SessionState.Connected:
Debug.Log("Session state changed: Session connected.");
break;
case SessionState.Disconnected:
Debug.Log("Session state changed: Session disconnected.");
break;
case SessionState.Deleted:
Debug.Log("Session state changed: Session deleted.");
break;
default:
throw new ArgumentOutOfRangeException(nameof(sessionState), sessionState, null);
}
}
void OnSessionDeleted()
{
Debug.Log("Session deleted.");
ResetSession();
EndTracking();
}
void OnPlayerJoined(string playerId)
{
Debug.Log($"Player joined: {playerId}");
}
void OnPlayerHasLeft(string playerId)
{
Debug.Log($"Player has left: {playerId}");
}
void OnRemovedFromSession()
{
Debug.Log("Removed from Session.");
ResetSession();
EndTracking();
}
void OnPlayerPropertiesChanged()
{
Debug.Log("Player properties changed.");
}
void OnSessionPropertiesChanged()
{
Debug.Log("Session properties changed.");
}
/// <summary>
/// Used for getting the list of all active sessions, without needing full info for each.
/// </summary>
public async Task RetrieveAndPublishSessionListAsync()
{
if (!m_RateLimitQuery.CanCall)
{
Debug.LogWarning("Retrieving the session list hit the rate limit. Will try again soon...");
return;
}
try
{
var queryResults = await m_MultiplayerServicesInterface.QuerySessions();
m_SessionListFetchedPub.Publish(new SessionListFetchedMessage(queryResults.Sessions));
}
catch (Exception e)
{
PublishError(e);
}
}
public async Task<ISession> ReconnectToSessionAsync()
{
try
{
return await m_MultiplayerServicesInterface.ReconnectToSession(m_LocalSession.SessionID);
}
catch (Exception e)
{
PublishError(e, true);
}
return null;
}
/// <summary>
/// Attempt to leave a session
/// </summary>
async void LeaveSessionAsync()
{
try
{
await CurrentUnitySession.LeaveAsync();
}
catch (Exception e)
{
PublishError(e, true);
}
finally
{
ResetSession();
}
}
public async void RemovePlayerFromSessionAsync(string uasId)
{
if (m_LocalUser.IsHost)
{
try
{
await CurrentUnitySession.AsHost().RemovePlayerAsync(uasId);
}
catch (Exception e)
{
PublishError(e);
}
}
else
{
Debug.LogError("Only the host can remove other players from the session.");
}
}
async void DeleteSessionAsync()
{
if (m_LocalUser.IsHost)
{
try
{
await CurrentUnitySession.AsHost().DeleteAsync();
}
catch (Exception e)
{
PublishError(e);
}
finally
{
ResetSession();
}
}
else
{
Debug.LogError("Only the host can delete a session.");
}
}
void PublishError(Exception e, bool checkIfDeleted = false)
{
if (e is not AggregateException aggregateException)
{
m_UnityServiceErrorMessagePub.Publish(new UnityServiceErrorMessage("Session Error", e.Message, UnityServiceErrorMessage.Service.Session, e));
return;
}
if (aggregateException.InnerException is not SessionException sessionException)
{
m_UnityServiceErrorMessagePub.Publish(new UnityServiceErrorMessage("Session Error", e.Message, UnityServiceErrorMessage.Service.Session, e));
return;
}
// If session is not found and if we are not the host, it has already been deleted. No need to publish the error here.
if (checkIfDeleted)
{
if (sessionException.Error == SessionError.SessionNotFound && !m_LocalUser.IsHost)
{
return;
}
}
if (sessionException.Error == SessionError.RateLimitExceeded)
{
m_RateLimitJoin.PutOnCooldown();
return;
}
var reason = e.InnerException == null ? e.Message : $"{e.Message} ({e.InnerException.Message})"; // Session error type, then HTTP error type.
m_UnityServiceErrorMessagePub.Publish(new UnityServiceErrorMessage("Session Error", reason, UnityServiceErrorMessage.Service.Session, e));
}
}
}