Protobuf C++ 必填字段不是 checked/enforced

Protobuf C++ required fields are not checked/enforced

我是 Protocol Buffers 的新手,目前我看到以下问题:

我们在 Protocol Buffers 3.2.0 库中使用 proto2 语法,并观察到 ​​required 字段在序列化期间未强制执行。

这里是 Catch C++ 测试的基本示例:

syntax = "proto2";

package simple_test;

message SimpleMessage
{
  required string field1 = 1;
  required string field2 = 2;
}

#include "simple.pb.h"
#include <catch.hpp>
#include <string>

SCENARIO("Verify that serialization with missing required fields fails", "[protobuf]")
{
  GIVEN("a message")
  {
    simple_test::SimpleMessage m;

    WHEN("field1 is set and field2 is not and both are required")
    {
      m.set_field1("aaa");

      THEN("serializing this message to string buffer must fail")
      {
        std::string buffer;
        CHECK_FALSE(m.SerializeToString(&buffer));
        REQUIRE(buffer.empty());
      }
    }
  }
}

m.SerializeToString(&buffer) returns truebuffer.empty()false.

我所知道的

required 字段已在 Protobuf v3 中删除。

我的问题

Is there a setting or any kind of config switch that I can enforce these checks with Protobuf v3?

您是否尝试过在调试配置中构建 protobuf?我想你会发现在这种情况下它会断言。

What happens with the use case:

proto2 Message compiled with Protobuf v3 compiler. This message ends up with partially filled required fields and is going to be send to Protobuf v2 enpoint which enforces the required fields. Does this effectively mean that there were just bytes sent for nothing, because the message is invalid and will be rejected?

在这种情况下,接收方可以ParsePartialFromXXX接收发送的内容。他可以使用 message.has_xxx()

来测试消息的有效性

Should I downgrade from v3.2.0 to 2.x to disallow sending of incomplete messages at client side?

我不会。也许为每种消息类型编写一个检查器来断言每个必需的字段都存在。更好的是,以 proto3 的方式考虑它,并将缺少的字段视为接收器中的默认值。 protobuf 文档建议不要向现有消息类型添加 required 字段,并建议在创建字段 required 之前添加 'thinking very carefully'。您可以将其理解为 'oops, the concept of required fields was an error'.

我看到了这份我之前监督过的文档:

Standard Message Methods 并且有以下文档:

Standard Message Methods

Each message class also contains a number of other methods that let you check or manipulate the entire message, including:

bool IsInitialized() const;: checks if all the required fields have been set.

这就是我需要的! Protobuf 又很棒了!