Skip to content
This repository was archived by the owner on Jul 10, 2025. It is now read-only.
Merged
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
6 changes: 3 additions & 3 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/aquamarine-interpreter": "0.7.2",
"@fluencelabs/aquamarine-interpreter": "0.7.9",
"async": "3.2.0",
"base64-js": "1.3.1",
"bs58": "4.0.1",
Expand Down
17 changes: 13 additions & 4 deletions src/FluenceClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import PeerId, { isPeerId } from 'peer-id';
import { AquaCallHandler } from './internal/AquaHandler';
import { ClientImpl } from './internal/ClientImpl';
import { PeerIdB58 } from './internal/commonTypes';
import { FluenceConnectionOptions } from './internal/FluenceConnection';
import { generatePeerId, seedToPeerId } from './internal/peerIdUtils';
import { RequestFlow } from './internal/RequestFlow';
import { RequestFlowBuilder } from './internal/RequestFlowBuilder';
Expand Down Expand Up @@ -63,11 +64,13 @@ type Node = {
* 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 { 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
*/
export const createClient = async (
connectTo?: string | Multiaddr | Node,
peerIdOrSeed?: PeerId | string,
options?: FluenceConnectionOptions,
): Promise<FluenceClient> => {
let peerId;
if (!peerIdOrSeed) {
Expand All @@ -92,9 +95,14 @@ export const createClient = async (
theAddress = new Multiaddr(connectTo as string);
}

await client.connect(theAddress);
if (!(await checkConnection(client))) {
throw new Error('Connection check failed. Check if the node is working or try to connect to another node');
await client.connect(theAddress, options);

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',
);
}
}
}

Expand All @@ -105,7 +113,7 @@ export const createClient = async (
* Checks the network connection by sending a ping-like request to relat node
* @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) {
return false;
}
Expand All @@ -121,6 +129,7 @@ export const checkConnection = async (client: FluenceClient): Promise<boolean> =
(call %init_peer_id% ("${callbackService}" "${callbackFn}") [result])
)`,
)
.withTTL(ttl)
.withVariables({
msg,
})
Expand Down
4 changes: 2 additions & 2 deletions src/__test__/integration/builtins.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ describe('Builtins usage suite', () => {

let bpIdReturned = await addBlueprint(client, 'test_broken_blueprint', ['test_broken_module'], bpId);
let allBps = await getBlueprints(client);
const allBpIds = allBps.map(x => x.id);
const allBpIds = allBps.map((x) => x.id);

expect(allBpIds).toContain(bpIdReturned);
});
Expand All @@ -85,7 +85,7 @@ describe('Builtins usage suite', () => {
let promise = createService(client, 'test_broken_blueprint');

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'),
});
});
Expand Down
45 changes: 45 additions & 0 deletions src/__test__/integration/client.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ describe('Typescript usage suite', () => {
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 () => {
// arrange
const client1 = await createClient(nodes[0].multiaddr);
Expand Down Expand Up @@ -136,6 +145,42 @@ describe('Typescript usage suite', () => {
// assert
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 () {
Expand Down
2 changes: 1 addition & 1 deletion src/__test__/unit/air.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ describe('== AIR suite', () => {
const script = `(null)`;
// prettier-ignore
const [request, promise] = new RequestFlowBuilder()
.withTTL(0)
.withTTL(1)
.withRawScript(script)
.buildAsFetch();

Expand Down
6 changes: 3 additions & 3 deletions src/__test__/unit/ast.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ describe('== AST parsing suite', () => {
it('parse simple script and return ast', async function () {
const interpreter = await AquamarineInterpreter.create({} as any);
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);

expect(ast).toEqual({
Call: {
peer_part: { PeerPk: { Variable: 'node' } },
peer_part: { PeerPk: { Literal: 'node' } },
function_part: { ServiceIdWithFuncName: [{ Literal: 'service' }, { Literal: 'function' }] },
args: [
{
Expand All @@ -29,7 +30,6 @@ describe('== AST parsing suite', () => {
Int: 3,
},
},
{ Variable: 'arg' },
],
output: { Scalar: 'output' },
},
Expand Down
6 changes: 3 additions & 3 deletions src/internal/ClientImpl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

import * as PeerId from 'peer-id';
import Multiaddr from 'multiaddr';
import { FluenceConnection } from './FluenceConnection';
import { FluenceConnection, FluenceConnectionOptions } from './FluenceConnection';

import { CallServiceResult, ParticleHandler, PeerIdB58, SecurityTetraplet } from './commonTypes';
import { FluenceClient } from '../FluenceClient';
Expand Down Expand Up @@ -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);

const nodePeerId = multiaddr.getPeerId();
Expand All @@ -96,7 +96,7 @@ export class ClientImpl implements FluenceClient {
this.selfPeerIdFull,
this.executeIncomingParticle.bind(this),
);
await connection.connect();
await connection.connect(options);
this.connection = connection;
this.initWatchDog();
}
Expand Down
28 changes: 26 additions & 2 deletions src/internal/FluenceConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ import * as log from 'loglevel';
import { parseParticle, Particle, toPayload } from './particle';
import { NOISE } from 'libp2p-noise';
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';

Expand All @@ -33,6 +34,26 @@ enum Status {
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 {
private readonly selfPeerId: PeerId;
private node: Peer;
Expand All @@ -54,7 +75,7 @@ export class FluenceConnection {
this.nodePeerId = hostPeerId;
}

async connect() {
async connect(options?: FluenceConnectionOptions) {
let peerInfo = this.selfPeerId;
this.node = await Peer.create({
peerId: peerInfo,
Expand All @@ -64,6 +85,9 @@ export class FluenceConnection {
streamMuxer: [Mplex],
connEncryption: [NOISE],
},
dialer: {
timeout: options?.dialTimeout,
},
});

await this.startReceiving();
Expand Down
6 changes: 4 additions & 2 deletions src/internal/RequestFlowBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,10 @@ export class RequestFlowBuilder {
return this;
}

withTTL(ttl: number): RequestFlowBuilder {
this.ttl = ttl;
withTTL(ttl?: number): RequestFlowBuilder {
if (ttl) {
this.ttl = ttl;
}
return this;
}

Expand Down