Code Monkey home page Code Monkey logo

gentle_rpc's Issues

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

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);

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?

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.

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

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.