Giter Club home page Giter Club logo

webrpc's Introduction

webrpc

webrpc is a schema-driven approach to writing backend servers for the Web. Write your server's API interface in a schema format of RIDL or JSON, and then run webrpc-gen to generate the networking source code for your server and client apps. From the schema, webrpc-gen will generate application base class types/interfaces, JSON encoders, and networking code. In doing so, it's able to generate fully functioning and typed client libraries to communicate with your server. Enjoy strongly-typed Web services and never having to write an API client library again.

Under the hood, webrpc is a Web service meta-protocol, schema and code-generator tool for simplifying the development of backend services for modern Web applications.

Getting started

  1. Install webrpc-gen
  2. Write+design a webrpc schema file for your Web service
  3. Run the code-generator to create your server interface and client, ie.
    • webrpc-gen -schema=example.ridl -target=golang -pkg=service -server -client -out=./service/proto.gen.go
    • webrpc-gen -schema=example.ridl -target=typescript -client -out=./web/client.ts
  4. Implement the handlers for your server -- of course, it can't guess the server logic :)

another option is to copy the hello-webrpc example, and adapt for your own webapp and server.

Btw, check out https://marketplace.visualstudio.com/items?itemName=XanderAppWorks.vscode-webrpc-ridl-syntax for VSCode plugin for RIDL synx highlighting.

Code generators

Generator Description Schema Client Server
golang Go 1.16+ v1
typescript TypeScript v1
javascript JavaScript (ES6) v1
kotlin Kotlin (coroutines, moshi, ktor) v1
dart Dart 3.1+ v1
openapi OpenAPI 3.x (Swagger) v1 * *

..contribute more! webrpc generators are just Go templates (similar to Hugo or Helm).

Quick example

Here is an example webrpc schema in RIDL format (a new documentation-like format introduced by webrpc)

webrpc = v1

name = your-app
version = v0.1.0

struct User
  - id: uint64
  - username: string
  - createdAt?: timestamp

struct UsersQueryFilter
  - page?: uint32
  - name?: string
  - location?: string

service ExampleService
  - Ping()
  - Status() => (status: bool)
  - GetUserByID(userID: uint64) => (user: User)
  - IsOnline(user: User) => (online: bool)
  - ListUsers(q?: UsersQueryFilter) => (page: uint32, users: []User)

error 100 RateLimited     "too many requests"   HTTP 429
error 101 DatabaseDown    "service outage"      HTTP 503

Generate webrpc Go server+client code:

webrpc-gen -schema=example.ridl -target=golang -pkg=main -server -client -out=./example.gen.go

and see the generated ./example.gen.go file of types, server and client in Go. This is essentially how the golang-basics example was built.

Example apps

Example Description
hello-webrpc Go server <=> Javascript webapp
hello-webrpc-ts Go server <=> Typescript webapp
golang-basics Go server <=> Go client
golang-nodejs Go server <=> Node.js (Javascript ES6) client
node-ts Node.js server <=> Typescript webapp client

Why

TLDR; it's much simpler + faster to write and consume a webrpc service than traditional approaches like a REST API or gRPC service.

  1. Code-generate your client libraries in full -- never write another API client again
  2. Compatible with the Web. A Webrpc server is just a HTTP/HTTPS server that speaks JSON, and thus all existing browsers, http clients, load balancers, proxies, caches, and tools work out of the box (versus gRPC). cURL "just works".
  3. Be more productive, write more correct systems.

Writing a Web service / microservice takes a lot of work and time. REST is making me tired. There are many pieces to build -- designing the routes of your service, agreeing on conventions for the routes with your team, the request payloads, the response payloads, writing the actual server logic, routing the methods and requests to the server handlers, implementing the handlers, and then writing a client library for your desired language so it can speak to your Web service. Yikes, it's a lot of work. Want to add an additional field or handler? yea, you have to go through the entire cycle. And what about type-safety across the wire?

webrpc automates a lot the work for you. Now from a single webrpc schema file, you can use the webrpc-gen cli to generate source code for:

  • Strongly-typed request / response data payloads for your target language
  • Strongly-typed server interface and methods on the service, aka the RPC methods
  • Complete client library to communicate with the web service

Design / architecture

webrpc services speak JSON, as our goals are to build services that communicate with webapps. We optimize for developer experience, ease of use and productivity when building backends for modern webapps. However, webrpc also works great for service<->service communication, but it won't be as fast as gRPC in that scenario, but I'd be surprised to hear if for the majority of cases that this would be a bottleneck or costly tradeoff.

webrpc is heavily inspired by gRPC and Twirp. It is architecturally the same and has a similar workflow, but simpler. In fact, the webrpc schema is similar in design to protobuf, as in we have messages (structs) and RPC methods, but the type system is arguably more flexible and code-gen tooling is simpler. The webrpc schema is a documentation-like language for describing a server's api interface and the type system within is inspired by Go, Typescript and WASM.

We've been thinking about webrpc's design for years, and were happy to see gRPC and Twirp come onto the scene and pave the way with some great patterns. Over the years and after writing dozens of backends for Javascript-based Webapps and native mobile apps, and even built prior libraries like chi, a HTTP router for Go -- we asked ourselves:

Why have "Rails" and "Django" been such productive frameworks for writing webapps? And the answer we came to is that its productive because the server and client are the same program, running in the same process on the same computer. Rails/Django/others like it, when rendering client-state can just call a function in the same program, the client and the server are within the same domain and same state -- everything is a function-call away. Compare this to modern app development such as writing a React.js SPA or a native iOS mobile app, where the app speaks to an external API server with now the huge added effort to bridge data/runtime from one namespace (the app) to an entirely other namespace (the server). It's too much work and takes too much time, and is too brittle. There is a better way! instead of writing the code.. just generate it. If we generate all of the code to native objects in both app/server, suddenly, we can make a remote service once again feel like calling a method on the same program running on the same computer/process. Remote-Procedure-Call works!

Finally, we'd like to compare generated RPC services (gRPC/Twirp/webrpc/other) to the most common pattern to writing services by "making a RESTful API", where the machinery is similar to RPC services. Picture the flow of data when a client calls out to a server -- from a client runtime proxy-object, we encode that object, send it over the wire, the server decodes it into a server runtime proxy-object, the server handler queries the db, returns a proxy object, encodes it, and sends the function return data over the wire again. That is a ton of work, especially if you have to write it by hand and then maintain robust code in both the client and the server. Ahh, I just want to call a function on my server from my app! Save yourself the work and time, and code-generate it instead - Enter gRPC / Twirp .. and now, webrpc :)

Future goals/work:

  1. Add RPC streaming support for client/server
  2. More code generators.. for Rust, Python, ..

Schema

The webrpc schema type system is inspired by Go and TypeScript, and is simple and flexible enough to cover the wide variety of language targets, designed to target RPC communication with Web applications and other Web services.

High-level features:

  • RIDL, aka RPC IDL, aka "RPC interface design language", format - a documentation-like schema format for describing a server application.
  • JSON schema format is also supported if you prefer to write tools to target webrpc's code-gen tools
  • Type system inspired by Go + Typescript
    • integers, floats, byte, bool, any, null, date/time
    • lists (multi-dimensional arrays supported too)
    • maps (with nesting / complex structures)
    • structs / objects
      • optional fields, default values, and pluggable code-generation for a language target
    • enums

For more information please see the schema readme.

Development

Building from source

  1. Install Go 1.16+
  2. $ make build
  3. $ make test
  4. $ make install

Writing your own code-generator

See webrpc-gen documentation.

Authors

Credits

  • Twirp authors for making twirp. Much of the webrpc-go library comes from the twirp project.
  • gRPC authors, for coming up with the overall architecture and patterns for code-generating the bindings between client and server from a common IDL.

License

MIT

webrpc's People

Contributors

austinmilt avatar c2h5oh avatar dependabot[bot] avatar klaidliadon avatar lukasjenicek avatar nuharaf avatar ottob avatar paulxuca avatar pieter-lazzaro avatar pkieltyka avatar robfordww avatar vojtechvitek avatar xiam 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webrpc's Issues

gen pkg: generate Go client+server

so.. I wrote an example by hand, inspired by twirp+grpc+other here: https://github.com/webrpc/webrpc-go/tree/master/_example/proto

the goal is to use this file: https://github.com/webrpc/webrpc-go/blob/master/_example/proto/example.webrpc.json

and generate .. https://github.com/webrpc/webrpc-go/blob/master/_example/proto/proto.gen.go file

by triggering the go generate command on this file, https://github.com/webrpc/webrpc-go/blob/master/_example/proto/proto.go#L1 which in turn will execute webrpc-gen with -target=go with -client and -server flags

I think the best approach is to find some templating pkg like text/template or something else, and copy the proto.gen.go (made by hand), and templatize it, and use the schema/ package I wrote to generate Go client/server for webrpc

Let's write the code-generator inside of the gen/ pkg

if anything is unclear, please let me know

Bidirectional rpc over websockets

I’m looking for a bidirectional rpc over websockets. How tied to plain http transport is this lib?

Streaming would also be nice. But I see you already have an issue for it.

Also, did you consider using JSON-RPC standard? I am hesitant at the lock-in that comes from a custom rpc standard. Are there advantages of your protocol over this?

rpc request: viable to cache with normal http caching

the design of webrpc is to HTTP-POST to /rpc/<serviceName>/<rpcMethod> a structured JSON string to the webrpc server. Great.. but, as the input argument is sent as the request body, can nginx/CloudFlare/other services use that request body to generate a cache-key needed for basic cache-control rules?

the standard way is to use the URI + query string to generate a cache string -- but, right now, the URI/query string would be the same for all requests in webrpc. But certainly some method calls could be cacheable, so let's make sure we can support it as its the easiest first step to scalability. Some ideas how to make these rpc requests cachable..

  1. out of the box support? maybe web servers like nginx already support a way to generate a cache-key for a request body?
  2. CloudFlare workers? CF rules, and their new workers stuff looks very flexible, we could probably make it work there
  3. Add a request mode in webrpc server to take the request as a query string, which would bring us back to normal http request world, and that could be okay but less ideal then option 1 or 2 above

Error handling in js/ts generated code

export interface WebRPCError extends Error {
  code: string;
  msg: string;
  status: number;
}

export const throwHTTPError = (resp: Response) => {
  return resp.json().then((err: WebRPCError) => {
    throw err;
  });
};

This is all fine and dandy, but if the response is anything that isn't json serializable, this causes an error to be thrown when calling resp.json(). I think a more suitable method of handling an error would be to first attempt json deseraialization, and then if it throws an error, throw a new error with either the response body/ status code.

Custom errors: Define API errors in RIDL

Would it be useful to be able to enumerate all possible errors for an API in the RIDL file?

This way API consumers could have a single place to learn everything they need to know about the API. Right now RIDL helps amazingly with that, except that it doesn't "contractualize" errors, so they have to be documented separately.

Also, it would be nice to be able to return multiple errors from an API. An example of an API that could benefit from this is an API that handles a form submission. Instead of returning errors one by one, it could include all of them in the first response so that the frontend can prompt the user to fix all of them before submitting the form again.

ridl polish

  • gen/golang -- make sure to generate json struct tags always, even if we don't define them in meta

  • gen/golang -- add go.tag.json override, might already work for free..

  • enum error message is on wrong line -- enum Blah which misses : type should error on that line .. or set a default of uint32

  • bug, defining dupes of messages in RIDL, doesnt return an error?

    • ie. message Blah; - x: string; message Blah; -x: string

Generated client for Dart

Google's Flutter framework is becoming very popular and A Webrpc generated Dart client will greatly help Flutter/Dart developers to build cross platform apps with Webrtc. I request you to please consider this proposal as a priority.

gen/ts + gen/js: improve server code generation

  • error codes and messages, similar to gen/golang
  • formatting, hopefully some library out there to help clean up some of this formatting for generic source so it doesnt looks so bad. Or the templating system we use, Go's text/template could have some other useful notation/other to help with clean formatting easier during generation

Any way to generate "pointer" members?

A common pattern is to use pointers for values that might be null, say:

type Device struct {
	ID       int64
	DeviceID string `pg:",unique,notnull"`
	CreatedAt time.Time `pg:"default:now(),use_zero"`
	DeletedAt *time.Time
        ...

Could this make any sense in webrpc?
Also, in general, shuold we reuse the types that webrpc-gen generates when dealing with the database/persistence side?

Approach to documentation generator?

First off, huge thanks to this library!! It looks like exactly what I was looking for after evaluating Twirp, et al. I love that it is simple, and right to the point with little dependencies and easy to grep the source. Keep up the good work.

Although RIDL is fairly self documenting (good job), has there been any thought into a doc generator with outputs eg. swagger, etc? Just interested in your thoughts/recommendations as I was thinking about potentially writing a generator to build docs we could publish for our API.

gen/golang: faster json marshalling

As we have a well-defined schema, we have an opportunity to generate optimized JSON encoders/decoders for each different type that performs much better than Go's std "encoding/json". The std "encoding/json" uses the reflection to marshal/unmarshal in a flexible way, and its great, but produces extra garbage and costs more computer time then if we code-generated specific encoders for each message/type. See https://github.com/pquerna/ffjson as a viable tool we could use in gen/golang and offer 2x to 3x faster serialization performance by their benchmarks.

gen/ts always fails on empty response

If I have an rpc method like this...

  - Delete(id: string) => ()

... then the client always fails (after actually succeeding server-side) because the generated code looks like this:

      return buildResponse(res).then(_data => {
        return {
        }
      })

And buildResponse always tries parse the JSON body, which is empty.

An easy workaround is to just return something from the rpc call:

  - Delete(id: string) => (ok: boolean)

note: My server-side is Go and my client is TS.

schema: "imports" directive support

An import directive could help with a few things

  1. Schema organization -- split definitions up into multiple files.

  2. Internal service routing and proxying -- to have a front-end API service that can communicate to internal services just from the schema design

schema: def order

allow messages to be defined in any order in the json or ridl schemas

Rules for converting all-uppercase struct members

Since ID is the recommended spelling for identifier fields in Go, just wanted to let you know that a RIDL file like:

message DeviceInfo
    - ID: string

encodes to:

type DeviceInfo struct {
	ID        string     `json:"iD"`

instead of id. DeviceID encodes correctly to deviceID, though.

gen/golang: error on json unmarshalling

I got this error on my program when using a struct as function parameter and then I saw the same situation in the golang-basics example.

You can reproduce the error by running the example:

cd _examples/golang-basics
go run .

And when you try to find a user, it issues a fatal error:

curl -v -X POST -H"Content-Type: application/json" -v -d '{"q":"123"}' http://localhost:4244/rpc/ExampleService/FindUser

I figured out that the error is in the serveFindUserJSON function on the generated Go file example.gen.go:

// line 350
reqContent := struct {
  Arg0 *SearchFilter `json:"s"`
}{}

// line 362
err = json.Unmarshal(reqBody, &reqContent)

It's trying to unmarshall Arg0 from the received json, that's why it's crashing.

To fix it I just added .Arg0 to reqContent:

err = json.Unmarshal(reqBody, &reqContent.Arg0)

(The crash itself is not caused by this error, it's due to the lack of proper checking on the received parameters at the FindUser function.)

multiple input argument support

gRPC returns 1 input argument and 1 output argument, and we've gone with this 0 or 1 input args and 1 output arg in webrpc first implementation. But it should be easy to support multiple input arguments. Something to do later..

webrpc-gen cli

we need to implement all the flags such that it works as.......

-schema     -- webrpc schema file
-pkg        -- package name used for target language,
-target     -- target language: go, ts, ...
-client     -- flag, code-generate client
-server     -- flag, code-generate server
-out        -- Directory to output the ie. <pkg>.gen.go file, if empty will print to stdout

sample usage would be.......

webrpc-gen -schema=example.webrpc.json -target=go -pkg=proto -server -client -out=./proto

Data validation constraints in schema

It would be great, If we can define data validation constraints in schema for each message field and then generate code for validating message fields.

streaming support

I've spent a lot of time thinking about a suitable design to support streaming support for webrpc that will also work with browsers.

The approach is to use chunked transfer encoding for request or response bodies to handle streaming, https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding

As for RIDL support, it could look like below:

service ApiService
  - Ping() => (status: bool)

  # streaming request body, single response
  - stream Upload(base64: string) => (status: bool)

  # single request, streaming response body
  - Download(file: string) => stream (base64: string)

  # steaming request body and response body,
  - stream Bidirection(msg: string) => stream (msg: string)

this is a slight difference from what is currently implemented, which looks like

- Download(msg: string) => (msg: stream string)

however, moving stream at the front of input or output definition is the better approach since the entire request or response payload would need to be streamed.

as for the update to the schema, the schema/service.go structure should change to..

type Service struct {
	Name    VarName   `json:"name"`
	Methods []*Method `json:"methods"`

	Schema *WebRPCSchema `json:"-"` // denormalize/back-reference
}

type Method struct {
	Name    VarName           `json:"name"`
	Stream  string            `json:"stream"` // "input", "output", "input-output"
	Inputs  []*MethodArgument `json:"inputs"`
	Outputs []*MethodArgument `json:"outputs"`

	Service *Service `json:"-"` // denormalize/back-reference
}

type MethodArgument struct {
	Name     VarName  `json:"name"`
	Type     *VarType `json:"type"`
	Optional bool     `json:"optional"`

	InputArg  bool `json:"-"` // denormalize/back-reference
	OutputArg bool `json:"-"` // denormalize/back-reference
}

notice that Stream moved from MethodArgument to Method. As well, its defined as a string now, with values of "input", "output" or "input-output" to define the pipes that support streaming for the method.

as for implementation for Go server/client, or other languages a few notes:

  1. Browsers buffer the first 1kb of chunked response, see https://gist.github.com/CMCDragonkai/6bfade6431e9ffb7fe88 -- a good idea is then to send 1024 bytes of random data, and make sure client is aware of that to omit it

  2. 0\r\n\r\n defines the terminal signal that the chunked body is at EOF

  3. For response streaming, it's good practice to send \r\n every 10 seconds or so to keep connections alive, and clients to support this

For the Go implementation, the interface for above methods could be..

type ApiService interface {
  Ping(ctx context.Context) (bool, error)
  Upload(ctx context.Context, stream UploadReader) (bool, error)
  Download(ctx context.Context, file string) (DownloadWriter, error)
}
type UploadReader interface {
  Done() <-chan struct{}
  Read() (UploadRequestBody, error)
}

type DownloadWriter interface {
  Done()
  Write(v DownloadResponseBody, err error) error
}

type DownloadResponseBody struct {
  Base64 string `json:"base64"`
}

"time" imported but not used error - in the generated golang server file

BTW. Thank all you guys for creating the go-chi. 😃 I really like the minimalist vibe of it.

I don't have any messages with time.Time type in my ridl file, but time is imported anyway.

The ridl file
https://gist.github.com/pongsanti/6c38c1d28bb41c70d6d639b1e05657b1#file-schema-ridl

command:
webrpc-gen -schema=schema.ridl -target=go -pkg=main -server -out=./schema.gen.go

The generated file
https://gist.github.com/pongsanti/6c38c1d28bb41c70d6d639b1e05657b1#file-schema-gen-go

CBOR for serialization

The Concise Binary Object Representation (CBOR) http://cbor.io/ is a data format whose design goals include the possibility of extremely small code size, fairly small message size, and extensibility without the need for version negotiation.

CBOR is based on the wildly successful JSON data model: numbers, strings, arrays, maps (called objects in JSON), and a few values such as false, true, and null. It has support for many languages.

Please consider CBOR for faster serialization.

"-" fieldtag generates valid Go but invalid Javascript client

A RIDL spec like the following:

message User
  - id: uint64
  - isAdmin: bool
  - createdAt: timestamp
  - email: string
  - emailVerified: bool
  - passwordHash: string
    + json = -

will generate the following Javascript, instead of ignoring the field:

export class User {
  constructor(_data) {
    this._data = {}
    if (_data) {
     ...
      this._data['emailVerified'] = _data['emailVerified']
      this._data['-'] = _data['-']
    }
  }
  ...
  get emailVerified() {
    return this._data['emailVerified']
  }
  set emailVerified(value) {
    this._data['emailVerified'] = value
  }
  get -() {
    return this._data['-']
  }
  set -(value) {
    this._data['-'] = value
  }
 ...
}

Replacing json with go.tag.json is a temporary workaround, IIUC.

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.