@@ -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