|
| 1 | +package misk.grpc |
| 2 | + |
| 3 | +import com.squareup.wire.MessageSource |
| 4 | +import com.squareup.wire.ProtoAdapter |
| 5 | +import okio.Buffer |
| 6 | +import okio.BufferedSource |
| 7 | +import okio.buffer |
| 8 | +import java.io.Closeable |
| 9 | +import java.net.ProtocolException |
| 10 | + |
| 11 | +/** |
| 12 | + * Reads an HTTP/2 stream as a sequence of gRPC messages. |
| 13 | + * |
| 14 | + * This is derived from Wire's GrpcMessageSource.kt. |
| 15 | + * https://github.com/square/wire/blob/master/wire-grpc-client/src/main/java/com/squareup/wire/GrpcMessageSource.kt |
| 16 | + * |
| 17 | + * @param source the HTTP/2 stream body. |
| 18 | + * @param messageAdapter a proto adapter for each message. |
| 19 | + * @param grpcEncoding the "grpc-encoding" header, or null if it is absent. |
| 20 | + */ |
| 21 | +internal class GrpcMessageSource<T : Any>( |
| 22 | + private val source: BufferedSource, |
| 23 | + private val messageAdapter: ProtoAdapter<T>, |
| 24 | + private val grpcEncoding: String? = null |
| 25 | +) : MessageSource<T>, Closeable by source { |
| 26 | + override fun read(): T? { |
| 27 | + if (source.exhausted()) return null |
| 28 | + |
| 29 | + // Length-Prefixed-Message → Compressed-Flag Message-Length Message |
| 30 | + // Compressed-Flag → 0 / 1 # encoded as 1 byte unsigned integer |
| 31 | + // Message-Length → {length of Message} # encoded as 4 byte unsigned integer |
| 32 | + // Message → *{binary octet} |
| 33 | + |
| 34 | + val compressedFlag = source.readByte() |
| 35 | + val messageDecoding: GrpcDecoder = when { |
| 36 | + compressedFlag.toInt() == 0 -> GrpcDecoder.IdentityGrpcDecoder |
| 37 | + compressedFlag.toInt() == 1 -> { |
| 38 | + grpcEncoding?.toGrpcDecoding() ?: throw ProtocolException( |
| 39 | + "message is encoded but message-encoding header was omitted") |
| 40 | + } |
| 41 | + else -> throw ProtocolException("unexpected compressed-flag: $compressedFlag") |
| 42 | + } |
| 43 | + |
| 44 | + val encodedLength = source.readInt().toLong() and 0xffffffffL |
| 45 | + |
| 46 | + val encodedMessage = Buffer() |
| 47 | + encodedMessage.write(source, encodedLength) |
| 48 | + |
| 49 | + return messageAdapter.decode(messageDecoding.decode(encodedMessage).buffer()) |
| 50 | + } |
| 51 | + |
| 52 | + override fun toString() = "GrpcMessageSource" |
| 53 | +} |
0 commit comments