Skip to content

Commit

Permalink
Add client connect failed handler
Browse files Browse the repository at this point in the history
Signed-off-by: Yilun <[email protected]>
  • Loading branch information
yilunzhang committed Apr 16, 2022
1 parent b58f918 commit b67db9b
Show file tree
Hide file tree
Showing 8 changed files with 336 additions and 88 deletions.
136 changes: 106 additions & 30 deletions dist/nkn.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ class Client {
* Whether client is ready (connected to a node).
*/

/**
* Whether client fails to connect to node.
*/

/**
* Whether client is closed.
*/
Expand Down Expand Up @@ -81,6 +85,8 @@ class Client {

_defineProperty(this, "isReady", void 0);

_defineProperty(this, "isFailed", void 0);

_defineProperty(this, "isClosed", void 0);

_defineProperty(this, "wallet", void 0);
Expand All @@ -104,6 +110,7 @@ class Client {
this.addr = addr;
this.eventListeners = {
connect: [],
connectFailed: [],
message: []
};
this.sigChainBlockHash = null;
Expand All @@ -113,6 +120,7 @@ class Client {
this.ws = null;
this.node = null;
this.isReady = false;
this.isFailed = false;
this.isClosed = false;
this.wallet = wallet;

Expand Down Expand Up @@ -158,6 +166,8 @@ class Client {

if (this.shouldReconnect) {
this._reconnect();
} else if (!this.isClosed) {
this._connectFailed();
}
}

Expand All @@ -171,9 +181,27 @@ class Client {
}
}

_connectFailed() {
if (!this.isFailed) {
console.log('Client connect failed');
this.isFailed = true;

if (this.eventListeners.connectFailed.length > 0) {
this.eventListeners.connectFailed.forEach(async f => {
try {
await f();
} catch (e) {
console.log('Connect failed handler error:', e);
}
});
}
}
}
/**
* @deprecated please use onConnect, onMessage, etc.
*/


on(evt, func) {
if (!this.eventListeners[evt]) {
this.eventListeners[evt] = [];
Expand All @@ -192,6 +220,16 @@ class Client {
this.eventListeners.connect.push(func);
}

/**
* Add event listener function that will be called when client fails to
* connect to node. Multiple listeners will be called sequentially in the
* order of added. Note that listeners added after client fails to connect to
* node (i.e. `client.isFailed === true`) will not be called.
*/
onConnectFailed(func) {
this.eventListeners.connectFailed.push(func);
}

/**
* Add event listener function that will be called when client receives a
* message. Multiple listeners will be called sequentially in the order of
Expand Down Expand Up @@ -586,6 +624,8 @@ class Client {

if (this.shouldReconnect) {
this._reconnect();
} else if (!this.isClosed) {
this._connectFailed();
}

return;
Expand All @@ -603,6 +643,8 @@ class Client {

if (this.shouldReconnect) {
this._reconnect();
} else if (!this.isClosed) {
this._connectFailed();
}

return;
Expand Down Expand Up @@ -707,6 +749,8 @@ class Client {
console.warn('WebSocket unexpectedly closed.');

this._reconnect();
} else if (!this.isClosed) {
this._connectFailed();
}
};

Expand Down Expand Up @@ -10193,11 +10237,15 @@ class MultiClient {
*/

/**
* Whether client is ready (connected to a node).
* Whether multiclient is ready (at least one underylying client is ready).
*/

/**
* Whether client is closed.
* Whether multiclient fails to connect to node (all underlying clients failed).
*/

/**
* Whether multiclient is closed.
*/
constructor(options = {}) {
_defineProperty(this, "options", void 0);
Expand All @@ -10222,6 +10270,8 @@ class MultiClient {

_defineProperty(this, "isReady", void 0);

_defineProperty(this, "isFailed", void 0);

_defineProperty(this, "isClosed", void 0);

options = common.util.assignDefined({}, consts.defaultOptions, options);
Expand Down Expand Up @@ -10265,13 +10315,15 @@ class MultiClient {
this.addr = (baseIdentifier ? baseIdentifier + '.' : '') + this.key.publicKey;
this.eventListeners = {
connect: [],
connectFailed: [],
message: [],
session: []
};
this.msgCache = new _memoryCache.Cache();
this.acceptAddrs = [];
this.sessions = new Map();
this.isReady = false;
this.isFailed = false;
this.isClosed = false;

for (let clientID of Object.keys(clients)) {
Expand Down Expand Up @@ -10363,6 +10415,43 @@ class MultiClient {
return false;
});
}

let connectPromises = Object.keys(this.clients).map(clientID => new _promise.default((resolve, reject) => {
this.clients[clientID].onConnect(resolve);
}));

_promise.default.any(connectPromises).then(r => {
this.isReady = true;

if (this.eventListeners.connect.length > 0) {
this.eventListeners.connect.forEach(async f => {
try {
await f(r);
} catch (e) {
console.log('Connect handler error:', e);
}
});
}
});

let connectFailedPromises = Object.keys(this.clients).map(clientID => new _promise.default((resolve, reject) => {
this.clients[clientID].onConnectFailed(resolve);
}));

_promise.default.all(connectFailedPromises).then(() => {
console.log('All clients connect failed');
this.isFailed = true;

if (this.eventListeners.connectFailed.length > 0) {
this.eventListeners.connectFailed.forEach(async f => {
try {
await f();
} catch (e) {
console.log('Connect failed handler error:', e);
}
});
}
});
}
/**
* Get the secret seed of the client.
Expand Down Expand Up @@ -10540,23 +10629,11 @@ class MultiClient {


on(evt, func) {
switch (evt) {
case 'connect':
return this.onConnect(func);

case 'message':
return this.onMessage(func);

case 'session':
return this.onSession(func);

default:
if (!this.eventListeners[evt]) {
this.eventListeners[evt] = [];
}

this.eventListeners[evt].push(func);
if (!this.eventListeners[evt]) {
this.eventListeners[evt] = [];
}

this.eventListeners[evt].push(func);
}

/**
Expand All @@ -10565,20 +10642,19 @@ class MultiClient {
* in the order of added. Note that listeners added after client is connected
* to node (i.e. `multiclient.isReady === true`) will not be called.
*/
onConnect(f) {
let promises = Object.keys(this.clients).map(clientID => new _promise.default((resolve, reject) => {
this.clients[clientID].onConnect(resolve);
}));
onConnect(func) {
this.eventListeners.connect.push(func);
}
/**
* Add event listener function that will be called when all sub clients fail
* to connect to node. Multiple listeners will be called sequentially in the
* order of added. Note that listeners added after client fails to connect to
* node (i.e. `multiclient.isFailed === true`) will not be called.
*/

_promise.default.any(promises).then(async r => {
this.isReady = true;

try {
await f(r);
} catch (e) {
console.log('Connect handler error:', e);
}
});
onConnectFailed(func) {
this.eventListeners.connectFailed.push(func);
}
/**
* Add event listener function that will be called when client receives a
Expand Down
2 changes: 1 addition & 1 deletion dist/nkn.min.js

Large diffs are not rendered by default.

12 changes: 12 additions & 0 deletions examples/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ const useMultiClient = true;

console.log('Secret seed:', alice.getSeed());

alice.onConnectFailed(() => {
console.error('Alice connect failed');
});

if (useMultiClient) {
for (let clientID of Object.keys(alice.clients)) {
alice.clients[clientID].onConnectFailed(() => {
console.error('Alice client', clientID, 'connect failed');
});
}
}

await Promise.all([
new Promise((resolve, reject) => alice.onConnect(resolve)),
new Promise((resolve, reject) => bob.onConnect(resolve)),
Expand Down
7 changes: 7 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ declare namespace nkn {

onConnect(f: ConnectHandler): void

onConnectFailed(f: ConnectFailedHandler): void

onMessage(func: MessageHandler): void

onSession(func: SessionHandler): void
Expand Down Expand Up @@ -130,6 +132,8 @@ declare namespace nkn {

onConnect(func: ConnectHandler): void

onConnectFailed(f: ConnectFailedHandler): void

onMessage(func: MessageHandler): void

publish(topic: string, data: MessageData, options?: PublishOptions): Promise<null>
Expand Down Expand Up @@ -322,6 +326,8 @@ declare namespace nkn {

export type ConnectHandler = (params: {addr: string}) => void

export type ConnectFailedHandler = () => void

export type CreateTransactionOptions = {
fee: number | string | Amount | null | void
attrs: string | null | undefined
Expand Down Expand Up @@ -554,6 +560,7 @@ declare interface nkn {
Wallet: nkn.Wallet
Amount: nkn.Amount
ConnectHandler: nkn.ConnectHandler
ConnectFailedHandler: nkn.ConnectFailedHandler
CreateTransactionOptions: nkn.CreateTransactionOptions
Destination: nkn.Destination
DialOptions: nkn.DialOptions
Expand Down
Loading

0 comments on commit b67db9b

Please sign in to comment.