Giter Site home page Giter Site logo

timonson / gentle_rpc Goto Github PK

View Code? Open in Web Editor NEW
45.0 2.0 9.0 229 KB

JSON-RPC 2.0 library with HTTP and WebSockets support for deno and the browser

License: MIT License

TypeScript 100.00%
json-rpc2 deno typescript fetch rpc browser esmodules websocket websockets javascript

gentle_rpc's Introduction

gentle_rpc

JSON-RPC 2.0 library (server and client) with HTTP and WebSockets support for deno and the browser.

Server

respond

Takes Methods, ServerRequest and Options. Look here for more information about Options.

import { serve } from "https://deno.land/[email protected]/http/server.ts";
import { respond } from "https://deno.land/x/gentle_rpc/mod.ts";

const rpcMethods = {
  sayHello: ([w]: [string]) => `Hello ${w}`,
  callNamedParameters: ({ a, b, c }: { a: number; b: number; c: string }) =>
    `${c} ${a * b}`,
  animalsMakeNoise: (noise: string[]) =>
    noise.map((el) => el.toUpperCase()).join(" "),
};

serve((req) => respond(rpcMethods, req), { addr: ":8000" });

console.log("Listening on http://localhost:8000");

CustomError

Throw a CustomError to send a server-defined error response.

import { CustomError, respond } from "https://deno.land/x/gentle_rpc/mod.ts";

//..
await respond(
  {
    throwError: () => {
      throw new CustomError(
        -32040, // the JSON-RPC error code. Note, must be -32040 to -32099
        "An error occurred", // the error message, a short sentence
        { details: "..." }, // optional additional details, can be any `JsonValue`
      );
    },
  },
  req,
);
//..

Client

createRemote

Takes a Resource for HTTP or a WebSocket for WebSockets and returns Remote.

import { createRemote } from "https://deno.land/x/gentle_rpc/mod.ts";
// Or import directly into the browser with:
import { createRemote } from "https://cdn.jsdelivr.net/gh/timonson/[email protected]/client/dist/remote.js";

// HTTP:
const remote = createRemote("http://0.0.0.0:8000");

// WebSocket:
const remote = await createRemote(new WebSocket("ws://0.0.0.0:8000"));

HTTP

call

Takes a string and an Array<JsonValue> or Record<string, JsonValue> object and returns Promise<JsonValue>.

const greeting = await remote.call("sayHello", ["World"]);
// Hello World

const namedParams = await remote.call("callNamedParameters", {
  a: 5,
  b: 10,
  c: "result:",
});
// result: 50
notification

Using the option { isNotification: true } will retun Promise<undefined>.

const notification = await remote.call("sayHello", ["World"], {
  isNotification: true,
});
// undefined
jwt

Adding the option {jwt: string} will set the Authorization header to `Bearer ${jwt}`.

const user = await remote.call("login", undefined, { jwt });
// Bob

batch

const noise1 = await remote.batch([
  {
    animalsMakeNoise: [
      ["miaaow"],
      ["wuuuufu", "wuuuufu"],
      ["iaaaiaia", "iaaaiaia", "iaaaiaia"],
      ["fiiiiire"],
    ],
    sayHello: [["World"], undefined, ["World"]],
  },
]);
// [ "MIAAOW", "WUUUUFU WUUUUFU", "IAAAIAIA IAAAIAIA IAAAIAIA", "FIIIIIRE", "Hello World", "Hello ", "Hello World" ]

The following example uses the object keys cat, dog, donkey, dragon as RPC request object ids under the hood. The returned RPC result values will be assigned to these keys.

let noise2 = await remote.batch({
  cat: ["sayHello", ["miaaow"]],
  dog: ["animalsMakeNoise", ["wuuuufu"]],
  donkey: ["sayHello"],
  dragon: ["animalsMakeNoise", ["fiiiiire", "fiiiiire"]],
});
// { cat: "Hello miaaow", dog: "WUUUUFU", donkey: "Hello ", dragon: "FIIIIIRE FIIIIIRE" }

WebSockets

call

Takes a string and an Array<JsonValue> or Record<string, JsonValue> object and returns Promise<JsonValue>.

const noise = await remote.call("callNamedParameters", {
  a: 10,
  b: 20,
  c: "The result is:",
});
// The result is: 200

remote.socket.close();

Notifications return Promise<undefined>.

notification
const notification = await remote.call("animalsMakeNoise", ["wuufff"], {
  isNotification: true,
});
// undefined
messaging between multiple clients

By using the subscribe method you can send messages between multiple clients. It returns an object with a generator property { generator: AsyncGenerator<JsonValue>} and the methods emit and unsubscribe.

Other clients can listen to and emit messages by subscribing to the same method.

const firstClient = await createRemote(new WebSocket("ws://0.0.0.0:8000"));
const secondClient = await createRemote(new WebSocket("ws://0.0.0.0:8000"));

async function run(iter: AsyncGenerator<unknown>) {
  try {
    for await (let x of iter) {
      console.log(x);
    }
  } catch (err) {
    console.log(err.message, err.code, err.data);
  }
}

const greetingFirst = firstClient.subscribe("sayHello");
const greetingSecond = secondClient.subscribe("sayHello");

run(greetingFirst.generator);
run(greetingSecond.generator);
greetingFirst.emit(["first"]);
greetingSecond.emit(["second"]);
// Hello first
// Hello first
// Hello second
// Hello second

Proxy API

Optionally, you can import syntactical sugar and use a more friendly API supported by Proxy objects.

import {
  createRemote,
  HttpProxy,
  httpProxyHandler,
} from "https://deno.land/x/gentle_rpc/mod.ts";

const remote = new Proxy<HttpProxy>(
  createRemote("http://0.0.0.0:8000"),
  httpProxyHandler,
);

let greeting = await remote.sayHello(["World"]);
// Hello World

const namedParams = await remote.callNamedParameters({
  a: 5,
  b: 10,
  c: "result:",
});
// result: 50

Examples and Tests

Please checkout the examples and tests folders for more detailed examples.

Contribution

Every kind of contribution to this project is highly appreciated.
Please run deno fmt on the changed files before making a pull request.

gentle_rpc's People

Contributors

ethicnology avatar pawelmhm avatar pfrazee avatar sisou avatar timonson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

gentle_rpc's Issues

Error: The received data is no valid JSON-RPC 2.0 Response object.

I have what I believe is a valid JSONRPC response, but the above error gets thrown,

const response = await remote.call(
  "sys.versions",
  {},
  {
    jwt: "...",
  }
);

JSON response:

{"jsonrpc":"2.0","result":{"boost":{"version":"1.80.0"},"libtorrent":{"revision":"63e1ec8c8","version":"2.0.8.0"},"nlohmann_json":{"version":"3.11.2"},"openssl":{"release_date":"1 Nov 2022","version":"3.0.7","version_text":"OpenSSL 3.0.7 1 Nov 2022"},"porla":{"branch":"-","commitish":"-","version":"0.30.0"},"sqlite":{"source_id":"2022-11-16 12:10:08 89c459e766ea7e9165d0beeb124708b955a4950d0f4792f457465d71b158d318","version":"3.40.0"},"tomlplusplus":{"version":"3.1.0"}}}

Any help would be much appreciated.

Function call never yields result

I have an Elgato WaveLink microphone, and the user-space software for that exposes a JSON-RPC interface to control the microphone. Using the following code, I can connect and attempt to issue a command against the software. The handler I directly register on the socket will log the message coming back just fine, but the awaited call never resolves. Any idea what could be causing this?

❯ deno --version
deno 1.8.1 (release, x86_64-pc-windows-msvc)
v8 9.0.257.3
typescript 4.2.2
import { createRemote } from './deps.ts';

console.log('Opening connection...');

const socket = new WebSocket('ws://127.0.0.1:1824');
socket.addEventListener('open', () => console.log('connection open'));
socket.addEventListener('message', message => console.debug(message)); // This will successfully log out the response
socket.addEventListener('error', error => console.error(error));
socket.addEventListener('close', () => console.log('connection closed'));

const remote = await createRemote(socket);
const appInfo = await remote.getApplicationInfo(); // This never resolves

console.log('Got app info:')
console.debug(appInfo);

generateId() should not rely on window to get crypto object because there is no window in worker

Currently generateId() function called when creating remote is relying on window object to be available

https://github.com/timonson/gentle_rpc/blob/master/client/creation.ts#L5

IMO this is not correct, because there is no window when you launch deno worker. This means that library can't be used inside deno workers.

Steps to reproduce

Consider following server:

// rpcParent.ts
import {serve} from "https://deno.land/[email protected]/http/server.ts";
import { respond } from "https://deno.land/x/gentle_rpc/mod.ts";

const worker = new Worker(new URL("./rpcC.ts", import.meta.url).href, { type: "module" });
worker.postMessage("hello");

const rpcMethods = {
  bye: (name: string) => {
    console.log("bye", name);
    return "bye" + name;
  },
}
serve((req) => respond(rpcMethods, req), { port:9010 });

and finally a worker implementation

// file: rpcC.ts
import { createRemote } from "https://deno.land/x/gentle_rpc/mod.ts";

self.onmessage = async (e) => {
    const remote = await createRemote(new WebSocket("ws://0.0.0.0:9010"));
    const something = await remote.call("bye", ["arg1"])
    console.log(something)
    remote.socket.close()       
}

now if you launch parent file it will create a worker, post message, worker will try to create a remote, and it will crash with following

> deno run --allow-net --allow-read --allow-write --unstable --no-prompt tmp/rpcParent.ts
Listening on http://localhost:9010/
error: Uncaught (in worker "") (in promise) ReferenceError: window is not defined
  return window.crypto.getRandomValues(new Uint32Array(1))[0].toString(16);
  ^
    at generateId (https://deno.land/x/[email protected]/client/creation.ts:5:3)
    at createRequest (https://deno.land/x/[email protected]/client/creation.ts:24:61)
    at Remote.call (https://deno.land/x/[email protected]/client/ws.ts:170:24)
    at self.onmessage (file:///home/pawel/Documents/projects/.../client.ts

@timonson

Feature request

Hi!

Thank you for an excellent library first!

Now I'm trying to use the lib and found a few corner cases I would like to point out:

  1. Hardcoded JSON parse/stringify. I wonder if we could delegate them to an optional transformer (superjson?)
  2. Hardcoded request interface. I use oak. For reference, the converter could be
    router
      .post("JSONRPC", "/rpc", async (ctx) => {
        const req = {
          headers: ctx.request.headers,
          async text() {
            return await (ctx.request.body({ type: "text" }).value).catch(() => "")
          },
        }
        const res = await respond(rpcMethods, req as Request, {
          additionalArguments: [{ args: { _ctx: ctx.state }, allMethods: true }],
          // publicErrorStack: true,
        })
        ctx.response.status = res.status
        res.headers.forEach((value, key) => ctx.response.headers.set(key, value))
        ctx.response.body = res.body
      })
  3. Way rude batch behaviour. It throws at the first error as if the batch is a DB transaction:
    try { console.log(await remote.batch({ nonExisting1: ["nonExisting1"], existing: ["existing"] })) } catch (e) { console.error({ m: e.message, c: e.code, d: e.data, i: e.id }) }
  4. No hook available to operate responses. Say think of error logging/mangling/muting.

What do you think? Feasible to be fixed in library or should be left to app level?

TIA

Implement validation/schema

I am considering implementing valita for the validation of the arguments, especially on the server side. What do you guys think about this idea?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.