Skip to content

Commit b8be4a4

Browse files
Feature/initial relay utp remove relay sdk calls (#1034)
* DST-528: Extracted Relay SDK calls out of UTP adapter for MLAPI; it now accepts a variable passed in via a setter method. Also updated the sample test project included to illustrate these changes. * DST-528: Made some changes that address feedback comments; mainly restructured the manner that code external to UTPTransport passes in the requisite relay server data so that external code doesn't need to know about the internal data structures that UTPTransport uses. * DST-528: Removing minor changes that were erroneously left in when taking other approaches. * DST-528: Addressing minor code review changes. * Revert "Revert "Feature/initial relay utp remove relay sdk calls (#1032)" (#1033)" This reverts commit cd54529.
1 parent cd54529 commit b8be4a4

File tree

14 files changed

+405
-212
lines changed

14 files changed

+405
-212
lines changed

com.unity.multiplayer.transport.utp/Runtime/UTPTransport.cs

Lines changed: 83 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,6 @@
44
using System.Threading.Tasks;
55
using Unity.Networking.Transport;
66
using Unity.Networking.Transport.Relay;
7-
#if ENABLE_RELAY_SERVICE
8-
using Unity.Services.Relay;
9-
using Unity.Services.Relay.Allocations;
10-
using Unity.Services.Relay.Models;
11-
using Unity.Services.Core;
12-
#endif
137

148
using MLAPI.Transports.Tasks;
159
using UnityEngine;
@@ -42,14 +36,11 @@ private enum State
4236
[SerializeField] private int m_MessageBufferSize = MaximumMessageLength;
4337
[SerializeField] private string m_ServerAddress = "127.0.0.1";
4438
[SerializeField] private ushort m_ServerPort = 7777;
45-
[SerializeField] private int m_RelayMaxPlayers = 10;
46-
[SerializeField] private string m_RelayServer = "https://relay-allocations.cloud.unity3d.com";
4739

4840
private State m_State = State.Disconnected;
4941
private NetworkDriver m_Driver;
5042
private List<INetworkParameter> m_NetworkParameters;
5143
private byte[] m_MessageBuffer;
52-
private string m_RelayJoinCode;
5344
private ulong m_ServerClientId;
5445

5546
private NetworkPipeline m_UnreliableSequencedPipeline;
@@ -58,16 +49,20 @@ private enum State
5849

5950
public override ulong ServerClientId => m_ServerClientId;
6051

61-
public string RelayJoinCode => m_RelayJoinCode;
62-
6352
public ProtocolType Protocol => m_ProtocolType;
6453

54+
private RelayServerData m_RelayServerData;
55+
6556
private void InitDriver()
6657
{
6758
if (m_NetworkParameters.Count > 0)
59+
{
6860
m_Driver = NetworkDriver.Create(m_NetworkParameters.ToArray());
61+
}
6962
else
63+
{
7064
m_Driver = NetworkDriver.Create();
65+
}
7166

7267
m_UnreliableSequencedPipeline = m_Driver.CreatePipeline(typeof(UnreliableSequencedPipelineStage));
7368
m_ReliableSequencedPipeline = m_Driver.CreatePipeline(typeof(ReliableSequencedPipelineStage));
@@ -79,39 +74,8 @@ private void InitDriver()
7974
private void DisposeDriver()
8075
{
8176
if (m_Driver.IsCreated)
82-
m_Driver.Dispose();
83-
}
84-
85-
private static RelayAllocationId ConvertFromAllocationIdBytes(byte[] allocationIdBytes)
86-
{
87-
unsafe
8877
{
89-
fixed (byte* ptr = allocationIdBytes)
90-
{
91-
return RelayAllocationId.FromBytePointer(ptr, allocationIdBytes.Length);
92-
}
93-
}
94-
}
95-
96-
private static RelayHMACKey ConvertFromHMAC(byte[] hmac)
97-
{
98-
unsafe
99-
{
100-
fixed (byte* ptr = hmac)
101-
{
102-
return RelayHMACKey.FromBytePointer(ptr, RelayHMACKey.k_Length);
103-
}
104-
}
105-
}
106-
107-
private static RelayConnectionData ConvertConnectionData(byte[] connectionData)
108-
{
109-
unsafe
110-
{
111-
fixed (byte* ptr = connectionData)
112-
{
113-
return RelayConnectionData.FromBytePointer(ptr, RelayConnectionData.k_Length);
114-
}
78+
m_Driver.Dispose();
11579
}
11680
}
11781

@@ -134,7 +98,9 @@ private NetworkPipeline SelectSendPipeline(NetworkChannel channel, int size)
13498
case NetworkDelivery.ReliableFragmentedSequenced:
13599
// No need to send on the fragmented pipeline if data is smaller than MTU.
136100
if (size < NetworkParameterConstants.MTU)
101+
{
137102
return m_ReliableSequencedPipeline;
103+
}
138104

139105
return m_ReliableSequencedFragmentedPipeline;
140106

@@ -150,43 +116,17 @@ private IEnumerator ClientBindAndConnect(SocketTask task)
150116

151117
if (m_ProtocolType == ProtocolType.RelayUnityTransport)
152118
{
153-
#if !ENABLE_RELAY_SERVICE
154-
Debug.LogError("You must have Relay SDK installed via the UDash in order to use the relay transport");
155-
yield return null;
156-
#else
157-
var joinTask = RelayService.AllocationsApiClient.JoinRelayAsync(new JoinRelayRequest(new JoinRequest(m_RelayJoinCode)));
158-
159-
while(!joinTask.IsCompleted)
160-
yield return null;
161-
162-
if (joinTask.IsFaulted)
119+
//This comparison is currently slow since RelayServerData does not implement a custom comparison operator that doesn't use
120+
//reflection, but this does not live in the context of a performance-critical loop, it runs once at initial connection time.
121+
if(m_RelayServerData.Equals(default(RelayServerData)))
163122
{
164-
Debug.LogError("Join Relay request failed");
123+
Debug.LogError("You must call SetRelayServerData() at least once before calling StartRelayServer.");
165124
task.IsDone = true;
166125
task.Success = false;
167126
yield break;
168127
}
169128

170-
var allocation = joinTask.Result.Result.Data.Allocation;
171-
172-
serverEndpoint = NetworkEndPoint.Parse(allocation.RelayServer.IpV4, (ushort)allocation.RelayServer.Port);
173-
174-
var allocationId = ConvertFromAllocationIdBytes(allocation.AllocationIdBytes);
175-
176-
var connectionData = ConvertConnectionData(allocation.ConnectionData);
177-
var hostConnectionData = ConvertConnectionData(allocation.HostConnectionData);
178-
var key = ConvertFromHMAC(allocation.Key);
179-
180-
Debug.Log($"client: {allocation.ConnectionData[0]} {allocation.ConnectionData[1]}");
181-
Debug.Log($"host: {allocation.HostConnectionData[0]} {allocation.HostConnectionData[1]}");
182-
183-
Debug.Log($"client: {allocation.AllocationId}");
184-
185-
var relayServerData = new RelayServerData(ref serverEndpoint, 0, ref allocationId, ref connectionData, ref hostConnectionData, ref key);
186-
relayServerData.ComputeNewNonce();
187-
188-
m_NetworkParameters.Add(new RelayNetworkParameter{ ServerData = relayServerData });
189-
#endif
129+
m_NetworkParameters.Add(new RelayNetworkParameter{ ServerData = m_RelayServerData });
190130
}
191131
else
192132
{
@@ -223,8 +163,6 @@ private IEnumerator ClientBindAndConnect(SocketTask task)
223163
{
224164
Debug.LogError("Client failed to connect to server");
225165
}
226-
227-
228166
}
229167

230168
task.IsDone = true;
@@ -256,69 +194,82 @@ private IEnumerator ServerBindAndListen(SocketTask task, NetworkEndPoint endPoin
256194
{
257195
Debug.LogError("Server failed to listen");
258196
}
259-
260-
261197
}
262198

263199
task.IsDone = true;
264200
}
265201

266-
267-
private IEnumerator StartRelayServer(SocketTask task)
202+
private static RelayAllocationId ConvertFromAllocationIdBytes(byte[] allocationIdBytes)
268203
{
269-
#if !ENABLE_RELAY_SERVICE
270-
Debug.LogError("You must have Relay SDK installed via the UDash in order to use the relay transport");
271-
yield return null;
272-
#else
273-
var allocationTask = RelayService.AllocationsApiClient.CreateAllocationAsync(new CreateAllocationRequest(new AllocationRequest(m_RelayMaxPlayers)));
274-
275-
while(!allocationTask.IsCompleted)
204+
unsafe
276205
{
277-
yield return null;
206+
fixed (byte* ptr = allocationIdBytes)
207+
{
208+
return RelayAllocationId.FromBytePointer(ptr, allocationIdBytes.Length);
209+
}
278210
}
211+
}
279212

280-
if (allocationTask.IsFaulted)
213+
private static RelayHMACKey ConvertFromHMAC(byte[] hmac)
214+
{
215+
unsafe
281216
{
282-
Debug.LogError("Create allocation request failed");
283-
task.IsDone = true;
284-
task.Success = false;
285-
yield break;
217+
fixed (byte* ptr = hmac)
218+
{
219+
return RelayHMACKey.FromBytePointer(ptr, RelayHMACKey.k_Length);
220+
}
286221
}
222+
}
287223

288-
var allocation = allocationTask.Result.Result.Data.Allocation;
289-
290-
var joinCodeTask = RelayService.AllocationsApiClient.CreateJoincodeAsync(new CreateJoincodeRequest(new JoinCodeRequest(allocation.AllocationId)));
224+
private static RelayConnectionData ConvertConnectionData(byte[] connectionData)
225+
{
226+
unsafe
227+
{
228+
fixed (byte* ptr = connectionData)
229+
{
230+
return RelayConnectionData.FromBytePointer(ptr, RelayConnectionData.k_Length);
231+
}
232+
}
233+
}
291234

292-
while(!joinCodeTask.IsCompleted)
235+
public void SetRelayServerData(string ipv4address, ushort port, byte[] allocationIdBytes, byte[] keyBytes, byte[] connectionDataBytes, byte[] hostConnectionDataBytes = null)
236+
{
237+
RelayConnectionData hostConnectionData;
238+
239+
var serverEndpoint = NetworkEndPoint.Parse(ipv4address, port);
240+
var allocationId = ConvertFromAllocationIdBytes(allocationIdBytes);
241+
var key = ConvertFromHMAC(keyBytes);
242+
var connectionData = ConvertConnectionData(connectionDataBytes);
243+
244+
if (hostConnectionDataBytes != null)
245+
{
246+
hostConnectionData = ConvertConnectionData(hostConnectionDataBytes);
247+
}
248+
else
293249
{
294-
yield return null;
250+
hostConnectionData = connectionData;
295251
}
252+
m_RelayServerData = new RelayServerData(ref serverEndpoint, 0, ref allocationId, ref connectionData, ref hostConnectionData, ref key);
253+
m_RelayServerData.ComputeNewNonce();
254+
}
296255

297-
if (joinCodeTask.IsFaulted)
256+
private IEnumerator StartRelayServer(SocketTask task)
257+
{
258+
//This comparison is currently slow since RelayServerData does not implement a custom comparison operator that doesn't use
259+
//reflection, but this does not live in the context of a performance-critical loop, it runs once at initial connection time.
260+
if (m_RelayServerData.Equals(default(RelayServerData)))
298261
{
299-
Debug.LogError("Create join code request failed");
262+
Debug.LogError("You must call SetRelayServerData() at least once before calling StartRelayServer.");
300263
task.IsDone = true;
301264
task.Success = false;
302265
yield break;
303266
}
267+
else
268+
{
269+
m_NetworkParameters.Add(new RelayNetworkParameter { ServerData = m_RelayServerData });
304270

305-
m_RelayJoinCode = joinCodeTask.Result.Result.Data.JoinCode;
306-
307-
var serverEndpoint = NetworkEndPoint.Parse(allocation.RelayServer.IpV4, (ushort)allocation.RelayServer.Port);
308-
// Debug.Log($"Relay Server endpoint: {allocation.RelayServer.IpV4}:{(ushort)allocation.RelayServer.Port}");
309-
310-
var allocationId = ConvertFromAllocationIdBytes(allocation.AllocationIdBytes);
311-
var connectionData = ConvertConnectionData(allocation.ConnectionData);
312-
var key = ConvertFromHMAC(allocation.Key);
313-
314-
315-
var relayServerData = new RelayServerData(ref serverEndpoint, 0, ref allocationId, ref connectionData, ref connectionData, ref key);
316-
relayServerData.ComputeNewNonce();
317-
318-
m_NetworkParameters.Add(new RelayNetworkParameter{ ServerData = relayServerData });
319-
320-
yield return ServerBindAndListen(task, NetworkEndPoint.AnyIpv4);
321-
#endif
271+
yield return ServerBindAndListen(task, NetworkEndPoint.AnyIpv4);
272+
}
322273
}
323274

324275
private bool AcceptConnection()
@@ -396,8 +347,15 @@ private void Update()
396347
if (m_Driver.IsCreated)
397348
{
398349
m_Driver.ScheduleUpdate().Complete();
399-
while(AcceptConnection() && m_Driver.IsCreated);
400-
while(ProcessEvent() && m_Driver.IsCreated);
350+
while(AcceptConnection() && m_Driver.IsCreated)
351+
{
352+
;
353+
}
354+
355+
while (ProcessEvent() && m_Driver.IsCreated)
356+
{
357+
;
358+
}
401359
}
402360

403361
}
@@ -417,14 +375,6 @@ private static unsafe NetworkConnection ParseClientId(ulong mlapiConnectionId)
417375
return *(NetworkConnection*)&mlapiConnectionId;
418376
}
419377

420-
public void SetRelayJoinCode(string value)
421-
{
422-
if (m_State == State.Disconnected)
423-
{
424-
m_RelayJoinCode = value;
425-
}
426-
}
427-
428378
public override void DisconnectLocalClient()
429379
{
430380
Debug.Assert(m_State == State.Connected, "DisconnectLocalClient should be called on a connected client");
@@ -462,20 +412,13 @@ public override void Init()
462412

463413
m_NetworkParameters = new List<INetworkParameter>();
464414

465-
466415
// If we want to be able to actually handle messages MaximumMessageLength bytes in
467416
// size, we need to allow a bit more than that in FragmentationUtility since this needs
468417
// to account for headers and such. 128 bytes is plenty enough for such overhead.
469418
var maxFragmentationCapacity = MaximumMessageLength + 128;
470419
m_NetworkParameters.Add(new FragmentationUtility.Parameters(){PayloadCapacity = maxFragmentationCapacity});
471420

472421
m_MessageBuffer = new byte[m_MessageBufferSize];
473-
#if ENABLE_RELAY_SERVICE
474-
if (m_ProtocolType == ProtocolType.RelayUnityTransport) {
475-
Unity.Services.Relay.RelayService.Configuration.BasePath = m_RelayServer;
476-
UnityServices.Initialize();
477-
}
478-
#endif
479422
}
480423

481424
public override NetworkEvent PollEvent(out ulong clientId, out NetworkChannel networkChannel, out ArraySegment<byte> payload, out float receiveTime)
@@ -510,7 +453,9 @@ public override void Send(ulong clientId, ArraySegment<byte> data, NetworkChanne
510453
}
511454

512455
if (m_Driver.EndSend(writer) == size)
456+
{
513457
return;
458+
}
514459
}
515460

516461
Debug.LogError("Error sending the message");
@@ -519,7 +464,9 @@ public override void Send(ulong clientId, ArraySegment<byte> data, NetworkChanne
519464
public override SocketTasks StartClient()
520465
{
521466
if (m_Driver.IsCreated)
467+
{
522468
return SocketTask.Fault.AsTasks();
469+
}
523470

524471
var task = SocketTask.Working;
525472
StartCoroutine(ClientBindAndConnect(task));
@@ -529,7 +476,9 @@ public override SocketTasks StartClient()
529476
public override SocketTasks StartServer()
530477
{
531478
if (m_Driver.IsCreated)
479+
{
532480
return SocketTask.Fault.AsTasks();
481+
}
533482

534483
var task = SocketTask.Working;
535484
switch (m_ProtocolType)

com.unity.multiplayer.transport.utp/Runtime/com.unity.multiplayer.transport.utp.asmdef

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66
"Unity.Jobs",
77
"Unity.Burst",
88
"Unity.Multiplayer.MLAPI.Runtime",
9-
"Unity.Networking.Transport",
10-
"Unity.Services.Relay",
11-
"Unity.Services.Core"
9+
"Unity.Networking.Transport"
1210
],
1311
"includePlatforms": [],
1412
"excludePlatforms": [],
@@ -17,12 +15,6 @@
1715
"precompiledReferences": [],
1816
"autoReferenced": true,
1917
"defineConstraints": [],
20-
"versionDefines": [
21-
{
22-
"name": "com.unity.services.relay",
23-
"expression": "0.0.1-preview.3",
24-
"define": "ENABLE_RELAY_SERVICE"
25-
}
26-
],
18+
"versionDefines": [],
2719
"noEngineReferences": false
2820
}

0 commit comments

Comments
 (0)