rsocket / rsocket-js

JavaScript implementation of RSocket
https://github.com/rsocket/rsocket-js
Apache License 2.0
594 stars 97 forks source link

a problem of Buffer.allocUnsafe in encodeCustomMetadataHeader #230

Closed HrOice closed 2 years ago

HrOice commented 2 years ago
function encodeCustomMetadataHeader(customMime, metadataLength) {
    var metadataHeader = Buffer.allocUnsafe(4 + customMime.length);
    // reserve 1 byte for the customMime length
    // /!\ careful not to read that first byte, which is random at this point
    // int writerIndexInitial = metadataHeader.writerIndex();
    // metadataHeader.writerIndex(writerIndexInitial + 1);
    // write the custom mime in UTF8 but validate it is all ASCII-compatible
    // (which produces the right result since ASCII chars are still encoded on 1 byte in UTF8)
    var customMimeLength = metadataHeader.write(customMime, 1);
    if (!isAscii(metadataHeader, 1)) {
        throw new Error("Custom mime type must be US_ASCII characters only");
    }
    if (customMimeLength < 1 || customMimeLength > 128) {
        throw new Error("Custom mime type must have a strictly positive length that fits on 7 unsigned bits, ie 1-128");
    }
    // encoded length is one less than actual length, since 0 is never a valid length, which gives
    // wider representation range
    metadataHeader.writeUInt8(customMimeLength - 1);
    (0, rsocket_core_1.writeUInt24BE)(metadataHeader, metadataLength, customMimeLength + 1);
    return metadataHeader;
}

var metadataHeader = Buffer.allocUnsafe(4 + customMime.length); The bytes of metadataHeader will alloc some old bytes sometimes. but don't fill full.

my code

let data = Buffer.from([])
        data = encodeAndAddCustomMetadata(data, "message/x.rsocket.application+json", Buffer.from(JSON.stringify(this.namespace)))

There will throw a error like ' throw new Error("Custom mime type must be US_ASCII characters only");' sometimes, and there will run successfully othertimes.

what can i do for this problem?

Thanks!!!

viglucci commented 2 years ago

Hi @HrOice,

Which version of rsocket-js are you experiencing this issue with? Thanks

HrOice commented 2 years ago

Hi @HrOice,

Which version of rsocket-js are you experiencing this issue with? Thanks

"rsocket-composite-metadata": "^1.0.0-alpha.1",
"rsocket-core": "^1.0.0-alpha.1",
"rsocket-tcp-client": "^1.0.0-alpha.1",
"rsocket-tcp-server": "^1.0.0-alpha.1",
viglucci commented 2 years ago

@HrOice thanks. I've opened a PR to address this. We will cut new versions after it is reviewed.

HrOice commented 2 years ago

Your work is very efficient,Thanks:)

viglucci commented 2 years ago

Hey @HrOice , this should be fixed with 1.0.0-alpha.2

viglucci commented 2 years ago

Closing this as we haven't heard back. @HrOice please let us know if you experience further issues.