async __read()

in aws-greengrass-core-sdk/stream-manager/client.js [241:290]


    async __read(socket = this.#socket) {
        if (this.#connected) {
            const frame = await this.__readMessageFrame(socket);
            this.__handleReadResponse(cbor.decodeFirstSync(frame.payload), frame);
        } else {
            // Read connect version
            const connectResponseVersion = utilInternal.intFromBuffer(await this.__readSocket(1, socket));
            if (connectResponseVersion !== CONNECT_VERSION) {
                this.#logger.error('Unexpected response from the server, Connect version:', connectResponseVersion);
                throw new exceptions.ConnectFailedException('Failed to establish connection with the server');
            }

            // Read connect response
            let response = await this.__readMessageFrame(socket);

            if (response.operation === smData.Operation.ConnectResponse) {
                const payload = cbor.decodeFirstSync(response.payload);
                response = smData.ConnectResponse.fromMap(payload);
                this.#logger.debug('Received ConnectResponse from server:', response);
            } else {
                this.#logger.error('Received data with unexpected operation', response.operation);
                throw new exceptions.ConnectFailedException('Failed to establish connection with the server');
            }

            if (response.status !== smData.ResponseStatusCode.Success) {
                this.#logger.error('Received ConnectResponse with unexpected status', response.status);
                throw new exceptions.ConnectFailedException('Failed to establish connection with the server');
            }

            if (response.protocolVersion !== smData.VersionInfo.PROTOCOL_VERSION.asMap()) {
                this.#logger.warn('SDK with version %s using Protocol version %s is not fully compatible with '
                    + 'Server with version %s. '
                    + 'Client has connected in a compatibility mode using protocol version %s. '
                    + 'Some features will not work as expected', SDK_VERSION, smData.VersionInfo.PROTOCOL_VERSION.asMap(),
                response.serverVersion, response.protocolVersion);
            }
        }

        // Put ourselves back in the event loop to handle the next messages
        setImmediate(async () => {
            try {
                await this.__read();
            } catch (e) {
                // Only bubble up the errors when we're actually connected and not closed
                if (this.#connected && !this.#closed) {
                    this.errorCallbacks.forEach((f) => f(e));
                }
            }
        });
    }