Skip to content

Commit 4b0545d

Browse files
committed
fix: CLI issues found in two-editor testing (MTT-15298)
- profiler get_stats reads traffic from the message manager's hooks, as NGO's own metrics do: bytes and messages sent and received, per message type. The profiler's Network counters it read before stayed at zero in a live session. - session reconnect connects a client again after it was kicked or timed out, instead of refusing because it had already shut down. - Messages name an unsaved scene as such instead of leaving the name blank.
1 parent 9b649bc commit 4b0545d

9 files changed

Lines changed: 137 additions & 103 deletions

File tree

‎com.unity.netcode.gameobjects/Documentation~/unity-cli-commands.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c
4141

4242
| **Command** | **Description** |
4343
| :--- | :--- |
44-
| `get_stats` | Sample network traffic over a number of frames. Message and byte counters need the Multiplayer Tools package. |
44+
| `get_stats` | Sample network traffic over a number of frames: bytes and messages sent and received, per message type. |
4545

4646
### netcode.gameobjects.session
4747

@@ -50,7 +50,7 @@ To test with several players, use [Multiplayer Play Mode](https://docs.unity3d.c
5050
| `start` | Start the NetworkManager as host, server or client, optionally with another address and port. |
5151
| `stop` | Shut the NetworkManager down. |
5252
| `kick` | Disconnect a client from the server or host. |
53-
| `reconnect` | Disconnect a client and connect it again, then wait for it to be connected. |
53+
| `reconnect` | Disconnect a client and connect it again, then wait for it to be connected. A client that was already disconnected, for example kicked or timed out, just connects again. |
5454
| `wait_ready` | Wait until a client is connected, or a server has a number of clients. |
5555

5656
### netcode.gameobjects.simulator

‎com.unity.netcode.gameobjects/Editor/CLI/NetcodeGameObjectsCliCommands.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,13 @@ internal static float WaitSeconds(double timeoutInSeconds)
109109
}
110110
}
111111

112-
/// <summary>Network traffic, as the Network Profiler shows it: group <c>netcode.gameobjects.profiler</c>.</summary>
112+
/// <summary>Network traffic: group <c>netcode.gameobjects.profiler</c>.</summary>
113113
internal static class NetcodeGameObjectsProfilerCliCommands
114114
{
115115
private const string k_Group = NgoCliQueries.Group + ".profiler";
116116
private const string k_Tag = NetcodeGameObjectsCliCommands.Tag;
117117

118-
[CliGroupCommand(k_Group, "Sample network traffic over N frames: the profiler's network counters (messages, RPCs, NetworkVariables, spawns and bytes, with Multiplayer Tools installed), clients with round trip times, and the spawned object count. Requires a running session.", Tags = new[] { k_Tag })]
118+
[CliGroupCommand(k_Group, "Sample network traffic over N frames: bytes and messages sent and received, per message type, clients with round trip times, and the spawned object count. Requires a running session.", Tags = new[] { k_Tag })]
119119
private static async Task<object> GetStats(
120120
[CliArg("frames", "Frames to sample.")] int frames = 120,
121121
[CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null,
@@ -153,7 +153,7 @@ private static object Kick(
153153
[CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null)
154154
=> NgoCliOutput.ToWire(NgoCliQueries.Kick(clientId, reason, manager));
155155

156-
[CliGroupCommand(k_Group, "Shut a client down and connect it again with the same settings, then wait until it's connected. Tests reconnection handling.", Tags = new[] { k_Tag })]
156+
[CliGroupCommand(k_Group, "Shut a client down and connect it again with the same settings, then wait until it's connected. A client that was already disconnected (kicked or timed out) just connects again. Tests reconnection handling.", Tags = new[] { k_Tag })]
157157
private static async Task<object> Reconnect(
158158
[CliArg("manager", "NetworkManager name or hierarchy path, when there are several.")] string manager = null,
159159
[CliArg("timeout", "Seconds to wait for the reconnection.")] double timeoutInSeconds = 30)

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliModels.cs‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -359,21 +359,26 @@ internal class StatsResult
359359
public string Role;
360360
public int Frames;
361361
public double Seconds;
362-
public bool MultiplayerToolsInstalled;
363-
/// <summary>Counters with traffic during the sample, largest first.</summary>
364-
public List<CounterStat> Counters = new List<CounterStat>();
365-
/// <summary>Names of the counters that stayed at zero.</summary>
366-
public List<string> IdleCounters = new List<string>();
362+
/// <summary>Bytes handed to and read from the transport, in message batches.</summary>
363+
public long BytesSent;
364+
public long BytesReceived;
365+
public double BytesSentPerSecond;
366+
public double BytesReceivedPerSecond;
367+
public long MessagesSent;
368+
public long MessagesReceived;
369+
/// <summary>Traffic per message type, largest first.</summary>
370+
public List<MessageStat> Messages = new List<MessageStat>();
367371
public List<ClientInfo> Clients = new List<ClientInfo>();
368372
public int? SpawnedObjectCount;
369373
public string Note;
370374
}
371375

372-
internal class CounterStat
376+
internal class MessageStat
373377
{
374-
public string Name;
375-
public long Total;
376-
public double PerSecond;
377-
public long MaxPerFrame;
378+
public string Message;
379+
public long Sent;
380+
public long Received;
381+
public long BytesSent;
382+
public long BytesReceived;
378383
}
379384
}

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Authoring.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ internal static CreateNetworkManagerResult CreateNetworkManager(string name, Net
3838
var existing = FindManagers();
3939
if (existing.Count > 0)
4040
{
41-
throw new InvalidOperationException($"The open scenes already have a NetworkManager ({string.Join(", ", existing.Select(m => $"{GetHierarchyPath(m.transform)} in {m.gameObject.scene.name}"))}). A session uses one; inspect it with netcode.gameobjects.config get.");
41+
throw new InvalidOperationException($"The open scenes already have a NetworkManager ({string.Join(", ", existing.Select(m => $"{GetHierarchyPath(m.transform)} in {SceneLabel(m.gameObject.scene)}"))}). A session uses one; inspect it with netcode.gameobjects.config get.");
4242
}
4343

4444
var scene = SceneManager.GetActiveScene();

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Config.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ void Add(string severity, string code, string asset, string message)
242242

243243
private static void ValidateManager(NetworkManager manager, Action<string, string, string, string> add)
244244
{
245-
var where = $"{manager.gameObject.scene.name}/{GetHierarchyPath(manager.transform)}";
245+
var where = $"{SceneLabel(manager.gameObject.scene)}/{GetHierarchyPath(manager.transform)}";
246246
var config = manager.NetworkConfig;
247247
if (config == null)
248248
{

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Session.cs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,15 +129,23 @@ internal static SessionResult Kick(long clientId, string reason, string managerF
129129
internal static async Task<WaitReadyResult> ReconnectAsync(string managerFilter, float timeoutSeconds)
130130
{
131131
ValidateTimeout(timeoutSeconds);
132-
var manager = ResolveRunningManager(managerFilter);
132+
var manager = ResolveManager(managerFilter);
133+
if (!EditorApplication.isPlaying)
134+
{
135+
throw new InvalidOperationException(NotPlayingMessage);
136+
}
133137
if (manager.IsServer)
134138
{
135139
throw new InvalidOperationException($"{manager.name} is the {GetRole(manager)}. reconnect is for clients; restart a server with netcode.gameobjects.session stop, then start.");
136140
}
137141

138142
var started = EditorApplication.timeSinceStartup;
139-
manager.Shutdown();
140-
await WaitUntilAsync(() => !manager.IsListening && !manager.ShutdownInProgress, timeoutSeconds, "the client to shut down");
143+
// A client that was kicked or timed out has already shut down; connect it again as it is.
144+
if (manager.IsListening || manager.ShutdownInProgress)
145+
{
146+
manager.Shutdown();
147+
await WaitUntilAsync(() => !manager.IsListening && !manager.ShutdownInProgress, timeoutSeconds, "the client to shut down");
148+
}
141149

142150
using (var errors = new LogCapture())
143151
{

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.Stats.cs‎

Lines changed: 95 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
using System.Collections.Generic;
33
using System.Linq;
44
using System.Threading.Tasks;
5-
using Unity.Profiling;
6-
using Unity.Profiling.LowLevel;
7-
using Unity.Profiling.LowLevel.Unsafe;
85
using UnityEditor;
96
using UnityEngine;
107

@@ -13,9 +10,9 @@ namespace Unity.Netcode.GameObjects.Editor.Cli
1310
internal static partial class NgoCliQueries
1411
{
1512
/// <summary>
16-
/// Samples the profiler's Network counters for <paramref name="frames"/> frames: with Multiplayer Tools
17-
/// installed these are Netcode for GameObjects' message, RPC, NetworkVariable, spawn and byte counters.
18-
/// Adds the manager's clients with their round trip times. Doesn't block the main thread.
13+
/// Samples the manager's network traffic for <paramref name="frames"/> frames: the bytes and messages it sends
14+
/// and receives, per message type, read from its message manager as Netcode for GameObjects' own metrics
15+
/// are. Adds the manager's clients with their round trip times. Doesn't block the main thread.
1916
/// </summary>
2017
internal static Task<StatsResult> SampleStatsAsync(string managerFilter, int frames, float timeoutSeconds)
2118
{
@@ -30,129 +27,144 @@ internal static Task<StatsResult> SampleStatsAsync(string managerFilter, int fra
3027
throw new InvalidOperationException("Play mode is paused, so no frames run. Unpause (editor.playmode pause) and retry.");
3128
}
3229

33-
var recorders = StartNetworkRecorders(frames);
30+
var messageManager = manager.MessageManager;
31+
var traffic = new TrafficHooks();
32+
messageManager.Hook(traffic);
3433
var completion = new TaskCompletionSource<StatsResult>();
3534
var startFrame = Time.frameCount;
3635
var startTime = EditorApplication.timeSinceStartup;
3736
var deadline = startTime + timeoutSeconds;
3837

39-
void Finish()
38+
void Stop()
4039
{
4140
EditorApplication.update -= Tick;
42-
try
43-
{
44-
completion.TrySetResult(BuildStats(manager, recorders, Time.frameCount - startFrame, EditorApplication.timeSinceStartup - startTime));
45-
}
46-
catch (Exception e)
47-
{
48-
completion.TrySetException(e);
49-
}
50-
finally
51-
{
52-
foreach (var recorder in recorders.Values)
53-
{
54-
recorder.Dispose();
55-
}
56-
}
41+
messageManager.Unhook(traffic);
5742
}
5843

5944
void Tick()
6045
{
6146
if (!EditorApplication.isPlaying || manager == null)
6247
{
63-
EditorApplication.update -= Tick;
64-
foreach (var recorder in recorders.Values)
65-
{
66-
recorder.Dispose();
67-
}
48+
Stop();
6849
completion.TrySetException(new InvalidOperationException("Play mode stopped while sampling."));
6950
return;
7051
}
71-
if (Time.frameCount - startFrame >= frames || EditorApplication.timeSinceStartup >= deadline)
52+
if (Time.frameCount - startFrame < frames && EditorApplication.timeSinceStartup < deadline)
53+
{
54+
return;
55+
}
56+
Stop();
57+
try
58+
{
59+
completion.TrySetResult(BuildStats(manager, traffic, Time.frameCount - startFrame, EditorApplication.timeSinceStartup - startTime));
60+
}
61+
catch (Exception e)
7262
{
73-
Finish();
63+
completion.TrySetException(e);
7464
}
7565
}
7666

7767
EditorApplication.update += Tick;
7868
return completion.Task;
7969
}
8070

81-
private static Dictionary<string, ProfilerRecorder> StartNetworkRecorders(int capacity)
82-
{
83-
var handles = new List<ProfilerRecorderHandle>();
84-
ProfilerRecorderHandle.GetAvailable(handles);
85-
var recorders = new Dictionary<string, ProfilerRecorder>();
86-
foreach (var handle in handles)
87-
{
88-
var description = ProfilerRecorderHandle.GetDescription(handle);
89-
// Counters only: the Network category also holds the editor connection's timing markers.
90-
if (description.Category != ProfilerCategory.Network || (description.Flags & MarkerFlags.Counter) == 0 || recorders.ContainsKey(description.Name))
91-
{
92-
continue;
93-
}
94-
recorders[description.Name] = ProfilerRecorder.StartNew(ProfilerCategory.Network, description.Name, capacity);
95-
}
96-
return recorders;
97-
}
98-
99-
private static StatsResult BuildStats(NetworkManager manager, Dictionary<string, ProfilerRecorder> recorders, int frames, double seconds)
71+
private static StatsResult BuildStats(NetworkManager manager, TrafficHooks traffic, int frames, double seconds)
10072
{
10173
var result = new StatsResult
10274
{
10375
Manager = manager.name,
10476
Role = GetRole(manager),
10577
Frames = frames,
10678
Seconds = Math.Round(seconds, 3),
107-
MultiplayerToolsInstalled = MultiplayerToolsInstalled,
79+
BytesSent = traffic.BytesSent,
80+
BytesReceived = traffic.BytesReceived,
81+
BytesSentPerSecond = seconds > 0 ? Math.Round(traffic.BytesSent / seconds, 1) : 0,
82+
BytesReceivedPerSecond = seconds > 0 ? Math.Round(traffic.BytesReceived / seconds, 1) : 0,
83+
MessagesSent = traffic.Messages.Values.Sum(m => m.Sent),
84+
MessagesReceived = traffic.Messages.Values.Sum(m => m.Received),
85+
Messages = traffic.Messages.Values
86+
.OrderByDescending(m => m.BytesSent + m.BytesReceived)
87+
.ThenBy(m => m.Message, StringComparer.Ordinal)
88+
.ToList(),
10889
SpawnedObjectCount = manager.SpawnManager?.SpawnedObjects.Count,
10990
};
11091

111-
foreach (var pair in recorders)
92+
if (manager.IsListening)
11293
{
113-
var recorder = pair.Value;
114-
if (!recorder.Valid)
115-
{
116-
continue;
117-
}
118-
long total = 0;
119-
long max = 0;
120-
for (var i = 0; i < recorder.Count; i++)
121-
{
122-
var value = recorder.GetSample(i).Value;
123-
total += value;
124-
max = Math.Max(max, value);
125-
}
126-
if (total == 0)
94+
result.Clients = ListClients(manager).Clients;
95+
}
96+
if (result.MessagesSent == 0 && result.MessagesReceived == 0)
97+
{
98+
result.Note = "No messages were sent or received during the sample. A host on its own sends nothing over the network; connect a client (another editor or a Multiplayer Play Mode player).";
99+
}
100+
return result;
101+
}
102+
103+
/// <summary>
104+
/// Counts what the message manager sends and receives, from the same hooks that feed Netcode for GameObjects'
105+
/// metrics: message sizes per type, and batch sizes for the bytes handed to and read from the transport.
106+
/// </summary>
107+
private sealed class TrafficHooks : INetworkHooks
108+
{
109+
public long BytesSent;
110+
public long BytesReceived;
111+
public readonly Dictionary<Type, MessageStat> Messages = new Dictionary<Type, MessageStat>();
112+
113+
private MessageStat For(Type type)
114+
{
115+
if (!Messages.TryGetValue(type, out var stat))
127116
{
128-
result.IdleCounters.Add(pair.Key);
129-
continue;
117+
stat = new MessageStat { Message = type.Name };
118+
Messages[type] = stat;
130119
}
131-
result.Counters.Add(new CounterStat
132-
{
133-
Name = pair.Key,
134-
Total = total,
135-
MaxPerFrame = max,
136-
PerSecond = seconds > 0 ? Math.Round(total / seconds, 1) : 0,
137-
});
120+
return stat;
138121
}
139-
result.IdleCounters.Sort(StringComparer.Ordinal);
140-
result.Counters = result.Counters.OrderByDescending(c => c.Total).ThenBy(c => c.Name, StringComparer.Ordinal).ToList();
141122

142-
if (manager.IsListening)
123+
public void OnAfterSendMessage<T>(ulong clientId, ref T message, NetworkDelivery delivery, int messageSizeBytes) where T : INetworkMessage
143124
{
144-
result.Clients = ListClients(manager).Clients;
125+
var stat = For(typeof(T));
126+
stat.Sent++;
127+
stat.BytesSent += messageSizeBytes;
145128
}
146129

147-
if (!MultiplayerToolsInstalled)
130+
public void OnBeforeReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes)
148131
{
149-
result.Note = "Netcode for GameObjects reports message and byte counters through Multiplayer Tools. Install it (package add com.unity.multiplayer.tools) for per-message-type traffic.";
132+
var stat = For(messageType);
133+
stat.Received++;
134+
stat.BytesReceived += messageSizeBytes;
150135
}
151-
else if (result.Counters.Count == 0)
136+
137+
public void OnAfterSendBatch(ulong clientId, int messageCount, int batchSizeInBytes, NetworkDelivery delivery) => BytesSent += batchSizeInBytes;
138+
139+
public void OnAfterReceiveBatch(ulong senderId, int messageCount, int batchSizeInBytes) => BytesReceived += batchSizeInBytes;
140+
141+
public void OnBeforeSendMessage<T>(ulong clientId, ref T message, NetworkDelivery delivery) where T : INetworkMessage
142+
{
143+
}
144+
145+
public void OnAfterReceiveMessage(ulong senderId, Type messageType, int messageSizeBytes)
146+
{
147+
}
148+
149+
public void OnBeforeSendBatch(ulong clientId, int messageCount, int batchSizeInBytes, NetworkDelivery delivery)
150+
{
151+
}
152+
153+
public void OnBeforeReceiveBatch(ulong senderId, int messageCount, int batchSizeInBytes)
154+
{
155+
}
156+
157+
public bool OnVerifyCanSend(ulong destinationId, Type messageType, NetworkDelivery delivery) => true;
158+
159+
public bool OnVerifyCanReceive(ulong senderId, Type messageType, FastBufferReader messageContent, ref NetworkContext context) => true;
160+
161+
public void OnBeforeHandleMessage<T>(ref T message, ref NetworkContext context) where T : INetworkMessage
162+
{
163+
}
164+
165+
public void OnAfterHandleMessage<T>(ref T message, ref NetworkContext context) where T : INetworkMessage
152166
{
153-
result.Note = "No network traffic was recorded. A host on its own sends nothing; connect a client (a Multiplayer Play Mode player or another editor), and check that NetworkConfig network_message_metrics is on (netcode.gameobjects.config get).";
154167
}
155-
return result;
156168
}
157169
}
158170
}

‎com.unity.netcode.gameobjects/Editor/CliQueries/NgoCliQueries.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ internal static NetworkManager ResolveManager(string filter, List<NetworkManager
394394
throw new ArgumentException($"Several NetworkManagers. Pass manager with one of: {string.Join(", ", managers.Select(m => GetHierarchyPath(m.transform)))}.");
395395
}
396396

397+
// A scene's name for messages; an unsaved scene has none.
398+
internal static string SceneLabel(UnityEngine.SceneManagement.Scene scene) => string.IsNullOrEmpty(scene.name) ? "an unsaved scene" : scene.name;
399+
397400
internal static NetworkManager ResolveRunningManager(string filter)
398401
{
399402
// Report a missing NetworkManager first: entering play mode wouldn't help.

0 commit comments

Comments
 (0)