Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WebSocket plugin #1092

Merged
merged 5 commits into from
Aug 18, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/js/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
"@polywrap/tracing-js": "0.3.0",
"@polywrap/uts46-plugin-js": "0.3.0",
"@polywrap/wrap-manifest-types-js": "0.3.0",
"@polywrap/ws-plugin-js": "0.3.0",
"graphql": "15.5.0",
"js-yaml": "3.14.0",
"uuid": "8.3.2"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const defaultPlugins = [
"wrap://ens/fs.polywrap.eth",
"wrap://ens/fs-resolver.polywrap.eth",
"wrap://ens/ipfs-resolver.polywrap.eth",
"wrap://ens/ws.polywrap.eth",
];

describe("plugin-wrapper", () => {
Expand Down
1 change: 1 addition & 0 deletions packages/js/client/src/__tests__/core/sanity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe("sanity", () => {
new Uri("wrap://ens/fs.polywrap.eth"),
new Uri("wrap://ens/fs-resolver.polywrap.eth"),
new Uri("wrap://ens/ipfs-resolver.polywrap.eth"),
new Uri("wrap://ens/ws.polywrap.eth"),
]);
expect(client.getInterfaces()).toStrictEqual([
{
Expand Down
5 changes: 5 additions & 0 deletions packages/js/client/src/default-client-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { fileSystemPlugin } from "@polywrap/fs-plugin-js";
import { uts46Plugin } from "@polywrap/uts46-plugin-js";
import { sha3Plugin } from "@polywrap/sha3-plugin-js";
import { loggerPlugin } from "@polywrap/logger-plugin-js";
import { wsPlugin } from "@polywrap/ws-plugin-js";
import { Tracer } from "@polywrap/tracing-js";
import { fileSystemResolverPlugin } from "@polywrap/fs-resolver-plugin-js";

Expand Down Expand Up @@ -90,6 +91,10 @@ export const getDefaultClientConfig = Tracer.traceFunc(
uri: new Uri("wrap://ens/ipfs-resolver.polywrap.eth"),
plugin: ipfsResolverPlugin({}),
},
{
uri: new Uri("wrap://ens/ws.polywrap.eth"),
plugin: wsPlugin({}),
},
],
interfaces: [
{
Expand Down
130 changes: 130 additions & 0 deletions packages/js/plugins/ws/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# @polywrap/ws-plugin-js

WebSocket plugin allows Polywrap Client to interact with WebSocket servers.

## interface

``` typescript
# subset of JS MessageEvent interface
type Message {
data: String!
origin: String!
lastEventId: String!
}

# path to WRAP method
type Callback {
uri: String!,
method: String!
}

# optional fields are `Number | null` instead of `Option<i32>`
type Number {
value: Int!
}
Comment on lines +21 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are we doing this?

Copy link
Contributor Author

@fetsorn fetsorn Aug 10, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional Int is currently implemented as Option<i32> in wasm and schema/bind.
But to omit optional fields from the function parameters we need a | null union type.
So we wrap Int in a reference type and make it optional, Number | null.

I mentioned this in #944, but now I think we might want to implement Optional Int as Option<i32> | null and always use null instead of Option.None<i32>(), to no longer require wrapping such as this one.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't we use Box instead in that case?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i.e. Box<i32> | null instead of Option<i32> | null

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exactly, created an issue for that #1132.


type Module {
# create a socket with id
## can return after `timeout` if the server is not responding
open(url: String!, timeout: Number): Int!

# close socket `id`
close(id: Int!): Boolean

# send message via socket `id`
send(id: Int!, message: String!): Boolean

# pass all messages to callback
addCallback(id: Int!, callback: Callback!): Boolean

# stop passing messages to callback
removeCallback(id: Int!, callback: Callback!): Boolean

# save messages to ws plugin cache
addCache(id: Int!): Boolean

# stop caching messages
removeCache(id: Int!): Boolean

# get [messages], flush cache
## can wait until receives `min` events or reaches `timeout`
receive(id: Int!, min: Number, timeout: Number): [Message!]!
}
```

## callback

Every incoming WebSocket message can be passed to a callback function in another wrapper. Use `addCallback` to start passing messages and `removeCallback` to stop. The callback function is expected to have a parameter `data`, i.e. `foo(data: string)`.

``` typescript
//assemblyscript

export function callback(args: Args_callback): boolean {
Logger_Module.log({message: args.data})
return true;
}

export function subscribe(args: Args_subscribe): boolean {
const id = WS_Module.open({
url: args.url
}).unwrap();

WS_Module.addCallback({
id,
callback: {
uri: "wrap://ens/this.polywrap.eth",
method: "callback"
}
})

return true;
}

export function unsubscribe(args: Args_subscribe): boolean {
const id = WS_Module.open({
url: args.url
}).unwrap();

WS_Module.removeCallback({
id,
callback: {
uri: "wrap://ens/this.polywrap.eth",
method: "callback"
}
})

return true;
}
```

## cache

Incoming WebSocket messages can be stored in the plugin and retrieved as an array later. Use `addCache` to start caching messages and `removeCache` to stop. Use `receive` to get an array of cached messages and empty the cache. Optionally, wait for a timeout, or a minimum number of cached messages before retrieving the array.

``` typescript
//assemblyscript
export function get(args: Args_get): string[] {
const id = WS_Module.open({
url: args.url
}).unwrap();

WS_Module.addCache({
id
}).unwrap().unwrap()

WS_Module.send({
id,
message: args.message
}).unwrap().unwrap();

const messages = WS_Module.receive{
id,
timeout: { value: 200 },
quote: { value: 3 }
}).unwrap();

const data: string[] = messages.map<string>((msg) => msg.data);

return data;
}
```
22 changes: 22 additions & 0 deletions packages/js/plugins/ws/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
module.exports = {
"roots": [
"<rootDir>/src"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
modulePathIgnorePatterns: [
"<rootDir>/src/__tests__/e2e/integration/"
],
testPathIgnorePatterns: [
"<rootDir>/src/__tests__/e2e/integration/"
],
transformIgnorePatterns: [
"<rootDir>/src/__tests__/e2e/integration/"
],
testEnvironment: 'node'
}
41 changes: 41 additions & 0 deletions packages/js/plugins/ws/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"name": "@polywrap/ws-plugin-js",
"description": "Polywrap WS javascript Plugin",
"version": "0.3.0",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/polywrap/monorepo.git"
},
"main": "build/index.js",
"files": [
"build"
],
"scripts": {
"build": "rimraf ./build && yarn codegen && tsc --project tsconfig.build.json",
"codegen": "node ../../../../dependencies/node_modules/polywrap/bin/polywrap plugin codegen",
"lint": "eslint --color -c ../../../../.eslintrc.js src/",
"test": "jest --passWithNoTests --runInBand --verbose",
"test:ci": "jest --passWithNoTests --runInBand --verbose",
"test:watch": "jest --watch --passWithNoTests --verbose"
},
"dependencies": {
"@polywrap/core-js": "0.3.0"
},
"devDependencies": {
"@polywrap/client-js": "0.3.0",
"@polywrap/test-env-js": "0.3.0",
"@types/jest": "26.0.8",
"@types/prettier": "2.6.0",
"jest": "26.6.3",
"jest-websocket-mock": "^2.3.0",
"rimraf": "3.0.2",
"ts-jest": "26.5.4",
"ts-node": "8.10.2",
"typescript": "4.0.7"
},
"gitHead": "7346adaf5adb7e6bbb70d9247583e995650d390a",
"publishConfig": {
"access": "public"
}
}
5 changes: 5 additions & 0 deletions packages/js/plugins/ws/polywrap.plugin.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
format: 0.1.0
language: plugin/typescript
name: Ws
module: ./src/index.ts
schema: ./src/schema.graphql
Loading