Encodes gRPC messages to be delivered via the transport layer which implements MessageFramer.Sink.
| 43 | * MessageFramer.Sink}. |
| 44 | */ |
| 45 | public class MessageFramer implements Framer { |
| 46 | |
| 47 | private static final int NO_MAX_OUTBOUND_MESSAGE_SIZE = -1; |
| 48 | |
| 49 | /** |
| 50 | * Sink implemented by the transport layer to receive frames and forward them to their |
| 51 | * destination. |
| 52 | */ |
| 53 | public interface Sink { |
| 54 | /** |
| 55 | * Delivers a frame via the transport. |
| 56 | * |
| 57 | * @param frame a non-empty buffer to deliver or {@code null} if the framer is being |
| 58 | * closed and there is no data to deliver. |
| 59 | * @param endOfStream whether the frame is the last one for the GRPC stream |
| 60 | * @param flush {@code true} if more data may not be arriving soon |
| 61 | * @param numMessages the number of messages that this series of frames represents |
| 62 | */ |
| 63 | void deliverFrame( |
| 64 | @Nullable WritableBuffer frame, |
| 65 | boolean endOfStream, |
| 66 | boolean flush, |
| 67 | int numMessages); |
| 68 | } |
| 69 | |
| 70 | private static final int HEADER_LENGTH = 5; |
| 71 | private static final byte UNCOMPRESSED = 0; |
| 72 | private static final byte COMPRESSED = 1; |
| 73 | |
| 74 | private final Sink sink; |
| 75 | // effectively final. Can only be set once. |
| 76 | private int maxOutboundMessageSize = NO_MAX_OUTBOUND_MESSAGE_SIZE; |
| 77 | private WritableBuffer buffer; |
| 78 | /** |
| 79 | * if > 0 - the number of bytes to allocate for the current known-length message. |
| 80 | */ |
| 81 | private int knownLengthPendingAllocation; |
| 82 | private Compressor compressor = Codec.Identity.NONE; |
| 83 | private boolean messageCompression = true; |
| 84 | private final OutputStreamAdapter outputStreamAdapter = new OutputStreamAdapter(); |
| 85 | private final ByteBuffer headerScratch = ByteBuffer.allocate(HEADER_LENGTH); |
| 86 | private final WritableBufferAllocator bufferAllocator; |
| 87 | private final StatsTraceContext statsTraceCtx; |
| 88 | // transportTracer is nullable until it is integrated with client transports |
| 89 | private boolean closed; |
| 90 | |
| 91 | // Tracing and stats-related states |
| 92 | private int messagesBuffered; |
| 93 | private int currentMessageSeqNo = -1; |
| 94 | private long currentMessageWireSize; |
| 95 | |
| 96 | /** |
| 97 | * Creates a {@code MessageFramer}. |
| 98 | * |
| 99 | * @param sink the sink used to deliver frames to the transport |
| 100 | * @param bufferAllocator allocates buffers that the transport can commit to the wire. |
| 101 | */ |
| 102 | public MessageFramer( |