Returned built-in Aquamarine calls, updated docs (#11)

This commit is contained in:
Dima 2021-01-29 16:48:27 +03:00 committed by GitHub
parent b9d146c653
commit 92980379bd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 1039 additions and 325 deletions

13
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,13 @@
## Contribute Code
You are welcome to contribute to Fluence.
Things you need to know:
1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
### Contributor License Agreement
When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

131
README.md
View File

@ -1,31 +1,128 @@
# Fluence browser client # Fluence JS SDK
[![npm version](https://badge.fury.io/js/%40fluencelabs%2Ffluence.svg)](https://badge.fury.io/js/%40fluencelabs%2Ffluence) [![npm](https://img.shields.io/npm/v/@fluencelabs/fluence)](https://www.npmjs.com/package/@fluencelabs/fluence)
Browser client for the Fluence network based on the js-libp2p. Official SDK for building web-based applications for Fluence
## How to build ## About Fluence
With `npm` installed building could be done as follows: Fluence is an open application platform where apps can build on each other, share data and users
| Layer | Tech | Scale | State | Based on |
| :-------------------: | :-------------------------------------------------------------------------------------------------------------------------------: | :------------------------------: | :-------------------------------: | :-----------------------------------------------------------------------------------------------------------: |
| Execution | [FCE](https://github.com/fluencelabs/fce) | Single peer | Disk, network, external processes | Wasm, [IT](https://github.com/fluencelabs/interface-types), [Wasmer\*](https://github.com/fluencelabs/wasmer) |
| Composition | [Aquamarine](https://github.com/fluencelabs/aquamarine) | Involved peers | Results and signatures | ⇅, π-calculus |
| Topology | [TrustGraph](https://github.com/fluencelabs/fluence/tree/master/trust-graph), [DHT\*](https://github.com/fluencelabs/rust-libp2p) | Distributed with Kademlia\* algo | Actual state of the network | [libp2p](https://github.com/libp2p/rust-libp2p) |
| Security & Accounting | Blockchain | Whole network | Licenses & payments | substrate? |
<img alt="aquamarine scheme" align="center" src="doc/stack.png"/>
## Installation
With npm
```bash ```bash
npm install fluence npm install @fluencelabs/fluence
``` ```
## Example With yarn
Shows how to register and call new service in Fluence network. ```bash
yarn add @fluencelabs/fluence
Generate new peer ids for clients.
```typescript
let peerId1 = await Fluence.generatePeerId();
let peerId2 = await Fluence.generatePeerId();
``` ```
Establish connections to predefined nodes. ## Getting started
Pick a node to connect to the Fluence network. The easiest way to do so is by using [fluence-network-environment](https://github.com/fluencelabs/fluence-network-environment) package
```typescript ```typescript
let client1 = await Fluence.connect("/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb", peerId1); import { dev } from '@fluencelabs/fluence-network-environment';
let client2 = await Fluence.connect("/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er", peerId2);
export const relayNode = dev[0];
``` ```
Initialize client
```typescript
import { createClient, FluenceClient } from '@fluencelabs/fluence';
const client = await createClient(relayNode);
```
Add response service function calls
```typescript
subscribeToEvent(client, 'helloService', 'helloFunction', (args) => {
const [networkInfo] = args;
console.log(networkInfo);
});
```
Make a particle
```typescript
const particle = new Particle(`
(seq
(call myRelay ("op" "identify") [] result)
(call %init_peer_id% ("helloService" "helloFunction") [result])
)`,
{
myRelay: client.relayPeerId,
},
);
```
Send it to the network
```typescript
await sendParticle(client, particle);
```
Observe the result in browser console
```json
{
"external_addresses": [ "/ip4/1.2.3.4/tcp/7777", "/dns4/dev.fluence.dev/tcp/19002" ]
}
```
## Documentation
SDK Reference: [readme.io](https://fluence-labs.readme.io/docs/js-sdk)
Detailed guide on building applications: [readme.io](https://fluence-labs.readme.io/docs/build-an-app)
Sample applications:
* [FluentPad](https://github.com/fluencelabs/fluent-pad): a collaborative text editor with users online status synchronization
* [Other demos](https://github.com/fluencelabs/aqua-demo): (Chat app, Social feed app, Blog platform app)
About [Fluence](https://fluence.network/)
## Developing
### Setting up Dev
Install node packages
```bash
npm install
```
### Running tests
To run test execute
```bash
npm test
```
## Contributing
While the project is a still in the early stage of development, you are welcome to track progress and contribute. At the current moment we don't have detailed instructions on how to join development or which code guidelines to follow. However, you can expect more info to appear soon enough. In the meanwhile, check out the [basic contributing rules](CONTRIBUTING.md).
## License
[Apache 2.0](LICENSE)

BIN
doc/stack.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 83 KiB

8
package-lock.json generated
View File

@ -1,6 +1,6 @@
{ {
"name": "@fluencelabs/fluence", "name": "@fluencelabs/fluence",
"version": "0.8.0", "version": "0.9.2",
"lockfileVersion": 1, "lockfileVersion": 1,
"requires": true, "requires": true,
"dependencies": { "dependencies": {
@ -25,9 +25,9 @@
} }
}, },
"@fluencelabs/aquamarine-stepper": { "@fluencelabs/aquamarine-stepper": {
"version": "0.0.30", "version": "0.3.4",
"resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-stepper/-/aquamarine-stepper-0.0.30.tgz", "resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-stepper/-/aquamarine-stepper-0.3.4.tgz",
"integrity": "sha512-XIgRgyVgPJXvXB3NuYHpSdJ0EFcFZ+K4uduGFf8PfnFii/bFs4F1n3MBB+b4D0y59HR4F9ZQUC4fXxcf6UCYWA==" "integrity": "sha512-0NPg9dWvANtc3If8C8O8XjKwzMCq2492lA73faKJdCwUv7m+xHX9G3l6UJULTfV1T4mWVtMQZIKopNOlRYSrKA=="
}, },
"@sinonjs/commons": { "@sinonjs/commons": {
"version": "1.7.2", "version": "1.7.2",

View File

@ -1,6 +1,6 @@
{ {
"name": "@fluencelabs/fluence", "name": "@fluencelabs/fluence",
"version": "0.9.0", "version": "0.9.3",
"description": "JS SDK for the Fluence network", "description": "JS SDK for the Fluence network",
"main": "./dist/index.js", "main": "./dist/index.js",
"typings": "./dist/index.d.ts", "typings": "./dist/index.d.ts",
@ -13,7 +13,7 @@
"author": "Fluence Labs", "author": "Fluence Labs",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@fluencelabs/aquamarine-stepper": "0.0.30", "@fluencelabs/aquamarine-stepper": "0.3.4",
"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

@ -14,239 +14,22 @@
* limitations under the License. * limitations under the License.
*/ */
import log from 'loglevel'; import { PeerIdB58 } from './internal/commonTypes';
import PeerId from 'peer-id'; import Multiaddr from 'multiaddr';
import { SecurityTetraplet, StepperOutcome } from './internal/commonTypes';
import { FluenceClientBase } from './internal/FluenceClientBase';
import { build, genUUID, ParticleDto } from './internal/particle';
import { ParticleProcessor } from './internal/ParticleProcessor';
import { ParticleProcessorStrategy } from './internal/ParticleProcessorStrategy';
const fetchCallbackServiceName = '__callback'; export interface FluenceClient {
const selfRelayVarName = '__relay'; readonly relayPeerId: PeerIdB58;
readonly selfPeerId: PeerIdB58;
readonly isConnected: boolean;
const wrapRelayBasedCall = (script: string) => { disconnect(): Promise<void>;
return `
(seq
(call ${selfRelayVarName} ("op" "identity") [])
${script}
)
`;
};
const wrapFetchCall = (script: string, particleId: string, resultArgNames: string[]) => { /**
// TODO: sanitize * Establish a connection to the node. If the connection is already established, disconnect and reregister all services in a new connection.
const resultTogether = resultArgNames.join(' '); *
let res = ` * @param multiaddr
(seq */
${script} connect(multiaddr: string | Multiaddr): Promise<void>;
(seq
(call ${selfRelayVarName} ("op" "identity") [])
(call %init_peer_id% ("${fetchCallbackServiceName}" "${particleId}") [${resultTogether}])
)
)`;
return wrapRelayBasedCall(res);
};
export interface FluenceEvent { sendScript(script: string, data?: Map<string, any>, ttl?: number): Promise<string>;
type: string;
args: any[];
}
export type FluenceEventHandler = (event: FluenceEvent) => void;
export class FluenceClient extends FluenceClientBase {
private eventSubscribers: Map<string, FluenceEventHandler[]> = new Map();
private eventValidators: Map<string, Function> = new Map();
private callbacks: Map<string, Function> = new Map();
private fetchParticles: Map<string, { resolve: Function; reject: Function }> = new Map();
constructor(selfPeerId: PeerId) {
super(selfPeerId);
this.processor = new ParticleProcessor(this.strategy, selfPeerId);
}
async fetch<T>(script: string, resultArgNames: string[], data?: Map<string, any>, ttl?: number): Promise<T> {
data = this.addRelayToArgs(data);
const callBackId = genUUID();
script = wrapFetchCall(script, callBackId, resultArgNames);
const particle = await build(this.selfPeerIdFull, script, data, ttl, callBackId);
return new Promise<T>((resolve, reject) => {
this.fetchParticles.set(callBackId, { resolve, reject });
this.processor.executeLocalParticle(particle);
});
}
// TODO:: better naming probably?
async fireAndForget(script: string, data?: Map<string, any>, ttl?: number) {
data = this.addRelayToArgs(data);
script = wrapRelayBasedCall(script);
await this.sendScript(script, data, ttl);
}
registerEvent(
channel: string,
eventName: string,
validate?: (channel: string, eventName: string, args: any[], tetraplets: any[][]) => boolean,
) {
if (!validate) {
validate = (c, e, a, t) => true;
}
this.eventValidators.set(`${channel}/${eventName}`, validate);
}
unregisterEvent(channel: string, eventName: string) {
this.eventValidators.delete(`${channel}/${eventName}`);
}
registerCallback(
serviceId: string,
fnName: string,
callback: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
) {
this.callbacks.set(`${serviceId}/${fnName}`, callback);
}
unregisterCallback(channel: string, eventName: string) {
this.eventValidators.delete(`${channel}/${eventName}`);
}
subscribe(channel: string, handler: FluenceEventHandler) {
if (!this.eventSubscribers.get(channel)) {
this.eventSubscribers.set(channel, []);
}
this.eventSubscribers.get(channel).push(handler);
}
protected strategy: ParticleProcessorStrategy = {
particleHandler: (serviceId: string, fnName: string, args: any[], tetraplets: SecurityTetraplet[][]) => {
// missing built-in op
if (serviceId === 'op' && fnName === 'identity') {
return {
ret_code: 0,
result: JSON.stringify(args),
};
}
// async fetch model handling
if (serviceId === fetchCallbackServiceName) {
const executingParticlePromiseFns = this.fetchParticles.get(fnName);
if (executingParticlePromiseFns) {
// don't block
setImmediate(() => {
this.fetchParticles.delete(fnName);
executingParticlePromiseFns.resolve(args);
});
}
return {
ret_code: 0,
result: JSON.stringify({}),
};
}
// event model handling
const eventPair = `${serviceId}/${fnName}`;
const eventValidator = this.eventValidators.get(eventPair);
if (eventValidator) {
try {
if (!eventValidator(serviceId, fnName, args, tetraplets)) {
return {
ret_code: 1, // TODO:: error codes
result: 'validation failed',
};
}
} catch (e) {
log.error('error running validation function: ' + e);
return {
ret_code: 1, // TODO:: error codes
result: 'validation failed',
};
}
// don't block
setImmediate(() => {
this.pushEvent(serviceId, {
type: fnName,
args: args,
});
});
return {
ret_code: 0,
result: JSON.stringify({}),
};
}
// callback model handling
const callback = this.callbacks.get(eventPair);
if (callback) {
try {
const res = callback(args, tetraplets);
return {
ret_code: 0,
result: JSON.stringify(res),
};
} catch (e) {
return {
ret_code: 1, // TODO:: error codes
result: JSON.stringify(e),
};
}
}
return {
ret_code: 1,
result: `Error. There is no service: ${serviceId}`,
};
},
sendParticleFurther: async (particle: ParticleDto) => {
try {
await this.connection.sendParticle(particle);
} catch (reason) {
log.error(`Error on sending particle with id ${particle.id}: ${reason}`);
}
},
onParticleTimeout: (particle: ParticleDto, now: number) => {
log.info(`Particle expired. Now: ${now}, ttl: ${particle.ttl}, ts: ${particle.timestamp}`);
const executingParticle = this.fetchParticles.get(particle.id);
if (executingParticle) {
executingParticle.reject(new Error(`particle ${particle.id} timed out`));
}
},
onLocalParticleRecieved: (particle: ParticleDto) => {},
onExternalParticleRecieved: (particle: ParticleDto) => {},
onStepperExecuting: (particle: ParticleDto) => {},
onStepperExecuted: (stepperOutcome: StepperOutcome) => {
log.info('inner interpreter outcome:');
log.info(stepperOutcome);
},
};
private pushEvent(channel: string, event: FluenceEvent) {
const subs = this.eventSubscribers.get(channel);
if (subs) {
for (let sub of subs) {
sub(event);
}
}
}
private addRelayToArgs(data: Map<string, any>) {
if (data === undefined) {
data = new Map();
}
if (!data.has(selfRelayVarName)) {
data.set(selfRelayVarName, this.relayPeerId);
}
return data;
}
} }

View File

@ -6,11 +6,15 @@ import { certificateFromString, certificateToString, issue } from '../internal/t
import { TrustGraph } from '../internal/trust/trust_graph'; import { TrustGraph } from '../internal/trust/trust_graph';
import { nodeRootCert } from '../internal/trust/misc'; import { nodeRootCert } from '../internal/trust/misc';
import { generatePeerId, peerIdToSeed, seedToPeerId } from '../internal/peerIdUtils'; import { generatePeerId, peerIdToSeed, seedToPeerId } from '../internal/peerIdUtils';
import { FluenceClient } from '../FluenceClient'; import { FluenceClientImpl } from '../internal/FluenceClientImpl';
import { createConnectedClient, createLocalClient } from './util'; import { createConnectedClient, createLocalClient } from './util';
import log from 'loglevel'; import log from 'loglevel';
import { createClient } from '../api'; import { createClient } from '../api';
import Multiaddr from 'multiaddr'; import Multiaddr from 'multiaddr';
import { getModules } from '../internal/builtins';
const devNodeAddress = '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
const devNodePeerId = '12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
describe('Typescript usage suite', () => { describe('Typescript usage suite', () => {
it('should create private key from seed and back', async function () { it('should create private key from seed and back', async function () {
@ -49,7 +53,7 @@ describe('Typescript usage suite', () => {
describe.skip('should make connection to network', async function () { describe.skip('should make connection to network', async function () {
this.timeout(30000); this.timeout(30000);
const testProcedure = async (client: FluenceClient) => { const testProcedure = async (client: FluenceClientImpl) => {
let resMakingPromise = new Promise((resolve) => { let resMakingPromise = new Promise((resolve) => {
client.registerCallback('test', 'test', (args, _) => { client.registerCallback('test', 'test', (args, _) => {
resolve(args); resolve(args);
@ -75,11 +79,10 @@ describe('Typescript usage suite', () => {
it('address as string', async function () { it('address as string', async function () {
// arrange // arrange
const addr = const addr = devNodeAddress;
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
// act // act
const client = await createClient(addr); const client = (await createClient(addr)) as FluenceClientImpl;
// assert // assert
const res = await testProcedure(client); const res = await testProcedure(client);
@ -88,12 +91,10 @@ describe('Typescript usage suite', () => {
it('address as multiaddr', async function () { it('address as multiaddr', async function () {
// arrange // arrange
const addr = new Multiaddr( const addr = new Multiaddr(devNodeAddress);
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
// act // act
const client = await createClient(addr); const client = (await createClient(addr)) as FluenceClientImpl;
// assert // assert
const res = await testProcedure(client); const res = await testProcedure(client);
@ -103,13 +104,12 @@ describe('Typescript usage suite', () => {
it('address as node', async function () { it('address as node', async function () {
// arrange // arrange
const addr = { const addr = {
multiaddr: multiaddr: devNodeAddress,
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9', peerId: devNodePeerId,
peerId: '12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
}; };
// act // act
const client = await createClient(addr); const client = (await createClient(addr)) as FluenceClientImpl;
// assert // assert
const res = await testProcedure(client); const res = await testProcedure(client);
@ -118,26 +118,24 @@ describe('Typescript usage suite', () => {
it('peerid as peer id', async function () { it('peerid as peer id', async function () {
// arrange // arrange
const addr = const addr = devNodeAddress;
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
const pid = await generatePeerId(); const pid = await generatePeerId();
// act // act
const client = await createClient(addr, pid); const client = (await createClient(addr, pid)) as FluenceClientImpl;
// assert // assert
const res = await testProcedure(client); const res = await testProcedure(client);
expect(res).to.deep.equal(['world']); expect(res).to.deep.equal(['world']);
}); });
it('peerid as see', async function () { it('peerid as seed', async function () {
// arrange // arrange
const addr = const addr = devNodeAddress;
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
const pid = peerIdToSeed(await generatePeerId()); const pid = peerIdToSeed(await generatePeerId());
// act // act
const client = await createClient(addr, pid); const client = (await createClient(addr, pid)) as FluenceClientImpl;
// assert // assert
const res = await testProcedure(client); const res = await testProcedure(client);
@ -148,9 +146,7 @@ describe('Typescript usage suite', () => {
it.skip('should make a call through the network', async function () { it.skip('should make a call through the network', async function () {
this.timeout(30000); this.timeout(30000);
// arrange // arrange
const client = await createConnectedClient( const client = await createConnectedClient(devNodeAddress);
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
client.registerCallback('test', 'test', (args, _) => { client.registerCallback('test', 'test', (args, _) => {
log.trace('should make a call through the network, called "test" "test" with args', args); log.trace('should make a call through the network, called "test" "test" with args', args);
@ -191,9 +187,7 @@ describe('Typescript usage suite', () => {
it.skip('fireAndForget should work', async function () { it.skip('fireAndForget should work', async function () {
this.timeout(30000); this.timeout(30000);
// arrange // arrange
const client = await createConnectedClient( const client = await createConnectedClient(devNodeAddress);
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
let resMakingPromise = new Promise((resolve) => { let resMakingPromise = new Promise((resolve) => {
client.registerCallback('test', 'reverse_args', (args, _) => { client.registerCallback('test', 'reverse_args', (args, _) => {
@ -220,13 +214,23 @@ describe('Typescript usage suite', () => {
expect(res).to.deep.equal(['some d', 'some c', 'some b', 'some a']); expect(res).to.deep.equal(['some d', 'some c', 'some b', 'some a']);
}); });
it.skip('fetch should work', async function () { it.skip('add_module', async function () {
this.timeout(30000); this.timeout(30000);
// arrange // arrange
const client = await createConnectedClient( const client = await createConnectedClient(
'/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9', '/dns4/dev.fluence.dev/tcp/19003/wss/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb',
); );
let a = await getModules(client);
expect(a).not.to.be.undefined;
});
it.skip('fetch should work', async function () {
this.timeout(30000);
// arrange
const client = await createConnectedClient(devNodeAddress);
// act // act
let script = ` let script = `
(call "${client.relayPeerId}" ("op" "identify") [] result) (call "${client.relayPeerId}" ("op" "identify") [] result)
@ -243,16 +247,12 @@ describe('Typescript usage suite', () => {
it.skip('two clients should work inside the same time browser', async function () { it.skip('two clients should work inside the same time browser', async function () {
// arrange // arrange
const pid1 = await generatePeerId(); const pid1 = await generatePeerId();
const client1 = new FluenceClient(pid1); const client1 = new FluenceClientImpl(pid1);
await client1.connect( await client1.connect(devNodeAddress);
'/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
const pid2 = await generatePeerId(); const pid2 = await generatePeerId();
const client2 = new FluenceClient(pid2); const client2 = new FluenceClientImpl(pid2);
await client2.connect( await client2.connect(devNodeAddress);
'/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
let resMakingPromise = new Promise((resolve) => { let resMakingPromise = new Promise((resolve) => {
client2.registerCallback('test', 'test', (args, _) => { client2.registerCallback('test', 'test', (args, _) => {
@ -283,16 +283,12 @@ describe('Typescript usage suite', () => {
it.skip('event registration should work', async function () { it.skip('event registration should work', async function () {
// arrange // arrange
const pid1 = await generatePeerId(); const pid1 = await generatePeerId();
const client1 = new FluenceClient(pid1); const client1 = new FluenceClientImpl(pid1);
await client1.connect( await client1.connect(devNodeAddress);
'/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
const pid2 = await generatePeerId(); const pid2 = await generatePeerId();
const client2 = new FluenceClient(pid2); const client2 = new FluenceClientImpl(pid2);
await client2.connect( await client2.connect(devNodeAddress);
'/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
);
client2.registerEvent('event_stream', 'test'); client2.registerEvent('event_stream', 'test');
const resMakingPromise = new Promise((resolve) => { const resMakingPromise = new Promise((resolve) => {
@ -323,8 +319,8 @@ export async function testCerts() {
const key2 = await generatePeerId(); const key2 = await generatePeerId();
// connect to two different nodes // connect to two different nodes
const cl1 = new FluenceClient(key1); const cl1 = new FluenceClientImpl(key1);
const cl2 = new FluenceClient(key2); const cl2 = new FluenceClientImpl(key2);
await cl1.connect('/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb'); await cl1.connect('/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb');
await cl2.connect('/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er'); await cl2.connect('/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er');

View File

@ -1,15 +1,16 @@
import { FluenceClient, generatePeerId } from '..'; import { generatePeerId } from '..';
import { FluenceClientImpl } from '../internal/FluenceClientImpl';
export const createLocalClient = async () => { export const createLocalClient = async () => {
const peerId = await generatePeerId(); const peerId = await generatePeerId();
const client = new FluenceClient(peerId); const client = new FluenceClientImpl(peerId);
await client.local(); await client.local();
return client; return client;
}; };
export const createConnectedClient = async (node: string) => { export const createConnectedClient = async (node: string) => {
const peerId = await generatePeerId(); const peerId = await generatePeerId();
const client = new FluenceClient(peerId); const client = new FluenceClientImpl(peerId);
await client.connect(node); await client.connect(node);
return client; return client;
}; };

View File

@ -4,12 +4,19 @@ import { genUUID, Particle } from './internal/particle';
import Multiaddr from 'multiaddr'; import Multiaddr from 'multiaddr';
import PeerId, { isPeerId } from 'peer-id'; import PeerId, { isPeerId } from 'peer-id';
import { generatePeerId, seedToPeerId } from './internal/peerIdUtils'; import { generatePeerId, seedToPeerId } from './internal/peerIdUtils';
import { FluenceClientImpl } from './internal/FluenceClientImpl';
type Node = { type Node = {
peerId: string; peerId: string;
multiaddr: string; multiaddr: string;
}; };
/**
* 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
* @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,
@ -25,7 +32,7 @@ export const createClient = async (
peerId = await seedToPeerId(peerIdOrSeed); peerId = await seedToPeerId(peerIdOrSeed);
} }
const client = new FluenceClient(peerId); const client = new FluenceClientImpl(peerId);
if (connectTo) { if (connectTo) {
let theAddress: Multiaddr; let theAddress: Multiaddr;
@ -42,28 +49,55 @@ export const createClient = async (
return client; return client;
}; };
/**
* Send a particle to Fluence Network using the specified Fluence Client.
* @param { FluenceClient } client - The Fluence Client instance.
* @param { Particle } particle - The particle to send.
*/
export const sendParticle = async (client: FluenceClient, particle: Particle): Promise<string> => { export const sendParticle = async (client: FluenceClient, particle: Particle): Promise<string> => {
return await client.sendScript(particle.script, particle.data, particle.ttl); return await client.sendScript(particle.script, particle.data, particle.ttl);
}; };
/**
* Registers a function which can be called on the client from Aquamarine. The registration is per client basis.
* @param { FluenceClient } client - The Fluence Client instance.
* @param { string } serviceId - The identifier of service which would be used to make calls from Aquamarine
* @param { string } fnName - The identifier of function which would be used to make calls from Aquamarine
* @param { (args: any[], tetraplets: SecurityTetraplet[][]) => object } handler - The handler which would be called by Aquamarine infrastructure. The result is any object passed back to Aquamarine
*/
export const registerServiceFunction = ( export const registerServiceFunction = (
client: FluenceClient, client: FluenceClient,
serviceId: string, serviceId: string,
fnName: string, fnName: string,
handler: (args: any[], tetraplets: SecurityTetraplet[][]) => object, handler: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
) => { ) => {
client.registerCallback(serviceId, fnName, handler); (client as FluenceClientImpl).registerCallback(serviceId, fnName, handler);
}; };
// prettier-ignore // prettier-ignore
/**
* Removes registers for the function previously registered with {@link registerServiceFunction}
* @param { FluenceClient } client - The Fluence Client instance.
* @param { string } serviceId - The identifier of service used in {@link registerServiceFunction} call
* @param { string } fnName - The identifier of function used in {@link registerServiceFunction} call
*/
export const unregisterServiceFunction = ( export const unregisterServiceFunction = (
client: FluenceClient, client: FluenceClient,
serviceId: string, serviceId: string,
fnName: string fnName: string
) => { ) => {
client.unregisterCallback(serviceId, fnName); (client as FluenceClientImpl).unregisterCallback(serviceId, fnName);
}; };
/**
* Registers an event-like handler for all calls to the specific service\function pair from from Aquamarine. The registration is per client basis. Return a function which when called removes the subscription.
* Same as registerServiceFunction which immediately returns empty object.
* @param { FluenceClient } client - The Fluence Client instance.
* @param { string } serviceId - The identifier of service calls to which from Aquamarine are transformed into events.
* @param { string } fnName - The identifier of function calls to which from Aquamarine are transformed into events.
* @param { (args: any[], tetraplets: SecurityTetraplet[][]) => object } handler - The handler which would be called by Aquamarine infrastructure
* @returns { Function } - A function which when called removes the subscription.
*/
export const subscribeToEvent = ( export const subscribeToEvent = (
client: FluenceClient, client: FluenceClient,
serviceId: string, serviceId: string,
@ -84,6 +118,14 @@ export const subscribeToEvent = (
}; };
}; };
/**
* Send a particle with a fetch-like semantics. In order to for this to work you have to you have to make a call to the same callbackServiceId\callbackFnName pair from Air script as specified by the parameters. The arguments of the call are returned as the resolve value of promise
* @param { FluenceClient } client - The Fluence Client instance.
* @param { Particle } particle - The particle to send.
* @param { string } callbackFnName - The identifier of function which should be used in Air script to pass the data to fetch "promise"
* @param { [string]='_callback' } callbackServiceId - The service identifier which should be used in Air script to pass the data to fetch "promise"
* @returns { Promise<T> } - A promise which would be resolved with the data returned from Aquamarine
*/
export const sendParticleAsFetch = async <T>( export const sendParticleAsFetch = async <T>(
client: FluenceClient, client: FluenceClient,
particle: Particle, particle: Particle,

View File

@ -19,3 +19,4 @@ export { FluenceClient } from './FluenceClient';
export { SecurityTetraplet, PeerIdB58 } from './internal/commonTypes'; export { SecurityTetraplet, PeerIdB58 } from './internal/commonTypes';
export * from './api'; export * from './api';
export { Particle } from './internal/particle'; export { Particle } from './internal/particle';
export * from './internal/builtins';

View File

@ -21,7 +21,6 @@ import { FluenceConnection } from './FluenceConnection';
import { ParticleProcessor } from './ParticleProcessor'; import { ParticleProcessor } from './ParticleProcessor';
import { ParticleProcessorStrategy } from './ParticleProcessorStrategy'; import { ParticleProcessorStrategy } from './ParticleProcessorStrategy';
import log from 'loglevel';
import { PeerIdB58 } from './commonTypes'; import { PeerIdB58 } from './commonTypes';
export abstract class FluenceClientBase { export abstract class FluenceClientBase {

View File

@ -0,0 +1,253 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import log from 'loglevel';
import PeerId from 'peer-id';
import { SecurityTetraplet, StepperOutcome } from './commonTypes';
import { FluenceClientBase } from './FluenceClientBase';
import { FluenceClient } from '../FluenceClient';
import { build, genUUID, ParticleDto } from './particle';
import { ParticleProcessor } from './ParticleProcessor';
import { ParticleProcessorStrategy } from './ParticleProcessorStrategy';
const fetchCallbackServiceName = '__callback';
const selfRelayVarName = '__relay';
const wrapRelayBasedCall = (script: string) => {
return `
(seq
(call ${selfRelayVarName} ("op" "identity") [])
${script}
)
`;
};
const wrapFetchCall = (script: string, particleId: string, resultArgNames: string[]) => {
// TODO: sanitize
const resultTogether = resultArgNames.join(' ');
let res = `
(seq
${script}
(seq
(call ${selfRelayVarName} ("op" "identity") [])
(call %init_peer_id% ("${fetchCallbackServiceName}" "${particleId}") [${resultTogether}])
)
)`;
return wrapRelayBasedCall(res);
};
export interface FluenceEvent {
type: string;
args: any[];
}
export type FluenceEventHandler = (event: FluenceEvent) => void;
export class FluenceClientImpl extends FluenceClientBase implements FluenceClient {
private eventSubscribers: Map<string, FluenceEventHandler[]> = new Map();
private eventValidators: Map<string, Function> = new Map();
private callbacks: Map<string, Function> = new Map();
private fetchParticles: Map<string, { resolve: Function; reject: Function }> = new Map();
constructor(selfPeerId: PeerId) {
super(selfPeerId);
this.processor = new ParticleProcessor(this.strategy, selfPeerId);
}
async fetch<T>(script: string, resultArgNames: string[], data?: Map<string, any>, ttl?: number): Promise<T> {
data = this.addRelayToArgs(data);
const callBackId = genUUID();
script = wrapFetchCall(script, callBackId, resultArgNames);
const particle = await build(this.selfPeerIdFull, script, data, ttl, callBackId);
return new Promise<T>((resolve, reject) => {
this.fetchParticles.set(callBackId, { resolve, reject });
this.processor.executeLocalParticle(particle);
});
}
// TODO:: better naming probably?
async fireAndForget(script: string, data?: Map<string, any>, ttl?: number) {
data = this.addRelayToArgs(data);
script = wrapRelayBasedCall(script);
await this.sendScript(script, data, ttl);
}
registerEvent(
channel: string,
eventName: string,
validate?: (channel: string, eventName: string, args: any[], tetraplets: any[][]) => boolean,
) {
if (!validate) {
validate = (c, e, a, t) => true;
}
this.eventValidators.set(`${channel}/${eventName}`, validate);
}
unregisterEvent(channel: string, eventName: string) {
this.eventValidators.delete(`${channel}/${eventName}`);
}
registerCallback(
serviceId: string,
fnName: string,
callback: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
) {
this.callbacks.set(`${serviceId}/${fnName}`, callback);
}
unregisterCallback(channel: string, eventName: string) {
this.eventValidators.delete(`${channel}/${eventName}`);
}
subscribe(channel: string, handler: FluenceEventHandler) {
if (!this.eventSubscribers.get(channel)) {
this.eventSubscribers.set(channel, []);
}
this.eventSubscribers.get(channel).push(handler);
}
protected strategy: ParticleProcessorStrategy = {
particleHandler: (serviceId: string, fnName: string, args: any[], tetraplets: SecurityTetraplet[][]) => {
// missing built-in op
if (serviceId === 'op' && fnName === 'identity') {
return {
ret_code: 0,
result: JSON.stringify(args),
};
}
// async fetch model handling
if (serviceId === fetchCallbackServiceName) {
const executingParticlePromiseFns = this.fetchParticles.get(fnName);
if (executingParticlePromiseFns) {
// don't block
setImmediate(() => {
this.fetchParticles.delete(fnName);
executingParticlePromiseFns.resolve(args);
});
}
return {
ret_code: 0,
result: JSON.stringify({}),
};
}
// event model handling
const eventPair = `${serviceId}/${fnName}`;
const eventValidator = this.eventValidators.get(eventPair);
if (eventValidator) {
try {
if (!eventValidator(serviceId, fnName, args, tetraplets)) {
return {
ret_code: 1, // TODO:: error codes
result: 'validation failed',
};
}
} catch (e) {
log.error('error running validation function: ' + e);
return {
ret_code: 1, // TODO:: error codes
result: 'validation failed',
};
}
// don't block
setImmediate(() => {
this.pushEvent(serviceId, {
type: fnName,
args: args,
});
});
return {
ret_code: 0,
result: JSON.stringify({}),
};
}
// callback model handling
const callback = this.callbacks.get(eventPair);
if (callback) {
try {
const res = callback(args, tetraplets);
return {
ret_code: 0,
result: JSON.stringify(res),
};
} catch (e) {
return {
ret_code: 1, // TODO:: error codes
result: JSON.stringify(e),
};
}
}
return {
ret_code: 1,
result: `Error. There is no service: ${serviceId}`,
};
},
sendParticleFurther: async (particle: ParticleDto) => {
try {
await this.connection.sendParticle(particle);
} catch (reason) {
log.error(`Error on sending particle with id ${particle.id}: ${reason}`);
}
},
onParticleTimeout: (particle: ParticleDto, now: number) => {
log.info(`Particle expired. Now: ${now}, ttl: ${particle.ttl}, ts: ${particle.timestamp}`);
const executingParticle = this.fetchParticles.get(particle.id);
if (executingParticle) {
executingParticle.reject(new Error(`particle ${particle.id} timed out`));
}
},
onLocalParticleRecieved: (particle: ParticleDto) => {},
onExternalParticleRecieved: (particle: ParticleDto) => {},
onStepperExecuting: (particle: ParticleDto) => {},
onStepperExecuted: (stepperOutcome: StepperOutcome) => {
log.info('inner interpreter outcome:');
log.info(stepperOutcome);
},
};
private pushEvent(channel: string, event: FluenceEvent) {
const subs = this.eventSubscribers.get(channel);
if (subs) {
for (let sub of subs) {
sub(event);
}
}
}
private addRelayToArgs(data: Map<string, any>) {
if (data === undefined) {
data = new Map();
}
if (!data.has(selfRelayVarName)) {
data.set(selfRelayVarName, this.relayPeerId);
}
return data;
}
}

280
src/internal/builtins.ts Normal file
View File

@ -0,0 +1,280 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import bs58 from 'bs58';
import { sendParticleAsFetch } from '../api';
import { Particle } from './particle';
import { FluenceClient } from '../FluenceClient';
import { ModuleConfig } from './moduleConfig';
const nodeIdentityCall = (client: FluenceClient): string => {
return `(call "${client.relayPeerId}" ("op" "identity") [])`;
};
const requestResponse = async <T>(
client: FluenceClient,
name: string,
call: (nodeId: string) => string,
returnValue: string,
data: Map<string, any>,
handleResponse: (args: any[]) => T,
nodeId?: string,
ttl?: number,
): Promise<T> => {
if (!ttl) {
ttl = 10000;
}
if (!nodeId) {
nodeId = client.relayPeerId;
}
let serviceCall = call(nodeId);
let script = `(seq
${nodeIdentityCall(client)}
(seq
(seq
${serviceCall}
${nodeIdentityCall(client)}
)
(call "${client.selfPeerId}" ("_callback" "${name}") [${returnValue}])
)
)
`;
const res = await sendParticleAsFetch<any[]>(client, new Particle(script, data, ttl), '');
return handleResponse(res);
};
/**
* Get all available modules hosted on a connected relay. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @returns { Array<string> } - list of available modules on the connected relay
*/
export const getModules = async (client: FluenceClient): Promise<string[]> => {
const particle = new Particle(
`
(seq
(call __relay ("dist" "get_modules") [] result)
(call myPeerId ("_callback" "getModules") [result])
)
`,
{
__relay: client.relayPeerId,
myPeerId: client.selfPeerId,
},
);
return sendParticleAsFetch(client, particle, 'getModules');
};
/**
* Send a script to add module to a relay. Waiting for a response from a relay. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param { string } name - Name of the uploaded module
* @param { string } moduleBase64 - Base64 content of the module
* @param { ModuleConfig } config - Module config
*/
export const uploadModule = async (
client: FluenceClient,
name: string,
moduleBase64: string,
config?: ModuleConfig,
): Promise<string[]> => {
if (!config) {
config = {
name: name,
mem_pages_count: 100,
logger_enabled: true,
wasi: {
envs: {},
preopened_files: ['/tmp'],
mapped_dirs: {},
},
};
}
let data = new Map();
data.set('module_bytes', moduleBase64);
data.set('module_config', config);
data.set('__relay', client.relayPeerId);
data.set('myPeerId', client.selfPeerId);
let script = `
(seq
(call __relay ("dist" "add_module") [module_bytes module_config] result)
(call myPeerId ("_callback" "getModules") [result])
)
`;
return sendParticleAsFetch(client, new Particle(script, data), 'result');
};
/**
* Send a script to add module to a relay. Waiting for a response from a relay. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param { string } name - Name of the blueprint
* @param { Array<string> } dependencies - Array of it's dependencies
* @param {[string]} blueprintId - Optional blueprint ID
* @param {[string]} nodeId - Optional node peer id to deploy blueprint to
* @param {[number]} ttl - Optional ttl for the particle which does the job
* @returns { string } - Created blueprint ID
*/
export const addBlueprint = async (
client: FluenceClient,
name: string,
dependencies: string[],
blueprintId?: string,
nodeId?: string,
ttl?: number,
): Promise<string> => {
let returnValue = 'blueprint_id';
let call = (nodeId: string) => `(call "${nodeId}" ("dist" "add_blueprint") [blueprint] ${returnValue})`;
let data = new Map();
data.set('blueprint', { name: name, dependencies: dependencies, id: blueprintId });
return requestResponse(
client,
'addBlueprint',
call,
returnValue,
data,
(args: any[]) => args[0] as string,
nodeId,
ttl,
);
};
/**
* Send a script to create a service on the connected relay. Waiting for a response from the relay. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param {string} blueprintId - The blueprint of the service
* @param {[string]} nodeId - Optional node peer id to deploy service to
* @param {[number]} ttl - Optional ttl for the particle which does the job
* @returns { string } - Created service ID
*/
export const createService = async (
client: FluenceClient,
blueprintId: string,
nodeId?: string,
ttl?: number,
): Promise<string> => {
let returnValue = 'service_id';
let call = (nodeId: string) => `(call "${nodeId}" ("srv" "create") [blueprint_id] ${returnValue})`;
let data = new Map();
data.set('blueprint_id', blueprintId);
return requestResponse(
client,
'createService',
call,
returnValue,
data,
(args: any[]) => args[0] as string,
nodeId,
ttl,
);
};
/**
* Get all available blueprints hosted on a connected relay. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param {[string]} nodeId - Optional node peer id to get available blueprints from
* @param {[number]} ttl - Optional ttl for the particle which does the job
* @returns { Array<string> } - List of available blueprints
*/
export const getBlueprints = async (client: FluenceClient, nodeId: string, ttl?: number): Promise<string[]> => {
let returnValue = 'blueprints';
let call = (nodeId: string) => `(call "${nodeId}" ("dist" "get_blueprints") [] ${returnValue})`;
return requestResponse(
client,
'getBlueprints',
call,
returnValue,
new Map(),
(args: any[]) => args[0] as string[],
nodeId,
ttl,
);
};
/**
* Add a provider to DHT network to neighborhood around a key. @deprecated prefer using raw Particles instead
*/
export const addProvider = async (
client: FluenceClient,
key: Buffer,
providerPeer: string,
providerServiceId?: string,
nodeId?: string,
ttl?: number,
): Promise<void> => {
let call = (nodeId: string) => `(call "${nodeId}" ("dht" "add_provider") [key provider] void[])`;
key = bs58.encode(key) as any;
let provider = {
peer: providerPeer,
service_id: providerServiceId,
};
let data = new Map();
data.set('key', key);
data.set('provider', provider);
return requestResponse(client, 'addProvider', call, '', data, () => {}, nodeId, ttl);
};
/**
* Get a provider from DHT network from neighborhood around a key. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param {[string]} nodeId - Optional node peer id to get providers from
* @param {[number]} ttl - Optional ttl for the particle which does the job
* @returns { Array<object> } - List of providers
*/
export const getProviders = async (client: FluenceClient, key: Buffer, nodeId?: string, ttl?: number): Promise<any> => {
key = bs58.encode(key) as any;
let returnValue = 'providers';
let call = (nodeId: string) => `(call "${nodeId}" ("dht" "get_providers") [key] providers[])`;
let data = new Map();
data.set('key', key);
return requestResponse(client, 'getProviders', call, returnValue, data, (args) => args[0], nodeId, ttl);
};
/**
* Get relays neighborhood. @deprecated prefer using raw Particles instead
* @param { FluenceClient } client - The Fluence Client instance.
* @param {[string]} nodeId - Optional node peer id to get neighborhood from
* @param {[number]} ttl - Optional ttl for the particle which does the job
* @returns { Array<string> } - List of peer ids of neighbors of the node
*/
export const neighborhood = async (client: FluenceClient, node: string, ttl?: number): Promise<string[]> => {
let returnValue = 'neighborhood';
let call = (nodeId: string) => `(call "${nodeId}" ("dht" "neighborhood") [node] ${returnValue})`;
let data = new Map();
data.set('node', node);
return requestResponse(client, 'neighborhood', call, returnValue, data, (args) => args[0] as string[], node, ttl);
};

View File

@ -0,0 +1,29 @@
/*
* Copyright 2020 Fluence Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
export interface ModuleConfig {
name: string;
mem_pages_count?: number;
logger_enabled?: boolean;
wasi?: Wasi;
mounted_binaries?: object;
}
export interface Wasi {
envs?: object;
preopened_files?: string[];
mapped_dirs?: object;
}

View File

@ -22,11 +22,20 @@ import { injectDataIntoParticle } from './ParticleProcessor';
const DEFAULT_TTL = 7000; const DEFAULT_TTL = 7000;
/**
* 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.
*/
export class Particle { export class Particle {
script: string; script: string;
data: Map<string, any>; data: Map<string, any>;
ttl: number; ttl: number;
/**
* Creates a particle with specified parameters.
* @param { String }script - Air script which defines the execution of a particle its path, functions it triggers on peers, and so on.
* @param { Map<string, any> | Record<string, any> } data - Variables passed to the particle in the form of either JS Map or JS object with keys representing variable names and values representing values correspondingly
* @param { [Number]=7000 } ttl - Time to live, a timout after which the particle execution is stopped by Aquamarine.
*/
constructor(script: string, data?: Map<string, any> | Record<string, any>, ttl?: number) { constructor(script: string, data?: Map<string, any> | Record<string, any>, ttl?: number) {
this.script = script; this.script = script;
if (data === undefined) { if (data === undefined) {

View File

@ -19,20 +19,30 @@ import { decode, encode } from 'bs58';
import { keys } from 'libp2p-crypto'; import { keys } from 'libp2p-crypto';
/** /**
* @param seed 32 bytes * Converts seed string which back to peer id. Seed string can be obtained by using @see {@link peerIdToSeed} function
* @param { string } seed - Seed to convert to peer id
* @returns { PeerId } - Peer id
*/ */
export async function seedToPeerId(seed: string): Promise<PeerId> { export const seedToPeerId = async (seed: string): Promise<PeerId> => {
let seedArr = decode(seed); const seedArr = decode(seed);
const privateKey = await keys.generateKeyPairFromSeed('Ed25519', Uint8Array.from(seedArr), 256);
return await PeerId.createFromPrivKey(privateKey.bytes);
};
let privateK = await keys.generateKeyPairFromSeed('Ed25519', Uint8Array.from(seedArr), 256); /**
return await PeerId.createFromPrivKey(privateK.bytes); * Converts peer id to a string which can be used to restore back to peer id format with. @see {@link seedToPeerId}
} * @param { PeerId } peerId - Peer id to convert to seed
* @returns { string } - Seed string
export function peerIdToSeed(peerId: PeerId): string { */
let seedBuf = peerId.privKey.marshal().subarray(0, 32); export const peerIdToSeed = (peerId: PeerId): string => {
const seedBuf = peerId.privKey.marshal().subarray(0, 32);
return encode(seedBuf); return encode(seedBuf);
} };
export async function generatePeerId(): Promise<PeerId> { /**
* Generates a new peer id with random private key
* @returns { Promise<PeerId> } - Promise with the created Peer Id
*/
export const generatePeerId = async (): Promise<PeerId> => {
return await PeerId.create({ keyType: 'Ed25519' }); return await PeerId.create({ keyType: 'Ed25519' });
} };

View File

@ -36,8 +36,8 @@ type ImportObject = {
'./aquamarine_client_bg.js': { './aquamarine_client_bg.js': {
// fn call_service_impl(service_id: String, fn_name: String, args: String, security_tetraplets: String) -> String; // fn call_service_impl(service_id: String, fn_name: String, args: String, security_tetraplets: String) -> String;
// prettier-ignore // prettier-ignore
__wbg_callserviceimpl_94e62d12c5d03766: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any, arg8: any, ) => void; __wbg_callserviceimpl_6c417d87790b1ab9: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any, arg8: any, ) => void;
__wbg_getcurrentpeeridimpl_154ce1848a306ff5: (arg0: any) => void; __wbg_getcurrentpeeridimpl_7eaedb265739e0d2: (arg0: any) => void;
__wbindgen_throw: (arg: any) => void; __wbindgen_throw: (arg: any) => void;
}; };
host: LogImport; host: LogImport;
@ -153,7 +153,7 @@ function newImportObject(particleHandler: ParticleHandler, cfg: HostImportsConfi
// If so, an error with a new name will be occurred after wasm initialization. // If so, an error with a new name will be occurred after wasm initialization.
'./aquamarine_client_bg.js': { './aquamarine_client_bg.js': {
// prettier-ignore // prettier-ignore
__wbg_callserviceimpl_94e62d12c5d03766: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any, arg8: any) => { __wbg_callserviceimpl_6c417d87790b1ab9: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: any, arg5: any, arg6: any, arg7: any, arg8: any) => {
let wasm = cfg.exports; let wasm = cfg.exports;
try { try {
let serviceId = getStringFromWasm0(wasm, arg1, arg2); let serviceId = getStringFromWasm0(wasm, arg1, arg2);
@ -177,7 +177,7 @@ function newImportObject(particleHandler: ParticleHandler, cfg: HostImportsConfi
free(wasm, arg7, arg8); free(wasm, arg7, arg8);
} }
}, },
__wbg_getcurrentpeeridimpl_154ce1848a306ff5: (arg0: any) => { __wbg_getcurrentpeeridimpl_7eaedb265739e0d2: (arg0: any) => {
let peerIdStr = peerId.toB58String(); let peerIdStr = peerId.toB58String();
let wasm = cfg.exports; let wasm = cfg.exports;
return_current_peer_id(wasm, peerIdStr, arg0); return_current_peer_id(wasm, peerIdStr, arg0);
@ -194,8 +194,8 @@ function newLogImport(cfg: HostImportsConfig): ImportObject {
return { return {
host: log_import(cfg), host: log_import(cfg),
'./aquamarine_client_bg.js': { './aquamarine_client_bg.js': {
__wbg_callserviceimpl_94e62d12c5d03766: (_) => {}, __wbg_callserviceimpl_6c417d87790b1ab9: (_) => {},
__wbg_getcurrentpeeridimpl_154ce1848a306ff5: (_) => {}, __wbg_getcurrentpeeridimpl_7eaedb265739e0d2: (_) => {},
__wbindgen_throw: (_) => {}, __wbindgen_throw: (_) => {},
}, },
}; };