Socket
Socket
Sign inDemoInstall

aws-crt

Package Overview
Dependencies
Maintainers
4
Versions
123
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

aws-crt - npm Package Compare versions

Comparing version 1.15.18 to 1.15.19

60

dist.browser/browser/mqtt.d.ts

@@ -6,4 +6,4 @@ import * as WebsocketUtils from "./ws";

import { ClientBootstrap, SocketOptions } from "./io";
import { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
import { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult } from "../common/mqtt";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult } from "../common/mqtt";
/**

@@ -27,4 +27,36 @@ * Listener signature for event emitted from an {@link MqttClientConnection} when an error occurs

/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every successful connect and every successful reconnect.
*
* @param callback_data Data returned containing information about the successful connection.
*
* @category MQTT
*/
export declare type MqttConnectionSuccess = (callback_data: OnConnectionSuccessResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has failed
* to connect.
*
* This listener is invoked for every failed connect and every failed reconnect.
*
* @param callback_data Data returned containing information about the failed connection.
*
* @category MQTT
*/
export declare type MqttConnectionFailure = (callback_data: OnConnectionFailedResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* disconnected and shutdown successfully.
*
* @param callback_data Data returned containing information about the closed/disconnected connection.
* Currently empty, but may contain data in the future.
*
* @category MQTT
*/
export declare type MqttConnectionClosed = (callback_data: OnConnectionClosedResult) => void;
/**
* @category MQTT
*/
export declare type WebsocketOptions = WebsocketUtils.WebsocketOptions;

@@ -145,2 +177,3 @@ /**

private reconnectTask?;
private lastError?;
/**

@@ -189,2 +222,22 @@ * @param client The client that owns this connection

static MESSAGE: string;
/**
* Emitted on every successful connect and reconnect.
* Will contain a boolean indicating whether the connection resumed a session.
*
* @event
*/
static CONNECTION_SUCCESS: string;
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
static CONNECTION_FAILURE: string;
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
static CLOSED: string;
on(event: 'connect', listener: MqttConnectionConnected): this;

@@ -194,2 +247,5 @@ on(event: 'disconnect', listener: MqttConnectionDisconnected): this;

on(event: 'interrupt', listener: MqttConnectionInterrupted): this;
on(event: 'connection_success', listener: MqttConnectionSuccess): this;
on(event: 'connection_failure', listener: MqttConnectionFailure): this;
on(event: 'closed', listener: MqttConnectionClosed): this;
on(event: 'resume', listener: MqttConnectionResumed): this;

@@ -196,0 +252,0 @@ on(event: 'message', listener: OnMessageCallback): this;

@@ -225,4 +225,9 @@ "use strict";

}
// Call connection success every time we connect, whether it is a first connect or a reconnect
var successCallbackData = { session_present: session_present };
_this.emit('connection_success', successCallbackData);
};
_this.on_close = function () {
var _a;
var lastError = _this.lastError;
/*

@@ -235,5 +240,12 @@ * Only emit an interruption event if we were connected, otherwise we just failed to reconnect after

_this.emit('interrupt', -1);
/* Did we intend to disconnect? If so, then emit the event */
if (_this.desiredState == MqttBrowserClientState.Stopped) {
_this.emit("closed");
}
}
/* Only try and reconnect if our desired state is connected, ie no one has called disconnect() */
/* Only try and reconnect if our desired state is connected, or in other words, no one has called disconnect() */
if (_this.desiredState == MqttBrowserClientState.Connected) {
var crtError = new browser_1.CrtError((_a = lastError === null || lastError === void 0 ? void 0 : lastError.toString()) !== null && _a !== void 0 ? _a : "connectionFailure");
var failureCallbackData = { error: crtError };
_this.emit('connection_failure', failureCallbackData);
var waitTime = _this.get_reconnect_time_sec();

@@ -246,7 +258,17 @@ _this.reconnectTask = setTimeout(function () {

}
_this.lastError = undefined;
};
_this.on_disconnected = function () {
_this.emit('disconnect');
/**
* This shouldn't ever occur, but in THEORY it could be possible to have on_disconnected called with the intent
* to disconnect without on_close called first. This would properly emit 'closed' should that unlikely event occur.
*/
if (_this.currentState == MqttBrowserClientState.Connected && _this.desiredState == MqttBrowserClientState.Stopped) {
var closedCallbackData = {};
_this.emit("closed", closedCallbackData);
}
};
_this.on_error = function (error) {
_this.lastError = error;
_this.emit('error', new browser_1.CrtError(error));

@@ -344,4 +366,8 @@ };

on_connect_error = function (error) {
reject(new browser_1.CrtError(error));
var crtError = new browser_1.CrtError(error);
var failureCallbackData = { error: crtError };
_this.emit('connection_failure', failureCallbackData);
reject(crtError);
};
this.connection.once('error', on_connect_error);
this.connection.once('connect', function (connack) {

@@ -351,3 +377,2 @@ _this.connection.removeListener('error', on_connect_error);

});
this.connection.once('error', on_connect_error);
return [2 /*return*/];

@@ -579,2 +604,22 @@ }

MqttClientConnection.MESSAGE = 'message';
/**
* Emitted on every successful connect and reconnect.
* Will contain a boolean indicating whether the connection resumed a session.
*
* @event
*/
MqttClientConnection.CONNECTION_SUCCESS = 'connection_success';
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
MqttClientConnection.CONNECTION_FAILURE = 'connection_failure';
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
MqttClientConnection.CLOSED = 'closed';
return MqttClientConnection;

@@ -581,0 +626,0 @@ }(event_1.BufferedEventEmitter));

@@ -8,2 +8,3 @@ /**

*/
import { ICrtError } from './error';
/**

@@ -74,2 +75,35 @@ * Quality of service control for mqtt publish operations

/**
* The data returned from an on_connection_success callback
*
* @category MQTT
*/
export interface OnConnectionSuccessResult {
/**
* A boolean indicating if the connection resumed a session.
*/
session_present: boolean;
/**
* An optional connect return code received from the server, if a connect return code was returned.
*/
reason_code?: number;
}
/**
* The data returned from an on_connection_failed callback
*
* @category MQTT
*/
export interface OnConnectionFailedResult {
/**
* Error description of the error that occurred
*/
error: ICrtError;
}
/**
* The data returned from the on_connection_closed callback
*
* @category MQTT
*/
export interface OnConnectionClosedResult {
}
/**
* Subscription SUBACK result

@@ -76,0 +110,0 @@ *

7

dist.browser/common/mqtt.js

@@ -9,9 +9,2 @@ "use strict";

/**
*
* A module containing support for mqtt connection establishment and operations.
*
* @packageDocumentation
* @module mqtt
*/
/**
* Quality of service control for mqtt publish operations

@@ -18,0 +11,0 @@ *

@@ -8,2 +8,3 @@ /**

*/
import { ICrtError } from './error';
/**

@@ -74,2 +75,35 @@ * Quality of service control for mqtt publish operations

/**
* The data returned from an on_connection_success callback
*
* @category MQTT
*/
export interface OnConnectionSuccessResult {
/**
* A boolean indicating if the connection resumed a session.
*/
session_present: boolean;
/**
* An optional connect return code received from the server, if a connect return code was returned.
*/
reason_code?: number;
}
/**
* The data returned from an on_connection_failed callback
*
* @category MQTT
*/
export interface OnConnectionFailedResult {
/**
* Error description of the error that occurred
*/
error: ICrtError;
}
/**
* The data returned from the on_connection_closed callback
*
* @category MQTT
*/
export interface OnConnectionClosedResult {
}
/**
* Subscription SUBACK result

@@ -76,0 +110,0 @@ *

@@ -9,9 +9,2 @@ "use strict";

/**
*
* A module containing support for mqtt connection establishment and operations.
*
* @packageDocumentation
* @module mqtt
*/
/**
* Quality of service control for mqtt publish operations

@@ -18,0 +11,0 @@ *

@@ -250,2 +250,8 @@ /*

/** @internal */
export function mqtt_client_connection_on_closed(
connection: NativeHandle,
on_closed?: () => void
): void;
/** @internal */
export function mqtt_client_connection_unsubscribe(

@@ -252,0 +258,0 @@ connection: NativeHandle,

@@ -7,4 +7,4 @@ import { NativeResource } from "./native_resource";

export { HttpProxyOptions } from './http';
import { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
import { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult } from "../common/mqtt";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult } from "../common/mqtt";
/**

@@ -28,2 +28,34 @@ * Listener signature for event emitted from an {@link MqttClientConnection} when an error occurs

/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every successful connect and every successful reconnect.
*
* @param callback_data Data returned containing information about the successful connection.
*
* @category MQTT
*/
export declare type MqttConnectionSucess = (callback_data: OnConnectionSuccessResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every failed connect and every failed reconnect.
*
* @param callback_data Data returned containing information about the failed connection.
*
* @category MQTT
*/
export declare type MqttConnectionFailure = (callback_data: OnConnectionFailedResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* disconnected and shutdown successfully.
*
* @param callback_data Data returned containing information about the closed/disconnected connection.
* Currently empty, but may contain data in the future.
*
* @category MQTT
*/
export declare type MqttConnectionClosed = (callback_data: OnConnectionClosedResult) => void;
/**
* MQTT client

@@ -220,2 +252,23 @@ *

static MESSAGE: string;
/**
* Emitted on every successful connect and reconnect.
* Will contain a number with the connection reason code and
* a boolean indicating whether the connection resumed a session.
*
* @event
*/
static CONNECTION_SUCCESS: string;
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
static CONNECTION_FAILURE: string;
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
static CLOSED: string;
on(event: 'connect', listener: MqttConnectionConnected): this;

@@ -227,2 +280,5 @@ on(event: 'disconnect', listener: MqttConnectionDisconnected): this;

on(event: 'message', listener: OnMessageCallback): this;
on(event: 'connection_success', listener: MqttConnectionSucess): this;
on(event: 'connection_failure', listener: MqttConnectionFailure): this;
on(event: 'closed', listener: MqttConnectionClosed): this;
/**

@@ -306,2 +362,3 @@ * Open the actual connection to the server (async).

private _on_any_publish;
private _on_connection_closed;
private _on_connect_callback;

@@ -308,0 +365,0 @@ private _on_puback_callback;

@@ -136,2 +136,3 @@ "use strict";

binding_1.default.mqtt_client_connection_on_message(this.native_handle(), this._on_any_publish.bind(this));
binding_1.default.mqtt_client_connection_on_closed(this.native_handle(), this._on_connection_closed.bind(this));
/*

@@ -342,2 +343,4 @@ * Failed mqtt operations (which is normal) emit error events as well as rejecting the original promise.

this.emit('resume', return_code, session_present);
let successCallbackData = { session_present: session_present, reason_code: return_code };
this.emit('connection_success', successCallbackData);
}

@@ -347,2 +350,11 @@ _on_any_publish(topic, payload, dup, qos, retain) {

}
_on_connection_closed() {
let closedCallbackData = {};
this.emit('closed', closedCallbackData);
/**
* We call close() here instead of on disconnect because on_close is always called AFTER disconnect
* but if we call close() before, then we cannot emit the closed callback.
*/
this.close();
}
_on_connect_callback(resolve, reject, error_code, return_code, session_present) {

@@ -352,8 +364,14 @@ if (error_code == 0 && return_code == 0) {

this.emit('connect', session_present);
let successCallbackData = { session_present: session_present, reason_code: return_code };
this.emit('connection_success', successCallbackData);
}
else if (error_code != 0) {
reject("Failed to connect: " + io.error_code_to_string(error_code));
let failureCallbackData = { error: new error_1.CrtError(error_code) };
this.emit('connection_failure', failureCallbackData);
}
else {
reject("Server rejected connection.");
let failureCallbackData = { error: new error_1.CrtError(5134) }; // 5134 = AWS_ERROR_MQTT_UNEXPECTED_HANGUP
this.emit('connection_failure', failureCallbackData);
}

@@ -388,3 +406,4 @@ }

this.emit('disconnect');
this.close();
/** NOTE: We are NOT calling close() here but instead calling it at
* on_closed because it is always called after disconnect */
}

@@ -431,2 +450,23 @@ }

MqttClientConnection.MESSAGE = 'message';
/**
* Emitted on every successful connect and reconnect.
* Will contain a number with the connection reason code and
* a boolean indicating whether the connection resumed a session.
*
* @event
*/
MqttClientConnection.CONNECTION_SUCCESS = 'connection_success';
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
MqttClientConnection.CONNECTION_FAILURE = 'connection_failure';
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
MqttClientConnection.CLOSED = 'closed';
//# sourceMappingURL=mqtt.js.map

@@ -11,3 +11,6 @@ /*

import { v4 as uuid } from 'uuid';
import {once} from "events";
jest.setTimeout(10000);
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_custom_auth_unsigned())('Aws Iot Core Mqtt over websockets with Non-Signing Custom Auth - Connection Success', async () => {

@@ -50,3 +53,3 @@

test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_cred())('MQTT Native Websocket Connect/Disconnect', async () => {
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_cred())('MQTT Browser Websocket Connect/Disconnect', async () => {
let builder = aws_iot_mqtt311.AwsIotMqttConnectionConfigBuilder.new_with_websockets();

@@ -64,7 +67,16 @@ builder.with_endpoint(test_env.AWS_IOT_ENV.MQTT311_HOST);

let connection = client.new_connection(config);
const connectionSuccess = once(connection, "connection_success");
await connection.connect();
let connectionSuccessEvent: mqtt311.OnConnectionSuccessResult = (await connectionSuccess)[0];
expect(connectionSuccessEvent.session_present).toBeFalsy();
expect(connectionSuccessEvent.reason_code).toBeUndefined();
const closed = once(connection, "closed");
await connection.disconnect();
await closed;
});
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_cred())('MQTT Native Websocket Connect/Disconnect No Bootstrap', async () => {
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_cred())('MQTT Browser Websocket Connect/Disconnect No Bootstrap', async () => {
let builder = aws_iot_mqtt311.AwsIotMqttConnectionConfigBuilder.new_with_websockets();

@@ -80,6 +92,47 @@ builder.with_endpoint(test_env.AWS_IOT_ENV.MQTT311_HOST);

let config = builder.build();
let client = new mqtt311.MqttClient();
let connection = client.new_connection(config);
const connectionSuccess = once(connection, "connection_success");
await connection.connect();
let connectionSuccessEvent: mqtt311.OnConnectionSuccessResult = (await connectionSuccess)[0];
expect(connectionSuccessEvent.session_present).toBeFalsy();
expect(connectionSuccessEvent.reason_code).toBeUndefined();
const closed = once(connection, "closed");
await connection.disconnect();
await closed;
});
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_custom_auth_signed())('MQTT Browser Websocket Connect/Disconnect - Connection Failure', async () => {
let builder = aws_iot_mqtt311.AwsIotMqttConnectionConfigBuilder.new_default_builder();
builder.with_custom_authorizer(
test_env.AWS_IOT_ENV.MQTT311_CUSTOM_AUTH_SIGNED_USERNAME,
test_env.AWS_IOT_ENV.MQTT311_CUSTOM_AUTH_SIGNED_NAME,
test_env.AWS_IOT_ENV.MQTT311_CUSTOM_AUTH_SIGNED_SIGNATURE,
"Thisisnotthepassword",
test_env.AWS_IOT_ENV.MQTT311_CUSTOM_AUTH_SIGNED_KEY_NAME,
test_env.AWS_IOT_ENV.MQTT311_CUSTOM_AUTH_SIGNED_TOKEN,
)
builder.with_endpoint(test_env.AWS_IOT_ENV.MQTT311_HOST);
builder.with_client_id(`node-mqtt-unit-test-${uuid()}`)
let config = builder.build();
let client = new mqtt311.MqttClient();
let connection = client.new_connection(config);
const connectionFailure = once(connection, "connection_failure")
try {
connection.connect();
} catch (error) {
// Skip - this is expected because we are intentionally using a bad password
}
let connectionFailedEvent: mqtt311.OnConnectionFailedResult = (await connectionFailure)[0];
expect(connectionFailedEvent).toBeDefined();
expect(connectionFailedEvent.error).toBeDefined();
// Disconnect to stop trying to reconnect
connection.disconnect();
});

@@ -34,7 +34,13 @@ /*

DEFAULT_RECONNECT_MIN_SEC,
DEFAULT_RECONNECT_MAX_SEC
DEFAULT_RECONNECT_MAX_SEC,
OnConnectionSuccessResult,
OnConnectionFailedResult,
OnConnectionClosedResult
} from "../common/mqtt";
import {normalize_payload} from "../common/mqtt_shared";
import { normalize_payload } from "../common/mqtt_shared";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
export {
QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected,
MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult
} from "../common/mqtt";

@@ -61,4 +67,39 @@ /**

/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every successful connect and every successful reconnect.
*
* @param callback_data Data returned containing information about the successful connection.
*
* @category MQTT
*/
export type MqttConnectionSuccess = (callback_data: OnConnectionSuccessResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has failed
* to connect.
*
* This listener is invoked for every failed connect and every failed reconnect.
*
* @param callback_data Data returned containing information about the failed connection.
*
* @category MQTT
*/
export type MqttConnectionFailure = (callback_data: OnConnectionFailedResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* disconnected and shutdown successfully.
*
* @param callback_data Data returned containing information about the closed/disconnected connection.
* Currently empty, but may contain data in the future.
*
* @category MQTT
*/
export type MqttConnectionClosed = (callback_data: OnConnectionClosedResult) => void;
/**
* @category MQTT
*/
export type WebsocketOptions = WebsocketUtils.WebsocketOptions;

@@ -253,2 +294,5 @@

// The last error reported by MQTT.JS - or undefined if none has occurred or the error has been processed.
private lastError? : Error;
/**

@@ -294,8 +338,8 @@ * @param client The client that owns this connection

if (this.config.credentials_provider == undefined &&
this.config.credentials != undefined){
this.config.credentials != undefined) {
const provider = new auth.StaticCredentialProvider(
{ aws_region: this.config.credentials.aws_region,
aws_access_id: this.config.credentials.aws_access_id,
aws_secret_key: this.config.credentials.aws_secret_key,
aws_sts_token: this.config.credentials.aws_sts_token});
aws_access_id: this.config.credentials.aws_access_id,
aws_secret_key: this.config.credentials.aws_secret_key,
aws_sts_token: this.config.credentials.aws_sts_token});
this.config.credentials_provider = provider;

@@ -372,2 +416,25 @@ }

/**
* Emitted on every successful connect and reconnect.
* Will contain a boolean indicating whether the connection resumed a session.
*
* @event
*/
static CONNECTION_SUCCESS = 'connection_success';
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
static CONNECTION_FAILURE = 'connection_failure';
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
static CLOSED = 'closed'
on(event: 'connect', listener: MqttConnectionConnected): this;

@@ -381,2 +448,8 @@

on(event: 'connection_success', listener: MqttConnectionSuccess): this;
on(event: 'connection_failure', listener: MqttConnectionFailure): this;
on(event: 'closed', listener: MqttConnectionClosed): this;
on(event: 'resume', listener: MqttConnectionResumed): this;

@@ -408,4 +481,10 @@

const on_connect_error = (error: Error) => {
reject(new CrtError(error));
let crtError = new CrtError(error);
let failureCallbackData = { error: crtError } as OnConnectionFailedResult;
this.emit('connection_failure', failureCallbackData);
reject(crtError);
};
this.connection.once('error', on_connect_error);
this.connection.once('connect', (connack: mqtt.IConnackPacket) => {

@@ -415,3 +494,2 @@ this.connection.removeListener('error', on_connect_error);

});
this.connection.once('error', on_connect_error);
});

@@ -469,3 +547,3 @@ }

}
resolve({packet_id: id} );
resolve({ packet_id: id });
});

@@ -581,5 +659,11 @@ });

}
// Call connection success every time we connect, whether it is a first connect or a reconnect
let successCallbackData = { session_present: session_present } as OnConnectionSuccessResult;
this.emit('connection_success', successCallbackData);
}
private on_close = () => {
let lastError : Error | undefined = this.lastError;
/*

@@ -592,6 +676,15 @@ * Only emit an interruption event if we were connected, otherwise we just failed to reconnect after

this.emit('interrupt', -1);
/* Did we intend to disconnect? If so, then emit the event */
if (this.desiredState == MqttBrowserClientState.Stopped) {
this.emit("closed");
}
}
/* Only try and reconnect if our desired state is connected, ie no one has called disconnect() */
/* Only try and reconnect if our desired state is connected, or in other words, no one has called disconnect() */
if (this.desiredState == MqttBrowserClientState.Connected) {
let crtError = new CrtError(lastError?.toString() ?? "connectionFailure")
let failureCallbackData = { error: crtError } as OnConnectionFailedResult;
this.emit('connection_failure', failureCallbackData);
const waitTime = this.get_reconnect_time_sec();

@@ -605,2 +698,4 @@ this.reconnectTask = setTimeout(() => {

}
this.lastError = undefined;
}

@@ -610,5 +705,15 @@

this.emit('disconnect');
/**
* This shouldn't ever occur, but in THEORY it could be possible to have on_disconnected called with the intent
* to disconnect without on_close called first. This would properly emit 'closed' should that unlikely event occur.
*/
if (this.currentState == MqttBrowserClientState.Connected && this.desiredState == MqttBrowserClientState.Stopped) {
let closedCallbackData = {} as OnConnectionClosedResult;
this.emit("closed", closedCallbackData);
}
}
private on_error = (error: Error) => {
this.lastError = error;
this.emit('error', new CrtError(error))

@@ -628,4 +733,3 @@ }

private reset_reconnect_times()
{
private reset_reconnect_times() {
this.reconnect_count = 0;

@@ -632,0 +736,0 @@ }

@@ -14,2 +14,4 @@ /*

import { ICrtError } from './error';
/**

@@ -86,2 +88,37 @@ * Quality of service control for mqtt publish operations

/**
* The data returned from an on_connection_success callback
*
* @category MQTT
*/
export interface OnConnectionSuccessResult {
/**
* A boolean indicating if the connection resumed a session.
*/
session_present: boolean;
/**
* An optional connect return code received from the server, if a connect return code was returned.
*/
reason_code?: number;
}
/**
* The data returned from an on_connection_failed callback
*
* @category MQTT
*/
export interface OnConnectionFailedResult {
/**
* Error description of the error that occurred
*/
error: ICrtError;
}
/**
* The data returned from the on_connection_closed callback
*
* @category MQTT
*/
export interface OnConnectionClosedResult {}
/**
* Subscription SUBACK result

@@ -155,3 +192,3 @@ *

* Const value for max reconnection back off time
*
*
* @category MQTT

@@ -163,6 +200,5 @@ */

* Const value for min reconnection back off time
*
*
* @category MQTT
*/
export const DEFAULT_RECONNECT_MIN_SEC = 1;

@@ -12,4 +12,4 @@ /*

import { v4 as uuid } from 'uuid';
import {once} from "events";
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_custom_auth_unsigned())('Aws Iot Core Mqtt over websockets with Non-Signing Custom Auth - Connection Success', async () => {

@@ -166,6 +166,47 @@ let builder = aws_iot_mqtt311.AwsIotMqttConnectionConfigBuilder.new_builder_for_websocket();

let connection = client.new_connection(config);
const connectionSuccess = once(connection, "connection_success");
await connection.connect();
let connectionSuccessEvent: mqtt311.OnConnectionSuccessResult = (await connectionSuccess)[0];
expect(connectionSuccessEvent.session_present).toBeFalsy();
expect(connectionSuccessEvent.reason_code).toBeDefined();
expect(connectionSuccessEvent.reason_code).toBe(0); // Success
const closed = once(connection, "closed");
await connection.disconnect();
await closed;
});
test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_cred())('MQTT Native Websocket Connect/Disconnect - Connection Failure', async () => {
let builder = aws_iot_mqtt311.AwsIotMqttConnectionConfigBuilder.new_with_websockets();
builder.with_client_id(`node-mqtt-unit-test-${uuid()}`)
builder.with_credentials(
test_env.AWS_IOT_ENV.MQTT311_REGION,
test_env.AWS_IOT_ENV.MQTT311_CRED_ACCESS_KEY,
test_env.AWS_IOT_ENV.MQTT311_CRED_SECRET_ACCESS_KEY,
test_env.AWS_IOT_ENV.MQTT311_CRED_SESSION_TOKEN
);
/* Use the wrong port and endpoint ensure a fail */
builder.with_endpoint("testendpointhere");
builder.with_port(321);
let config = builder.build();
let client = new mqtt311.MqttClient();
let connection = client.new_connection(config);
const connectionFailure = once(connection, "connection_failure")
let expected_error = false;
try {
await connection.connect();
} catch (error) {
expected_error = true;
}
expect(expected_error).toBeTruthy();
let connectionFailedEvent: mqtt311.OnConnectionFailedResult = (await connectionFailure)[0];
expect(connectionFailedEvent).toBeDefined();
expect(connectionFailedEvent.error).toBeDefined();
});
// requires correct credentials to be sourced from the default credentials provider chain

@@ -180,5 +221,7 @@ test_env.conditional_test(test_env.AWS_IOT_ENV.mqtt311_is_valid_websocket())('MQTT Native Websocket Default AWS Credentials', async () => {

builder.with_client_id(`node-mqtt-unit-test-${uuid()}`)
builder.with_port(443);
let config = builder.build();
let client = new mqtt311.MqttClient();
let connection = client.new_connection(config);
await connection.connect();

@@ -185,0 +228,0 @@ await connection.disconnect();

@@ -250,2 +250,8 @@ /*

/** @internal */
export function mqtt_client_connection_on_closed(
connection: NativeHandle,
on_closed?: () => void
): void;
/** @internal */
export function mqtt_client_connection_unsubscribe(

@@ -252,0 +258,0 @@ connection: NativeHandle,

@@ -10,4 +10,6 @@ /*

import { v4 as uuid } from 'uuid';
import { OnConnectionSuccessResult, OnConnectionClosedResult } from '../common/mqtt';
import {HttpProxyOptions, HttpProxyAuthenticationType, HttpProxyConnectionType} from "./http"
import { AwsIotMqttConnectionConfigBuilder } from './aws_iot';
import {once} from "events";

@@ -19,2 +21,5 @@ jest.setTimeout(10000);

const promise = new Promise(async (resolve, reject) => {
let onConnectionSuccessCalled = false;
let onConnectionDisconnectCalled = false;
connection.on('connect', async (session_present) => {

@@ -30,4 +35,23 @@ const disconnected = connection.disconnect();

reject(error);
});
connection.on('disconnect', () => {
onConnectionDisconnectCalled = true;
});
connection.on('connection_success', (callback_data:OnConnectionSuccessResult) => {
expect(callback_data.session_present).toBe(false);
expect(callback_data.reason_code).toBeDefined();
expect(callback_data.reason_code).toBe(0); // Success
onConnectionSuccessCalled = true;
})
connection.on('disconnect', () => {
connection.on('closed', async (callback_data:OnConnectionClosedResult) => {
/**
* We want to wait *just* a little bit, as we might be still processing the disconnect callback
* at the exact same time as this callback is called (closed is called RIGHT after disconnect)
*/
await new Promise(r => setTimeout(r, 500));
// Make sure connection_success was called before us
expect(onConnectionSuccessCalled).toBeTruthy();
// Make sure disconnect was called before us
expect(onConnectionDisconnectCalled).toBeTruthy();
resolve(true);

@@ -247,4 +271,4 @@ })

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.

@@ -262,4 +286,4 @@ const test_topic = `/test/me/senpai/${uuid()}`;

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.

@@ -276,3 +300,3 @@ const disconnected = connection.disconnect();

reject(error);
})
});
const connected = connection.connect();

@@ -295,4 +319,4 @@ await expect(connected).resolves.toBeDefined();

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.

@@ -318,8 +342,8 @@ const test_topic = `/test/me/senpai/${uuid()}`;

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(test_topic.length + test_payload.length + 4);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.
});
connection.on('error', (error) => {
reject(error);
})
});
const connected = connection.connect();

@@ -337,3 +361,5 @@ await expect(connected).resolves.toBeDefined();

await connection.connect();
const closed = once(connection, "closed");
await connection.disconnect();
await closed;

@@ -357,3 +383,5 @@ // Native resources should have been cleaned on the disconnect, so the connect attempt should throw.

await connection.connect();
const closed = once(connection, "closed");
await connection.disconnect();
await closed;

@@ -360,0 +388,0 @@ // Doing any operations after disconnect should throw because the client is cleaned up

@@ -35,4 +35,10 @@ /*

DEFAULT_RECONNECT_MAX_SEC,
OnConnectionSuccessResult,
OnConnectionFailedResult,
OnConnectionClosedResult
} from "../common/mqtt";
export { QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected, MqttConnectionResumed } from "../common/mqtt";
export {
QoS, Payload, MqttRequest, MqttSubscribeRequest, MqttWill, OnMessageCallback, MqttConnectionConnected, MqttConnectionDisconnected,
MqttConnectionResumed, OnConnectionSuccessResult, OnConnectionFailedResult, OnConnectionClosedResult
} from "../common/mqtt";

@@ -59,2 +65,37 @@ /**

/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every successful connect and every successful reconnect.
*
* @param callback_data Data returned containing information about the successful connection.
*
* @category MQTT
*/
export type MqttConnectionSucess = (callback_data: OnConnectionSuccessResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* connected successfully.
*
* This listener is invoked for every failed connect and every failed reconnect.
*
* @param callback_data Data returned containing information about the failed connection.
*
* @category MQTT
*/
export type MqttConnectionFailure = (callback_data: OnConnectionFailedResult) => void;
/**
* Listener signature for event emitted from an {@link MqttClientConnection} when the connection has been
* disconnected and shutdown successfully.
*
* @param callback_data Data returned containing information about the closed/disconnected connection.
* Currently empty, but may contain data in the future.
*
* @category MQTT
*/
export type MqttConnectionClosed = (callback_data: OnConnectionClosedResult) => void;
/**
* MQTT client

@@ -192,3 +233,3 @@ *

*/
export interface ConnectionStatistics {
export interface ConnectionStatistics {

@@ -199,3 +240,3 @@ /**

*/
incompleteOperationCount : number;
incompleteOperationCount: number;

@@ -206,3 +247,3 @@ /**

*/
incompleteOperationSize : number;
incompleteOperationSize: number;

@@ -213,3 +254,3 @@ /**

*/
unackedOperationCount : number;
unackedOperationCount: number;

@@ -220,3 +261,3 @@ /**

*/
unackedOperationSize : number;
unackedOperationSize: number;
};

@@ -291,2 +332,3 @@

crt_native.mqtt_client_connection_on_message(this.native_handle(), this._on_any_publish.bind(this));
crt_native.mqtt_client_connection_on_closed(this.native_handle(), this._on_connection_closed.bind(this));

@@ -299,3 +341,3 @@ /*

*/
this.on('error', (error) => {});
this.on('error', (error) => { });
}

@@ -351,2 +393,26 @@

/**
* Emitted on every successful connect and reconnect.
* Will contain a number with the connection reason code and
* a boolean indicating whether the connection resumed a session.
*
* @event
*/
static CONNECTION_SUCCESS = 'connection_success';
/**
* Emitted on an unsuccessful connect and reconnect.
* Will contain an error code indicating the reason for the unsuccessful connection.
*
* @event
*/
static CONNECTION_FAILURE = 'connection_failure';
/**
* Emitted when the MQTT connection was disconnected and shutdown successfully.
*
* @event
*/
static CLOSED = 'closed'
on(event: 'connect', listener: MqttConnectionConnected): this;

@@ -364,2 +430,8 @@

on(event: 'connection_success', listener: MqttConnectionSucess): this;
on(event: 'connection_failure', listener: MqttConnectionFailure): this;
on(event: 'closed', listener: MqttConnectionClosed): this;
// Overridden to allow uncorking on ready

@@ -554,3 +626,3 @@ on(event: string | symbol, listener: (...args: any[]) => void): this {

*/
getQueueStatistics() : ConnectionStatistics {
getQueueStatistics(): ConnectionStatistics {
return crt_native.mqtt_client_connection_get_queue_statistics(this.native_handle());

@@ -576,2 +648,4 @@ }

this.emit('resume', return_code, session_present);
let successCallbackData = { session_present: session_present, reason_code: return_code } as OnConnectionSuccessResult;
this.emit('connection_success', successCallbackData);
}

@@ -583,14 +657,30 @@

private _on_connect_callback(resolve : (value: (boolean | PromiseLike<boolean>)) => void, reject : (reason?: any) => void, error_code: number, return_code: number, session_present: boolean) {
private _on_connection_closed() {
let closedCallbackData = {} as OnConnectionClosedResult;
this.emit('closed', closedCallbackData);
/**
* We call close() here instead of on disconnect because on_close is always called AFTER disconnect
* but if we call close() before, then we cannot emit the closed callback.
*/
this.close();
}
private _on_connect_callback(resolve: (value: (boolean | PromiseLike<boolean>)) => void, reject: (reason?: any) => void, error_code: number, return_code: number, session_present: boolean) {
if (error_code == 0 && return_code == 0) {
resolve(session_present);
this.emit('connect', session_present);
let successCallbackData = { session_present: session_present, reason_code: return_code } as OnConnectionSuccessResult;
this.emit('connection_success', successCallbackData);
} else if (error_code != 0) {
reject("Failed to connect: " + io.error_code_to_string(error_code));
let failureCallbackData = { error: new CrtError(error_code) } as OnConnectionFailedResult;
this.emit('connection_failure', failureCallbackData);
} else {
reject("Server rejected connection.");
let failureCallbackData = { error: new CrtError(5134) } as OnConnectionFailedResult; // 5134 = AWS_ERROR_MQTT_UNEXPECTED_HANGUP
this.emit('connection_failure', failureCallbackData);
}
}
private _on_puback_callback(resolve : (value: (MqttRequest | PromiseLike<MqttRequest>)) => void, reject : (reason?: any) => void, packet_id: number, error_code: number) {
private _on_puback_callback(resolve: (value: (MqttRequest | PromiseLike<MqttRequest>)) => void, reject: (reason?: any) => void, packet_id: number, error_code: number) {
if (error_code == 0) {

@@ -603,3 +693,3 @@ resolve({ packet_id });

private _on_suback_callback(resolve : (value: (MqttSubscribeRequest | PromiseLike<MqttSubscribeRequest>)) => void, reject : (reason?: any) => void, packet_id: number, topic: string, qos: QoS, error_code: number) {
private _on_suback_callback(resolve: (value: (MqttSubscribeRequest | PromiseLike<MqttSubscribeRequest>)) => void, reject: (reason?: any) => void, packet_id: number, topic: string, qos: QoS, error_code: number) {
if (error_code == 0) {

@@ -612,3 +702,3 @@ resolve({ packet_id, topic, qos, error_code });

private _on_unsuback_callback(resolve : (value: (MqttRequest | PromiseLike<MqttRequest>)) => void, reject : (reason?: any) => void, packet_id: number, error_code: number) {
private _on_unsuback_callback(resolve: (value: (MqttRequest | PromiseLike<MqttRequest>)) => void, reject: (reason?: any) => void, packet_id: number, error_code: number) {
if (error_code == 0) {

@@ -624,4 +714,5 @@ resolve({ packet_id });

this.emit('disconnect');
this.close();
/** NOTE: We are NOT calling close() here but instead calling it at
* on_closed because it is always called after disconnect */
}
}

@@ -617,4 +617,4 @@ /*

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.

@@ -636,4 +636,4 @@ let topic : string = `test-${uuid()}`;

expect(statistics.incompleteOperationSize).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationCount).toBeLessThanOrEqual(0);
expect(statistics.unackedOperationSize).toBeLessThanOrEqual(0);
// Skip checking unacked operations - it heavily depends on socket speed and makes tests flakey
// TODO - find a way to test unacked operations reliably without worrying about socket speed.

@@ -640,0 +640,0 @@ client.stop();

{
"name": "aws-crt",
"version": "1.15.18",
"version": "1.15.19",
"description": "NodeJS/browser bindings to the aws-c-* libraries",

@@ -5,0 +5,0 @@ "homepage": "https://github.com/awslabs/aws-crt-nodejs",

@@ -7,2 +7,8 @@ ## AWS CRT JS

## Impending Node Version Update
In the coming months, the AWS Common Runtime will be updating its Node baseline from 10.16 to 14. A
[discussion thread](https://github.com/awslabs/aws-crt-nodejs/discussions/468)
has been created for any questions or feedback you may have. We do not yet have a concrete timeline for when the
update will happen.
## License

@@ -9,0 +15,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc