using Grpc.Core;
using ZB.MOM.WW.MxGateway.Contracts;
namespace ZB.MOM.WW.MxGateway.Client;
///
/// Exception thrown when the gateway answers gRPC ResourceExhausted. The
/// distinguishes "you fell behind and events were lost" (re-subscribe and
/// resync) from "a limit was reached" (back off, do not retry immediately). It derives from
/// , so existing catch blocks keep working.
///
public sealed class MxGatewayResourceExhaustedException : MxGatewayException
{
/// Initializes a new instance.
/// Diagnostic message describing the failure.
/// The gateway's machine-readable reason code, or null when absent (older gateway).
/// The underlying .
public MxGatewayResourceExhaustedException(string message, string? reason, Exception? innerException = null)
: base(message, innerException)
{
Reason = reason;
}
///
/// Gets the reason code from the mxgw-reason trailer (see ),
/// or null when the gateway sent none.
///
public string? Reason { get; }
/// Gets a value indicating whether events were lost because the subscriber fell behind (event-stream or alarm-feed overflow); the caller should re-subscribe and resync.
public bool IsOverflow =>
Reason is ResourceExhaustedReasons.EventQueueOverflow or ResourceExhaustedReasons.AlarmFeedOverflow;
/// Gets a value indicating whether the failure was a subscriber-count limit rejection.
public bool IsSubscriberLimit =>
Reason is ResourceExhaustedReasons.SubscriberLimit or ResourceExhaustedReasons.SubscriberAlreadyActive;
internal static string? ReadReason(RpcException exception)
{
foreach (Metadata.Entry entry in exception.Trailers)
{
if (!entry.IsBinary
&& string.Equals(entry.Key, ResourceExhaustedReasons.TrailerKey, StringComparison.OrdinalIgnoreCase))
{
return entry.Value;
}
}
return null;
}
}