- TypeScript 100%
- Shell <1%
Swift Service Protobuf #
This is a Protobuf plugin intended to be used alongside Swift Protobuf.
This project currently isn't published anywhere so to set it up, you'll need Node.js and pnpm and to follow these steps:
- Clone this repo
- Open a terminal in the repo folder and run
pnpm install - Run
pnpm link
And then to use it:
protoc --swift-service_out=. path/to/target.proto
This will emit a services.pb.swift file which is intended to be used alongside .pb.swift files generated by Swift Protobuf.
This project is extremely alpha and only works in limited cases. I only developed it exactly enough for it to be useful to me.
Example #
Input:
syntax = "proto3";
service Foo {
rpc bar(Baz) returns (Qux);
}
message Baz {}
message Qux {}
Output:
import Foundation
import SwiftProtobuf
class ProtoBufInvalidMethodError: Error {}
protocol ProtoBufRpc {
func request(_ serviceName: String, _ methodName: String, _ input: Data) async throws -> Data
}
protocol Foo {
func bar(_: Baz) async throws -> Qux
}
extension Foo {
func call(method methodName: String, input: Data) async throws -> Data {
if methodName == "bar" {
return try (try await self.bar(try Baz(serializedBytes: input))).serializedData()
}
throw ProtoBufInvalidMethodError()
}
}
struct FooRpc: Foo {
let rpc: ProtoBufRpc
func bar(_ input: Baz) async throws -> Qux {
return try Qux(serializedBytes: try await rpc.request("Foo", "bar", input.serializedData()))
}
}
Handling RPC Calls #
Going by the example above, to handle received RPC calls, you'll need to write a class that conforms to Foo. Get an
instance of that class and .call() it with the method name, and input data. You'll then need to reply to the RPC call
with the returned output data. How you recieve the method name and input data, and respond with the output data is up to
you.
Making RPC Calls #
To be able to make RPC calls, you'll need to implement ProtoBufRpc which has a method that receives the service name,
method name, and input data, and returns output data recieved from the other side. The implementation of how it sends
the service name, method name, and input data, and receives a reply of output data is completely up to you. You'll then
need to pass an instance to construct FooRpc which you'll be able to call methods on.
This is and inspired by and modeled after ts-proto.