Skip to content

Commit 6013f62

Browse files
authored
Tidy up api (#31)
Tidy up api
1 parent 7839130 commit 6013f62

File tree

10 files changed

+159
-229
lines changed

10 files changed

+159
-229
lines changed

src/FluenceClient.ts

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import log from 'loglevel';
2+
import Multiaddr from 'multiaddr';
3+
import PeerId, { isPeerId } from 'peer-id';
4+
5+
import { AquaCallHandler } from './internal/AquaHandler';
6+
import { ClientImpl } from './internal/ClientImpl';
7+
import { PeerIdB58 } from './internal/commonTypes';
8+
import { generatePeerId, seedToPeerId } from './internal/peerIdUtils';
9+
import { RequestFlow } from './internal/RequestFlow';
10+
import { RequestFlowBuilder } from './internal/RequestFlowBuilder';
11+
12+
/**
13+
* The class represents interface to Fluence Platform. To create a client use @see {@link createClient} function.
14+
*/
15+
export interface FluenceClient {
16+
/**
17+
* { string } Gets the base58 representation of the current peer id. Read only
18+
*/
19+
readonly relayPeerId: PeerIdB58 | undefined;
20+
21+
/**
22+
* { string } Gets the base58 representation of the connected relay's peer id. Read only
23+
*/
24+
readonly selfPeerId: PeerIdB58;
25+
26+
/**
27+
* { string } True if the client is connected to network. False otherwise. Read only
28+
*/
29+
readonly isConnected: boolean;
30+
31+
/**
32+
* The base handler which is used by every RequestFlow executed by this FluenceClient.
33+
* Please note, that the handler is combined with the handler from RequestFlow before the execution occures.
34+
* After this combination, middlewares from RequestFlow are executed before client handler's middlewares.
35+
*/
36+
readonly aquaCallHandler: AquaCallHandler;
37+
38+
/**
39+
* Disconnects the client from the network
40+
*/
41+
disconnect(): Promise<void>;
42+
43+
/**
44+
* Establish a connection to the node. If the connection is already established, disconnect and reregister all services in a new connection.
45+
*
46+
* @param multiaddr
47+
*/
48+
connect(multiaddr: string | Multiaddr): Promise<void>;
49+
50+
/**
51+
* Initiates RequestFlow execution @see { @link RequestFlow }
52+
* @param { RequestFlow } [ request ] - RequestFlow to start the execution of
53+
*/
54+
initiateFlow(request: RequestFlow): Promise<void>;
55+
}
56+
57+
type Node = {
58+
peerId: string;
59+
multiaddr: string;
60+
};
61+
62+
/**
63+
* Creates a Fluence client. If the `connectTo` is specified connects the client to the network
64+
* @param { string | Multiaddr | Node } [connectTo] - Node in Fluence network to connect to. If not specified client will not be connected to the n
65+
* @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
66+
* @returns { Promise<FluenceClient> } Promise which will be resolved with the created FluenceClient
67+
*/
68+
export const createClient = async (
69+
connectTo?: string | Multiaddr | Node,
70+
peerIdOrSeed?: PeerId | string,
71+
): Promise<FluenceClient> => {
72+
let peerId;
73+
if (!peerIdOrSeed) {
74+
peerId = await generatePeerId();
75+
} else if (isPeerId(peerIdOrSeed)) {
76+
// keep unchanged
77+
peerId = peerIdOrSeed;
78+
} else {
79+
// peerId is string, therefore seed
80+
peerId = await seedToPeerId(peerIdOrSeed);
81+
}
82+
83+
const client = new ClientImpl(peerId);
84+
await client.initAquamarineRuntime();
85+
86+
if (connectTo) {
87+
let theAddress: Multiaddr;
88+
let fromNode = (connectTo as any).multiaddr;
89+
if (fromNode) {
90+
theAddress = new Multiaddr(fromNode);
91+
} else {
92+
theAddress = new Multiaddr(connectTo as string);
93+
}
94+
95+
await client.connect(theAddress);
96+
if (!(await checkConnection(client))) {
97+
throw new Error('Connection check failed. Check if the node is working or try to connect to another node');
98+
}
99+
}
100+
101+
return client;
102+
};
103+
104+
/**
105+
* Checks the network connection by sending a ping-like request to relat node
106+
* @param { FluenceClient } client - The Fluence Client instance.
107+
*/
108+
export const checkConnection = async (client: FluenceClient): Promise<boolean> => {
109+
if (!client.isConnected) {
110+
return false;
111+
}
112+
113+
const msg = Math.random().toString(36).substring(7);
114+
const callbackFn = 'checkConnection';
115+
const callbackService = '_callback';
116+
117+
const [request, promise] = new RequestFlowBuilder()
118+
.withRawScript(
119+
`(seq
120+
(call init_relay ("op" "identity") [msg] result)
121+
(call %init_peer_id% ("${callbackService}" "${callbackFn}") [result])
122+
)`,
123+
)
124+
.withVariables({
125+
msg,
126+
})
127+
.buildAsFetch<[[string]]>(callbackService, callbackFn);
128+
129+
await client.initiateFlow(request);
130+
131+
try {
132+
const [[result]] = await promise;
133+
if (result != msg) {
134+
log.warn("unexpected behavior. 'identity' must return arguments the passed arguments.");
135+
}
136+
return true;
137+
} catch (e) {
138+
log.error('Error on establishing connection: ', e);
139+
return false;
140+
}
141+
};

src/__test__/integration/builtins.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
uploadModule,
1010
} from '../../internal/builtins';
1111
import { ModuleConfig } from '../../internal/moduleConfig';
12-
import { createClient, FluenceClient } from '../../api.unstable';
12+
import { createClient, FluenceClient } from '../../FluenceClient';
1313
import { nodes } from '../connection';
1414

1515
let client: FluenceClient;

src/__test__/integration/client.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { checkConnection, createClient, FluenceClient } from '../../api.unstable';
1+
import { checkConnection, createClient, FluenceClient } from '../../FluenceClient';
22
import Multiaddr from 'multiaddr';
33
import { nodes } from '../connection';
44
import { RequestFlowBuilder } from '../../internal/RequestFlowBuilder';

src/__test__/integration/legacy.api.spec.ts

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,5 @@
1-
import {
2-
createClient,
3-
Particle,
4-
FluenceClient,
5-
sendParticle,
6-
registerServiceFunction,
7-
subscribeToEvent,
8-
sendParticleAsFetch,
9-
} from '../../api';
1+
import { Particle, sendParticle, registerServiceFunction, subscribeToEvent, sendParticleAsFetch } from '../../api';
2+
import { FluenceClient, createClient } from '../../FluenceClient';
103
import { nodes } from '../connection';
114

125
let client: FluenceClient;

src/__test__/unit/air.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { createClient, FluenceClient } from '../../api.unstable';
1+
import { createClient, FluenceClient } from '../../FluenceClient';
22
import { RequestFlow } from '../../internal/RequestFlow';
33
import { RequestFlowBuilder } from '../../internal/RequestFlowBuilder';
44

src/api.ts

Lines changed: 5 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -1,65 +1,6 @@
1-
import Multiaddr from 'multiaddr';
2-
import PeerId from 'peer-id';
3-
import { PeerIdB58, SecurityTetraplet } from './internal/commonTypes';
4-
import * as unstable from './api.unstable';
5-
import { ClientImpl } from './internal/ClientImpl';
1+
import { SecurityTetraplet } from './internal/commonTypes';
62
import { RequestFlowBuilder } from './internal/RequestFlowBuilder';
7-
import { RequestFlow } from './internal/RequestFlow';
8-
9-
/**
10-
* The class represents interface to Fluence Platform. To create a client @see {@link createClient} function.
11-
*/
12-
export interface FluenceClient {
13-
/**
14-
* { string } Gets the base58 representation of the current peer id. Read only
15-
*/
16-
readonly relayPeerId: PeerIdB58 | undefined;
17-
18-
/**
19-
* { string } Gets the base58 representation of the connected relay's peer id. Read only
20-
*/
21-
readonly selfPeerId: PeerIdB58;
22-
23-
/**
24-
* { string } True if the client is connected to network. False otherwise. Read only
25-
*/
26-
readonly isConnected: boolean;
27-
28-
/**
29-
* Disconnects the client from the network
30-
*/
31-
disconnect(): Promise<void>;
32-
33-
/**
34-
* Establish a connection to the node. If the connection is already established, disconnect and reregister all services in a new connection.
35-
*
36-
* @param {string | Multiaddr} [multiaddr] - Address of the node in Fluence network.
37-
*/
38-
connect(multiaddr: string | Multiaddr): Promise<void>;
39-
}
40-
41-
type Node = {
42-
peerId: string;
43-
multiaddr: string;
44-
};
45-
46-
/**
47-
* Creates a Fluence client. If the `connectTo` is specified connects the client to the network
48-
* @param { string | Multiaddr | Node } [connectTo] - Node in Fluence network to connect to. If not specified client will not be connected to the n
49-
* @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
50-
* @returns { Promise<FluenceClient> } Promise which will be resolved with the created FluenceClient
51-
*/
52-
export const createClient = async (
53-
connectTo?: string | Multiaddr | Node,
54-
peerIdOrSeed?: PeerId | string,
55-
): Promise<FluenceClient> => {
56-
const res = await unstable.createClient(connectTo, peerIdOrSeed);
57-
return res as any;
58-
};
59-
60-
export const checkConnection = async (client: FluenceClient): Promise<boolean> => {
61-
return unstable.checkConnection(client as any);
62-
};
3+
import { FluenceClient } from './FluenceClient';
634

645
/**
656
* The class representing Particle - a data structure used to perform operations on Fluence Network. It originates on some peer in the network, travels the network through a predefined path, triggering function execution along its way.
@@ -102,7 +43,6 @@ export const sendParticle = async (
10243
particle: Particle,
10344
onError?: (err) => void,
10445
): Promise<string> => {
105-
const c = client as ClientImpl;
10646
const [req, errorPromise] = new RequestFlowBuilder()
10747
.withRawScript(particle.script)
10848
.withVariables(particle.data)
@@ -111,7 +51,7 @@ export const sendParticle = async (
11151

11252
errorPromise.catch(onError);
11353

114-
await c.initiateFlow(req);
54+
await client.initiateFlow(req);
11555
return req.id;
11656
};
11757

@@ -139,7 +79,7 @@ export const registerServiceFunction = (
13979
fnName: string,
14080
handler: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
14181
) => {
142-
const unregister = (client as ClientImpl).aquaCallHandler.on(serviceId, fnName, handler);
82+
const unregister = client.aquaCallHandler.on(serviceId, fnName, handler);
14383
handlersUnregistratorsMap.set(makeKey(client, serviceId, fnName), unregister);
14484
};
14585

@@ -212,7 +152,7 @@ export const sendParticleAsFetch = async <T>(
212152
.withTTL(particle.ttl)
213153
.buildAsFetch<T>(callbackServiceId, callbackFnName);
214154

215-
await (client as ClientImpl).initiateFlow(request);
155+
await client.initiateFlow(request);
216156

217157
return promise;
218158
};

0 commit comments

Comments
 (0)