feat(commons): GrpcEndpointRules for site gRPC address validation

This commit is contained in:
Joseph Doherty
2026-10-22 06:05:06 -04:00
parent 3a53e7059b
commit 15c9de0f4a
2 changed files with 74 additions and 0 deletions
@@ -0,0 +1,37 @@
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;
}
}
@@ -0,0 +1,37 @@
using ZB.MOM.WW.ScadaBridge.Commons.Validation;
namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Validation;
public class GrpcEndpointRulesTests
{
[Theory]
[InlineData("scadabridge-site-a-node-a")]
[InlineData("site-a-node-a:8083")]
[InlineData("ftp://x:1")]
public void TryValidate_RejectsNonHttpEndpoints(string value)
{
Assert.False(GrpcEndpointRules.TryValidate(value, false, out var error));
Assert.NotNull(error);
}
[Theory]
[InlineData("http://site-a-node-a:8083")]
[InlineData("https://h")]
public void TryValidate_AcceptsHttpEndpoints(string value)
{
Assert.True(GrpcEndpointRules.TryValidate(value, false, out var error));
Assert.Null(error);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void TryValidate_EmptyHonoursAllowEmpty(string? value)
{
Assert.True(GrpcEndpointRules.TryValidate(value, true, out var ok));
Assert.Null(ok);
Assert.False(GrpcEndpointRules.TryValidate(value, false, out var err));
Assert.NotNull(err);
}
}