coders51 / rabbitmq-stream-js-client

rabbitmq-stream-js-client
MIT License
34 stars 5 forks source link

RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to access memory outside buffer bounds #215

Open MartianH opened 1 month ago

MartianH commented 1 month ago

Environment

OS: macOS 15.0 24A335 arm64 Node: v20.12.2

Dependencies:

"@nestjs/common": "^10.4.4",
"@nestjs/config": "3.2.3",
"@nestjs/core": "^10.4.4",
"dd-trace": "^5.22.0",
"nestjs-ddtrace": "^5.0.0",
"rabbitmq-stream-js-client": "^0.4.2",

Description

While using this library as a single page script works fine, it seems like wrapping it into a NestJS module results in unforseen errors.

here is the code at hand

import {
  DynamicModule,
  FactoryProvider,
  Logger,
  Module,
  Provider,
} from '@nestjs/common';
import { ConfigurationOptions } from '../lib';
import { hostname } from 'os';
import { Client, connect } from 'rabbitmq-stream-js-client';

import { RabbitStreamService } from './rabbitStream.service';

@Module({})
export class RabbitStreamModule {
  private static appLogger = new Logger(RabbitStreamModule.name);

  static async tryConfigure({
    connection,
  }: ConfigurationOptions): Promise<Client> {
    try {
      let client: Client;
      const connectionClosedCallback = () => {
        this.appLogger.log(`In connection closed event...`);
        client
          .restart()
          .then(() => {
            this.appLogger.log(`Connections restarted!`);
          })
          .catch((reason) => {
            this.appLogger.warn(`Could not reconnect to Rabbit! ${reason}`);
          });
      };
      client = await connect({
        hostname: connection.server ? connection.server[0] : 'localhost',
        port: 5552,
        username: connection.user as string,
        password: connection.pass as string,
        vhost: connection.vhost || '/',
        heartbeat: connection.heartbeat,
        listeners: { connection_closed: connectionClosedCallback },
        connectionName: `${hostname()}:${connection.serviceName}:pid-${
          process.pid
        }`,
      });
      return client;
    } catch (error) {
      this.appLogger.error(`Error: ${error}`);
      throw error;
    }
  }

  static forRootAsync(
    options: Omit<FactoryProvider, 'provide'>,
  ): DynamicModule {
    const asyncProviders = this.createAsyncOptionsProvider(options);
    const rabbitProvider = {
      provide: 'RABBIT_MQ_STREAM',
      useFactory: (rabbitConfig: ConfigurationOptions): Promise<Client> =>
        this.tryConfigure(rabbitConfig),
      inject: ['RABBIT_CONFIG'],
    };
    return {
      module: RabbitStreamModule,
      providers: [asyncProviders, rabbitProvider, RabbitStreamService],
      exports: [RabbitStreamService],
    };
  }

  private static createAsyncOptionsProvider(
    options: Omit<FactoryProvider<ConfigurationOptions>, 'provide'>,
  ): Provider {
    return {
      provide: 'RABBIT_CONFIG',
      useFactory: options.useFactory,
      inject: options.inject || [],
    };
  }
}

Resulting logs (sensitive data omitted):

[Nest] 41154  - 11/10/2024, 11:25:45     LOG [NestFactory] Starting Nest application...
[Nest] 41154  - 11/10/2024, 11:25:45     LOG [InstanceLoader] ConfigHostModule dependencies initialized +0ms
[Nest] 41154  - 11/10/2024, 11:25:45     LOG [InstanceLoader] CacheModule dependencies initialized +1ms
[Nest] 41154  - 11/10/2024, 11:25:45     LOG [InstanceLoader] ConfigModule dependencies initialized +0ms
[Nest] 41154  - 11/10/2024, 11:25:45     LOG [InstanceLoader] DatadogTraceModule dependencies initialized +0ms
[Nest] 41154  - 11/10/2024, 11:25:45     LOG [InstanceLoader] CouchbaseModule dependencies initialized +2ms
node:internal/buffer:86
    throw new ERR_BUFFER_OUT_OF_BOUNDS();
    ^

RangeError [ERR_BUFFER_OUT_OF_BOUNDS]: Attempt to access memory outside buffer bounds
    at boundsError (node:internal/buffer:86:11)
    at Buffer.readInt32BE (node:internal/buffer:484:5)
    at BufferDataReader.readInt32 ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/response_decoder.ts:537:27)
    at OpenResponse ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/responses/open_response.ts:14:43)
    at ResponseDecoder.emitResponseReceived ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/response_decoder.ts:736:19)
    at ResponseDecoder.add ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/response_decoder.ts:691:14)
    at Connection.received ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/connection.ts:374:18)
    at Socket.<anonymous> ({{ommitted_path}}/backend/src/node_modules/rabbitmq-stream-js-client/src/connection.ts:164:14)
    at Socket.emit (node:events:518:28)
    at Socket.emit ({{ommitted_path}}/backend/src/node_modules/dd-trace/packages/datadog-instrumentations/src/net.js:69:25)
    at Socket.emit ({{ommitted_path}}/backend/src/node_modules/dd-trace/packages/datadog-shimmer/src/shimmer.js:31:21)
    at addChunk (node:internal/streams/readable:559:12)
    at readableAddChunkPushByteMode (node:internal/streams/readable:510:3)
    at Readable.push (node:internal/streams/readable:390:5)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17) {
  code: 'ERR_BUFFER_OUT_OF_BOUNDS'
}
Node.js v20.12.2
icappello commented 1 month ago

Thanks for taking the time to open the issue and provide the information. We will get back to you in the following days.

MartianH commented 1 month ago

It has been a week. Any update on this?

Gsantomaggio commented 3 weeks ago

Hi @MartianH, thank you for using the client. The client is a best effort by Corders51, and they will have a look as soon as possible. Feel free to propose a PR to fix the problem.