Skip to content

Protobuf and gRPC ​

This guide covers Protobuf and gRPC with neutrino:

  • Install
  • Schemas
  • Configure
  • Register the provider
  • Encode and decode
  • gRPC services
  • Protecting calls
  • In production
  • Not here yet

@c9up/neutrino gives an application a schema-enforced contract across languages: one .proto shared by the server and its non-JS clients — a mobile app, a Go or Rust service — instead of a JSON shape documented by hand.

A neutrino passes through almost anything without being stopped: this one carries a message from one language to another. It is not a speed play. JSON stays the default for the web path, and an application that does not use Neutrino never installs it.

What it does:

  • loads compiled schemas — descriptor sets or generated files — and encodes / decodes messages over them;
  • serves gRPC on the application's HTTP port: a request whose content-type is application/grpc is a gRPC call, anything else is HTTP as before;
  • protects those calls with interceptors — authentication and rate limiting — since middleware never sees them.

Install ​

sh
pnpm add @c9up/neutrino

Schemas ​

Neutrino reads compiled schemas, not .proto text. Two forms, usable together:

  • a binary FileDescriptorSet, as buf build -o app.binpb or protoc --include_imports --descriptor_set_out=app.binpb app.proto writes it;
  • the files protoc-gen-es generates, which also give typed messages and services.

Generate both with buf and protoc-gen-es, installed from npm — nothing to set up on the machine:

sh
pnpm add -D @bufbuild/buf @bufbuild/protoc-gen-es
yaml
# buf.yaml
version: v2
modules:
  - path: proto
yaml
# buf.gen.yaml
version: v2
plugins:
  - local: protoc-gen-es
    out: app/generated
    opt:
      - target=ts
      - import_extension=js
sh
pnpm buf generate                  # proto/*.proto → app/generated/*_pb.ts
pnpm buf build -o proto/app.binpb  # the descriptor set, if you load one

Generation is a server-side step: the generated files are ordinary modules, and nothing that reaches the browser needs a build to run.

Messages are @bufbuild/protobuf messages. Decoding generates no code at runtime — it works under a script-src without 'unsafe-eval', Blackhole's default — keeps the fields it does not know (decode(schema, bytes, { readUnknownFields: false }) drops them), and stops at a nesting depth of 100.

Configure ​

ts
// config/protobuf.ts
import { defineConfig } from '@c9up/neutrino'
import app from '@c9up/ream/services/app'
import { file_echo } from '#generated/echo_pb.js'

export default defineConfig({
  descriptorSets: [app.makePath('proto/app.binpb')],
  files: [file_echo],
})

defineConfig refuses a config that loads no schema.

Two sources that declare the same type differently stop the start with E_NEUTRINO_DUPLICATE_TYPE, naming both — a stale copy of a .proto loaded after the current one would otherwise decode every message of that type with the wrong fields. The same file loaded twice is fine, compared on what affects the wire: the source positions buf keeps in a descriptor set do not count.

Register the provider ​

ts
// reamrc.ts
providers: [() => import('@c9up/neutrino/provider')]

The schemas load at boot, so a missing file or a conflict stops the start rather than the first request that needs a message type. The provider binds the schemas as protobuf and the gRPC services as grpc, and hands the gRPC dispatcher to the server.

Encode and decode ​

ts
import { create } from '@bufbuild/protobuf'
import protobuf from '@c9up/neutrino/services/main'
import { SayRequestSchema } from '#generated/echo_pb.js'

const bytes = protobuf.encode(SayRequestSchema, create(SayRequestSchema, { text: 'hi' }))
const request = protobuf.decode(SayRequestSchema, bytes)

protobuf.message('echo.SayRequest') // a schema by type name
protobuf.service('echo.Echo')       // a service by name
protobuf.method('/echo.Echo/Say')   // a method by gRPC path: input, output, kind

Bytes that do not decode — truncated, malformed, invalid UTF-8 in a string, nested too deep — raise E_NEUTRINO_INVALID_MESSAGE: the error a transport answers with a client error.

gRPC services ​

Register services in a preload, which runs after the provider has booted:

ts
// start/grpc.ts
import { errors, GrpcStatus } from '@c9up/neutrino'
import grpc from '@c9up/neutrino/services/grpc'
import { Echo } from '#generated/echo_pb.js'

grpc.service(Echo, {
  say(request) {
    if (request.times > 100) {
      throw new errors.E_NEUTRINO_GRPC_STATUS(GrpcStatus.INVALID_ARGUMENT, 'times must be at most 100')
    }
    return { text: request.text.repeat(request.times) }
  },
})
  • With a service generated by protoc-gen-es, requests and replies are typed from the .proto: a wrong reply, a misspelt method or a streaming method is a compile error.
  • A service from a descriptor set is reached with protobuf.service('echo.Echo'); its requests are untyped messages.
  • An implementation can be an object literal or a class instance; its methods are called on it.
  • A method left out answers UNIMPLEMENTED.
  • An E_NEUTRINO_GRPC_STATUS is answered with its status and message. Any other error is answered INTERNAL without its message, and reported — to console.error unless new GrpcServices(protobuf, { onError }) says otherwise.
  • Registration refuses what would otherwise fail quietly later: a misspelt method name, a streaming method, a service registered twice.
  • A request is decoded without the fields its schema does not know: each would cost an object, so a 4 MiB request made of them would hold some 300 MB. grpc: { keepUnknownFields: true } keeps them, for a method that forwards its request elsewhere.

Unary methods only for now. Streaming methods are refused at registration.

Each call crosses to JavaScript once, in bytes, and never goes through the HTTP body limit or the body parser.

The call context ​

A method (and an interceptor) receives the call's context:

  • context.metadata.get(key) — every value of a metadata key, in order; [] when absent. Keys ending in -bin are decoded to Uint8Array (a value that is not base64 is answered INTERNAL). context.metadata.getMap() gives the first value of each key. The transport's own headers — content-type, te, grpc-timeout, grpc-encoding, grpc-accept-encoding, accept-encoding — are not metadata.
  • context.ip — the client IP, by the trusted-proxy rules of request.ip().
  • context.deadline — when the client stops waiting, from its grpc-timeout, in epoch milliseconds; Infinity without one. Past it the call is answered DEADLINE_EXCEEDED; a malformed grpc-timeout is answered INTERNAL.
  • context.signal — aborted when the call is answered without the method: its deadline passed, or the client cancelled it. Hand it to the query or the HTTP call the method waits on, so that the work stops with the call.

Message size ​

ts
// config/protobuf.ts
export default defineConfig({
  descriptorSets: [app.makePath('proto/app.binpb')],
  grpc: {
    maxReceiveMessageLength: 1024 * 1024, // default 4 MiB; -1: no limit
    maxSendMessageLength: 8 * 1024 * 1024, // default -1: no limit
    maxInFlightRequestBytes: 16 * 1024 * 1024, // default 8 MiB; -1: no limit
  },
})

A request past maxReceiveMessageLength is answered RESOURCE_EXHAUSTED before any interceptor runs; a reply past maxSendMessageLength is answered RESOURCE_EXHAUSTED instead of being sent. A value that is not a whole number of bytes (or -1) stops the start. The native server applies the same limits: a request is refused on its length prefix, before the message is read.

The message limit alone does not bound memory. A decoded request is far larger than its bytes: every element of a repeated message field becomes a full object with every field set to its default, so a 4 MiB request of empty elements holds some 280 MB of heap, and a few such calls at once exhaust a process. maxInFlightRequestBytes bounds the request bytes decoded and held at once, over every call whose method has not finished: a call that would go past it is answered RESOURCE_EXHAUSTED before any interceptor runs or any byte is decoded. A call is always admitted when nothing else is in flight, and a call answered DEADLINE_EXCEEDED or CANCELLED stays counted until its method stops, since the method still holds its request. Clients see RESOURCE_EXHAUSTED as a signal to retry later.

The request side of a call must arrive whole — one message, then the end of the stream — within the server's requestTimeout (config/app.ts → http), or the call is answered DEADLINE_EXCEEDED. A second message is answered UNIMPLEMENTED and request trailers INTERNAL, before the method runs: the metadata is the request headers only.

Protecting calls ​

Middleware and the router never see a gRPC call. Authentication, rate limiting, anything a middleware does for HTTP has to be done again for gRPC — with interceptors.

An interceptor runs around every call it is registered for, before the request is even decoded: a call it refuses never has its bytes read. It refuses by throwing an E_NEUTRINO_GRPC_STATUS, lets the call through by returning next(), and hands the method a value through a GrpcContextKey.

ts
grpc.use(async (context, next) => {          // every service
  if (context.ip.startsWith('10.')) return next()
  throw new errors.E_NEUTRINO_GRPC_STATUS(GrpcStatus.PERMISSION_DENIED, 'internal only')
})

grpc.service(Admin, impl, { interceptors: [audit] })   // this service only

Interceptors run in order: those given to use(), then the service's own. A call to a method nobody serves is answered UNIMPLEMENTED without running any.

Two come with the package. Both take the protecting object structurally, so Neutrino imports neither Warden nor Blackhole:

ts
import app from '@c9up/ream/services/app'
import auth from '@c9up/warden/services/main'
import { bearerAuth, rateLimit } from '@c9up/neutrino'

grpc.use(rateLimit(await app.container.make('blackhole')))

const signedIn = bearerAuth(auth, { guard: 'jwt' })
grpc.service(
  Account,
  { me: (_request, context) => ({ id: signedIn.user(context).id }) },
  { interceptors: [signedIn.interceptor] },
)
  • bearerAuth(verifier, { guard }) checks authorization: Bearer <token> with anything that has verify(token, guard) — Warden's auth manager as it is. A missing, malformed or refused token is answered UNAUTHENTICATED, and so is a call carrying two authorization values; a verifier that breaks is answered INTERNAL. signedIn.user(context) returns the user, and fails closed in a method the interceptor did not protect.
  • rateLimit(limiter, { keyFor }) counts with anything that has checkRateLimit(key) — Blackhole with a rateLimit.store configured. Over the limit, the call is answered RESOURCE_EXHAUSTED. The key defaults to the client IP, the key Blackhole counts HTTP requests under: with the same store, a client has one budget for both. Without a store, Blackhole counts in its native engine, per HTTP request, and that count cannot be reached from a gRPC call.

In production ​

Terminate TLS at the reverse proxy and forward gRPC as plaintext HTTP/2 to the port the HTTP traffic goes to. With nginx:

nginx
server {
  listen 443 ssl;
  http2 on;
  location / {
    if ($content_type ~ "^application/grpc") {
      grpc_pass grpc://127.0.0.1:3000;
    }
    proxy_pass http://127.0.0.1:3000;
  }
}

Services inside the same network can call the application's port directly: it accepts HTTP/2 without TLS.

Not here yet ​

  • Streaming methods — server, client and bidirectional.
  • gRPC-web — browsers cannot speak gRPC directly.
  • Protobuf over REST — an application/x-protobuf body on an ordinary route.