Go 大小语义

解释如何(不)使用 proto.Size

proto.Size 函数通过遍历 proto.Message 的所有字段(包括子消息),返回其线格式编码的大小(以字节为单位)。

特别是,它返回 Go Protobuf 将如何编码消息 的大小。

典型用法

识别空消息

检查 proto.Size 是否返回 0 是识别空消息的一种简单方法

if proto.Size(m) == 0 {
    // No fields set (or, in proto3, all fields matching the default);
    // skip processing this message, or return an error, or similar.
}

限制程序输出的大小

假设您正在编写一个批处理管道,该管道为另一个系统(在此示例中称为“下游系统”)生成工作任务。下游系统配置用于处理中小型任务,但负载测试表明,当遇到超过 500 MB 的工作任务时,系统会发生级联故障。

最好的修复方法是为下游系统添加保护(参见 https://cloud.google.com/blog/products/gcp/using-load-shedding-to-survive-a-success-disaster-cre-life-lessons),但在无法实现负载卸载时,您可以决定在管道中添加一个快速修复。

func (*beamFn) ProcessElement(key string, value []byte, emit func(proto.Message)) {
  task := produceWorkTask(value)
  if proto.Size(task) > 500 * 1024 * 1024 {
    // Skip every work task over 500 MB to not overwhelm
    // the brittle downstream system.
    return
  }
  emit(task)
}

不正确用法:与 Unmarshal 无关

由于 proto.Size 返回 Go Protobuf 将如何编码消息的字节数,因此在 unmarshaling(解码)传入的 Protobuf 消息流时使用 proto.Size 是不安全的。

func bytesToSubscriptionList(data []byte) ([]*vpb.EventSubscription, error) {
    subList := []*vpb.EventSubscription{}
    for len(data) > 0 {
        subscription := &vpb.EventSubscription{}
        if err := proto.Unmarshal(data, subscription); err != nil {
            return nil, err
        }
        subList = append(subList, subscription)
        data = data[:len(data)-proto.Size(subscription)]
    }
    return subList, nil
}

data 包含 非最小线格式 的消息时,proto.Size 返回的大小可能与实际 unmarshal 的大小不同,这可能导致解析错误(最好情况)或最坏情况下的数据解析不正确。

因此,此示例仅在所有输入消息由 Go Protobuf(相同版本)生成时才能可靠工作。这是令人惊讶的,并且可能并非预期用途。

提示: 请改用 protodelim 包来读取/写入带有大小分隔符的 Protobuf 消息流。

高级用法:预设缓冲区大小

proto.Size 的高级用法是在 marshaling 之前确定缓冲区所需的空间大小。

opts := proto.MarshalOptions{
    // Possibly avoid an extra proto.Size in Marshal itself (see docs):
    UseCachedSize: true,
}
// DO NOT SUBMIT without implementing this Optimization opportunity:
// instead of allocating, grab a sufficiently-sized buffer from a pool.
// Knowing the size of the buffer means we can discard
// outliers from the pool to prevent uncontrolled
// memory growth in long-running RPC services.
buf := make([]byte, 0, opts.Size(m))
var err error
buf, err = opts.MarshalAppend(buf, m) // does not allocate
// Note that len(buf) might be less than cap(buf)! Read below:

请注意,当启用延迟解码时,proto.Size 返回的字节数可能比 proto.Marshal(以及 proto.MarshalAppend 等变体)实际写入的要多!因此,当您将编码的字节放在线上(或磁盘上)时,请务必使用 len(buf) 并丢弃任何之前的 proto.Size 结果。

具体来说,在 proto.Sizeproto.Marshal 之间,当出现以下情况时,一个(子)消息可能会“缩小”:

  1. 启用了延迟解码
  2. 并且消息以 非最小线格式 到达
  3. 并且在调用 proto.Size 之前未访问该消息,意味着它尚未被解码
  4. 并且在调用 proto.Size 之后(但在调用 proto.Marshal 之前)访问了该消息,导致其被延迟解码

解码会导致后续的 proto.Marshal 调用对消息进行编码(而不是仅仅复制其线格式),从而隐式地规范化为 Go 编码消息的方式,当前是最小线格式(但请不要依赖这一点!)。

如您所见,这种情况相当特殊,但尽管如此,proto.Size 的结果视为上限是最佳实践,切勿假定结果与实际编码的消息大小匹配。

背景:非最小线格式

编码 Protobuf 消息时,存在一个最小线格式大小和多个解码为相同消息的较大非最小线格式

非最小线格式(有时也称为“非规范化线格式”)指的是非重复字段多次出现、非最优 varint 编码、在线上以非 packed 形式出现的 packed repeated 字段等情况。

我们可能在不同情况下遇到非最小线格式

  • 有意为之。 Protobuf 支持通过连接消息的线格式来连接消息。
  • 意外发生。 (可能是第三方的)Protobuf 编码器编码不理想(例如,编码 varint 时使用了比必要更多的空间)。
  • 恶意为之。 攻击者可以专门构造 Protobuf 消息以触发网络上的崩溃。