Skip to content

neutrino ​

@c9up/neutrino: Protocol Buffers and unary gRPC, so that non-JS clients share one .proto contract with the server; gRPC calls are served on the application's HTTP port. Guide: Protobuf and gRPC.

Installation ​

bash
pnpm add @c9up/neutrino

Register the provider in reamrc.ts (providers: [() => import('@c9up/neutrino/provider')]) and write config/protobuf.ts yourself: the package has no configure hook. Messages are @bufbuild/protobuf messages; typed messages and services come from protoc-gen-es (pnpm add -D @bufbuild/buf @bufbuild/protoc-gen-es).

Entry points ​

ImportContents
@c9up/neutrinoProtobuf, GrpcServices, the interceptors, defineConfig, the errors and the types.
@c9up/neutrino/providerNeutrinoProvider (default export): loads the schemas at boot and serves gRPC on the HTTP port.
@c9up/neutrino/services/mainThe booted Protobuf (default export), plus setProtobuf, getProtobuf, clearProtobuf.
@c9up/neutrino/services/grpcThe booted GrpcServices (default export), plus setGrpc, getGrpc, clearGrpc.

The two service modules resolve the instance on first member access; reading one before the provider has booted throws.

Exports ​

@c9up/neutrino ​

ExportKindDescription
ProtobufclassThe loaded schemas and their codec.
GrpcServicesclassThe gRPC services served, and the dispatcher handed to the server.
GrpcMetadataclassA call's metadata, -bin values decoded.
GrpcStatusconstThe gRPC status codes, OK: 0 to UNAUTHENTICATED: 16.
GrpcContextKeyclassA value an interceptor sets on a call for the method to read.
bearerAuthfunctionInterceptor that requires authorization: Bearer <token>.
rateLimitfunctionInterceptor that answers RESOURCE_EXHAUSTED over the limit.
defineConfigfunctiondefineConfig(config: ProtobufConfig): ProtobufConfig. Throws when no schema is given.
errorsnamespaceThe package's errors, one class per code, see Errors
ProtobufConfiginterfaceThe shape of config/protobuf.ts.
GrpcConfigtypeThe GrpcServicesOptions a config can set: keepUnknownFields, maxReceiveMessageLength, maxSendMessageLength, maxInFlightRequestBytes.
ProtobufSourcesinterface{ descriptorSets?: readonly Uint8Array[]; files?: readonly DescFile[] }.
DecodeOptionsinterface{ readUnknownFields?: boolean }, true by default.
GrpcServicesOptionsinterfaceSee GrpcServices.
ServiceImpltypeOne function per method, keyed by the method's local name (say for rpc Say); typed from a generated service.
ServiceOptionsinterface{ interceptors?: readonly GrpcInterceptor[] }.
UntypedMethodtype(request: Message, context: GrpcContext) => Promise<Record<string, unknown>> | Record<string, unknown>: a method of a service loaded from a descriptor set.
GrpcInterceptortype(context: GrpcContext, next: () => Promise<unknown>) => Promise<unknown>.
GrpcContextinterfaceWhat a method receives beside the request.
GrpcCallinterfaceOne call as the server hands it over: { path: string; metadata: Readonly<Record<string, string | readonly string[]>>; message: Uint8Array; ip: string; signal?: AbortSignal }.
GrpcReplytype{ message: Uint8Array } | { code: number; details: string }.
GrpcStatusCodetypeA value of GrpcStatus.
MetadataValuetypestring | Uint8Array.
BearerAuthinterfaceWhat bearerAuth returns.
TokenVerifierinterfaceWhat bearerAuth takes; warden's auth manager fits.
CallLimiterinterfaceWhat rateLimit takes; blackhole with a rateLimit.store fits.

Protobuf ​

MemberSignatureDescription
constructornew Protobuf(sources: ProtobufSources)Two sources that declare one type differently throw E_NEUTRINO_DUPLICATE_TYPE; the same file twice is accepted.
messagemessage(typeName: string): DescMessageA message schema by full name (package.Message).
serviceservice(typeName: string): DescServiceA service by full name.
methodmethod(path: string): DescMethodThe method a gRPC path names (/package.Service/Method).
decodedecode<Desc extends DescMessage>(schema: Desc, bytes: Uint8Array, options?: DecodeOptions): MessageShape<Desc>Throws E_NEUTRINO_INVALID_MESSAGE on bytes that do not decode (truncated, malformed, invalid UTF-8, nested too deep).
encodeencode<Desc extends DescMessage>(schema: Desc, message: MessageShape<Desc>): Uint8Array

GrpcServices ​

MemberSignatureDescription
constructornew GrpcServices(protobuf: Protobuf, options?: GrpcServicesOptions)
useuse(interceptor: GrpcInterceptor): thisRuns around every call, in the order added, before the request is decoded.
serviceservice<S extends DescService>(service: S, impl: ServiceImpl<S>, options?: ServiceOptions): thisServes a service. A method left out answers UNIMPLEMENTED. Refuses a key that is not a method of the service, a non-function implementation, a streaming method and a service registered twice.
handlereadonly handle: (call: GrpcCall) => Promise<GrpcReply>Serves one call; the function the provider hands to the server.

An E_NEUTRINO_GRPC_STATUS is answered with its grpcStatus and message. Any other error is answered INTERNAL without its message and passed to onError.

GrpcServicesOptionsTypeDefaultDescription
onError(error: unknown, call: { path: string }) => voidconsole.errorTold about every error that is not an E_NEUTRINO_GRPC_STATUS.
keepUnknownFieldsbooleanfalseKeep the request fields the schema does not know.
maxReceiveMessageLengthnumber4194304 (4 MiB)Largest request, in bytes; -1 for no limit. A larger one is answered RESOURCE_EXHAUSTED before any interceptor.
maxSendMessageLengthnumber-1Largest reply, in bytes; -1 for no limit.
maxInFlightRequestBytesnumber8388608 (8 MiB)Request bytes decoded and held at once, over every call still running; -1 for no limit. A call is always admitted when nothing else is in flight.

GrpcContext ​

MemberSignatureDescription
metadatareadonly metadata: GrpcMetadataRequest metadata, without the transport's headers (content-type, te, grpc-timeout, grpc-encoding, grpc-accept-encoding, accept-encoding).
ipreadonly ip: stringResolved client IP.
methodreadonly method: DescMethodThe method called.
deadlinereadonly deadline: numberEpoch milliseconds from the client's grpc-timeout; Infinity without one. Past it the call is answered DEADLINE_EXCEEDED.
signalreadonly signal: AbortSignalAborted when the call is answered without the method (deadline passed, client cancelled). Pass it on to what the method waits for.

GrpcMetadata ​

MemberSignatureDescription
constructornew GrpcMetadata(headers?: Readonly<Record<string, string | readonly string[]>>)Throws E_NEUTRINO_INVALID_METADATA (with key) on a -bin value that is not base64.
getget(key: string): MetadataValue[]Every value of the key, in order; [] when absent.
getMapgetMap(): Record<string, MetadataValue>The first value of each key.

GrpcContextKey ​

MemberSignatureDescription
constructornew GrpcContextKey<T>(fallback: T)
getget(context: GrpcContext): TThe value set on this call, or fallback.
setset(context: GrpcContext, value: T): void

Interceptors ​

FunctionSignatureDescription
bearerAuthbearerAuth<User>(verifier: TokenVerifier<User>, options?: { guard?: string }): BearerAuth<User>interceptor answers UNAUTHENTICATED without a valid bearer token, or with two authorization values. user(context) returns the user, and throws UNAUTHENTICATED on a call the interceptor did not run for.
rateLimitrateLimit(limiter: CallLimiter, options?: { keyFor?: (context: GrpcContext) => string }): GrpcInterceptorThe key is the client IP by default, the key blackhole counts HTTP requests under.
ts
interface TokenVerifier<User> {
  verify(token: string, guard?: string): Promise<{ authenticated: boolean; user?: User; strategyCrash?: boolean }>
}
interface CallLimiter {
  checkRateLimit(key: string): Promise<{ allowed: boolean; resetSeconds: number }>
}

Configuration ​

config/protobuf.ts exports defineConfig({ … }). The schemas load at boot: a missing file or a conflict stops the start.

OptionTypeDefaultDescription
descriptorSetsreadonly string[][]Paths of binary FileDescriptorSets (buf build -o app.binpb).
filesreadonly DescFile[][]File descriptors generated by protoc-gen-es (its file_* exports).
grpcGrpcConfig{}keepUnknownFields, maxReceiveMessageLength, maxSendMessageLength, maxInFlightRequestBytes, with the defaults of GrpcServicesOptions.

At least one of descriptorSets and files must name a schema. The message limits are also handed to the server, which refuses a larger message before reading it.

Container bindings ​

TokenResolves to
Protobuf (class), 'neutrino.protobuf', 'protobuf'The Protobuf over the configured schemas.
GrpcServices (class), 'neutrino.grpc', 'grpc'The GrpcServices, with the grpc config.

The string tokens are declared on ContainerBindings. At boot the provider hands grpc.handle to the server binding's grpc() method; without a server binding, nothing is served.

Errors ​

CodeRaised when
E_NEUTRINO_INVALID_DESCRIPTORThe bytes are not a valid FileDescriptorSet.
E_NEUTRINO_DUPLICATE_TYPETwo sources declare the same type differently.
E_NEUTRINO_UNKNOWN_TYPENo message or service of this name is loaded.
E_NEUTRINO_UNKNOWN_METHODNo method of this path is loaded, or an implementation names a method the service does not have.
E_NEUTRINO_INVALID_MESSAGEThe bytes are not a valid message of the type.
E_NEUTRINO_INVALID_METADATAA -bin metadata value is not base64; the call is answered INTERNAL.
E_NEUTRINO_GRPC_STATUSThrown by a method or an interceptor to answer a gRPC status instead of a reply: new errors.E_NEUTRINO_GRPC_STATUS(GrpcStatus.NOT_FOUND, message). The status is grpcStatus; the message goes to the client.
E_NEUTRINO_DUPLICATE_SERVICEA service is registered twice.
E_NEUTRINO_INVALID_IMPLEMENTATIONA method implementation is not a function.
E_NEUTRINO_STREAMING_UNSUPPORTEDA streaming method was implemented; only unary methods are served.
E_NEUTRINO_INVALID_OPTIONA size option is not a whole number of bytes, or -1.
E_NEUTRINO_GRPC_UNSUPPORTEDThe server has no grpc() method. Upgrade @c9up/ream.
E_NEUTRINO_INVALID_CONFIGdefineConfig loads no schema, or config/protobuf.ts does not export defineConfig's shape.
E_NEUTRINO_MISSING_CONFIGconfig/protobuf.ts is missing at boot.
E_NEUTRINO_INVALID_BINDINGThe container returned something else for the Protobuf or GrpcServices token.
E_NEUTRINO_NOT_BOOTED@c9up/neutrino/services/main or services/grpc was used before NeutrinoProvider booted.
E_NEUTRINO_INVALID_REPLYA method, or an interceptor, returned something other than a message object; the call is answered INTERNAL and the error goes to onError.
E_NEUTRINO_NEXT_CALLED_TWICEAn interceptor called next() more than once; the call is answered INTERNAL.
E_NEUTRINO_VERIFIER_FAILEDThe bearerAuth token verifier itself failed; the call is answered INTERNAL.

Migration ​

  • NeutrinoError is gone, and so are InvalidDescriptorError, DuplicateTypeError, UnknownTypeError, UnknownMethodError, InvalidMessageError and InvalidMetadataError: test error.code, or error instanceof errors.E_NEUTRINO_* with import { errors } from '@c9up/neutrino'.
  • GrpcError is now errors.E_NEUTRINO_GRPC_STATUS, built the same way: throw new errors.E_NEUTRINO_GRPC_STATUS(GrpcStatus.NOT_FOUND, 'no such text'). Its gRPC status moved from status to grpcStatus; status is now the HTTP status, as on every error.

See also ​