Files
ScadaBridge/src/ZB.MOM.WW.ScadaBridge.Commons/Validation/GrpcEndpointRules.cs
T

38 lines
1.2 KiB
C#

namespace ZB.MOM.WW.ScadaBridge.Commons.Validation;
/// <summary>
/// Validation for site gRPC endpoint addresses (<c>Site.GrpcNodeAAddress</c>/<c>GrpcNodeBAddress</c>).
/// A bare host or <c>host:port</c> is rejected because the gRPC channel needs an absolute http(s) URI.
/// </summary>
public static class GrpcEndpointRules
{
/// <summary>
/// Validates a gRPC endpoint. Null/whitespace is "not configured": valid only when
/// <paramref name="allowEmpty"/> is true.
/// </summary>
public static bool TryValidate(string? value, bool allowEmpty, out string? error)
{
error = null;
if (string.IsNullOrWhiteSpace(value))
{
if (allowEmpty)
{
return true;
}
error = "gRPC endpoint is required (e.g. http://host:8083).";
return false;
}
if (!Uri.TryCreate(value.Trim(), UriKind.Absolute, out var uri)
|| (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)
|| string.IsNullOrEmpty(uri.Host))
{
error = $"gRPC endpoint '{value}' must be an absolute http:// or https:// URL with a host (e.g. http://host:8083).";
return false;
}
return true;
}
}