Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failover configuration #760

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions examples/cookbook/api-keys/near-connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,15 @@ const CREDENTIALS_DIR = ".near-credentials";
const credentialsPath = path.join(homedir, CREDENTIALS_DIR);
const keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath);

const RPC_API_ENDPOINT = '<Replace this string with your RPC server URL>';
const API_KEY = '<Replace this string with your API KEY>';

const ACCOUNT_ID = '<Replace this string with existing account ID>';

const config = {
networkId: 'testnet',
keyStore,
nodeUrl: RPC_API_ENDPOINT,
headers: { 'x-api-key': API_KEY },
nodeUrl: '<Replace this string with your RPC server URL>',
// RPC server URL in apiKeys should match the one specified in nodeUrl
apiKeys: { '<Replace this string with your RPC server URL>': API_KEY },
};

async function getState(accountId) {
Expand Down
6 changes: 3 additions & 3 deletions examples/cookbook/api-keys/provider-example.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
// demonstrates how to use API-KEY with provider
const { providers } = require("near-api-js");

const RPC_API_ENDPOINT = '<Replace this string with your RPC server URL>';
const API_KEY = '<Replace this string with your API KEY>';

const provider = new providers.JsonRpcProvider({
url: RPC_API_ENDPOINT,
headers: { 'x-api-key': API_KEY },
url: '<Replace this string with your RPC server URL>',
// RPC server URL in apiKeys should match the one specified in url
apiKeys: { '<Replace this string with your RPC server URL>': API_KEY }
});

getNetworkStatus();
Expand Down
36 changes: 36 additions & 0 deletions examples/cookbook/failover-configuration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Demonstrates how to use failover functionality RPC Servers
const { providers, connect } = require("near-api-js");

const MAIN_RPC_SERVER = '<RPC Server 1>';
const FAILOVER_RPC_SERVER_1 = '<RPC Server 2>';
const FAILOVER_RPC_SERVER_2 = '<RPC Server 1>';

// Provider example
const provider = new providers.JsonRpcProvider({
// preoritized list of RPC Servers
url: [MAIN_RPC_SERVER, FAILOVER_RPC_SERVER_1, FAILOVER_RPC_SERVER_2],
});

async function getNetworkStatus() {
const result = await provider.status();
console.log(result);
}

getNetworkStatus();

// Connection example
const ACCOUNT_ID = "<Account ID>";

const config = {
networkId: 'testnet',
nodeUrl: [MAIN_RPC_SERVER, FAILOVER_RPC_SERVER_1, FAILOVER_RPC_SERVER_2],
};

async function getState(accountId) {
const near = await connect(config);
const account = await near.account(accountId);
const state = await account.state();
console.log(state);
}

getState(ACCOUNT_ID);
9 changes: 7 additions & 2 deletions lib/near.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 7 additions & 1 deletion lib/near.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions lib/providers/json-rpc-provider.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions lib/providers/json-rpc-provider.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion lib/utils/web.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 10 additions & 5 deletions lib/utils/web.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

18 changes: 15 additions & 3 deletions src/near.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,16 @@ export interface NearConfig {
networkId: string;

/**
* NEAR RPC API url. used to make JSON RPC calls to interact with NEAR.
* NEAR RPC API url. Used to make JSON RPC calls to interact with NEAR.
* You can set multiple RPC Server URLs to turn on failover functionality.
* @see {@link JsonRpcProvider.JsonRpcProvider | JsonRpcProvider}
*/
nodeUrl: string;
nodeUrl: string | string[];

/**
* RPC API Keys. Used to authenticate users on RPC Server.
*/
apiKeys: string;

/**
* NEAR RPC API headers. Can be used to pass API KEY and other parameters.
Expand Down Expand Up @@ -84,7 +90,13 @@ export class Near {
this.config = config;
this.connection = Connection.fromConfig({
networkId: config.networkId,
provider: { type: 'JsonRpcProvider', args: { url: config.nodeUrl, headers: config.headers } },
provider: {
type: 'JsonRpcProvider', args: {
url: config.nodeUrl,
apiKeys: config.apiKeys,
headers: config.headers,
}
},
signer: config.signer || { type: 'InMemorySigner', keyStore: config.keyStore || (config.deps && config.deps.keyStore) }
});
if (config.masterAccount) {
Expand Down
17 changes: 16 additions & 1 deletion src/providers/json-rpc-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,19 @@ export class JsonRpcProvider extends Provider {
return await this.sendJsonRpc('gas_price', [blockId]);
}

/**
* Part of the RPC failover design.
* Changing current (first) rpc server and moves it to the and of the queue.
*/
private rotateRpcServers() {
if (typeof this.connection.url === 'string') { return; }
const currentRpcServer = this.connection.url.shift();
this.connection.url.push(currentRpcServer);
if (!process.env['NEAR_NO_LOGS']) {
console.warn(`Switched from ${currentRpcServer} RPC Server to ${this.connection.url[0]}`);
}
}

/**
* Directly call the RPC specifying the method and params
*
Expand Down Expand Up @@ -379,9 +392,11 @@ export class JsonRpcProvider extends Provider {
return response;
} catch (error) {
if (error.type === 'TimeoutError') {
if (!process.env['NEAR_NO_LOGS']){
if (!process.env['NEAR_NO_LOGS']) {
console.warn(`Retrying request to ${method} as it has timed out`, params);
}
// switch to another server if it's available
this.rotateRpcServers();
return null;
}

Expand Down
20 changes: 14 additions & 6 deletions src/utils/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ const BACKOFF_MULTIPLIER = 1.5;
const RETRY_NUMBER = 10;

export interface ConnectionInfo {
url: string;
// RPC Server URL or the prioritized array of such URLs
url: string | string[];
apiKeys?: { [url: string]: string };
user?: string;
password?: string;
allowInsecure?: boolean;
Expand All @@ -25,31 +27,37 @@ export async function fetchJson(connectionInfoOrUrl: string | ConnectionInfo, js
connectionInfo = connectionInfoOrUrl as ConnectionInfo;
}

const currentRpcServer = typeof connectionInfo.url === 'string' ? connectionInfo.url : connectionInfo.url[0];

const response = await exponentialBackoff(START_WAIT_TIME_MS, RETRY_NUMBER, BACKOFF_MULTIPLIER, async () => {
try {
const response = await fetch(connectionInfo.url, {
const response = await fetch(currentRpcServer, {
method: json ? 'POST' : 'GET',
body: json ? json : undefined,
headers: { ...connectionInfo.headers, 'Content-Type': 'application/json' }
headers: {
'Content-Type': 'application/json',
'x-api-key': connectionInfo.apiKeys ? connectionInfo.apiKeys[currentRpcServer] : undefined,
...connectionInfo.headers,
},
});
if (!response.ok) {
if (response.status === 503) {
logWarning(`Retrying HTTP request for ${connectionInfo.url} as it's not available now`);
logWarning(`Retrying HTTP request for ${currentRpcServer} as it's not available now`);
return null;
}
throw createError(response.status, await response.text());
}
return response;
} catch (error) {
if (error.toString().includes('FetchError') || error.toString().includes('Failed to fetch')) {
logWarning(`Retrying HTTP request for ${connectionInfo.url} because of error: ${error}`);
logWarning(`Retrying HTTP request for ${currentRpcServer} because of error: ${error}`);
return null;
}
throw error;
}
});
if (!response) {
throw new TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${connectionInfo.url}.`, 'RetriesExceeded');
throw new TypedError(`Exceeded ${RETRY_NUMBER} attempts for ${currentRpcServer}.`, 'RetriesExceeded');
}
return await response.json();
}
Loading