Code/RpcCallbackManager.cs
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;

namespace Orizon;

/// <summary>
/// Manages the callback operations for RPC requests.
/// </summary>
internal static class RpcCallbackManager
{
	/// <summary>
	/// Stores the callback operations.
	/// </summary>
	private static readonly ConcurrentDictionary<Guid, object> _operations = new();

	/// <summary>
	/// Waits for the response to the RPC request.
	/// </summary>
	/// <param name="id">The unique identifier of the request.</param>
	/// <returns>The response to the RPC request.</returns>
	public static async Task<TResponse> WaitForResponse<TResponse>( Guid id )
	{
		while ( !_operations.ContainsKey( id ) )
			await Task.Delay( 1 );

		_operations.TryRemove( id, out var result );
		return (TResponse)result!;
	}

	/// <summary>
	/// Completes the response to the RPC request.
	/// </summary>
	/// <param name="id">The unique identifier of the request.</param>
	/// <param name="response">The response to the RPC request.</param>
	public static void CompleteResponse( Guid id, IRpcResponse response )
	{
		_operations.TryAdd( id, response );
	}
}