Add AvmRunnerBackground implementation (#1)

This commit is contained in:
Pavel 2021-12-28 19:05:31 +03:00 committed by GitHub
parent c7993db0b2
commit c126c3efaf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
67 changed files with 58472 additions and 5 deletions

View File

@ -0,0 +1,5 @@
{
"template": "${{CHANGELOG}}\n\n${{UNCATEGORIZED}}",
"pr_template": "- #${{NUMBER}} ${{TITLE}}",
"empty_template": "- no changes"
}

View File

@ -3,10 +3,6 @@ name: "publish-branch"
on:
workflow_dispatch
defaults:
run:
working-directory: avm-runner-background
jobs:
npm-publish:
name: "Publish"
@ -14,6 +10,7 @@ jobs:
defaults:
run:
shell: bash
working-directory: avm-runner-background
steps:
- name: Checkout repository

66
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,66 @@
name: Create release
on:
push:
tags:
- "v*"
defaults:
run:
working-directory: avm-runner-background
jobs:
npm-publish:
name: "Publish"
runs-on: ubuntu-latest
defaults:
run:
shell: bash
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Set env
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
### Set version
- name: Set version to ${{ env.RELEASE_VERSION }}
run: npm version --new-version --allow-same-version ${{ env.RELEASE_VERSION }} --no-git-tag-version
### Publish to NPM registry
- uses: actions/setup-node@v1
with:
node-version: '16'
registry-url: 'https://registry.npmjs.org'
### release AVM runner
- name: publish AVM runner
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
npm install
./build_runner.sh
npm run build
npm publish --access public
### Create a release
- name: Build Changelog
id: changelog
uses: mikepenz/release-changelog-builder-action@v1
with:
configuration: ".github/workflows/changelog_config.json"
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Release
id: release
uses: softprops/action-gh-release@v1
with:
name: Background AVM runner ${{ env.RELEASE_VERSION }}
tag_name: ${{ env.RELEASE_VERSION }}
body: ${{steps.changelog.outputs.changelog}}
draft: false
prerelease: false
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

17
.github/workflows/tag.yml vendored Normal file
View File

@ -0,0 +1,17 @@
name: Create tag
on:
workflow_dispatch:
jobs:
tag:
name: "Tag"
runs-on: "ubuntu-latest"
steps:
- uses: actions/checkout@v2
- name: Bump version and push tag
id: tag_version
uses: mathieudutour/github-tag-action@v5.5
with:
github_token: ${{ secrets.PERSONAL_TOKEN }}

45
.github/workflows/test_node.yml vendored Normal file
View File

@ -0,0 +1,45 @@
name: Run tests in nodejs
on:
push:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [15.x, 16.x]
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-v1-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-v1-node-${{ matrix.node-version }}
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build avm-runner-background
working-directory: avm-runner-background
env:
CI: true
run: |
npm i
./build_runner.sh
npm run build
- name: run tests
working-directory: "tests/node"
env:
CI: true
run: |
npm install
npm run install:local
npm run test

View File

@ -0,0 +1,45 @@
name: Run negative tests for nodejs
on:
push:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [15.x, 16.x]
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-v1-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-v1-node-${{ matrix.node-version }}
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build avm-runner-background
working-directory: avm-runner-background
env:
CI: true
run: |
npm i
./build_runner.sh
npm run build
- name: run tests
working-directory: "tests/node-negative"
env:
CI: true
run: |
npm install
npm run install:local
npm run test

45
.github/workflows/test_web.yml vendored Normal file
View File

@ -0,0 +1,45 @@
name: Run tests in browser
on:
push:
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x]
steps:
- uses: actions/checkout@v2
- uses: actions/cache@v2
with:
path: ~/.npm
key: ${{ runner.os }}-v1-node-${{ matrix.node-version }}-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-v1-node-${{ matrix.node-version }}
- name: Setup Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: build avm-runner-background
working-directory: avm-runner-background
env:
CI: true
run: |
npm i
./build_runner.sh
npm run build
- name: run tests
working-directory: "tests/web"
env:
CI: true
run: |
./build_test_project.sh
npm install
npm run test

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.

View File

@ -1 +1,21 @@
TBD
# Background AVM Runner
`AvmRunnerBackground` is the implementation of AVM Runner which doesn't block main thread and runs in the background.
AVM Runner is an abstraction over Aqua Virtual Machine (AVM). It allows to run AVM in different contexts, e.g. web workers in browsers or worker threads on nodejs.
## Project structure
- [avm-runner-background](avm-runner-background/README.md): the main package published to npm. Provides `AvmRunnerBackground` class.
- [runner-script](runner-script/README.md): web workers and worker threads script which runs AVM
- [tests/node](tests/node/README.md): testing usage of `avm-worker-background` in nodejs
- [tests/node-negative](tests/node-negative/README.md): negative tests check if `AvmRunnerBackground` works correctly in case of misconfigured packages
- [tests/web](tests/web/README.md): testing usage of `avm-worker-background` in web.
## Contributing
While the project is still in the early stages of development, you are welcome to track progress and contribute. As the project is undergoing rapid changes, interested contributors should contact the team before embarking on larger pieces of work. All contributors should consult with and agree to our [basic contributing rules](CONTRIBUTING.md).
## License
[Apache 2.0](LICENSE)

22
avm-runner-background/.gitignore vendored Normal file
View File

@ -0,0 +1,22 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/disttmp/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea
runner-scripts

View File

@ -0,0 +1,11 @@
.idea
.gitignore
node_modules
types
src/
tsconfig.json
webpack.config.js
.prettierrc.js
build_runner.sh

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

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.

View File

@ -0,0 +1,39 @@
# AVM runner implementation which executes in the background.
`AvmRunnerBackground` is the implementation of AVM Runner which doesn't block main thread and runs in the background.
AVM Runner is the abstraction over Aqua Virtual Machine (AVM). It is allows to run AVM in different contexts, e.g. web workers in browsers or worker threads on nodejs.
## Getting started
To use `AvmRunnerBackground` with Fluence JS refer to the [documentation](https://doc.fluence.dev/docs/fluence-js)
## Overview
The project relies heavily on [threads.js](https://github.com/andywer/threads.js). It takes advantage of the unified abstraction to run the same script in both web workers and worker threads. Two script versions (one for nodejs and one for web) are embedded as base64 in code. The hosts pick one corresponding to the environment and loads it as blob URLs.
The worker script source can be found in the [runner-script](../runner-script/README.md) directory
AVM wasm file is required to run worker. It is not bundled and provided by `@fluencelabs/avm` package. The loading methods are different for nodejs and web environments:
- node: wasm file is loaded from the filesystem. By default the runner locates in the node_modules.
- web: wasm file is loaded from the server via http request. The end-user is responsible for web server configuration. `@fluencelabs/avm` provides `copyAvm` binary which helps distributing the wasm file.
## Building
First you need to build the runner script:
```
./build_runner.sh
```
Then build the npm package:
```
npm install
npm run build
```
## License
[Apache 2.0](LICENSE)

View File

@ -0,0 +1,15 @@
#!/bin/sh
# set current working directory to script directory to run script from everywhere
cd "$(dirname "$0")"
(
cd ../runner-script
npm i
npm run build:web
npm run build:node
)
mkdir -p runner-scripts
cp ../runner-script/dist/web.js runner-scripts/runnerScript.web.js
cp ../runner-script/dist/node.js runner-scripts/runnerScript.node.js

210
avm-runner-background/package-lock.json generated Normal file
View File

@ -0,0 +1,210 @@
{
"name": "@fluencelabs/avm-runner-background",
"version": "0.0.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@fluencelabs/avm-runner-background",
"version": "0.0.1",
"license": "Apache-2.0",
"dependencies": {
"@fluencelabs/avm-runner-interface": "^0.2.0",
"browser-or-node": "^2.0.0",
"threads": "^1.7.0"
},
"devDependencies": {
"@types/node": "^16.11.10",
"typescript": "^4.0.0"
}
},
"node_modules/@fluencelabs/avm-runner-interface": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@fluencelabs/avm-runner-interface/-/avm-runner-interface-0.2.0.tgz",
"integrity": "sha512-Y41pL+UwZZVdormxju8cJQsNRp6tdER0VqJ9Kg9gH2wd1KJAaYTJkyVbn8NB7fEFRUbqfbb1BXHi9wWBYOgGYQ=="
},
"node_modules/@types/node": {
"version": "16.11.14",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.14.tgz",
"integrity": "sha512-mK6BKLpL0bG6v2CxHbm0ed6RcZrAtTHBTd/ZpnlVPVa3HkumsqLE4BC4u6TQ8D7pnrRbOU0am6epuALs+Ncnzw==",
"dev": true
},
"node_modules/browser-or-node": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/browser-or-node/-/browser-or-node-2.0.0.tgz",
"integrity": "sha512-3Lrks/Okgof+/cRguUNG+qRXSeq79SO3hY4QrXJayJofwJwHiGC0qi99uDjsfTwULUFSr1OGVsBkdIkygKjTUA=="
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
"integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
"engines": {
"node": ">=6"
}
},
"node_modules/debug": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
"integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
"dependencies": {
"ms": "2.1.2"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/esm": {
"version": "3.2.25",
"resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz",
"integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==",
"optional": true,
"engines": {
"node": ">=6"
}
},
"node_modules/is-observable": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-observable/-/is-observable-2.1.0.tgz",
"integrity": "sha512-DailKdLb0WU+xX8K5w7VsJhapwHLZ9jjmazqCJq4X12CTgqq73TKnbRcnSLuXYPOoLQgV5IrD7ePiX/h1vnkBw==",
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"node_modules/observable-fns": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/observable-fns/-/observable-fns-0.6.1.tgz",
"integrity": "sha512-9gRK4+sRWzeN6AOewNBTLXir7Zl/i3GB6Yl26gK4flxz8BXVpD3kt8amREmWNb0mxYOGDotvE5a4N+PtGGKdkg=="
},
"node_modules/threads": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/threads/-/threads-1.7.0.tgz",
"integrity": "sha512-Mx5NBSHX3sQYR6iI9VYbgHKBLisyB+xROCBGjjWm1O9wb9vfLxdaGtmT/KCjUqMsSNW6nERzCW3T6H43LqjDZQ==",
"dependencies": {
"callsites": "^3.1.0",
"debug": "^4.2.0",
"is-observable": "^2.1.0",
"observable-fns": "^0.6.1"
},
"funding": {
"url": "https://github.com/andywer/threads.js?sponsor=1"
},
"optionalDependencies": {
"tiny-worker": ">= 2"
}
},
"node_modules/tiny-worker": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/tiny-worker/-/tiny-worker-2.3.0.tgz",
"integrity": "sha512-pJ70wq5EAqTAEl9IkGzA+fN0836rycEuz2Cn6yeZ6FRzlVS5IDOkFHpIoEsksPRQV34GDqXm65+OlnZqUSyK2g==",
"optional": true,
"dependencies": {
"esm": "^3.2.25"
}
},
"node_modules/typescript": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz",
"integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
}
}
},
"dependencies": {
"@fluencelabs/avm-runner-interface": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/@fluencelabs/avm-runner-interface/-/avm-runner-interface-0.2.0.tgz",
"integrity": "sha512-Y41pL+UwZZVdormxju8cJQsNRp6tdER0VqJ9Kg9gH2wd1KJAaYTJkyVbn8NB7fEFRUbqfbb1BXHi9wWBYOgGYQ=="
},
"@types/node": {
"version": "16.11.14",
"resolved": "https://registry.npmjs.org/@types/node/-/node-16.11.14.tgz",
"integrity": "sha512-mK6BKLpL0bG6v2CxHbm0ed6RcZrAtTHBTd/ZpnlVPVa3HkumsqLE4BC4u6TQ8D7pnrRbOU0am6epuALs+Ncnzw==",
"dev": true
},
"browser-or-node": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/browser-or-node/-/browser-or-node-2.0.0.tgz",
"integrity": "sha512-3Lrks/Okgof+/cRguUNG+qRXSeq79SO3hY4QrXJayJofwJwHiGC0qi99uDjsfTwULUFSr1OGVsBkdIkygKjTUA=="
},
"callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
"integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="
},
"debug": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.3.tgz",
"integrity": "sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==",
"requires": {
"ms": "2.1.2"
}
},
"esm": {
"version": "3.2.25",
"resolved": "https://registry.npmjs.org/esm/-/esm-3.2.25.tgz",
"integrity": "sha512-U1suiZ2oDVWv4zPO56S0NcR5QriEahGtdN2OR6FiOG4WJvcjBVFB0qI4+eKoWFH483PKGuLuu6V8Z4T5g63UVA==",
"optional": true
},
"is-observable": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-observable/-/is-observable-2.1.0.tgz",
"integrity": "sha512-DailKdLb0WU+xX8K5w7VsJhapwHLZ9jjmazqCJq4X12CTgqq73TKnbRcnSLuXYPOoLQgV5IrD7ePiX/h1vnkBw=="
},
"ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
"integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
},
"observable-fns": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/observable-fns/-/observable-fns-0.6.1.tgz",
"integrity": "sha512-9gRK4+sRWzeN6AOewNBTLXir7Zl/i3GB6Yl26gK4flxz8BXVpD3kt8amREmWNb0mxYOGDotvE5a4N+PtGGKdkg=="
},
"threads": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/threads/-/threads-1.7.0.tgz",
"integrity": "sha512-Mx5NBSHX3sQYR6iI9VYbgHKBLisyB+xROCBGjjWm1O9wb9vfLxdaGtmT/KCjUqMsSNW6nERzCW3T6H43LqjDZQ==",
"requires": {
"callsites": "^3.1.0",
"debug": "^4.2.0",
"is-observable": "^2.1.0",
"observable-fns": "^0.6.1",
"tiny-worker": ">= 2"
}
},
"tiny-worker": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/tiny-worker/-/tiny-worker-2.3.0.tgz",
"integrity": "sha512-pJ70wq5EAqTAEl9IkGzA+fN0836rycEuz2Cn6yeZ6FRzlVS5IDOkFHpIoEsksPRQV34GDqXm65+OlnZqUSyK2g==",
"optional": true,
"requires": {
"esm": "^3.2.25"
}
},
"typescript": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz",
"integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==",
"dev": true
}
}
}

View File

@ -0,0 +1,26 @@
{
"name": "@fluencelabs/avm-runner-background",
"version": "0.0.1",
"description": "AVM runner implementation which executed in the background",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
"bin": {
"copy-avm-runner": "./dist/copyRunnerScript.js"
},
"scripts": {
"build": "tsc",
"postbuild": "cp -v runner-scripts/runnerScript* dist/",
"test": "jest"
},
"author": "Fluence Labs",
"license": "Apache-2.0",
"devDependencies": {
"@types/node": "^16.11.10",
"typescript": "^4.0.0"
},
"dependencies": {
"@fluencelabs/avm-runner-interface": "^0.2.0",
"browser-or-node": "^2.0.0",
"threads": "^1.7.0"
}
}

View File

@ -0,0 +1,33 @@
#! /usr/bin/env node
import fs from 'fs';
import path from 'path';
const firstArgument = process.argv[2];
if (!firstArgument) {
console.log(`Expected exactly 1 argument, got 0. Usage: ${path.basename(process.argv[1])} <destination directory>`);
process.exit(1);
}
let destPath = firstArgument;
if (!path.isAbsolute(destPath)) {
destPath = path.join(process.cwd(), destPath);
}
const scriptName = 'runnerScript.web.js';
const packageName = '@fluencelabs/avm-runner-background';
const modulePath = require.resolve(packageName);
const source = path.join(path.dirname(modulePath), scriptName);
const dest = path.join(destPath, scriptName);
console.log('ensure directory exists: ', destPath);
fs.mkdirSync(destPath, { recursive: true });
console.log('copying avm runner script');
console.log('from: ', source);
console.log('to: ', dest);
fs.copyFileSync(source, dest);
console.log('done!');

View File

@ -0,0 +1,102 @@
/*
* Copyright 2021 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 { AvmRunner, CallResultsArray, LogLevel, InterpreterResult } from '@fluencelabs/avm-runner-interface';
import { isBrowser, isNode } from 'browser-or-node';
import { Thread, ModuleThread, spawn, Worker } from 'threads';
import { RunnerScriptInterface, wasmLoadingMethod } from './types';
export { wasmLoadingMethod } from './types';
const defaultAvmFileName = 'avm.wasm';
const avmPackageName = '@fluencelabs/avm';
const runnerScriptNodePath = './runnerScript.node.js';
const runnerScriptWebPath = './runnerScript.web.js';
export class AvmRunnerBackground implements AvmRunner {
private _worker?: ModuleThread<RunnerScriptInterface>;
private _loadingMethod?: wasmLoadingMethod;
constructor(loadingMethod?: wasmLoadingMethod) {
this._loadingMethod = loadingMethod;
}
async init(logLevel: LogLevel): Promise<void> {
let workerPath: string;
let method: wasmLoadingMethod;
// check if we are running inside the browser and instantiate worker with the corresponding script
if (isBrowser) {
method = this._loadingMethod || {
method: 'fetch-from-url',
baseUrl: document.baseURI,
filePath: defaultAvmFileName,
};
workerPath = runnerScriptWebPath;
}
// check if we are running inside nodejs and instantiate worker with the corresponding script
else if (isNode) {
workerPath = runnerScriptNodePath;
if (this._loadingMethod) {
method = this._loadingMethod;
} else {
try {
// webpack will complain about missing dependencies for web target
// to fix this we have to use eval('require')
const path = eval('require')('path');
const fluencePath = eval('require').resolve(avmPackageName);
const filePath = path.join(path.dirname(fluencePath), defaultAvmFileName);
method = {
method: 'read-from-fs',
filePath: filePath,
};
} catch (e: any) {
throw new Error(
'Failed to load avm.wasm. Did you forget to install @fluencelabs/avm? Original error: ' +
e.toString(),
);
}
}
} else {
throw new Error('Unknown environment');
}
this._worker = await spawn<RunnerScriptInterface>(new Worker(workerPath));
await this._worker.init(logLevel, method);
}
async terminate(): Promise<void> {
if (!this._worker) {
return;
}
await this._worker.terminate();
await Thread.terminate(this._worker);
}
async run(
air: string,
prevData: Uint8Array,
data: Uint8Array,
params: { initPeerId: string; currentPeerId: string },
callResults: CallResultsArray,
): Promise<InterpreterResult> {
if (!this._worker) {
throw 'Worker is not initialized';
}
return this._worker.run(air, prevData, data, params, callResults);
}
}

View File

@ -0,0 +1,43 @@
/*
* Copyright 2021 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 { CallResultsArray, InterpreterResult, LogLevel } from '@fluencelabs/avm-runner-interface';
export type wasmLoadingMethod =
| {
method: 'fetch-from-url';
baseUrl: string;
filePath: string;
}
| {
method: 'read-from-fs';
filePath: string;
};
export type RunnerScriptInterface = {
init: (logLevel: LogLevel, loadMethod: wasmLoadingMethod) => Promise<void>;
terminate: () => Promise<void>;
run: (
air: string,
prevData: Uint8Array,
data: Uint8Array,
params: {
initPeerId: string;
currentPeerId: string;
},
callResults: CallResultsArray,
) => Promise<InterpreterResult>;
};

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"lib": [
"es2015",
"dom"
],
"outDir": "./dist/",
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": true,
},
"exclude": [
"node_modules",
"dist"
],
"include": [
"src"
],
}

19
runner-script/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

21
runner-script/README.md Normal file
View File

@ -0,0 +1,21 @@
# Runner script
Source code for the script which runs the AVM in the background
## Overview
The project relies heavily on [threads.js](https://github.com/andywer/threads.js). It takes advantage of the unified abstraction to run the same script in both web workers and worker threads. The runner script is responsible to instantiate AVM, allocate necessary resources and execute calls to AVM.
The source code is built and minified using WebPack. There are two configurations:
- webpack.config.node.js for node build target
- webpack.config.web.js for web build target
To build package locally:
```
npm run build:node
npm run build:web
```
`avm-worker-background` uses both of the build to embed into the host library

9764
runner-script/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
{
"name": "runner-script",
"version": "1.0.0",
"scripts": {
"build:web": "webpack -c webpack.config.web.js",
"build:node": "webpack -c webpack.config.node.js"
},
"devDependencies": {
"@types/node": "^17.0.0",
"ts-loader": "^8.3.0",
"typescript": "^4.0.0",
"util": "^0.12.4",
"webpack": "^4.46.0",
"webpack-cli": "^4.9.1"
},
"dependencies": {
"@fluencelabs/avm": "0.19.6",
"@fluencelabs/avm-runner-interface": "^0.2.0",
"browser-or-node": "^2.0.0",
"threads": "^1.7.0"
}
}

View File

@ -0,0 +1,96 @@
import { LogLevel, CallResultsArray, InterpreterResult } from '@fluencelabs/avm-runner-interface';
import { AirInterpreter } from '@fluencelabs/avm';
import { isBrowser, isNode, isWebWorker } from 'browser-or-node';
import { expose } from 'threads';
import { wasmLoadingMethod, RunnerScriptInterface } from './types';
const logFunction = (level: LogLevel, message: string) => {
switch (level) {
case 'error':
console.error(message);
break;
case 'warn':
console.warn(message);
break;
case 'info':
console.info(message);
break;
case 'debug':
case 'trace':
console.log(message);
break;
}
};
let airInterpreter: AirInterpreter | 'not-set' | 'terminated' = 'not-set';
const toExpose: RunnerScriptInterface = {
init: async (logLevel: LogLevel, loadMethod: wasmLoadingMethod) => {
let module: WebAssembly.Module;
if (isBrowser || isWebWorker) {
if (loadMethod.method !== 'fetch-from-url') {
throw new Error("Only 'fetch-from-url' is supported for browsers");
}
const url = loadMethod.baseUrl + loadMethod.filePath;
try {
module = await WebAssembly.compileStreaming(fetch(url));
} catch (e) {
throw new Error(
`Failed to load ${
loadMethod.filePath
}. This usually means that the web server is not serving avm file correctly. Original error: ${e.toString()}`,
);
}
} else if (isNode) {
if (loadMethod.method !== 'read-from-fs') {
throw new Error("Only 'read-from-fs' is supported for nodejs");
}
try {
// webpack will complain about missing dependencies for web target
// to fix this we have to use eval('require')
const fs = eval('require')('fs');
const file = fs.readFileSync(loadMethod.filePath);
module = await WebAssembly.compile(file);
} catch (e) {
throw new Error(
`Failed to load ${
loadMethod.filePath
}. Did you forget to install @fluencelabs/avm? Original error: ${e.toString()}`,
);
}
} else {
throw new Error('Environment not supported');
}
airInterpreter = await AirInterpreter.create(module, logLevel, logFunction);
},
terminate: async () => {
airInterpreter = 'not-set';
},
run: async (
air: string,
prevData: Uint8Array,
data: Uint8Array,
params: {
initPeerId: string;
currentPeerId: string;
},
callResults: CallResultsArray,
): Promise<InterpreterResult> => {
if (airInterpreter === 'not-set') {
throw new Error('Interpreter is not initialized');
}
if (airInterpreter === 'terminated') {
throw new Error('Interpreter is terminated');
}
return airInterpreter.invoke(air, prevData, data, params, callResults);
},
};
expose(toExpose);

View File

@ -0,0 +1,43 @@
/*
* Copyright 2021 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 { CallResultsArray, InterpreterResult, LogLevel } from '@fluencelabs/avm-runner-interface';
export type wasmLoadingMethod =
| {
method: 'fetch-from-url';
baseUrl: string;
filePath: string;
}
| {
method: 'read-from-fs';
filePath: string;
};
export type RunnerScriptInterface = {
init: (logLevel: LogLevel, loadMethod: wasmLoadingMethod) => Promise<void>;
terminate: () => Promise<void>;
run: (
air: string,
prevData: Uint8Array,
data: Uint8Array,
params: {
initPeerId: string;
currentPeerId: string;
},
callResults: CallResultsArray,
) => Promise<InterpreterResult>;
};

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"outDir": "./dist/",
"allowJs": true,
"baseUrl": ".",
"sourceMap": false,
"inlineSources": false,
"pretty": true,
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"declaration": true,
"esModuleInterop": true,
"declarationMap": false,
"strict": true,
"noImplicitAny": false,
"alwaysStrict": true,
"noImplicitThis": true,
"strictNullChecks": false,
},
"exclude": [
"node_modules",
"dist",
],
"include": [
"src",
],
}

View File

@ -0,0 +1,36 @@
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require('path');
const isProduction = true;
// uncomment to debug
// const isProduction = false;
const config = {
entry: './src/index.ts',
output: {
path: path.resolve('dist'),
},
module: {
rules: [
{
test: /\.(ts|tsx)$/i,
use: 'ts-loader',
exclude: ['/node_modules/', '/src/BackgroundWorker.ts', '/src/index.ts'],
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
} else {
config.mode = 'development';
}
return config;
};

View File

@ -0,0 +1,22 @@
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const config = require('./webpack.config.js');
module.exports = () => {
const cfg = config();
cfg.output.filename = 'node.js';
cfg.target = 'node';
//
// TODO: we want to reuse code from node_modules
// instead of bundling AVM inside base64
// ||
// \/
// cfg.externals = [
// {
// ['@fluencelabs/avm']: {
// root: '@fluencelabs/avm',
// },
// },
// ];
return cfg;
};

View File

@ -0,0 +1,10 @@
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const config = require('./webpack.config.js');
module.exports = () => {
const cfg = config();
cfg.output.filename = 'web.js';
cfg.target = 'web';
return cfg;
};

19
tests/node-negative/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

View File

@ -0,0 +1,23 @@
# Negative test cases for `AvmRunnerBackground` in nodejs
Negative tests check if `AvmRunnerBackground` works correctly in case of misconfigured packages. Integration tests run in nodejs environment. To simulate full development cycle `avm-runner-background` is installed locally as if it was taken from npm. This is possible thanks to [install-local](https://github.com/nicojs/node-install-local) package. The installation can be simulated by the `npm run install:local` command.
## Running the tests
First build the `avm-runner-background` package.
In `$repo_root/avm-runner-background` run:
```bash
npm i
./build_runner.sh
npm run build
```
Then in `$repo_root/tests/node-negative` run:
```bash
npm install
npm run install:local
npm run test
```

View File

@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['dist'],
};

7447
tests/node-negative/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
{
"scripts": {
"install:local": "install-local ../../avm-runner-background",
"build": "tsc",
"test": "jest"
},
"devDependencies": {
"@types/jest": "^27.0.3",
"@types/node": "^16.11.10",
"install-local": "^3.0.1",
"jest": "^27.4.0",
"ts-jest": "^27.0.7",
"typescript": "^4.0.0"
},
"dependencies": {}
}

View File

@ -0,0 +1,20 @@
import { AvmRunnerBackground } from '@fluencelabs/avm-runner-background';
const vmPeerId = '12D3KooWNzutuy8WHXDKFqFsATvCR6j9cj2FijYbnd47geRKaQZS';
const b = (s: string) => {
return Buffer.from(s);
};
describe('NodeJS negative tests', () => {
it('Should display correct error message if wasm is not served', async () => {
// arrange
const testRunner = new AvmRunnerBackground();
// act
const res = await testRunner.init('off').catch((e) => e.message);
// assert
expect(res).toMatch('Failed to load avm.wasm. Did you forget to install @fluencelabs/avm?');
});
});

View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"lib": [
"es2015",
"dom"
],
"outDir": "./dist/",
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": true
},
"exclude": [
"node_modules",
"dist"
],
"include": [
"src"
]
}

19
tests/node/.gitignore vendored Normal file
View File

@ -0,0 +1,19 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

23
tests/node/README.md Normal file
View File

@ -0,0 +1,23 @@
# Tests for AvmRunnerBackground` in nodejs
Integration tests for `AvmRunnerBackground` in nodejs environment. To simulate full development cycle `avm-runner-background` is installed locally as if it was taken from npm. This is possible thanks to [install-local](https://github.com/nicojs/node-install-local) package. The installation can be simulated by the `npm run install:local` command.
## Running the tests
First build the `avm-runner-background` package.
In `$repo_root/avm-runner-background` run:
```bash
npm i
./build_runner.sh
npm run build
```
Then in `$repo_root/tests/node` run:
```bash
npm install
npm run install:local
npm run test
```

View File

@ -0,0 +1,5 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['dist'],
};

7463
tests/node/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

18
tests/node/package.json Normal file
View File

@ -0,0 +1,18 @@
{
"scripts": {
"install:local": "install-local ../../avm-runner-background",
"build": "tsc",
"test": "jest"
},
"devDependencies": {
"@types/jest": "^27.0.3",
"@types/node": "^16.11.10",
"install-local": "^3.0.1",
"jest": "^27.4.0",
"ts-jest": "^27.0.7",
"typescript": "^4.0.0"
},
"dependencies": {
"@fluencelabs/avm": "0.19.6"
}
}

View File

@ -0,0 +1,31 @@
import { AvmRunnerBackground } from '@fluencelabs/avm-runner-background';
const vmPeerId = '12D3KooWNzutuy8WHXDKFqFsATvCR6j9cj2FijYbnd47geRKaQZS';
const b = (s: string) => {
return Buffer.from(s);
};
describe('Nodejs integration tests', () => {
it('AvmRunnerBackground should work correctly execute simple script', async () => {
// arrange
const testRunner = new AvmRunnerBackground();
await testRunner.init('off');
const s = `(seq
(par
(call "${vmPeerId}" ("local_service_id" "local_fn_name") [] result_1)
(call "remote_peer_id" ("service_id" "fn_name") [] g)
)
(call "${vmPeerId}" ("local_service_id" "local_fn_name") [] result_2)
)`;
// act
const params = { initPeerId: vmPeerId, currentPeerId: vmPeerId };
const res = await testRunner.run(s, b(''), b(''), params, []);
await testRunner.terminate();
// assert
expect(res).not.toBeUndefined();
});
});

25
tests/node/tsconfig.json Normal file
View File

@ -0,0 +1,25 @@
{
"compilerOptions": {
"lib": [
"es2015",
"dom"
],
"outDir": "./dist/",
"target": "es5",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": true
},
"exclude": [
"node_modules",
"dist"
],
"include": [
"src"
]
}

21
tests/web/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
public/*.wasm
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea

8
tests/web/.prettierrc.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

38
tests/web/README.md Normal file
View File

@ -0,0 +1,38 @@
# Tests for `AvmRunnerBackground` usage in browsers
Browser tests are made of two moving parts:
- Test project which uses WebPack to make a bundle for browsers
- The test shell which spins a WebPack's dev server and performs the test via puppeteer
## Test project
Test project simulates `AvmRunnerBackground` usage in browser-targeted application. To simulate full development cycle `avm-runner-background` is installed locally as if it was taken from npm. This is possible thanks to [install-local](https://github.com/nicojs/node-install-local) package. The installation can be simulated by the `npm run install:local` command.
To run test project in dev mode:
```bash
npm i
npm run install:local
npm start
```
## Running the tests
First build the `avm-runner-background` package.
In `$repo_root/avm-runner-background` run:
```bash
npm i
./build_runner.sh
npm run build
```
Then in `$repo_root/tests/web` run:
```bash
./build_test_project.sh
npm install
npm run test
```

12
tests/web/build_test_project.sh Executable file
View File

@ -0,0 +1,12 @@
#!/bin/sh
# set current working directory to script directory to run script from everywhere
cd "$(dirname "$0")"
(
cd test-project
npm i
npm run install:local
npm run copy-public
npm run build
)

8
tests/web/jest.config.js Normal file
View File

@ -0,0 +1,8 @@
module.exports = {
preset: 'jest-puppeteer',
testMatch: ['**/?(*.)+(spec|test).[t]s'],
testPathIgnorePatterns: ['/node_modules/', 'dist'],
transform: {
'^.+\\.ts?$': 'ts-jest',
},
};

15390
tests/web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

16
tests/web/package.json Normal file
View File

@ -0,0 +1,16 @@
{
"scripts": {
"test": "jest --runInBand"
},
"devDependencies": {
"@types/jest": "^27.0.3",
"@types/jest-environment-puppeteer": "^4.4.1",
"@types/puppeteer": "^5.4.4",
"jest": "^27.4.0",
"jest-puppeteer": "^6.0.2",
"ts-jest": "^27.0.7",
"typescript": "^4.0.0",
"webpack": "^5.65.0",
"webpack-dev-server": "^4.6.0"
}
}

View File

@ -0,0 +1,83 @@
import Webpack from 'webpack';
import WebpackDevServer from 'webpack-dev-server';
import webpackConfig from '../../test-project/webpack.config.js';
import process from 'process';
import path from 'path';
// change directory to the location to the test-project.
// run all the subsequent Webpack scripts in that directory
process.chdir(path.join(__dirname, '../../test-project/'));
let server;
jest.setTimeout(10000);
const startServer = async (modifyConfig?) => {
const loadInBrowserToDebug = true; // set to true to debug
modifyConfig = modifyConfig || ((_) => {});
const cfg = webpackConfig();
modifyConfig(cfg);
const compiler = Webpack(cfg);
const devServerOptions = { ...cfg.devServer, open: loadInBrowserToDebug };
server = new WebpackDevServer(devServerOptions, compiler);
await server.start();
// wait for webpack to load
await new Promise((resolve) => setTimeout(resolve, 1000));
};
const stopServer = async () => {
console.log('test: stopping server');
await server.stop();
};
describe('Integration tests for web target', () => {
afterEach(async () => {
await stopServer();
});
it('AvmRunnerBackground should work correctly execute simple script"', async () => {
console.log('test: starting server...');
await startServer();
console.log('test: navigating to page...');
await page.goto('http://localhost:8080/');
console.log('test: running script in browser...');
// @ts-ignore
const res = await page.evaluate(async () => {
// @ts-ignore
return await window.MAIN();
});
console.log('test: checking expectations...');
await expect(res).toMatchObject({
retCode: 0,
errorMessage: '',
});
});
it.skip('Should display correct error message if wasm is not served', async () => {
console.log('test: starting server...');
await startServer((cfg) => {
// simulating incorrect webpack setup
cfg.devServer.static.directory = 'public2';
});
console.log('test: navigating to page...');
await page.goto('http://localhost:8080/');
console.log('test: running script in browser...');
// @ts-ignore
const error = await page
.evaluate(async () => {
// @ts-ignore
return await window.MAIN();
})
.catch((e) => e.message);
console.log('test: checking expectations...');
await expect(error).toMatch(
'Failed to load avm.wasm. This usually means that the web server is not serving avm file correctly',
);
});
});

21
tests/web/test-project/.gitignore vendored Normal file
View File

@ -0,0 +1,21 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
public/*.wasm
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
bundle/
/dist/
/worker/dist/
# Dependency directories
node_modules/
jspm_packages/
.idea

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
</head>
<body>
<h1>Hello world!</h1>
<h2>Tip: Check your console</h2>
</body>
</html>

16258
tests/web/test-project/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
{
"scripts": {
"start": "webpack serve",
"copy-public": "copy-avm public && copy-avm-runner public",
"install:local": "install-local ../../../avm-runner-background",
"build": "webpack --mode=production --node-env=production",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
},
"devDependencies": {
"@webpack-cli/generators": "^2.4.1",
"css-loader": "^6.5.1",
"html-webpack-plugin": "^5.5.0",
"install-local": "^3.0.1",
"style-loader": "^3.3.1",
"ts-loader": "^8.3.0",
"typescript": "^4.5.4",
"util": "^0.12.4",
"webpack": "^5.65.0",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0",
"@fluencelabs/avm": "0.19.6"
},
"dependencies": {
"js-base64": "^3.7.2"
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,31 @@
import { AvmRunnerBackground } from '@fluencelabs/avm-runner-background';
import { toUint8Array } from 'js-base64';
const vmPeerId = '12D3KooWNzutuy8WHXDKFqFsATvCR6j9cj2FijYbnd47geRKaQZS';
const b = (s: string) => {
return toUint8Array(s);
};
const main = async () => {
const runner = new AvmRunnerBackground();
await runner.init('off');
const s = `(seq
(par
(call "${vmPeerId}" ("local_service_id" "local_fn_name") [] result_1)
(call "remote_peer_id" ("service_id" "fn_name") [] g)
)
(call "${vmPeerId}" ("local_service_id" "local_fn_name") [] result_2)
)`;
// act
const params = { initPeerId: vmPeerId, currentPeerId: vmPeerId };
const res = await runner.run(s, b(''), b(''), params, []);
await runner.terminate();
return res;
};
// @ts-ignore
window.MAIN = main;

View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"outDir": "./dist/",
"allowJs": true,
"baseUrl": ".",
"sourceMap": false,
"inlineSources": false,
"pretty": true,
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"declaration": false,
"esModuleInterop": true,
"declarationMap": false,
"strict": true,
"noImplicitAny": false,
"alwaysStrict": true,
"noImplicitThis": true,
"strictNullChecks": false
},
"exclude": [
"node_modules",
"dist",
],
"include": [
"src"
, "../src/demo.ts" ]
}

View File

@ -0,0 +1,62 @@
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProduction = process.env.NODE_ENV == 'production';
const stylesHandler = 'style-loader';
const config = {
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
},
devServer: {
open: true,
host: 'localhost',
static: {
directory: path.join(__dirname, 'public'),
},
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(ts|tsx)$/i,
loader: 'ts-loader',
exclude: ['/node_modules/'],
},
{
test: /\.css$/i,
use: [stylesHandler, 'css-loader'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
} else {
config.mode = 'development';
}
return config;
};

28
tests/web/tsconfig.json Normal file
View File

@ -0,0 +1,28 @@
{
"compilerOptions": {
"outDir": "./dist/",
"allowJs": true,
"baseUrl": ".",
"sourceMap": false,
"inlineSources": false,
"pretty": true,
"target": "esnext",
"module": "esnext",
"moduleResolution": "node",
"declaration": false,
"esModuleInterop": true,
"declarationMap": false,
"strict": true,
"noImplicitAny": false,
"alwaysStrict": true,
"noImplicitThis": true,
"strictNullChecks": false
},
"exclude": [
"node_modules",
"dist",
],
"include": [
"src"
]
}