Skip to content

Commit f338988

Browse files
author
Sergey Saltykov
committed
allow write buffer to server stream
1 parent 666a374 commit f338988

File tree

2 files changed

+32
-9
lines changed

2 files changed

+32
-9
lines changed

packages/grpc-js/src/object-stream.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ export interface IntermediateObjectWritable<T> extends Writable {
4949
}
5050

5151
export interface ObjectWritable<T> extends IntermediateObjectWritable<T> {
52-
_write(chunk: T, encoding: string, callback: Function): void;
53-
write(chunk: T, cb?: Function): boolean;
54-
write(chunk: T, encoding?: any, cb?: Function): boolean;
52+
_write(chunk: T | Buffer, encoding: string, callback: Function): void;
53+
write(chunk: T | Buffer, cb?: Function): boolean;
54+
write(chunk: T | Buffer, encoding?: any, cb?: Function): boolean;
5555
setDefaultEncoding(encoding: string): this;
5656
end(): ReturnType<Writable['end']> extends Writable ? this : void;
5757
end(

packages/grpc-js/src/server-call.ts

+29-6
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ export class ServerWritableStreamImpl<RequestType, ResponseType>
222222
}
223223

224224
_write(
225-
chunk: ResponseType,
225+
chunk: ResponseType | Buffer,
226226
encoding: string,
227227
// eslint-disable-next-line @typescript-eslint/no-explicit-any
228228
callback: (...args: any[]) => void
@@ -654,15 +654,38 @@ export class Http2ServerCallStream<
654654
}
655655
}
656656

657-
serializeMessage(value: ResponseType) {
657+
serializeMessage(value: ResponseType | Buffer) {
658+
// TODO(cjihrig): Call compression aware serializeMessage().
659+
660+
if (value instanceof Buffer) {
661+
return this.serializeMessageHandleBuffer(value);
662+
}
663+
658664
const messageBuffer = this.handler.serialize(value);
665+
return this.addCompressionAndLength(messageBuffer);
666+
}
659667

660-
// TODO(cjihrig): Call compression aware serializeMessage().
661-
const byteLength = messageBuffer.byteLength;
668+
private serializeMessageHandleBuffer(value: Buffer): Buffer {
669+
const byteLength = value.byteLength;
670+
// checking if this is a protobuf message or a gRPC frame
671+
if (
672+
byteLength >= 5 &&
673+
(value.readUInt8(0) === 0 || value.readUint8(0) === 1) &&
674+
value.readUInt32BE(1) === byteLength - 5
675+
) {
676+
return value;
677+
}
678+
679+
return this.addCompressionAndLength(value);
680+
}
681+
682+
private addCompressionAndLength(value: Buffer, compressed = false) {
683+
const byteLength = value.byteLength;
684+
const compressionByte = compressed ? 1 : 0;
662685
const output = Buffer.allocUnsafe(byteLength + 5);
663-
output.writeUInt8(0, 0);
686+
output.writeUInt8(compressionByte, 0);
664687
output.writeUInt32BE(byteLength, 1);
665-
messageBuffer.copy(output, 5);
688+
value.copy(output, 5);
666689
return output;
667690
}
668691

0 commit comments

Comments
 (0)