private TResponse HandleRules()

in src/Elastic.Transport.VirtualizedCluster/Components/VirtualClusterConnection.cs [182:225]


	private TResponse HandleRules<TResponse, TRule>(
		Endpoint endpoint,
		BoundConfiguration boundConfiguration,
		PostData? postData,
		string origin,
		IList<TRule> rules,
		TimeSpan timeout,
		Action<TRule> beforeReturn,
		Func<TRule, byte[]?> successResponse
	)
		where TResponse : TransportResponse, new()
		where TRule : IRule
	{
		if (rules.Count == 0)
			throw new Exception($"No {origin} defined for the current VirtualCluster, so we do not know how to respond");

		foreach (var rule in rules.Where(s => s.OnPort.HasValue))
		{
			var always = rule.Times.Match(t => true, t => false);
			var times = rule.Times.Match(t => -1, t => t);

			if (rule.OnPort == null || rule.OnPort.Value != endpoint.Uri.Port) continue;

			if (always)
				return Always<TResponse, TRule>(endpoint, boundConfiguration, postData, timeout, beforeReturn, successResponse, rule);

			if (rule.ExecuteCount > times) continue;

			return Sometimes<TResponse, TRule>(endpoint, boundConfiguration, postData, timeout, beforeReturn, successResponse, rule);
		}
		foreach (var rule in rules.Where(s => !s.OnPort.HasValue))
		{
			var always = rule.Times.Match(t => true, t => false);
			var times = rule.Times.Match(t => -1, t => t);
			if (always)
				return Always<TResponse, TRule>(endpoint, boundConfiguration, postData, timeout, beforeReturn, successResponse, rule);

			if (rule.ExecuteCount > times) continue;

			return Sometimes<TResponse, TRule>(endpoint, boundConfiguration, postData, timeout, beforeReturn, successResponse, rule);
		}
		var count = _calls.Select(kv => kv.Value.Called).Sum();
		throw new Exception($@"No global or port specific {origin} rule ({endpoint.Uri.Port}) matches any longer after {count} calls in to the cluster");
	}