protobuf 0.0.1-preview.1
Protocol Buffers and gRPC
protobuf#
A Protocol Buffers (.proto) code generator, wire-format runtime, and gRPC / gRPC-fallback transports for Zena.
Installation#
zena pkg add @zena/protobuf
Generating Code#
protobuf/generator compiles .proto schemas into Zena source code with no I/O of its own—you supply the entry file paths and a callback that reads imported .proto files:
import { generate } from 'protobuf/generator';
let source = await generate({
files: ['service.proto'],
read: async (path) => readProtoFile(path),
});
Options (GenerateOptions)#
files:Array<String>— entry.protofiles to generate from.read:(path: String) => Future<String | null>— returns the.prototext forpath, ornullif not found.roots:Array<String>(optional) — generate only the named messages, enums, or services (by full name) and the types they transitively reference. When omitted or empty, everything declared infilesis generated.runtimeImport:String(optional) — module specifier that generated code imports runtime helpers from (defaults to'protobuf/runtime').
Using Generated Code#
For each message M, the generator emits a view class M (which reads an encoded message in place without eagerly allocating child objects) and a record type MInit, which M.of encodes:
import { HashMap } from 'zena:collections';
// Decoding wire bytes
let doc = Document.decode(bytes);
let title = doc.fields.getOr('title', Value.of({}));
let text = match (title.valueType) {
case ValueStringValue {value}: value
case _: ''
};
// Encoding a message
let fields = new HashMap<String, Value>();
fields['title'] = Value.of({stringValue: 'Hello'});
let encoded = Document.of({name, fields}).protoView.toByteArray();
A message-typed field accepts the message's class, so nested messages are built inside out with M.of, and a message read from one response can be passed into another message unchanged without re-encoding.
Services and Transports#
For each service in a .proto file, the generator emits a client class over ProtoTransport (protobuf/runtime). Two transports speak over wasi:http, both supporting unary and server-streaming RPCs (and GrpcTransport also supporting client-streaming RPCs):
protobuf/grpc(GrpcTransport): standard gRPC over HTTP/2 (https://via ALPN or cleartext HTTP/2 forhttp://).protobuf/fallback(FallbackTransport): Google's gRPC HTTP/1.1$rpcfallback protocol (binary protobuf posted to/$rpc/<service>/<method>), usable on hosts whose outgoing HTTP is HTTP/1.1 only.
import { GrpcTransport } from 'protobuf/grpc';
let transport = new GrpcTransport('https://example.googleapis.com', credentials);
let client = new MyServiceClient(transport);
let response = await client.getItem({name: 'items/1'});
credentials is any Credentials (protobuf/runtime), which supplies the authorization header before each call. Generated clients also populate the x-goog-request-params routing header from google.api.http and google.api.routing options (AIP-4222). Failed calls throw RpcError (protobuf/runtime) carrying the google.rpc.Code.
Libraries#
protobuf/runtime— Wire-format views and writers (ProtoView,ProtoWriter,ProtoList,ProtoMap,ProtoBytes,ProtoStream),ProtoTransport,Credentials,RpcMetadata,RpcMethod, andRpcError.protobuf/grpc—GrpcTransportover HTTP/2.protobuf/fallback—FallbackTransportover Google's HTTP/1.1$rpcfallback protocol.protobuf/generator—generateandGenerateOptionsfor turning.protofiles into Zena source.protobuf/parserandprotobuf/lexer—.protosyntax tree and tokenizer (parseProto,Lexer).protobuf/schemaandprotobuf/emitter— Schema resolution and Zena code emission.protobuf/text— Protobuf text format helpers.
License#
MIT
/**
* Generates Zena source from `.proto` files.
*
* import {generate} from 'protobuf/generator';
* let source = generate({
* files: ['google/firestore/v1/firestore.proto'],
* read: (path) => ...,
* });
*
* The generator does no I/O; `read` supplies every file, including
* imports, by its import path. See docs/design/protobuf.md for the shape
* of the generated code.
*/
import {Future} from 'zena:async';
import {joinStrings} from './text.zena';
import {emitModule} from './emitter.zena';
import {loadSchema, markReached} from './schema.zena';
export {SchemaError} from './schema.zena';
export {ParseError} from './parser.zena';
export {LexError} from './lexer.zena';
/** What to generate. */
export type GenerateOptions = {
/** The files whose declarations are generated, by import path. */
files: Array<String>,
/** A file's source by import path, or null when there is no such file. */
read: (path: String) => Future<String | null>,
/**
* Full names of the messages, enums and services to generate, with
* everything they refer to. When absent, every declaration in `files`.
*/
roots?: Array<String>,
/** The specifier the generated module imports the runtime from. */
runtimeImport?: String
};
/** Generates one Zena module from `options.files`. */
export async function generate(options: GenerateOptions): Future<String> {
var roots: Array<String> = new GrowableArray<String>();
if (let {roots as given} = options) {
roots = given;
}
var runtimeImport = 'protobuf/runtime';
if (let {runtimeImport as given} = options) {
runtimeImport = given;
}
let schema = await loadSchema(options.files, options.read);
let services = markReached(schema, roots);
let primary = if (schema.rootFiles.length > 0) schema.rootFiles[0].package else '';
return emitModule(schema, services, primary, runtimeImport, joinStrings(options.files, ', '));
}
| Version | Published | Dependencies | Approved by |
|---|---|---|---|
| 0.0.1-preview.1 | 2026-11-19 | none |
|