fix(CLI-37,CLI-38): make status/HRESULT reply validation conformant across all five clients
One cross-client conformance pass; also closes first-cycle CLI-08. CLI-37: an MxStatusProxy entry is a failure iff `category != MX_STATUS_CATEGORY_OK`. The proto contract has always said so — `success` is the raw 16-bit COM member carried verbatim for diagnostics, not a boolean — but four clients branched on `success` alone and .NET required both, so the same gateway reply produced opposite verdicts per language. An absent entry stays success; a present entry with an UNSPECIFIED category is a failure, because the worker always maps a category and an unmapped one is not proven OK. CLI-38: a reply fails on HRESULT iff `hresult` is present and negative, so positive COM success codes such as S_FALSE (1) pass. .NET/Go/Java used `!= 0`, which errored on a parity-preserving S_FALSE that Python and Rust accepted. This makes the existing ClientLibrariesDesign.md claim true rather than rewriting the doc to describe the divergence. Four shared fixtures pin both rules cross-client, and each language suite also carries a table test for the two edges a fixture cannot express (absent entry, UNSPECIFIED category). A Java test fake that built a status with a bare `setSuccess(1)` and no category is fixed — under the category rule that reply was never a success.
This commit is contained in:
@@ -163,6 +163,12 @@ can keep the full `MxCommandReply`, HRESULT, and status array when MXAccess
|
||||
itself rejects a command. `MxAccessException.Reply` contains the raw generated
|
||||
reply.
|
||||
|
||||
`EnsureMxAccessSuccess()` follows COM semantics: only a **negative** HRESULT is
|
||||
a failure, so positive success codes such as `S_FALSE` (1) pass. A status entry
|
||||
fails only when `Category` is not `MxStatusCategory.Ok` — `MxStatusProxy.Success`
|
||||
mirrors the raw COM member for diagnostics and never decides the verdict, which
|
||||
is why `IsSuccess()` branches on the category alone.
|
||||
|
||||
## Write Semantics And Common Pitfalls
|
||||
|
||||
These are MXAccess parity behaviors that surprise new callers. The gateway
|
||||
|
||||
@@ -32,6 +32,57 @@ public sealed class MxCommandReplyExtensionsTests
|
||||
Assert.Contains("0x80040200", exception.Message);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a non-OK status category fails even when the raw success member is set.</summary>
|
||||
[Fact]
|
||||
public void EnsureMxAccessSuccess_WithNonOkCategoryAndSuccessSet_Throws()
|
||||
{
|
||||
MxCommandReply reply = ReadReplyFixture(
|
||||
"write.status-category-error-success-set.reply.json");
|
||||
|
||||
reply.EnsureProtocolSuccess();
|
||||
MxAccessException exception = Assert.Throws<MxAccessException>(
|
||||
reply.EnsureMxAccessSuccess);
|
||||
|
||||
Assert.Equal(1, Assert.Single(exception.Statuses).Success);
|
||||
Assert.Contains("CommunicationError", exception.Message, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an Ok status category succeeds even when the raw success member is zero.</summary>
|
||||
[Fact]
|
||||
public void EnsureMxAccessSuccess_WithOkCategoryAndZeroSuccess_ReturnsReply()
|
||||
{
|
||||
MxCommandReply reply = ReadReplyFixture(
|
||||
"write.status-category-ok-success-zero.reply.json");
|
||||
|
||||
Assert.Equal(0, Assert.Single(reply.Statuses).Success);
|
||||
Assert.Same(reply, reply.EnsureProtocolSuccess());
|
||||
Assert.Same(reply, reply.EnsureMxAccessSuccess());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a positive HResult (S_FALSE) is a COM success code, not a failure.</summary>
|
||||
[Fact]
|
||||
public void EnsureMxAccessSuccess_WithPositiveHResult_ReturnsReply()
|
||||
{
|
||||
MxCommandReply reply = ReadReplyFixture("write.hresult-s-false.reply.json");
|
||||
|
||||
Assert.Equal(1, reply.Hresult);
|
||||
Assert.Same(reply, reply.EnsureProtocolSuccess());
|
||||
Assert.Same(reply, reply.EnsureMxAccessSuccess());
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a negative HResult fails even when every status entry is Ok.</summary>
|
||||
[Fact]
|
||||
public void EnsureMxAccessSuccess_WithNegativeHResult_Throws()
|
||||
{
|
||||
MxCommandReply reply = ReadReplyFixture("write.hresult-e-fail.reply.json");
|
||||
|
||||
reply.EnsureProtocolSuccess();
|
||||
MxAccessException exception = Assert.Throws<MxAccessException>(
|
||||
reply.EnsureMxAccessSuccess);
|
||||
|
||||
Assert.Equal(-2147467259, exception.HResultCode);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that session-not-found protocol failures throw the correct gateway exception.</summary>
|
||||
[Fact]
|
||||
public void EnsureProtocolSuccess_WithSessionFailure_ThrowsSessionException()
|
||||
|
||||
@@ -19,9 +19,8 @@ public sealed class MxStatusProxyExtensionsTests
|
||||
{
|
||||
MxStatusProxy status = JsonParser.Default.Parse<MxStatusProxy>(
|
||||
testCase.GetProperty("status").GetRawText());
|
||||
int success = testCase.GetProperty("status").GetProperty("success").GetInt32();
|
||||
|
||||
Assert.Equal(success != 0 && status.Category is MxStatusCategory.Ok, status.IsSuccess());
|
||||
Assert.Equal(status.Category is MxStatusCategory.Ok, status.IsSuccess());
|
||||
Assert.Equal(
|
||||
testCase.GetProperty("status").GetProperty("rawCategory").GetInt32(),
|
||||
status.RawCategory);
|
||||
@@ -31,6 +30,22 @@ public sealed class MxStatusProxyExtensionsTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the raw success member never overrides the authoritative category.</summary>
|
||||
[Theory]
|
||||
[InlineData(MxStatusCategory.Ok, 0, true)]
|
||||
[InlineData(MxStatusCategory.Ok, 1, true)]
|
||||
[InlineData(MxStatusCategory.CommunicationError, 1, false)]
|
||||
[InlineData(MxStatusCategory.Unspecified, 1, false)]
|
||||
public void IsSuccess_BranchesOnCategoryOnly(
|
||||
MxStatusCategory category,
|
||||
int success,
|
||||
bool expected)
|
||||
{
|
||||
MxStatusProxy status = new() { Category = category, Success = success };
|
||||
|
||||
Assert.Equal(expected, status.IsSuccess());
|
||||
}
|
||||
|
||||
private static string ReadFixture(string category, string fileName)
|
||||
{
|
||||
DirectoryInfo directory = new(AppContext.BaseDirectory);
|
||||
|
||||
@@ -23,7 +23,11 @@ public static class MxCommandReplyExtensions
|
||||
throw CreateProtocolException(reply, code);
|
||||
}
|
||||
|
||||
/// <summary>Validates that the reply indicates MXAccess success (no HResult or status failures), throwing MxAccessException if not.</summary>
|
||||
/// <summary>
|
||||
/// Validates that the reply indicates MXAccess success, throwing MxAccessException if not.
|
||||
/// Following COM semantics, only a negative HResult is a failure — positive success codes
|
||||
/// such as <c>S_FALSE</c> pass — and a status entry fails only when its category is not Ok.
|
||||
/// </summary>
|
||||
/// <param name="reply">The command reply to check.</param>
|
||||
/// <returns>The same reply, for chaining.</returns>
|
||||
public static MxCommandReply EnsureMxAccessSuccess(this MxCommandReply reply)
|
||||
@@ -31,7 +35,7 @@ public static class MxCommandReplyExtensions
|
||||
ArgumentNullException.ThrowIfNull(reply);
|
||||
|
||||
bool mxAccessFailure = reply.ProtocolStatus?.Code is ProtocolStatusCode.MxaccessFailure;
|
||||
bool hResultFailure = reply.HasHresult && reply.Hresult != 0;
|
||||
bool hResultFailure = reply.HasHresult && reply.Hresult < 0;
|
||||
bool statusFailure = reply.Statuses.Any(status => !status.IsSuccess());
|
||||
|
||||
if (!mxAccessFailure && !hResultFailure && !statusFailure)
|
||||
|
||||
@@ -5,15 +5,18 @@ namespace ZB.MOM.WW.MxGateway.Client;
|
||||
/// <summary>Extension methods for MxStatusProxy values.</summary>
|
||||
public static class MxStatusProxyExtensions
|
||||
{
|
||||
/// <summary>Returns whether the status indicates success (success flag set and category is Ok).</summary>
|
||||
/// <summary>
|
||||
/// Returns whether the status indicates success, which the wire contract defines as
|
||||
/// <see cref="MxStatusCategory.Ok"/>. The raw <c>Success</c> member is a verbatim COM
|
||||
/// diagnostic, not a boolean, so it never participates in the verdict.
|
||||
/// </summary>
|
||||
/// <param name="status">The status to check.</param>
|
||||
/// <returns><see langword="true"/> if the status indicates success; otherwise <see langword="false"/>.</returns>
|
||||
public static bool IsSuccess(this MxStatusProxy status)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(status);
|
||||
|
||||
return status.Success != 0
|
||||
&& status.Category is MxStatusCategory.Ok;
|
||||
return status.Category is MxStatusCategory.Ok;
|
||||
}
|
||||
|
||||
/// <summary>Returns a formatted summary of the status for diagnostic output.</summary>
|
||||
|
||||
@@ -94,6 +94,12 @@ goroutine cleanup. Raw protobuf messages remain available through the
|
||||
`errors.As` for `GatewayError`, `CommandError`, and `MxAccessError`; command
|
||||
errors preserve the raw reply.
|
||||
|
||||
`EnsureMxAccessSuccess` follows COM semantics: only a **negative** HRESULT is a
|
||||
failure, so positive success codes such as `S_FALSE` (1) pass. `StatusSucceeded`
|
||||
judges each `MXSTATUS_PROXY` entry by its category — an entry fails when
|
||||
`Category` is not `MX_STATUS_CATEGORY_OK`, and the raw `Success` member is a
|
||||
diagnostic that never decides the verdict. A nil entry is success.
|
||||
|
||||
### Reconnect-replay gap
|
||||
|
||||
Each `EventResult` carries exactly one of `Event`, `ReplayGap`, or `Err`. When
|
||||
|
||||
@@ -65,7 +65,8 @@ func TestStatusConversionFixtures(t *testing.T) {
|
||||
if err := protojson.Unmarshal(tc.Status, &status); err != nil {
|
||||
t.Fatalf("parse status: %v", err)
|
||||
}
|
||||
if got, want := StatusSucceeded(&status), status.GetSuccess() != 0; got != want {
|
||||
want := status.GetCategory() == pb.MxStatusCategory_MX_STATUS_CATEGORY_OK
|
||||
if got := StatusSucceeded(&status); got != want {
|
||||
t.Fatalf("StatusSucceeded() = %v, want %v", got, want)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -180,11 +180,15 @@ func EnsureProtocolSuccess(op string, status *ProtocolStatus, reply *MxCommandRe
|
||||
|
||||
// EnsureMxAccessSuccess returns a typed MxAccessError for failing HRESULTs or
|
||||
// MXSTATUS_PROXY entries.
|
||||
//
|
||||
// Following COM semantics, only a negative HRESULT is a failure — positive
|
||||
// success codes such as S_FALSE (1) pass. Status entries are judged by
|
||||
// StatusSucceeded, which branches on the authoritative category.
|
||||
func EnsureMxAccessSuccess(op string, reply *MxCommandReply) error {
|
||||
if reply == nil {
|
||||
return nil
|
||||
}
|
||||
if reply.Hresult != nil && reply.GetHresult() != 0 {
|
||||
if reply.Hresult != nil && reply.GetHresult() < 0 {
|
||||
return &MxAccessError{Reply: reply}
|
||||
}
|
||||
for _, status := range reply.GetStatuses() {
|
||||
|
||||
@@ -48,6 +48,89 @@ func TestGeneratedGoldenFixturesParse(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCommandReplyValidationFixtures locks the shared reply-validation rules to
|
||||
// the behavior fixtures: a status entry fails iff its category is not OK (the
|
||||
// raw success member is diagnostics only), and an HRESULT fails iff it is
|
||||
// present and negative (S_FALSE and other positive COM success codes pass).
|
||||
func TestCommandReplyValidationFixtures(t *testing.T) {
|
||||
tests := []struct {
|
||||
fixture string
|
||||
wantFailure bool
|
||||
}{
|
||||
{fixture: "register.ok.reply.json", wantFailure: false},
|
||||
{fixture: "write.mxaccess-failure.reply.json", wantFailure: true},
|
||||
{fixture: "write.status-category-error-success-set.reply.json", wantFailure: true},
|
||||
{fixture: "write.status-category-ok-success-zero.reply.json", wantFailure: false},
|
||||
{fixture: "write.hresult-s-false.reply.json", wantFailure: false},
|
||||
{fixture: "write.hresult-e-fail.reply.json", wantFailure: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.fixture, func(t *testing.T) {
|
||||
data, err := os.ReadFile(filepath.Join(
|
||||
"..", "..", "proto", "fixtures", "behavior", "command-replies", tt.fixture))
|
||||
if err != nil {
|
||||
t.Fatalf("read fixture: %v", err)
|
||||
}
|
||||
|
||||
var reply pb.MxCommandReply
|
||||
if err := protojson.Unmarshal(data, &reply); err != nil {
|
||||
t.Fatalf("parse fixture: %v", err)
|
||||
}
|
||||
|
||||
err = EnsureMxAccessSuccess("invoke", &reply)
|
||||
if got := err != nil; got != tt.wantFailure {
|
||||
t.Fatalf("EnsureMxAccessSuccess() failed = %v (err %v), want %v", got, err, tt.wantFailure)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestStatusSucceededBranchesOnCategory pins the per-entry rule directly,
|
||||
// including the two edges the fixtures cannot express: a nil entry is success
|
||||
// and a present entry with an unspecified category is a failure.
|
||||
func TestStatusSucceededBranchesOnCategory(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status *MxStatusProxy
|
||||
want bool
|
||||
}{
|
||||
{name: "nil entry", status: nil, want: true},
|
||||
{
|
||||
name: "ok category with zero success",
|
||||
status: &pb.MxStatusProxy{
|
||||
Success: 0,
|
||||
Category: pb.MxStatusCategory_MX_STATUS_CATEGORY_OK,
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "error category with success set",
|
||||
status: &pb.MxStatusProxy{
|
||||
Success: 1,
|
||||
Category: pb.MxStatusCategory_MX_STATUS_CATEGORY_COMMUNICATION_ERROR,
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "unspecified category with success set",
|
||||
status: &pb.MxStatusProxy{
|
||||
Success: 1,
|
||||
Category: pb.MxStatusCategory_MX_STATUS_CATEGORY_UNSPECIFIED,
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := StatusSucceeded(tt.status); got != tt.want {
|
||||
t.Fatalf("StatusSucceeded() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenSessionFixtureProtocolVersions(t *testing.T) {
|
||||
data, err := os.ReadFile(filepath.Join("..", "..", "proto", "fixtures", "golden", "open-session-reply.ok.json"))
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,17 @@
|
||||
package mxgateway
|
||||
|
||||
import (
|
||||
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
|
||||
)
|
||||
|
||||
// StatusSucceeded reports whether an MXSTATUS_PROXY entry represents success.
|
||||
//
|
||||
// The wire contract makes Category authoritative: an entry succeeds only when
|
||||
// its category is MX_STATUS_CATEGORY_OK. The Success member mirrors the raw
|
||||
// 16-bit COM value verbatim for diagnostics and is not a boolean, so it takes
|
||||
// no part in the verdict. A nil entry is success (nothing was reported); a
|
||||
// present entry with an unspecified category is a failure, because the worker
|
||||
// always maps a category and an unmapped one is not proven OK.
|
||||
func StatusSucceeded(status *MxStatusProxy) bool {
|
||||
return status == nil || status.GetSuccess() != 0
|
||||
return status == nil || status.GetCategory() == pb.MxStatusCategory_MX_STATUS_CATEGORY_OK
|
||||
}
|
||||
|
||||
@@ -139,7 +139,12 @@ commands, so you do not need to build raw `MxCommand` messages:
|
||||
|
||||
All of them run the same MXAccess reply validation as the bulk helpers (protocol
|
||||
status plus HRESULT/`MxStatusProxy` check) via the shared `invoke` path, so an
|
||||
MXAccess COM-side failure surfaces as `MxAccessException`.
|
||||
MXAccess COM-side failure surfaces as `MxAccessException`. That validation
|
||||
follows COM semantics: only a **negative** HRESULT is a failure, so positive
|
||||
success codes such as `S_FALSE` (1) pass. `MxStatuses.succeeded` judges each
|
||||
entry by its category — an entry fails when its category is not
|
||||
`MX_STATUS_CATEGORY_OK`, and the raw `success` member is a diagnostic that never
|
||||
decides the verdict. A `null` entry is success.
|
||||
|
||||
**Secret redaction.** Credentials passed to `authenticateUser` (and the
|
||||
credential-sensitive values passed to `writeSecured`/`writeSecured2`) travel
|
||||
|
||||
+3
-1
@@ -47,7 +47,9 @@ final class MxGatewayErrors {
|
||||
if (reply == null) {
|
||||
return;
|
||||
}
|
||||
if (reply.hasHresult() && reply.getHresult() != 0) {
|
||||
// COM semantics: only a negative HRESULT is a failure. Positive success
|
||||
// codes such as S_FALSE (1) pass.
|
||||
if (reply.hasHresult() && reply.getHresult() < 0) {
|
||||
throw new MxAccessException(operation, reply);
|
||||
}
|
||||
for (var status : reply.getStatusesList()) {
|
||||
|
||||
+17
-7
@@ -8,8 +8,11 @@ import mxaccess_gateway.v1.MxaccessGateway.MxStatusSource;
|
||||
* Helpers for inspecting {@link MxStatusProxy} values returned by the gateway.
|
||||
*
|
||||
* <p>An {@code MxStatusProxy} mirrors the MXAccess COM {@code MXSTATUS_PROXY}
|
||||
* struct. The success flag uses the MXAccess convention where any non-zero
|
||||
* value indicates success.
|
||||
* struct. Per the wire contract, {@code category} is the authoritative verdict:
|
||||
* an entry succeeds only when its category is
|
||||
* {@code MX_STATUS_CATEGORY_OK}. The {@code success} member carries the raw
|
||||
* 16-bit COM value verbatim for diagnostics and is not a boolean, so it never
|
||||
* decides success or failure.
|
||||
*/
|
||||
public final class MxStatuses {
|
||||
private MxStatuses() {
|
||||
@@ -18,12 +21,17 @@ public final class MxStatuses {
|
||||
/**
|
||||
* Returns whether the supplied status proxy reports success.
|
||||
*
|
||||
* <p>A {@code null} status is success because nothing was reported. A
|
||||
* present entry whose category is {@code MX_STATUS_CATEGORY_UNSPECIFIED}
|
||||
* is a failure: the worker always maps a category, so an unmapped one is
|
||||
* not proven OK.
|
||||
*
|
||||
* @param status the status proxy, may be {@code null}
|
||||
* @return {@code true} if {@code status} is {@code null} or its success
|
||||
* flag is non-zero, {@code false} otherwise
|
||||
* @return {@code true} if {@code status} is {@code null} or its category is
|
||||
* {@code MX_STATUS_CATEGORY_OK}, {@code false} otherwise
|
||||
*/
|
||||
public static boolean succeeded(MxStatusProxy status) {
|
||||
return status == null || status.getSuccess() != 0;
|
||||
return status == null || status.getCategory() == MxStatusCategory.MX_STATUS_CATEGORY_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -44,9 +52,11 @@ public final class MxStatuses {
|
||||
*/
|
||||
public record MxStatusView(MxStatusProxy raw) {
|
||||
/**
|
||||
* Returns the raw success flag (non-zero indicates success).
|
||||
* Returns the raw {@code success} member exactly as MXAccess reported
|
||||
* it. This is a diagnostic value, not a verdict — use
|
||||
* {@link MxStatuses#succeeded(MxStatusProxy)} to decide success.
|
||||
*
|
||||
* @return the success flag value
|
||||
* @return the raw success member
|
||||
*/
|
||||
public int success() {
|
||||
return raw.getSuccess();
|
||||
|
||||
+7
-4
@@ -701,14 +701,17 @@ final class MxGatewayClientSessionTests {
|
||||
.setSessionId(request.getSessionId())
|
||||
.setKind(request.getCommand().getKind())
|
||||
.setProtocolStatus(ok());
|
||||
// `category` is the authoritative success indicator, so the fake
|
||||
// must set it — a bare non-zero `success` is not a success.
|
||||
var okStatus = mxaccess_gateway.v1.MxaccessGateway.MxStatusProxy.newBuilder()
|
||||
.setSuccess(1)
|
||||
.setCategory(mxaccess_gateway.v1.MxaccessGateway.MxStatusCategory.MX_STATUS_CATEGORY_OK);
|
||||
if (request.getCommand().getKind() == MxCommandKind.MX_COMMAND_KIND_SUSPEND) {
|
||||
reply.setSuspend(mxaccess_gateway.v1.MxaccessGateway.SuspendReply.newBuilder()
|
||||
.setStatus(mxaccess_gateway.v1.MxaccessGateway.MxStatusProxy.newBuilder()
|
||||
.setSuccess(1)));
|
||||
.setStatus(okStatus));
|
||||
} else if (request.getCommand().getKind() == MxCommandKind.MX_COMMAND_KIND_ACTIVATE) {
|
||||
reply.setActivate(mxaccess_gateway.v1.MxaccessGateway.ActivateReply.newBuilder()
|
||||
.setStatus(mxaccess_gateway.v1.MxaccessGateway.MxStatusProxy.newBuilder()
|
||||
.setSuccess(1)));
|
||||
.setStatus(okStatus));
|
||||
}
|
||||
responseObserver.onNext(reply.build());
|
||||
responseObserver.onCompleted();
|
||||
|
||||
+47
@@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertArrayEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
@@ -20,6 +21,8 @@ import mxaccess_gateway.v1.MxaccessGateway.MxStatusProxy;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.MxValue;
|
||||
import mxaccess_gateway.v1.MxaccessGateway.ProtocolStatusCode;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.CsvSource;
|
||||
|
||||
final class MxGatewayFixtureTests {
|
||||
@Test
|
||||
@@ -89,6 +92,50 @@ final class MxGatewayFixtureTests {
|
||||
throw new AssertionError("expected MxAccessException");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"register.ok.reply.json,false",
|
||||
"write.status-category-error-success-set.reply.json,true",
|
||||
"write.status-category-ok-success-zero.reply.json,false",
|
||||
"write.hresult-s-false.reply.json,false",
|
||||
"write.hresult-e-fail.reply.json,true",
|
||||
})
|
||||
void replyValidationFixturesBranchOnCategoryAndNegativeHresult(String fixture, boolean expectFailure)
|
||||
throws Exception {
|
||||
MxCommandReply.Builder builder = MxCommandReply.newBuilder();
|
||||
JsonFormat.parser().merge(
|
||||
Files.readString(fixtureRoot().resolve("command-replies/" + fixture)),
|
||||
builder);
|
||||
MxCommandReply reply = builder.build();
|
||||
|
||||
if (expectFailure) {
|
||||
assertThrows(MxAccessException.class, () -> MxGatewayErrors.ensureMxAccessSuccess("write", reply));
|
||||
} else {
|
||||
MxGatewayErrors.ensureMxAccessSuccess("write", reply);
|
||||
}
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@CsvSource({
|
||||
"MX_STATUS_CATEGORY_OK,0,true",
|
||||
"MX_STATUS_CATEGORY_OK,1,true",
|
||||
"MX_STATUS_CATEGORY_COMMUNICATION_ERROR,1,false",
|
||||
"MX_STATUS_CATEGORY_UNSPECIFIED,1,false",
|
||||
})
|
||||
void statusEntryVerdictIgnoresTheRawSuccessMember(String category, int success, boolean expectSucceeded) {
|
||||
MxStatusProxy status = MxStatusProxy.newBuilder()
|
||||
.setCategory(MxStatusCategory.valueOf(category))
|
||||
.setSuccess(success)
|
||||
.build();
|
||||
|
||||
assertEquals(expectSucceeded, MxStatuses.succeeded(status));
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentStatusEntryIsSuccess() {
|
||||
assertTrue(MxStatuses.succeeded(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void grpcAuthErrorsAreClassifiedAndRedacted() {
|
||||
RuntimeException authError = MxGatewayErrors.fromGrpc(
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"sessionId": "session-fixture",
|
||||
"correlationId": "gateway-correlation-write-e-fail",
|
||||
"kind": "MX_COMMAND_KIND_WRITE",
|
||||
"protocolStatus": {
|
||||
"code": "PROTOCOL_STATUS_CODE_OK",
|
||||
"message": "Write reached MXAccess."
|
||||
},
|
||||
"hresult": -2147467259,
|
||||
"returnValue": {
|
||||
"dataType": "MX_DATA_TYPE_NO_DATA",
|
||||
"variantType": "VT_EMPTY",
|
||||
"isNull": true,
|
||||
"rawDiagnostic": "MXAccess returned no value for the failed write.",
|
||||
"rawDataType": 2
|
||||
},
|
||||
"statuses": [
|
||||
{
|
||||
"success": 1,
|
||||
"category": "MX_STATUS_CATEGORY_OK",
|
||||
"detectedBy": "MX_STATUS_SOURCE_RESPONDING_LMX",
|
||||
"detail": 0,
|
||||
"rawCategory": 0,
|
||||
"rawDetectedBy": 3,
|
||||
"diagnosticText": "OK"
|
||||
}
|
||||
],
|
||||
"diagnosticMessage": "COM semantics: a negative HRESULT (E_FAIL, 0x80004005) is a failure even when every status entry is OK."
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"sessionId": "session-fixture",
|
||||
"correlationId": "gateway-correlation-write-s-false",
|
||||
"kind": "MX_COMMAND_KIND_WRITE",
|
||||
"protocolStatus": {
|
||||
"code": "PROTOCOL_STATUS_CODE_OK",
|
||||
"message": "Write completed with S_FALSE."
|
||||
},
|
||||
"hresult": 1,
|
||||
"returnValue": {
|
||||
"dataType": "MX_DATA_TYPE_NO_DATA",
|
||||
"variantType": "VT_EMPTY",
|
||||
"isNull": true,
|
||||
"rawDiagnostic": "MXAccess returned no value for the write.",
|
||||
"rawDataType": 2
|
||||
},
|
||||
"statuses": [
|
||||
{
|
||||
"success": 1,
|
||||
"category": "MX_STATUS_CATEGORY_OK",
|
||||
"detectedBy": "MX_STATUS_SOURCE_RESPONDING_LMX",
|
||||
"detail": 0,
|
||||
"rawCategory": 0,
|
||||
"rawDetectedBy": 3,
|
||||
"diagnosticText": "OK"
|
||||
}
|
||||
],
|
||||
"diagnosticMessage": "COM semantics: a positive HRESULT such as S_FALSE (1) is a success code, not a failure."
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"sessionId": "session-fixture",
|
||||
"correlationId": "gateway-correlation-write-category-error",
|
||||
"kind": "MX_COMMAND_KIND_WRITE",
|
||||
"protocolStatus": {
|
||||
"code": "PROTOCOL_STATUS_CODE_OK",
|
||||
"message": "Write reached MXAccess."
|
||||
},
|
||||
"hresult": 0,
|
||||
"returnValue": {
|
||||
"dataType": "MX_DATA_TYPE_NO_DATA",
|
||||
"variantType": "VT_EMPTY",
|
||||
"isNull": true,
|
||||
"rawDiagnostic": "MXAccess returned no value for the write.",
|
||||
"rawDataType": 2
|
||||
},
|
||||
"statuses": [
|
||||
{
|
||||
"success": 1,
|
||||
"category": "MX_STATUS_CATEGORY_COMMUNICATION_ERROR",
|
||||
"detectedBy": "MX_STATUS_SOURCE_RESPONDING_LMX",
|
||||
"detail": 77,
|
||||
"rawCategory": 5,
|
||||
"rawDetectedBy": 3,
|
||||
"diagnosticText": "Responding LMX lost communication mid-write."
|
||||
}
|
||||
],
|
||||
"diagnosticMessage": "Category is authoritative: a non-OK category is a failure even when the raw success member is non-zero."
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"sessionId": "session-fixture",
|
||||
"correlationId": "gateway-correlation-write-category-ok",
|
||||
"kind": "MX_COMMAND_KIND_WRITE",
|
||||
"protocolStatus": {
|
||||
"code": "PROTOCOL_STATUS_CODE_OK",
|
||||
"message": "Write completed."
|
||||
},
|
||||
"hresult": 0,
|
||||
"returnValue": {
|
||||
"dataType": "MX_DATA_TYPE_NO_DATA",
|
||||
"variantType": "VT_EMPTY",
|
||||
"isNull": true,
|
||||
"rawDiagnostic": "MXAccess returned no value for the write.",
|
||||
"rawDataType": 2
|
||||
},
|
||||
"statuses": [
|
||||
{
|
||||
"success": 0,
|
||||
"category": "MX_STATUS_CATEGORY_OK",
|
||||
"detectedBy": "MX_STATUS_SOURCE_RESPONDING_LMX",
|
||||
"detail": 0,
|
||||
"rawCategory": 0,
|
||||
"rawDetectedBy": 3,
|
||||
"diagnosticText": "OK, reported with a zero raw success member."
|
||||
}
|
||||
],
|
||||
"diagnosticMessage": "Category is authoritative: MX_STATUS_CATEGORY_OK is success even when the raw success member is zero."
|
||||
}
|
||||
@@ -20,6 +20,34 @@
|
||||
"path": "command-replies/write.mxaccess-failure.reply.json",
|
||||
"expectation": "MXAccess failures are data-bearing replies with HRESULT and status details, not transport failures."
|
||||
},
|
||||
{
|
||||
"id": "command-reply.write.status-category-error-success-set",
|
||||
"category": "command_replies",
|
||||
"messageType": "mxaccess_gateway.v1.MxCommandReply",
|
||||
"path": "command-replies/write.status-category-error-success-set.reply.json",
|
||||
"expectation": "A status entry fails when its category is not MX_STATUS_CATEGORY_OK, even though the raw success member is non-zero."
|
||||
},
|
||||
{
|
||||
"id": "command-reply.write.status-category-ok-success-zero",
|
||||
"category": "command_replies",
|
||||
"messageType": "mxaccess_gateway.v1.MxCommandReply",
|
||||
"path": "command-replies/write.status-category-ok-success-zero.reply.json",
|
||||
"expectation": "A status entry succeeds when its category is MX_STATUS_CATEGORY_OK, even though the raw success member is zero."
|
||||
},
|
||||
{
|
||||
"id": "command-reply.write.hresult-s-false",
|
||||
"category": "command_replies",
|
||||
"messageType": "mxaccess_gateway.v1.MxCommandReply",
|
||||
"path": "command-replies/write.hresult-s-false.reply.json",
|
||||
"expectation": "A positive HRESULT such as S_FALSE (1) is a COM success code and does not fail the reply."
|
||||
},
|
||||
{
|
||||
"id": "command-reply.write.hresult-e-fail",
|
||||
"category": "command_replies",
|
||||
"messageType": "mxaccess_gateway.v1.MxCommandReply",
|
||||
"path": "command-replies/write.hresult-e-fail.reply.json",
|
||||
"expectation": "A negative HRESULT fails the reply even when every status entry reports MX_STATUS_CATEGORY_OK."
|
||||
},
|
||||
{
|
||||
"id": "event-stream.session-ordered",
|
||||
"category": "event_streams",
|
||||
|
||||
@@ -137,8 +137,10 @@ def ensure_mxaccess_success(operation: str, reply: pb.MxCommandReply) -> pb.MxCo
|
||||
raw_reply=reply,
|
||||
)
|
||||
|
||||
# `category` is the authoritative verdict per the wire contract; `success`
|
||||
# is the raw COM member carried verbatim for diagnostics only.
|
||||
for mx_status in reply.statuses:
|
||||
if mx_status.success == 0:
|
||||
if mx_status.category != pb.MX_STATUS_CATEGORY_OK:
|
||||
raise MxAccessError(
|
||||
_mxaccess_message(operation, reply),
|
||||
protocol_status=status,
|
||||
|
||||
@@ -32,6 +32,55 @@ def test_write_failure_fixture_preserves_raw_reply() -> None:
|
||||
assert len(captured.value.raw_reply.statuses) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("fixture", "expect_failure"),
|
||||
[
|
||||
("command-replies/register.ok.reply.json", False),
|
||||
("command-replies/write.status-category-error-success-set.reply.json", True),
|
||||
("command-replies/write.status-category-ok-success-zero.reply.json", False),
|
||||
("command-replies/write.hresult-s-false.reply.json", False),
|
||||
("command-replies/write.hresult-e-fail.reply.json", True),
|
||||
],
|
||||
)
|
||||
def test_reply_validation_fixtures_branch_on_category_and_negative_hresult(
|
||||
fixture: str,
|
||||
expect_failure: bool,
|
||||
) -> None:
|
||||
reply = _load_reply(fixture)
|
||||
|
||||
if expect_failure:
|
||||
with pytest.raises(MxAccessError):
|
||||
ensure_mxaccess_success("write", reply)
|
||||
else:
|
||||
assert ensure_mxaccess_success("write", reply) is reply
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("category", "success", "expect_failure"),
|
||||
[
|
||||
(pb.MX_STATUS_CATEGORY_OK, 0, False),
|
||||
(pb.MX_STATUS_CATEGORY_OK, 1, False),
|
||||
(pb.MX_STATUS_CATEGORY_COMMUNICATION_ERROR, 1, True),
|
||||
(pb.MX_STATUS_CATEGORY_UNSPECIFIED, 1, True),
|
||||
],
|
||||
)
|
||||
def test_status_entry_verdict_ignores_the_raw_success_member(
|
||||
category: int,
|
||||
success: int,
|
||||
expect_failure: bool,
|
||||
) -> None:
|
||||
reply = pb.MxCommandReply(
|
||||
protocol_status=pb.ProtocolStatus(code=pb.PROTOCOL_STATUS_CODE_OK),
|
||||
statuses=[pb.MxStatusProxy(success=success, category=category)],
|
||||
)
|
||||
|
||||
if expect_failure:
|
||||
with pytest.raises(MxAccessError):
|
||||
ensure_mxaccess_success("write", reply)
|
||||
else:
|
||||
assert ensure_mxaccess_success("write", reply) is reply
|
||||
|
||||
|
||||
def test_session_status_maps_to_session_error() -> None:
|
||||
status = pb.ProtocolStatus(
|
||||
code=pb.PROTOCOL_STATUS_CODE_SESSION_NOT_FOUND,
|
||||
|
||||
@@ -308,10 +308,12 @@ pub fn ensure_command_success(reply: MxCommandReply) -> Result<MxCommandReply, E
|
||||
/// This is the second reply check applied to the typed command path, after
|
||||
/// [`ensure_command_success`] confirms the protocol envelope is `Ok`. It
|
||||
/// enforces MXAccess parity: a reply can carry an `Ok` protocol envelope while
|
||||
/// MXAccess itself rejected the operation. Following COM semantics (and the
|
||||
/// Python client), only a **negative** `hresult` is a failure — positive codes
|
||||
/// such as `S_FALSE = 1` are success. A `MXSTATUS_PROXY` entry is treated as a
|
||||
/// failure when its `success` member is `0`.
|
||||
/// MXAccess itself rejected the operation. Following COM semantics, only a
|
||||
/// **negative** `hresult` is a failure — positive codes such as `S_FALSE = 1`
|
||||
/// are success. A `MXSTATUS_PROXY` entry is treated as a failure when its
|
||||
/// `category` is not [`MxStatusCategory::Ok`]; the `success` member mirrors the
|
||||
/// raw COM value verbatim for diagnostics and never enters the verdict, so an
|
||||
/// entry with an unspecified category fails even when `success` is non-zero.
|
||||
///
|
||||
/// Per-item bulk failures are reported inside each result entry
|
||||
/// (`was_successful = false`) rather than in the top-level `hresult`/`statuses`
|
||||
@@ -320,10 +322,14 @@ pub fn ensure_command_success(reply: MxCommandReply) -> Result<MxCommandReply, E
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::MxAccess`] when `reply.hresult` is negative or any
|
||||
/// `reply.statuses` entry reports a non-success `success` member.
|
||||
/// `reply.statuses` entry reports a category other than
|
||||
/// [`MxStatusCategory::Ok`].
|
||||
pub fn ensure_mxaccess_success(reply: MxCommandReply) -> Result<MxCommandReply, Error> {
|
||||
let hresult_failure = reply.hresult.is_some_and(|hresult| hresult < 0);
|
||||
let status_failure = reply.statuses.iter().any(|status| status.success == 0);
|
||||
let status_failure = reply
|
||||
.statuses
|
||||
.iter()
|
||||
.any(|status| status.category != MxStatusCategory::Ok as i32);
|
||||
|
||||
if hresult_failure || status_failure {
|
||||
Err(Box::new(MxAccessError::new(reply)).into())
|
||||
@@ -412,8 +418,10 @@ mod tests {
|
||||
let mut reply = ok_reply();
|
||||
// Positive hresult (e.g. S_FALSE = 1) is a success, not a failure.
|
||||
reply.hresult = Some(1);
|
||||
// A zero `success` member with an OK category is still a success: the
|
||||
// category is authoritative and `success` is diagnostics only.
|
||||
reply.statuses = vec![MxStatusProxy {
|
||||
success: 1,
|
||||
success: 0,
|
||||
category: MxStatusCategory::Ok as i32,
|
||||
..MxStatusProxy::default()
|
||||
}];
|
||||
@@ -424,8 +432,9 @@ mod tests {
|
||||
#[test]
|
||||
fn ensure_mxaccess_success_flags_failing_status_entry() {
|
||||
let mut reply = ok_reply();
|
||||
// A non-OK category fails even though the raw `success` member is set.
|
||||
reply.statuses = vec![MxStatusProxy {
|
||||
success: 0,
|
||||
success: 1,
|
||||
category: MxStatusCategory::CommunicationError as i32,
|
||||
detail: 42,
|
||||
diagnostic_text: "write rejected for mxgw_visible_secret".to_owned(),
|
||||
|
||||
@@ -282,7 +282,11 @@ impl MxStatus {
|
||||
&self.raw
|
||||
}
|
||||
|
||||
/// `MXSTATUS_PROXY.Success` flag (0 = error, non-zero = good/warning).
|
||||
/// Raw `MXSTATUS_PROXY.Success` member, carried verbatim from COM.
|
||||
///
|
||||
/// This is a diagnostic value, not a verdict: the wire contract makes
|
||||
/// [`Self::category`] authoritative, and `ensure_mxaccess_success` branches
|
||||
/// on the category alone.
|
||||
pub fn success(&self) -> i32 {
|
||||
self.raw.success
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use tokio::sync::{mpsc, Mutex};
|
||||
use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream};
|
||||
use tonic::transport::Server;
|
||||
use tonic::{Request, Response, Status};
|
||||
use zb_mom_ww_mxgateway_client::error::ensure_mxaccess_success;
|
||||
use zb_mom_ww_mxgateway_client::generated::mxaccess_gateway::v1::mx_access_gateway_server::{
|
||||
MxAccessGateway, MxAccessGatewayServer,
|
||||
};
|
||||
@@ -337,6 +338,57 @@ fn authentication_and_authorization_statuses_are_distinct_and_redacted() {
|
||||
assert!(!auth.to_string().contains("visible_secret"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_reply_validation_fixtures_branch_on_category_and_negative_hresult() {
|
||||
// The shared behavior fixtures pin both reply-validation rules: a status
|
||||
// entry fails iff its category is not OK (the raw `success` member is
|
||||
// diagnostics only) and an HRESULT fails iff it is present and negative.
|
||||
for (fixture, expect_failure) in [
|
||||
("register.ok.reply.json", false),
|
||||
("write.status-category-error-success-set.reply.json", true),
|
||||
("write.status-category-ok-success-zero.reply.json", false),
|
||||
("write.hresult-s-false.reply.json", false),
|
||||
("write.hresult-e-fail.reply.json", true),
|
||||
] {
|
||||
let reply = command_reply_fixture(fixture);
|
||||
let result = ensure_mxaccess_success(reply);
|
||||
|
||||
assert_eq!(
|
||||
result.is_err(),
|
||||
expect_failure,
|
||||
"fixture {fixture} expected failure = {expect_failure}, got {result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_entry_verdict_ignores_the_raw_success_member() {
|
||||
// Edges the fixtures cannot express: an OK category always passes and an
|
||||
// unspecified category always fails, whatever `success` carries.
|
||||
for (category, success, expect_failure) in [
|
||||
(MxStatusCategory::Ok, 0, false),
|
||||
(MxStatusCategory::Ok, 1, false),
|
||||
(MxStatusCategory::CommunicationError, 1, true),
|
||||
(MxStatusCategory::Unspecified, 1, true),
|
||||
] {
|
||||
let reply = MxCommandReply {
|
||||
protocol_status: Some(ok_status("command ok")),
|
||||
statuses: vec![MxStatusProxy {
|
||||
success,
|
||||
category: category as i32,
|
||||
..MxStatusProxy::default()
|
||||
}],
|
||||
..MxCommandReply::default()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
ensure_mxaccess_success(reply).is_err(),
|
||||
expect_failure,
|
||||
"category {category:?} with success {success} expected failure = {expect_failure}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_error_display_keeps_raw_reply_accessible() {
|
||||
let reply = mxaccess_failure_reply();
|
||||
@@ -1358,6 +1410,52 @@ fn event(sequence: u64) -> MxEvent {
|
||||
}
|
||||
}
|
||||
|
||||
/// Load a shared command-reply fixture into an [`MxCommandReply`].
|
||||
///
|
||||
/// The fixtures are protobuf JSON, which prost cannot parse directly, so this
|
||||
/// reads the fields the reply-validation rules actually consume (`hresult` and
|
||||
/// the status `success`/`category` pair) and rebuilds the message. Enum names
|
||||
/// resolve through the generated `from_str_name`, so a fixture naming a
|
||||
/// category the contract does not define fails the test rather than silently
|
||||
/// degrading to `Unspecified`.
|
||||
fn command_reply_fixture(file_name: &str) -> MxCommandReply {
|
||||
let fixture = behavior_fixture(&format!("command-replies/{file_name}"));
|
||||
|
||||
let statuses = fixture["statuses"]
|
||||
.as_array()
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(|status| {
|
||||
let category_name = status["category"].as_str().unwrap();
|
||||
MxStatusProxy {
|
||||
success: status["success"].as_i64().unwrap() as i32,
|
||||
category: MxStatusCategory::from_str_name(category_name)
|
||||
.unwrap_or_else(|| panic!("unknown status category {category_name}"))
|
||||
as i32,
|
||||
detail: status["detail"].as_i64().unwrap_or_default() as i32,
|
||||
diagnostic_text: status["diagnosticText"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
..MxStatusProxy::default()
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
MxCommandReply {
|
||||
session_id: fixture["sessionId"].as_str().unwrap_or_default().to_owned(),
|
||||
correlation_id: fixture["correlationId"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_owned(),
|
||||
protocol_status: Some(ok_status("command ok")),
|
||||
hresult: fixture["hresult"].as_i64().map(|hresult| hresult as i32),
|
||||
statuses,
|
||||
..MxCommandReply::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn behavior_fixture(path: &str) -> Value {
|
||||
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../proto/fixtures/behavior")
|
||||
|
||||
Reference in New Issue
Block a user