| 1 |
using System; |
| 2 |
using System.Diagnostics.CodeAnalysis; |
| 3 |
using System.Collections.Generic; |
| 4 |
using System.IO; |
| 5 |
using System.Net; |
| 6 |
using System.Net.Sockets; |
| 7 |
using Newtonsoft.Json; |
| 8 |
using System.Threading; |
| 9 |
using System.Threading.Tasks; |
| 10 |
using GodotTools.IdeMessaging.Requests; |
| 11 |
using GodotTools.IdeMessaging.Utils; |
| 12 |
|
| 13 |
namespace GodotTools.IdeMessaging |
| 14 |
{ |
| 15 |
|
| 16 |
public sealed class Client : IDisposable |
| 17 |
{ |
| 18 |
private readonly ILogger logger; |
| 19 |
|
| 20 |
private readonly string identity; |
| 21 |
|
| 22 |
private string MetaFilePath { get; } |
| 23 |
private DateTime? metaFileModifiedTime; |
| 24 |
private GodotIdeMetadata godotIdeMetadata; |
| 25 |
private readonly FileSystemWatcher fsWatcher; |
| 26 |
|
| 27 |
public string GodotEditorExecutablePath => godotIdeMetadata.EditorExecutablePath; |
| 28 |
|
| 29 |
private readonly IMessageHandler messageHandler; |
| 30 |
|
| 31 |
private Peer? peer; |
| 32 |
private readonly SemaphoreSlim connectionSem = new SemaphoreSlim(1); |
| 33 |
|
| 34 |
private readonly Queue<NotifyAwaiter<bool>> clientConnectedAwaiters = new Queue<NotifyAwaiter<bool>>(); |
| 35 |
private readonly Queue<NotifyAwaiter<bool>> clientDisconnectedAwaiters = new Queue<NotifyAwaiter<bool>>(); |
| 36 |
|
| 37 |
|
| 38 |
public async Task<bool> AwaitConnected() |
| 39 |
{ |
| 40 |
var awaiter = new NotifyAwaiter<bool>(); |
| 41 |
clientConnectedAwaiters.Enqueue(awaiter); |
| 42 |
return await awaiter; |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
public async Task<bool> AwaitDisconnected() |
| 47 |
{ |
| 48 |
var awaiter = new NotifyAwaiter<bool>(); |
| 49 |
clientDisconnectedAwaiters.Enqueue(awaiter); |
| 50 |
return await awaiter; |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
public bool IsDisposed { get; private set; } |
| 55 |
|
| 56 |
|
| 57 |
[MemberNotNullWhen(true, "peer")] |
| 58 |
public bool IsConnected => peer != null && !peer.IsDisposed && peer.IsTcpClientConnected; |
| 59 |
|
| 60 |
|
| 61 |
public event Action Connected |
| 62 |
{ |
| 63 |
add |
| 64 |
{ |
| 65 |
if (peer != null && !peer.IsDisposed) |
| 66 |
peer.Connected += value; |
| 67 |
} |
| 68 |
remove |
| 69 |
{ |
| 70 |
if (peer != null && !peer.IsDisposed) |
| 71 |
peer.Connected -= value; |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
public event Action Disconnected |
| 77 |
{ |
| 78 |
add |
| 79 |
{ |
| 80 |
if (peer != null && !peer.IsDisposed) |
| 81 |
peer.Disconnected += value; |
| 82 |
} |
| 83 |
remove |
| 84 |
{ |
| 85 |
if (peer != null && !peer.IsDisposed) |
| 86 |
peer.Disconnected -= value; |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
~Client() |
| 91 |
{ |
| 92 |
Dispose(disposing: false); |
| 93 |
} |
| 94 |
|
| 95 |
public async void Dispose() |
| 96 |
{ |
| 97 |
if (IsDisposed) |
| 98 |
return; |
| 99 |
|
| 100 |
using (await connectionSem.UseAsync()) |
| 101 |
{ |
| 102 |
if (IsDisposed) |
| 103 |
return; |
| 104 |
IsDisposed = true; |
| 105 |
} |
| 106 |
|
| 107 |
Dispose(disposing: true); |
| 108 |
GC.SuppressFinalize(this); |
| 109 |
} |
| 110 |
|
| 111 |
private void Dispose(bool disposing) |
| 112 |
{ |
| 113 |
if (disposing) |
| 114 |
{ |
| 115 |
peer?.Dispose(); |
| 116 |
fsWatcher.Dispose(); |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
public Client(string identity, string godotProjectDir, IMessageHandler messageHandler, ILogger logger) |
| 121 |
{ |
| 122 |
this.identity = identity; |
| 123 |
this.messageHandler = messageHandler; |
| 124 |
this.logger = logger; |
| 125 |
|
| 126 |
string projectMetadataDir = Path.Combine(godotProjectDir, ".godot", "mono", "metadata"); |
| 127 |
|
| 128 |
if (!Directory.Exists(projectMetadataDir)) |
| 129 |
{ |
| 130 |
|
| 131 |
string nonHiddenProjectMetadataDir = Path.Combine(godotProjectDir, "godot", "mono", "metadata"); |
| 132 |
if (Directory.Exists(nonHiddenProjectMetadataDir)) |
| 133 |
{ |
| 134 |
projectMetadataDir = nonHiddenProjectMetadataDir; |
| 135 |
} |
| 136 |
else |
| 137 |
{ |
| 138 |
Directory.CreateDirectory(projectMetadataDir); |
| 139 |
} |
| 140 |
} |
| 141 |
|
| 142 |
MetaFilePath = Path.Combine(projectMetadataDir, GodotIdeMetadata.DefaultFileName); |
| 143 |
|
| 144 |
fsWatcher = new FileSystemWatcher(projectMetadataDir, GodotIdeMetadata.DefaultFileName); |
| 145 |
} |
| 146 |
|
| 147 |
private async void OnMetaFileChanged(object sender, FileSystemEventArgs e) |
| 148 |
{ |
| 149 |
if (IsDisposed) |
| 150 |
return; |
| 151 |
|
| 152 |
using (await connectionSem.UseAsync()) |
| 153 |
{ |
| 154 |
if (IsDisposed) |
| 155 |
return; |
| 156 |
|
| 157 |
if (!File.Exists(MetaFilePath)) |
| 158 |
return; |
| 159 |
|
| 160 |
var lastWriteTime = File.GetLastWriteTime(MetaFilePath); |
| 161 |
|
| 162 |
if (lastWriteTime == metaFileModifiedTime) |
| 163 |
return; |
| 164 |
|
| 165 |
metaFileModifiedTime = lastWriteTime; |
| 166 |
|
| 167 |
var metadata = ReadMetadataFile(); |
| 168 |
|
| 169 |
if (metadata != null && metadata != godotIdeMetadata) |
| 170 |
{ |
| 171 |
godotIdeMetadata = metadata.Value; |
| 172 |
_ = Task.Run(ConnectToServer); |
| 173 |
} |
| 174 |
} |
| 175 |
} |
| 176 |
|
| 177 |
private async void OnMetaFileDeleted(object sender, FileSystemEventArgs e) |
| 178 |
{ |
| 179 |
if (IsDisposed) |
| 180 |
return; |
| 181 |
|
| 182 |
if (IsConnected) |
| 183 |
{ |
| 184 |
using (await connectionSem.UseAsync()) |
| 185 |
peer?.Dispose(); |
| 186 |
} |
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
using (await connectionSem.UseAsync()) |
| 191 |
{ |
| 192 |
if (IsDisposed) |
| 193 |
return; |
| 194 |
|
| 195 |
if (IsConnected || !File.Exists(MetaFilePath)) |
| 196 |
return; |
| 197 |
|
| 198 |
var lastWriteTime = File.GetLastWriteTime(MetaFilePath); |
| 199 |
|
| 200 |
if (lastWriteTime == metaFileModifiedTime) |
| 201 |
return; |
| 202 |
|
| 203 |
metaFileModifiedTime = lastWriteTime; |
| 204 |
|
| 205 |
var metadata = ReadMetadataFile(); |
| 206 |
|
| 207 |
if (metadata != null) |
| 208 |
{ |
| 209 |
godotIdeMetadata = metadata.Value; |
| 210 |
_ = Task.Run(ConnectToServer); |
| 211 |
} |
| 212 |
} |
| 213 |
} |
| 214 |
|
| 215 |
private GodotIdeMetadata? ReadMetadataFile() |
| 216 |
{ |
| 217 |
using (var fileStream = new FileStream(MetaFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) |
| 218 |
using (var reader = new StreamReader(fileStream)) |
| 219 |
{ |
| 220 |
string? portStr = reader.ReadLine(); |
| 221 |
|
| 222 |
if (portStr == null) |
| 223 |
return null; |
| 224 |
|
| 225 |
string? editorExecutablePath = reader.ReadLine(); |
| 226 |
|
| 227 |
if (editorExecutablePath == null) |
| 228 |
return null; |
| 229 |
|
| 230 |
if (!int.TryParse(portStr, out int port)) |
| 231 |
return null; |
| 232 |
|
| 233 |
return new GodotIdeMetadata(port, editorExecutablePath); |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
private async Task AcceptClient(TcpClient tcpClient) |
| 238 |
{ |
| 239 |
logger.LogDebug("Accept client..."); |
| 240 |
|
| 241 |
using (peer = new Peer(tcpClient, new ClientHandshake(), messageHandler, logger)) |
| 242 |
{ |
| 243 |
|
| 244 |
peer.Connected += () => |
| 245 |
{ |
| 246 |
logger.LogInfo("Connection open with Ide Client"); |
| 247 |
|
| 248 |
while (clientConnectedAwaiters.Count > 0) |
| 249 |
clientConnectedAwaiters.Dequeue().SetResult(true); |
| 250 |
}; |
| 251 |
|
| 252 |
peer.Disconnected += () => |
| 253 |
{ |
| 254 |
while (clientDisconnectedAwaiters.Count > 0) |
| 255 |
clientDisconnectedAwaiters.Dequeue().SetResult(true); |
| 256 |
}; |
| 257 |
|
| 258 |
|
| 259 |
try |
| 260 |
{ |
| 261 |
if (!await peer.DoHandshake(identity)) |
| 262 |
{ |
| 263 |
logger.LogError("Handshake failed"); |
| 264 |
return; |
| 265 |
} |
| 266 |
} |
| 267 |
catch (Exception e) |
| 268 |
{ |
| 269 |
logger.LogError("Handshake failed with unhandled exception: ", e); |
| 270 |
return; |
| 271 |
} |
| 272 |
|
| 273 |
await peer.Process(); |
| 274 |
|
| 275 |
logger.LogInfo("Connection closed with Ide Client"); |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
private async Task ConnectToServer() |
| 280 |
{ |
| 281 |
var tcpClient = new TcpClient(); |
| 282 |
|
| 283 |
try |
| 284 |
{ |
| 285 |
logger.LogInfo("Connecting to Godot Ide Server"); |
| 286 |
|
| 287 |
await tcpClient.ConnectAsync(IPAddress.Loopback, godotIdeMetadata.Port); |
| 288 |
|
| 289 |
logger.LogInfo("Connection open with Godot Ide Server"); |
| 290 |
|
| 291 |
await AcceptClient(tcpClient); |
| 292 |
} |
| 293 |
catch (SocketException e) |
| 294 |
{ |
| 295 |
if (e.SocketErrorCode == SocketError.ConnectionRefused) |
| 296 |
logger.LogError("The connection to the Godot Ide Server was refused"); |
| 297 |
else |
| 298 |
throw; |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
|
| 303 |
public async void Start() |
| 304 |
{ |
| 305 |
fsWatcher.Created += OnMetaFileChanged; |
| 306 |
fsWatcher.Changed += OnMetaFileChanged; |
| 307 |
fsWatcher.Deleted += OnMetaFileDeleted; |
| 308 |
fsWatcher.EnableRaisingEvents = true; |
| 309 |
|
| 310 |
using (await connectionSem.UseAsync()) |
| 311 |
{ |
| 312 |
if (IsDisposed) |
| 313 |
return; |
| 314 |
|
| 315 |
if (IsConnected) |
| 316 |
return; |
| 317 |
|
| 318 |
if (!File.Exists(MetaFilePath)) |
| 319 |
{ |
| 320 |
logger.LogInfo("There is no Godot Ide Server running"); |
| 321 |
return; |
| 322 |
} |
| 323 |
|
| 324 |
var metadata = ReadMetadataFile(); |
| 325 |
|
| 326 |
if (metadata != null) |
| 327 |
{ |
| 328 |
godotIdeMetadata = metadata.Value; |
| 329 |
_ = Task.Run(ConnectToServer); |
| 330 |
} |
| 331 |
else |
| 332 |
{ |
| 333 |
logger.LogError("Failed to read Godot Ide metadata file"); |
| 334 |
} |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
public async Task<TResponse?> SendRequest<TResponse>(Request request) |
| 339 |
where TResponse : Response, new() |
| 340 |
{ |
| 341 |
if (!IsConnected) |
| 342 |
{ |
| 343 |
logger.LogError("Cannot write request. Not connected to the Godot Ide Server."); |
| 344 |
return null; |
| 345 |
} |
| 346 |
|
| 347 |
string body = JsonConvert.SerializeObject(request); |
| 348 |
return await peer.SendRequest<TResponse>(request.Id, body); |
| 349 |
} |
| 350 |
|
| 351 |
public async Task<TResponse?> SendRequest<TResponse>(string id, string body) |
| 352 |
where TResponse : Response, new() |
| 353 |
{ |
| 354 |
if (!IsConnected) |
| 355 |
{ |
| 356 |
logger.LogError("Cannot write request. Not connected to the Godot Ide Server."); |
| 357 |
return null; |
| 358 |
} |
| 359 |
|
| 360 |
return await peer.SendRequest<TResponse>(id, body); |
| 361 |
} |
| 362 |
} |
| 363 |
} |