update aqua version (#33)

* Bump aquamarine version

* Add connection options
This commit is contained in:
Pavel 2021-03-25 21:33:27 +03:00 committed by GitHub
parent f732a30eb8
commit 0ff10a25de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 101 additions and 21 deletions

6
package-lock.json generated
View File

@ -1088,9 +1088,9 @@
} }
}, },
"@fluencelabs/aquamarine-interpreter": { "@fluencelabs/aquamarine-interpreter": {
"version": "0.7.2", "version": "0.7.9",
"resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-interpreter/-/aquamarine-interpreter-0.7.2.tgz", "resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-interpreter/-/aquamarine-interpreter-0.7.9.tgz",
"integrity": "sha512-4LrcpeG0ONb3/kTFgt1QNERn9e7aAJBJgqbqNnx81NqFFngTi2xypKIuyPOttcxSdZTH5mpbwwn3JKFimvOvNA==" "integrity": "sha512-VXbHm0d05XMjTSzOTcb+spVRrIuMcrw8/3dl197wH0jx1C3Wou+vAapQLvGNcKzqDhktPOOzJTE4UARYd0lFMw=="
}, },
"@istanbuljs/load-nyc-config": { "@istanbuljs/load-nyc-config": {
"version": "1.1.0", "version": "1.1.0",

View File

@ -16,7 +16,7 @@
"author": "Fluence Labs", "author": "Fluence Labs",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@fluencelabs/aquamarine-interpreter": "0.7.2", "@fluencelabs/aquamarine-interpreter": "0.7.9",
"async": "3.2.0", "async": "3.2.0",
"base64-js": "1.3.1", "base64-js": "1.3.1",
"bs58": "4.0.1", "bs58": "4.0.1",

View File

@ -5,6 +5,7 @@ import PeerId, { isPeerId } from 'peer-id';
import { AquaCallHandler } from './internal/AquaHandler'; import { AquaCallHandler } from './internal/AquaHandler';
import { ClientImpl } from './internal/ClientImpl'; import { ClientImpl } from './internal/ClientImpl';
import { PeerIdB58 } from './internal/commonTypes'; import { PeerIdB58 } from './internal/commonTypes';
import { FluenceConnectionOptions } from './internal/FluenceConnection';
import { generatePeerId, seedToPeerId } from './internal/peerIdUtils'; import { generatePeerId, seedToPeerId } from './internal/peerIdUtils';
import { RequestFlow } from './internal/RequestFlow'; import { RequestFlow } from './internal/RequestFlow';
import { RequestFlowBuilder } from './internal/RequestFlowBuilder'; import { RequestFlowBuilder } from './internal/RequestFlowBuilder';
@ -63,11 +64,13 @@ type Node = {
* Creates a Fluence client. If the `connectTo` is specified connects the client to the network * Creates a Fluence client. If the `connectTo` is specified connects the client to the network
* @param { string | Multiaddr | Node } [connectTo] - Node in Fluence network to connect to. If not specified client will not be connected to the n * @param { string | Multiaddr | Node } [connectTo] - Node in Fluence network to connect to. If not specified client will not be connected to the n
* @param { PeerId | string } [peerIdOrSeed] - The Peer Id of the created client. Specified either as PeerId structure or as seed string. Will be generated randomly if not specified * @param { PeerId | string } [peerIdOrSeed] - The Peer Id of the created client. Specified either as PeerId structure or as seed string. Will be generated randomly if not specified
* @param { FluenceConnectionOptions } [options] - additional configuraton options for Fluence Connection made with the client
* @returns { Promise<FluenceClient> } Promise which will be resolved with the created FluenceClient * @returns { Promise<FluenceClient> } Promise which will be resolved with the created FluenceClient
*/ */
export const createClient = async ( export const createClient = async (
connectTo?: string | Multiaddr | Node, connectTo?: string | Multiaddr | Node,
peerIdOrSeed?: PeerId | string, peerIdOrSeed?: PeerId | string,
options?: FluenceConnectionOptions,
): Promise<FluenceClient> => { ): Promise<FluenceClient> => {
let peerId; let peerId;
if (!peerIdOrSeed) { if (!peerIdOrSeed) {
@ -92,9 +95,14 @@ export const createClient = async (
theAddress = new Multiaddr(connectTo as string); theAddress = new Multiaddr(connectTo as string);
} }
await client.connect(theAddress); await client.connect(theAddress, options);
if (!(await checkConnection(client))) {
throw new Error('Connection check failed. Check if the node is working or try to connect to another node'); if (options?.skipCheckConnection) {
if (!(await checkConnection(client, options.checkConnectionTTL))) {
throw new Error(
'Connection check failed. Check if the node is working or try to connect to another node',
);
}
} }
} }
@ -105,7 +113,7 @@ export const createClient = async (
* Checks the network connection by sending a ping-like request to relat node * Checks the network connection by sending a ping-like request to relat node
* @param { FluenceClient } client - The Fluence Client instance. * @param { FluenceClient } client - The Fluence Client instance.
*/ */
export const checkConnection = async (client: FluenceClient): Promise<boolean> => { export const checkConnection = async (client: FluenceClient, ttl?: number): Promise<boolean> => {
if (!client.isConnected) { if (!client.isConnected) {
return false; return false;
} }
@ -121,6 +129,7 @@ export const checkConnection = async (client: FluenceClient): Promise<boolean> =
(call %init_peer_id% ("${callbackService}" "${callbackFn}") [result]) (call %init_peer_id% ("${callbackService}" "${callbackFn}") [result])
)`, )`,
) )
.withTTL(ttl)
.withVariables({ .withVariables({
msg, msg,
}) })

View File

@ -74,7 +74,7 @@ describe('Builtins usage suite', () => {
let bpIdReturned = await addBlueprint(client, 'test_broken_blueprint', ['test_broken_module'], bpId); let bpIdReturned = await addBlueprint(client, 'test_broken_blueprint', ['test_broken_module'], bpId);
let allBps = await getBlueprints(client); let allBps = await getBlueprints(client);
const allBpIds = allBps.map(x => x.id); const allBpIds = allBps.map((x) => x.id);
expect(allBpIds).toContain(bpIdReturned); expect(allBpIds).toContain(bpIdReturned);
}); });
@ -85,7 +85,7 @@ describe('Builtins usage suite', () => {
let promise = createService(client, 'test_broken_blueprint'); let promise = createService(client, 'test_broken_blueprint');
await expect(promise).rejects.toMatchObject({ await expect(promise).rejects.toMatchObject({
error: expect.stringContaining("Blueprint wasn't found at"), error: expect.stringContaining("Blueprint 'test_broken_blueprint' wasn't found"),
instruction: expect.stringContaining('blueprint_id'), instruction: expect.stringContaining('blueprint_id'),
}); });
}); });

View File

@ -42,6 +42,15 @@ describe('Typescript usage suite', () => {
expect(isConnected).toEqual(true); expect(isConnected).toEqual(true);
}); });
it('check connection should work with ttl', async function () {
client = await createClient();
await client.connect(nodes[0].multiaddr);
let isConnected = await checkConnection(client, 10000);
expect(isConnected).toEqual(true);
});
it('two clients should work inside the same time browser', async () => { it('two clients should work inside the same time browser', async () => {
// arrange // arrange
const client1 = await createClient(nodes[0].multiaddr); const client1 = await createClient(nodes[0].multiaddr);
@ -136,6 +145,42 @@ describe('Typescript usage suite', () => {
// assert // assert
expect(isConnected).toBeTruthy; expect(isConnected).toBeTruthy;
}); });
it('With connection options: dialTimeout', async () => {
// arrange
const addr = nodes[0].multiaddr;
// act
client = await createClient(addr, undefined, { dialTimeout: 100000 });
const isConnected = await checkConnection(client);
// assert
expect(isConnected).toBeTruthy;
});
it('With connection options: skipCheckConnection', async () => {
// arrange
const addr = nodes[0].multiaddr;
// act
client = await createClient(addr, undefined, { skipCheckConnection: true });
const isConnected = await checkConnection(client);
// assert
expect(isConnected).toBeTruthy;
});
it('With connection options: checkConnectionTTL', async () => {
// arrange
const addr = nodes[0].multiaddr;
// act
client = await createClient(addr, undefined, { checkConnectionTTL: 1000 });
const isConnected = await checkConnection(client);
// assert
expect(isConnected).toBeTruthy;
});
}); });
it('xor handling should work with connected client', async function () { it('xor handling should work with connected client', async function () {

View File

@ -75,7 +75,7 @@ describe('== AIR suite', () => {
const script = `(null)`; const script = `(null)`;
// prettier-ignore // prettier-ignore
const [request, promise] = new RequestFlowBuilder() const [request, promise] = new RequestFlowBuilder()
.withTTL(0) .withTTL(1)
.withRawScript(script) .withRawScript(script)
.buildAsFetch(); .buildAsFetch();

View File

@ -4,14 +4,15 @@ describe('== AST parsing suite', () => {
it('parse simple script and return ast', async function () { it('parse simple script and return ast', async function () {
const interpreter = await AquamarineInterpreter.create({} as any); const interpreter = await AquamarineInterpreter.create({} as any);
let ast = interpreter.parseAir(` let ast = interpreter.parseAir(`
(call node ("service" "function") [1 2 3 arg] output) (call "node" ("service" "function") [1 2 3] output)
`); `);
console.log(ast);
ast = JSON.parse(ast); ast = JSON.parse(ast);
expect(ast).toEqual({ expect(ast).toEqual({
Call: { Call: {
peer_part: { PeerPk: { Variable: 'node' } }, peer_part: { PeerPk: { Literal: 'node' } },
function_part: { ServiceIdWithFuncName: [{ Literal: 'service' }, { Literal: 'function' }] }, function_part: { ServiceIdWithFuncName: [{ Literal: 'service' }, { Literal: 'function' }] },
args: [ args: [
{ {
@ -29,7 +30,6 @@ describe('== AST parsing suite', () => {
Int: 3, Int: 3,
}, },
}, },
{ Variable: 'arg' },
], ],
output: { Scalar: 'output' }, output: { Scalar: 'output' },
}, },

View File

@ -16,7 +16,7 @@
import * as PeerId from 'peer-id'; import * as PeerId from 'peer-id';
import Multiaddr from 'multiaddr'; import Multiaddr from 'multiaddr';
import { FluenceConnection } from './FluenceConnection'; import { FluenceConnection, FluenceConnectionOptions } from './FluenceConnection';
import { CallServiceResult, ParticleHandler, PeerIdB58, SecurityTetraplet } from './commonTypes'; import { CallServiceResult, ParticleHandler, PeerIdB58, SecurityTetraplet } from './commonTypes';
import { FluenceClient } from '../FluenceClient'; import { FluenceClient } from '../FluenceClient';
@ -77,7 +77,7 @@ export class ClientImpl implements FluenceClient {
}); });
} }
async connect(multiaddr: string | Multiaddr): Promise<void> { async connect(multiaddr: string | Multiaddr, options?: FluenceConnectionOptions): Promise<void> {
multiaddr = Multiaddr(multiaddr); multiaddr = Multiaddr(multiaddr);
const nodePeerId = multiaddr.getPeerId(); const nodePeerId = multiaddr.getPeerId();
@ -96,7 +96,7 @@ export class ClientImpl implements FluenceClient {
this.selfPeerIdFull, this.selfPeerIdFull,
this.executeIncomingParticle.bind(this), this.executeIncomingParticle.bind(this),
); );
await connection.connect(); await connection.connect(options);
this.connection = connection; this.connection = connection;
this.initWatchDog(); this.initWatchDog();
} }

View File

@ -23,7 +23,8 @@ import * as log from 'loglevel';
import { parseParticle, Particle, toPayload } from './particle'; import { parseParticle, Particle, toPayload } from './particle';
import { NOISE } from 'libp2p-noise'; import { NOISE } from 'libp2p-noise';
import PeerId from 'peer-id'; import PeerId from 'peer-id';
import Multiaddr from 'multiaddr' import Multiaddr from 'multiaddr';
import { options } from 'libp2p/src/keychain';
export const PROTOCOL_NAME = '/fluence/faas/1.0.0'; export const PROTOCOL_NAME = '/fluence/faas/1.0.0';
@ -33,6 +34,26 @@ enum Status {
Disconnected = 'Disconnected', Disconnected = 'Disconnected',
} }
/**
* Options to configure fluence connection
*/
export interface FluenceConnectionOptions {
/**
* @property {number} [checkConnectionTTL] - TTL for the check connection request in ms
*/
checkConnectionTTL?: number;
/**
* @property {number} [checkConnectionTTL] - set to true to skip check connection request completely
*/
skipCheckConnection?: boolean;
/**
* @property {number} [dialTimeout] - How long a dial attempt is allowed to take.
*/
dialTimeout?: number;
}
export class FluenceConnection { export class FluenceConnection {
private readonly selfPeerId: PeerId; private readonly selfPeerId: PeerId;
private node: Peer; private node: Peer;
@ -54,7 +75,7 @@ export class FluenceConnection {
this.nodePeerId = hostPeerId; this.nodePeerId = hostPeerId;
} }
async connect() { async connect(options?: FluenceConnectionOptions) {
let peerInfo = this.selfPeerId; let peerInfo = this.selfPeerId;
this.node = await Peer.create({ this.node = await Peer.create({
peerId: peerInfo, peerId: peerInfo,
@ -64,6 +85,9 @@ export class FluenceConnection {
streamMuxer: [Mplex], streamMuxer: [Mplex],
connEncryption: [NOISE], connEncryption: [NOISE],
}, },
dialer: {
timeout: options?.dialTimeout,
},
}); });
await this.startReceiving(); await this.startReceiving();

View File

@ -127,8 +127,10 @@ export class RequestFlowBuilder {
return this; return this;
} }
withTTL(ttl: number): RequestFlowBuilder { withTTL(ttl?: number): RequestFlowBuilder {
if (ttl) {
this.ttl = ttl; this.ttl = ttl;
}
return this; return this;
} }