/
PlayFabMultiplayerAgentAPI.cs
356 lines (295 loc) · 13.3 KB
/
PlayFabMultiplayerAgentAPI.cs
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
using UnityEngine.Networking;
#if ENABLE_PLAYFABSERVER_API
namespace PlayFab
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using MultiplayerAgent.Model;
using UnityEngine;
using MultiplayerAgent.Helpers;
#pragma warning disable 414
public class PlayFabMultiplayerAgentAPI
{
// These two keys are only available after allocation (once readyForPlayers returns true)
public const string SessionCookieKey = "sessionCookie";
public const string SessionIdKey = "sessionId";
public const string HeartbeatEndpointKey = "heartbeatEndpoint";
public const string ServerIdKey = "serverId";
public const string LogFolderKey = "logFolder";
public const string SharedContentFolderKey = "sharedContentFolder";
public const string CertificateFolderKey = "certificateFolder";
public const string TitleIdKey = "titleId";
public const string BuildIdKey = "buildId";
public const string RegionKey = "region";
public const string VmIdKey = "vmId";
public const string PublicIpV4AddressKey = "publicIpV4Address";
public const string FullyQualifiedDomainNameKey = "fullyQualifiedDomainName";
public delegate void OnAgentCommunicationErrorEvent(string error);
public delegate void OnMaintenanceEvent(DateTime? NextScheduledMaintenanceUtc);
public delegate void OnSessionConfigUpdate(SessionConfig sessionConfig);
public delegate void OnServerActiveEvent();
public delegate void OnShutdownEventk();
private const string GsdkConfigFileEnvVarKey = "GSDK_CONFIG_FILE";
private static string _baseUrl = string.Empty;
private static GSDKConfiguration _gsdkconfig;
private static IDictionary<string, string> _configMap;
private static SimpleJsonInstance _jsonInstance = new SimpleJsonInstance();
private static GameObject _agentView;
public static SessionConfig SessionConfig = new SessionConfig();
public static HeartbeatRequest CurrentState = new HeartbeatRequest();
public static ErrorStates CurrentErrorState = ErrorStates.Ok;
public static bool IsProcessing;
public static bool IsDebugging = true;
public static event OnShutdownEventk OnShutDownCallback;
public static event OnMaintenanceEvent OnMaintenanceCallback;
public static event OnAgentCommunicationErrorEvent OnAgentErrorCallback;
public static event OnServerActiveEvent OnServerActiveCallback;
public static event OnSessionConfigUpdate OnSessionConfigUpdateEvent;
public static void Start()
{
string fileName = Environment.GetEnvironmentVariable(GsdkConfigFileEnvVarKey);
if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
{
_gsdkconfig = _jsonInstance.DeserializeObject<GSDKConfiguration>(File.ReadAllText(fileName));
}
else
{
Debug.LogError(string.Format("Environment variable {0} not defined", GsdkConfigFileEnvVarKey));
Application.Quit();
}
_baseUrl = string.Format("http://{0}/v1/sessionHosts/{1}/heartbeats", _gsdkconfig.HeartbeatEndpoint, _gsdkconfig.SessionHostId);
CurrentState.CurrentGameState = GameState.Initializing;
CurrentErrorState = ErrorStates.Ok;
CurrentState.CurrentPlayers = new List<ConnectedPlayer>();
if (_configMap == null)
{
_configMap = CreateConfigMap(_gsdkconfig);
}
if (IsDebugging)
{
Debug.Log(_baseUrl);
Debug.Log(_gsdkconfig.SessionHostId);
Debug.Log(_gsdkconfig.LogFolder);
}
//Create an agent that can talk on the main-thread and pull on an interval.
//This is a unity thing, need an object in the scene.
if(_agentView == null)
{
_agentView = new GameObject("PlayFabAgentView");
_agentView.AddComponent<PlayFabMultiplayerAgentView>();
UnityEngine.Object.DontDestroyOnLoad(_agentView);
}
}
private static IDictionary<string, string> CreateConfigMap(GSDKConfiguration localConfig)
{
var finalConfig = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<string, string> certEntry in localConfig.GameCertificates)
{
finalConfig[certEntry.Key] = certEntry.Value;
}
foreach (KeyValuePair<string, string> metadata in localConfig.BuildMetadata)
{
finalConfig[metadata.Key] = metadata.Value;
}
foreach (KeyValuePair<string, string> port in localConfig.GamePorts)
{
finalConfig[port.Key] = port.Value;
}
finalConfig[HeartbeatEndpointKey] = localConfig.HeartbeatEndpoint;
finalConfig[ServerIdKey] = localConfig.SessionHostId;
finalConfig[VmIdKey] = localConfig.VmId;
finalConfig[LogFolderKey] = localConfig.LogFolder;
finalConfig[SharedContentFolderKey] = localConfig.SharedContentFolder;
finalConfig[CertificateFolderKey] = localConfig.CertificateFolder;
finalConfig[TitleIdKey] = localConfig.TitleId;
finalConfig[BuildIdKey] = localConfig.BuildId;
finalConfig[RegionKey] = localConfig.Region;
finalConfig[PublicIpV4AddressKey] = localConfig.PublicIpV4Address;
finalConfig[FullyQualifiedDomainNameKey] = localConfig.FullyQualifiedDomainName;
return finalConfig;
}
public static void ReadyForPlayers()
{
CurrentState.CurrentGameState = GameState.StandingBy;
}
public static GameServerConnectionInfo GetGameServerConnectionInfo()
{
return _gsdkconfig.GameServerConnectionInfo;
}
public static void UpdateConnectedPlayers(IList<ConnectedPlayer> currentlyConnectedPlayers)
{
CurrentState.CurrentPlayers = currentlyConnectedPlayers;
}
public static IDictionary<string, string> GetConfigSettings()
{
return new Dictionary<string, string>(_configMap, StringComparer.OrdinalIgnoreCase);
}
public static IList<string> GetInitialPlayers()
{
return new List<string>(SessionConfig.InitialPlayers);
}
public static IEnumerator SendHeartBeatRequest()
{
string payload = _jsonInstance.SerializeObject(CurrentState);
if (string.IsNullOrEmpty(payload))
{
yield break;
}
byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);
if (IsDebugging)
{
Debug.Log($"state: {CurrentState}, payload: {payload}");
}
using (UnityWebRequest req = new UnityWebRequest(_baseUrl, UnityWebRequest.kHttpVerbPOST))
{
req.SetRequestHeader("Accept","application/json");
req.SetRequestHeader("Content-Type","application/json");
req.downloadHandler = new DownloadHandlerBuffer();
req.uploadHandler = new UploadHandlerRaw(payloadBytes) {contentType = "application/json"};
yield return req.SendWebRequest();
if (req.isNetworkError || req.isHttpError)
{
Guid guid = Guid.NewGuid();
Debug.LogFormat("CurrentError: {0} - {1}", req.error, guid.ToString());
//Exponential backoff for 30 minutes for retries.
switch (CurrentErrorState)
{
case ErrorStates.Ok:
CurrentErrorState = ErrorStates.Retry30S;
if (IsDebugging)
{
Debug.Log("Retrying heartbeat in 30s");
}
break;
case ErrorStates.Retry30S:
CurrentErrorState = ErrorStates.Retry5M;
if (IsDebugging)
{
Debug.Log("Retrying heartbeat in 5m");
}
break;
case ErrorStates.Retry5M:
CurrentErrorState = ErrorStates.Retry10M;
if (IsDebugging)
{
Debug.Log("Retrying heartbeat in 10m");
}
break;
case ErrorStates.Retry10M:
CurrentErrorState = ErrorStates.Retry15M;
if (IsDebugging)
{
Debug.Log("Retrying heartbeat in 15m");
}
break;
case ErrorStates.Retry15M:
CurrentErrorState = ErrorStates.Cancelled;
if (IsDebugging)
{
Debug.Log("Agent reconnection cannot be established - cancelling");
}
break;
}
if (OnAgentErrorCallback != null)
{
OnAgentErrorCallback.Invoke(req.error);
}
IsProcessing = false;
}
else // success path
{
string json = Encoding.UTF8.GetString(req.downloadHandler.data);
if (string.IsNullOrEmpty(json))
{
yield break;
}
HeartbeatResponse hb = _jsonInstance.DeserializeObject<HeartbeatResponse>(json);
if (hb != null)
{
ProcessAgentResponse(hb);
}
CurrentErrorState = ErrorStates.Ok;
IsProcessing = false;
}
}
}
private static void ProcessAgentResponse(HeartbeatResponse heartBeat)
{
bool updateConfig = false;
if (SessionConfig != heartBeat.SessionConfig)
{
updateConfig = true;
}
SessionConfig.CopyNonNullFields(heartBeat.SessionConfig);
try
{
if(OnSessionConfigUpdateEvent != null)
OnSessionConfigUpdateEvent.Invoke(SessionConfig);
}
catch(Exception e)
{
if(IsDebugging)
{
Debug.LogException(e);
}
}
if (!string.IsNullOrEmpty(heartBeat.NextScheduledMaintenanceUtc))
{
DateTime scheduledMaintDate;
if (DateTime.TryParse(
heartBeat.NextScheduledMaintenanceUtc,
null,
DateTimeStyles.RoundtripKind,
out scheduledMaintDate))
{
if (OnMaintenanceCallback != null)
{
OnMaintenanceCallback.Invoke(scheduledMaintDate);
}
}
}
switch (heartBeat.Operation)
{
case GameOperation.Continue:
//No Action Required.
break;
case GameOperation.Active:
//Transition Server State to Active.
CurrentState.CurrentGameState = GameState.Active;
_configMap.Add(SessionIdKey, heartBeat.SessionConfig.SessionId);
_configMap.Add(SessionCookieKey, heartBeat.SessionConfig.SessionCookie);
if (OnServerActiveCallback != null)
{
OnServerActiveCallback.Invoke();
}
break;
case GameOperation.Terminate:
if (CurrentState.CurrentGameState == GameState.Terminated)
{
break;
}
//Transition Server to a Termination state.
CurrentState.CurrentGameState = GameState.Terminating;
if (OnShutDownCallback != null)
{
OnShutDownCallback.Invoke();
}
break;
default:
Debug.LogWarning("Unknown operation received: " + heartBeat.Operation);
break;
}
if (IsDebugging)
{
Debug.LogFormat("Operation: {0}, Maintenance:{1}, State: {2}", heartBeat.Operation, heartBeat.NextScheduledMaintenanceUtc,
CurrentState.CurrentGameState);
}
}
}
}
#endif