mirror of
https://github.com/google/flatbuffers.git
synced 2026-06-02 04:04:19 +00:00
bulk code format fix (#8707)
This commit is contained in:
@@ -1,40 +1,46 @@
|
||||
import sys
|
||||
import argparse
|
||||
import sys
|
||||
import grpc
|
||||
|
||||
sys.path.insert(0, '../../../../../flatbuffers/python')
|
||||
sys.path.insert(0, "../../../../../flatbuffers/python")
|
||||
|
||||
import flatbuffers
|
||||
from models import HelloReply, HelloRequest, greeter_grpc_fb
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("port", help="server port to connect to", default=3000)
|
||||
parser.add_argument("name", help="name to be sent to server", default="flatbuffers")
|
||||
parser.add_argument(
|
||||
"name", help="name to be sent to server", default="flatbuffers"
|
||||
)
|
||||
|
||||
|
||||
def say_hello(stub, hello_request):
|
||||
reply = stub.SayHello(hello_request)
|
||||
r = HelloReply.HelloReply.GetRootAs(reply)
|
||||
print(r.Message())
|
||||
reply = stub.SayHello(hello_request)
|
||||
r = HelloReply.HelloReply.GetRootAs(reply)
|
||||
print(r.Message())
|
||||
|
||||
|
||||
def say_many_hellos(stub, hello_request):
|
||||
greetings = stub.SayManyHellos(hello_request)
|
||||
for greeting in greetings:
|
||||
r = HelloReply.HelloReply.GetRootAs(greeting)
|
||||
print(r.Message())
|
||||
greetings = stub.SayManyHellos(hello_request)
|
||||
for greeting in greetings:
|
||||
r = HelloReply.HelloReply.GetRootAs(greeting)
|
||||
print(r.Message())
|
||||
|
||||
|
||||
def main():
|
||||
args = parser.parse_args()
|
||||
args = parser.parse_args()
|
||||
|
||||
with grpc.insecure_channel('localhost:' + args.port) as channel:
|
||||
builder = flatbuffers.Builder()
|
||||
ind = builder.CreateString(args.name)
|
||||
HelloRequest.HelloRequestStart(builder)
|
||||
HelloRequest.HelloRequestAddName(builder, ind)
|
||||
root = HelloRequest.HelloRequestEnd(builder)
|
||||
builder.Finish(root)
|
||||
output = bytes(builder.Output())
|
||||
stub = greeter_grpc_fb.GreeterStub(channel)
|
||||
say_hello(stub, output)
|
||||
say_many_hellos(stub, output)
|
||||
with grpc.insecure_channel("localhost:" + args.port) as channel:
|
||||
builder = flatbuffers.Builder()
|
||||
ind = builder.CreateString(args.name)
|
||||
HelloRequest.HelloRequestStart(builder)
|
||||
HelloRequest.HelloRequestAddName(builder, ind)
|
||||
root = HelloRequest.HelloRequestEnd(builder)
|
||||
builder.Finish(root)
|
||||
output = bytes(builder.Output())
|
||||
stub = greeter_grpc_fb.GreeterStub(channel)
|
||||
say_hello(stub, output)
|
||||
say_many_hellos(stub, output)
|
||||
|
||||
main()
|
||||
|
||||
main()
|
||||
|
||||
@@ -2,30 +2,29 @@
|
||||
|
||||
import flatbuffers
|
||||
import grpc
|
||||
|
||||
from models.HelloReply import HelloReply
|
||||
from models.HelloRequest import HelloRequest
|
||||
|
||||
|
||||
class GreeterStub(object):
|
||||
'''Interface exported by the server.'''
|
||||
"""Interface exported by the server."""
|
||||
|
||||
def __init__(self, channel):
|
||||
'''Constructor.
|
||||
"""Constructor.
|
||||
|
||||
Args:
|
||||
channel: A grpc.Channel.
|
||||
'''
|
||||
"""
|
||||
|
||||
self.SayHello = channel.unary_unary(
|
||||
method='/models.Greeter/SayHello')
|
||||
self.SayHello = channel.unary_unary(method='/models.Greeter/SayHello')
|
||||
|
||||
self.SayManyHellos = channel.unary_stream(
|
||||
method='/models.Greeter/SayManyHellos')
|
||||
method='/models.Greeter/SayManyHellos'
|
||||
)
|
||||
|
||||
|
||||
class GreeterServicer(object):
|
||||
'''Interface exported by the server.'''
|
||||
"""Interface exported by the server."""
|
||||
|
||||
def SayHello(self, request, context):
|
||||
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
|
||||
@@ -40,15 +39,14 @@ class GreeterServicer(object):
|
||||
|
||||
def add_GreeterServicer_to_server(servicer, server):
|
||||
rpc_method_handlers = {
|
||||
'SayHello': grpc.unary_unary_rpc_method_handler(
|
||||
servicer.SayHello),
|
||||
'SayManyHellos': grpc.unary_stream_rpc_method_handler(
|
||||
servicer.SayManyHellos),
|
||||
'SayHello': grpc.unary_unary_rpc_method_handler(servicer.SayHello),
|
||||
'SayManyHellos': grpc.unary_stream_rpc_method_handler(
|
||||
servicer.SayManyHellos
|
||||
),
|
||||
}
|
||||
|
||||
generic_handler = grpc.method_handlers_generic_handler(
|
||||
'models.Greeter', rpc_method_handlers)
|
||||
'models.Greeter', rpc_method_handlers
|
||||
)
|
||||
|
||||
server.add_generic_rpc_handlers((generic_handler,))
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
from concurrent import futures
|
||||
import sys
|
||||
import argparse
|
||||
from concurrent import futures
|
||||
import sys
|
||||
import grpc
|
||||
|
||||
sys.path.insert(0, '../../../../../flatbuffers/python')
|
||||
sys.path.insert(0, "../../../../../flatbuffers/python")
|
||||
|
||||
import flatbuffers
|
||||
from models import HelloReply, HelloRequest, greeter_grpc_fb
|
||||
@@ -11,47 +11,48 @@ from models import HelloReply, HelloRequest, greeter_grpc_fb
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("port", help="server on port", default=3000)
|
||||
|
||||
|
||||
def build_reply(message):
|
||||
builder = flatbuffers.Builder()
|
||||
ind = builder.CreateString(message)
|
||||
HelloReply.HelloReplyStart(builder)
|
||||
HelloReply.HelloReplyAddMessage(builder, ind)
|
||||
root = HelloReply.HelloReplyEnd(builder)
|
||||
builder.Finish(root)
|
||||
return bytes(builder.Output())
|
||||
builder = flatbuffers.Builder()
|
||||
ind = builder.CreateString(message)
|
||||
HelloReply.HelloReplyStart(builder)
|
||||
HelloReply.HelloReplyAddMessage(builder, ind)
|
||||
root = HelloReply.HelloReplyEnd(builder)
|
||||
builder.Finish(root)
|
||||
return bytes(builder.Output())
|
||||
|
||||
|
||||
class GreeterServicer(greeter_grpc_fb.GreeterServicer):
|
||||
|
||||
def __init__(self):
|
||||
self.greetings = ["Hi", "Hallo", "Ciao"]
|
||||
def __init__(self):
|
||||
self.greetings = ["Hi", "Hallo", "Ciao"]
|
||||
|
||||
def SayHello(self, request, context):
|
||||
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
|
||||
reply = "Unknown"
|
||||
if r.Name():
|
||||
reply = r.Name()
|
||||
return build_reply("welcome " + reply.decode('UTF-8'))
|
||||
def SayHello(self, request, context):
|
||||
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
|
||||
reply = "Unknown"
|
||||
if r.Name():
|
||||
reply = r.Name()
|
||||
return build_reply("welcome " + reply.decode("UTF-8"))
|
||||
|
||||
def SayManyHellos(self, request, context):
|
||||
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
|
||||
reply = "Unknown"
|
||||
if r.Name():
|
||||
reply = r.Name()
|
||||
def SayManyHellos(self, request, context):
|
||||
r = HelloRequest.HelloRequest().GetRootAs(request, 0)
|
||||
reply = "Unknown"
|
||||
if r.Name():
|
||||
reply = r.Name()
|
||||
|
||||
for greeting in self.greetings:
|
||||
print(type(reply))
|
||||
yield build_reply(greeting + " " + reply.decode("UTF-8"))
|
||||
|
||||
for greeting in self.greetings:
|
||||
print(type(reply))
|
||||
yield build_reply(greeting + " " + reply.decode('UTF-8'))
|
||||
|
||||
|
||||
def serve():
|
||||
args = parser.parse_args()
|
||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
|
||||
greeter_grpc_fb.add_GreeterServicer_to_server(
|
||||
GreeterServicer(), server
|
||||
)
|
||||
server.add_insecure_port('[::]:' + args.port)
|
||||
server.start()
|
||||
server.wait_for_termination()
|
||||
args = parser.parse_args()
|
||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
|
||||
greeter_grpc_fb.add_GreeterServicer_to_server(GreeterServicer(), server)
|
||||
server.add_insecure_port("[::]:" + args.port)
|
||||
server.start()
|
||||
server.wait_for_termination()
|
||||
|
||||
if __name__ == '__main__':
|
||||
serve()
|
||||
|
||||
if __name__ == "__main__":
|
||||
serve()
|
||||
|
||||
@@ -37,7 +37,8 @@ func greet(name: String, client greeter: models_GreeterServiceClient) {
|
||||
builder.finish(offset: root)
|
||||
|
||||
// Make the RPC call to the server.
|
||||
let sayHello = greeter
|
||||
let sayHello =
|
||||
greeter
|
||||
.SayHello(Message<models_HelloRequest>(builder: &builder))
|
||||
|
||||
// wait() on the response to stop the program from exiting before the response is received.
|
||||
@@ -76,7 +77,7 @@ func main(args: [String]) {
|
||||
print("Usage: PORT [NAME]")
|
||||
exit(1)
|
||||
|
||||
case let (.some(port), name):
|
||||
case (.some(let port), let name):
|
||||
// Setup an `EventLoopGroup` for the connection to run on.
|
||||
//
|
||||
// See: https://github.com/apple/swift-nio#eventloops-and-eventloopgroups
|
||||
|
||||
@@ -32,7 +32,8 @@ class Greeter: models_GreeterProvider {
|
||||
|
||||
func SayHello(
|
||||
request: Message<models_HelloRequest>,
|
||||
context: StatusOnlyCallContext)
|
||||
context: StatusOnlyCallContext
|
||||
)
|
||||
-> EventLoopFuture<Message<models_HelloReply>>
|
||||
{
|
||||
let recipient = request.object.name ?? "Stranger"
|
||||
@@ -47,12 +48,14 @@ class Greeter: models_GreeterProvider {
|
||||
|
||||
func SayManyHellos(
|
||||
request: Message<models_HelloRequest>,
|
||||
context: StreamingResponseCallContext<Message<models_HelloReply>>)
|
||||
context: StreamingResponseCallContext<Message<models_HelloReply>>
|
||||
)
|
||||
-> EventLoopFuture<GRPCStatus>
|
||||
{
|
||||
for name in greetings {
|
||||
var builder = FlatBufferBuilder()
|
||||
let off = builder
|
||||
let off =
|
||||
builder
|
||||
.create(string: "\(name) \(request.object.name ?? "Unknown")")
|
||||
let root = models_HelloReply.createHelloReply(
|
||||
&builder,
|
||||
|
||||
@@ -1,34 +1,39 @@
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import * as flatbuffers from 'flatbuffers';
|
||||
import { HelloReply } from './models/hello-reply';
|
||||
import { HelloRequest } from './models/hello-request';
|
||||
import { GreeterClient } from './greeter_grpc';
|
||||
import {GreeterClient} from './greeter_grpc';
|
||||
import {HelloReply} from './models/hello-reply';
|
||||
import {HelloRequest} from './models/hello-request';
|
||||
|
||||
async function main(PORT: Number, name: string) {
|
||||
const client = new GreeterClient(`localhost:${PORT}`, grpc.credentials.createInsecure());
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(name);
|
||||
const root = HelloRequest.createHelloRequest(builder, offset);
|
||||
builder.finish(root);
|
||||
const buffer = HelloRequest.getRootAsHelloRequest(new flatbuffers.ByteBuffer(builder.asUint8Array()));
|
||||
const client = new GreeterClient(
|
||||
`localhost:${PORT}`,
|
||||
grpc.credentials.createInsecure(),
|
||||
);
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(name);
|
||||
const root = HelloRequest.createHelloRequest(builder, offset);
|
||||
builder.finish(root);
|
||||
const buffer = HelloRequest.getRootAsHelloRequest(
|
||||
new flatbuffers.ByteBuffer(builder.asUint8Array()),
|
||||
);
|
||||
|
||||
client.SayHello(buffer, (err, response) => {
|
||||
console.log(response.message());
|
||||
});
|
||||
client.SayHello(buffer, (err, response) => {
|
||||
console.log(response.message());
|
||||
});
|
||||
|
||||
const data = client.SayManyHellos(buffer, null);
|
||||
const data = client.SayManyHellos(buffer, null);
|
||||
|
||||
data.on('data', (data) => {
|
||||
console.log(data.message());
|
||||
});
|
||||
data.on('data', (data) => {
|
||||
console.log(data.message());
|
||||
});
|
||||
}
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const args = process.argv.slice(2);
|
||||
const PORT = Number(args[0]);
|
||||
const name: string = args[1] ?? "flatbuffers";
|
||||
const name: string = args[1] ?? 'flatbuffers';
|
||||
|
||||
if (PORT) {
|
||||
main(PORT, name);
|
||||
main(PORT, name);
|
||||
} else {
|
||||
throw new Error("Requires a valid port number.")
|
||||
}
|
||||
throw new Error('Requires a valid port number.');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// automatically generated by the FlatBuffers compiler, do not modify
|
||||
|
||||
export { HelloReply } from './models/hello-reply.js';
|
||||
export { HelloRequest } from './models/hello-request.js';
|
||||
export {HelloReply} from './models/hello-reply.js';
|
||||
export {HelloRequest} from './models/hello-request.js';
|
||||
|
||||
@@ -1,49 +1,63 @@
|
||||
import * as grpc from '@grpc/grpc-js';
|
||||
import * as flatbuffers from 'flatbuffers';
|
||||
import { HelloReply } from './models/hello-reply';
|
||||
import { HelloRequest } from './models/hello-request';
|
||||
import { IGreeterServer, GreeterService } from './greeter_grpc';
|
||||
import {GreeterService, IGreeterServer} from './greeter_grpc';
|
||||
import {HelloReply} from './models/hello-reply';
|
||||
import {HelloRequest} from './models/hello-request';
|
||||
|
||||
const greeter: IGreeterServer = {
|
||||
SayHello(call: grpc.ServerUnaryCall<HelloRequest, HelloReply>, callback: grpc.sendUnaryData<HelloReply>): void {
|
||||
console.log(`SayHello ${call.request.name()}`);
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(`welcome ${call.request.name()}`);
|
||||
const root = HelloReply.createHelloReply(builder, offset);
|
||||
builder.finish(root);
|
||||
callback(null, HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())));
|
||||
},
|
||||
async SayManyHellos(call: grpc.ServerWritableStream<HelloRequest, HelloReply>): Promise<void> {
|
||||
const name = call.request.name();
|
||||
console.log(`${call.request.name()} saying hi in different langagues`);
|
||||
['Hi', 'Hallo', 'Ciao'].forEach(element => {
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(`${element} ${name}`);
|
||||
const root = HelloReply.createHelloReply(builder, offset);
|
||||
builder.finish(root);
|
||||
call.write(HelloReply.getRootAsHelloReply(new flatbuffers.ByteBuffer(builder.asUint8Array())))
|
||||
});
|
||||
call.end();
|
||||
}
|
||||
}
|
||||
SayHello(
|
||||
call: grpc.ServerUnaryCall<HelloRequest, HelloReply>,
|
||||
callback: grpc.sendUnaryData<HelloReply>,
|
||||
): void {
|
||||
console.log(`SayHello ${call.request.name()}`);
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(`welcome ${call.request.name()}`);
|
||||
const root = HelloReply.createHelloReply(builder, offset);
|
||||
builder.finish(root);
|
||||
callback(
|
||||
null,
|
||||
HelloReply.getRootAsHelloReply(
|
||||
new flatbuffers.ByteBuffer(builder.asUint8Array()),
|
||||
),
|
||||
);
|
||||
},
|
||||
async SayManyHellos(
|
||||
call: grpc.ServerWritableStream<HelloRequest, HelloReply>,
|
||||
): Promise<void> {
|
||||
const name = call.request.name();
|
||||
console.log(`${call.request.name()} saying hi in different langagues`);
|
||||
['Hi', 'Hallo', 'Ciao'].forEach((element) => {
|
||||
const builder = new flatbuffers.Builder();
|
||||
const offset = builder.createString(`${element} ${name}`);
|
||||
const root = HelloReply.createHelloReply(builder, offset);
|
||||
builder.finish(root);
|
||||
call.write(
|
||||
HelloReply.getRootAsHelloReply(
|
||||
new flatbuffers.ByteBuffer(builder.asUint8Array()),
|
||||
),
|
||||
);
|
||||
});
|
||||
call.end();
|
||||
},
|
||||
};
|
||||
|
||||
function serve(): void {
|
||||
const PORT = 3000;
|
||||
const server = new grpc.Server();
|
||||
server.addService(GreeterService, greeter);
|
||||
console.log(`Listening on ${PORT}`);
|
||||
server.bindAsync(
|
||||
`localhost:${PORT}`,
|
||||
grpc.ServerCredentials.createInsecure(),
|
||||
(err: Error | null, port: number) => {
|
||||
if (err) {
|
||||
console.error(`Server error: ${err.message}`);
|
||||
} else {
|
||||
console.log(`Server bound on port: ${port}`);
|
||||
server.start();
|
||||
}
|
||||
}
|
||||
);
|
||||
const PORT = 3000;
|
||||
const server = new grpc.Server();
|
||||
server.addService(GreeterService, greeter);
|
||||
console.log(`Listening on ${PORT}`);
|
||||
server.bindAsync(
|
||||
`localhost:${PORT}`,
|
||||
grpc.ServerCredentials.createInsecure(),
|
||||
(err: Error | null, port: number) => {
|
||||
if (err) {
|
||||
console.error(`Server error: ${err.message}`);
|
||||
} else {
|
||||
console.log(`Server bound on port: ${port}`);
|
||||
server.start();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
serve();
|
||||
serve();
|
||||
|
||||
@@ -19,99 +19,99 @@ import com.google.flatbuffers.Table;
|
||||
import io.grpc.Drainable;
|
||||
import io.grpc.KnownLength;
|
||||
import io.grpc.MethodDescriptor;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
public class FlatbuffersUtils {
|
||||
abstract public static class FBExtactor <T extends Table> {
|
||||
T extract (InputStream stream) throws IOException {
|
||||
if (stream instanceof KnownLength) {
|
||||
int size = stream.available();
|
||||
ByteBuffer buffer = ByteBuffer.allocate(size);
|
||||
stream.read(buffer.array());
|
||||
return extract(buffer);
|
||||
} else
|
||||
throw new RuntimeException("The class " + stream.getClass().getCanonicalName() + " does not extend from KnownLength ");
|
||||
}
|
||||
|
||||
public abstract T extract(ByteBuffer buffer);
|
||||
|
||||
public abstract static class FBExtactor<T extends Table> {
|
||||
T extract(InputStream stream) throws IOException {
|
||||
if (stream instanceof KnownLength) {
|
||||
int size = stream.available();
|
||||
ByteBuffer buffer = ByteBuffer.allocate(size);
|
||||
stream.read(buffer.array());
|
||||
return extract(buffer);
|
||||
} else
|
||||
throw new RuntimeException(
|
||||
"The class "
|
||||
+ stream.getClass().getCanonicalName()
|
||||
+ " does not extend from KnownLength ");
|
||||
}
|
||||
|
||||
static class FBInputStream extends InputStream implements Drainable, KnownLength {
|
||||
private final ByteBuffer buffer;
|
||||
private final int size;
|
||||
@Nullable private ByteArrayInputStream inputStream;
|
||||
public abstract T extract(ByteBuffer buffer);
|
||||
}
|
||||
|
||||
FBInputStream(ByteBuffer buffer) {
|
||||
this.buffer = buffer;
|
||||
this.size = buffer.remaining();
|
||||
}
|
||||
|
||||
private void makeStreamIfNotAlready() {
|
||||
if (inputStream == null)
|
||||
inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int drainTo(OutputStream target) throws IOException {
|
||||
target.write(buffer.array(), buffer.position(), size);
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
makeStreamIfNotAlready();
|
||||
return inputStream.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
makeStreamIfNotAlready();
|
||||
if (inputStream == null) {
|
||||
if (len >= size) {
|
||||
System.arraycopy(buffer.array(), buffer.position(), b, off, size);
|
||||
return size;
|
||||
} else {
|
||||
makeStreamIfNotAlready();
|
||||
return inputStream.read(b, off, len);
|
||||
}
|
||||
} else
|
||||
return inputStream.read(b, off, len);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int available() throws IOException {
|
||||
return inputStream == null ? size : inputStream.available();
|
||||
}
|
||||
static class FBInputStream extends InputStream implements Drainable, KnownLength {
|
||||
private final ByteBuffer buffer;
|
||||
private final int size;
|
||||
@Nullable private ByteArrayInputStream inputStream;
|
||||
|
||||
FBInputStream(ByteBuffer buffer) {
|
||||
this.buffer = buffer;
|
||||
this.size = buffer.remaining();
|
||||
}
|
||||
|
||||
public static <T extends Table> MethodDescriptor.Marshaller<T> marshaller(final Class<T> clazz, final FBExtactor<T> extractor) {
|
||||
return new MethodDescriptor.ReflectableMarshaller<T>() {
|
||||
@Override
|
||||
public Class<T> getMessageClass() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream stream(T value) {
|
||||
return new FBInputStream (value.getByteBuffer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public T parse(InputStream stream) {
|
||||
try {
|
||||
return extractor.extract(stream);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
private void makeStreamIfNotAlready() {
|
||||
if (inputStream == null)
|
||||
inputStream = new ByteArrayInputStream(buffer.array(), buffer.position(), size);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int drainTo(OutputStream target) throws IOException {
|
||||
target.write(buffer.array(), buffer.position(), size);
|
||||
return size;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read() throws IOException {
|
||||
makeStreamIfNotAlready();
|
||||
return inputStream.read();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int read(byte[] b, int off, int len) throws IOException {
|
||||
makeStreamIfNotAlready();
|
||||
if (inputStream == null) {
|
||||
if (len >= size) {
|
||||
System.arraycopy(buffer.array(), buffer.position(), b, off, size);
|
||||
return size;
|
||||
} else {
|
||||
makeStreamIfNotAlready();
|
||||
return inputStream.read(b, off, len);
|
||||
}
|
||||
} else return inputStream.read(b, off, len);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int available() throws IOException {
|
||||
return inputStream == null ? size : inputStream.available();
|
||||
}
|
||||
}
|
||||
|
||||
public static <T extends Table> MethodDescriptor.Marshaller<T> marshaller(
|
||||
final Class<T> clazz, final FBExtactor<T> extractor) {
|
||||
return new MethodDescriptor.ReflectableMarshaller<T>() {
|
||||
@Override
|
||||
public Class<T> getMessageClass() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InputStream stream(T value) {
|
||||
return new FBInputStream(value.getByteBuffer());
|
||||
}
|
||||
|
||||
@Override
|
||||
public T parse(InputStream stream) {
|
||||
try {
|
||||
return extractor.extract(stream);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,21 +8,22 @@
|
||||
namespace grpc_cpp_generator {
|
||||
namespace {
|
||||
|
||||
template<class T> static grpc::string as_string(T x) {
|
||||
template <class T>
|
||||
static grpc::string as_string(T x) {
|
||||
std::ostringstream out;
|
||||
out << x;
|
||||
return out.str();
|
||||
}
|
||||
|
||||
static inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
||||
static inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
|
||||
return method->ClientStreaming() && !method->ServerStreaming();
|
||||
}
|
||||
|
||||
static inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
|
||||
static inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
|
||||
return !method->ClientStreaming() && method->ServerStreaming();
|
||||
}
|
||||
|
||||
static grpc::string FilenameIdentifier(const grpc::string &filename) {
|
||||
static grpc::string FilenameIdentifier(const grpc::string& filename) {
|
||||
grpc::string result;
|
||||
for (unsigned i = 0; i < filename.size(); i++) {
|
||||
char c = filename[i];
|
||||
@@ -38,22 +39,25 @@ static grpc::string FilenameIdentifier(const grpc::string &filename) {
|
||||
return result;
|
||||
}
|
||||
|
||||
template<class T, size_t N> static T *array_end(T (&array)[N]) {
|
||||
template <class T, size_t N>
|
||||
static T* array_end(T (&array)[N]) {
|
||||
return array + N;
|
||||
}
|
||||
|
||||
static void PrintIncludes(grpc_generator::Printer *printer,
|
||||
const std::vector<grpc::string> &headers,
|
||||
const Parameters ¶ms) {
|
||||
static void PrintIncludes(grpc_generator::Printer* printer,
|
||||
const std::vector<grpc::string>& headers,
|
||||
const Parameters& params) {
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
|
||||
vars["l"] = params.use_system_headers ? '<' : '"';
|
||||
vars["r"] = params.use_system_headers ? '>' : '"';
|
||||
|
||||
auto &s = params.grpc_search_path;
|
||||
auto& s = params.grpc_search_path;
|
||||
if (!s.empty()) {
|
||||
vars["l"] += s;
|
||||
if (s[s.size() - 1] != '/') { vars["l"] += '/'; }
|
||||
if (s[s.size() - 1] != '/') {
|
||||
vars["l"] += '/';
|
||||
}
|
||||
}
|
||||
|
||||
for (auto i = headers.begin(); i != headers.end(); i++) {
|
||||
@@ -62,12 +66,11 @@ static void PrintIncludes(grpc_generator::Printer *printer,
|
||||
}
|
||||
if (params.generate_callback_api) {
|
||||
// Callback API headers (guarded later by feature macro in emitted code).
|
||||
static const char *cb_headers[] = {
|
||||
"grpcpp/impl/codegen/callback_common.h",
|
||||
"grpcpp/impl/codegen/server_callback_handlers.h",
|
||||
"grpcpp/support/client_callback.h"
|
||||
};
|
||||
for (auto &h : cb_headers) {
|
||||
static const char* cb_headers[] = {
|
||||
"grpcpp/impl/codegen/callback_common.h",
|
||||
"grpcpp/impl/codegen/server_callback_handlers.h",
|
||||
"grpcpp/support/client_callback.h"};
|
||||
for (auto& h : cb_headers) {
|
||||
vars["h"] = h;
|
||||
printer->Print(vars, "#include $l$$h$$r$\n");
|
||||
}
|
||||
@@ -76,8 +79,8 @@ static void PrintIncludes(grpc_generator::Printer *printer,
|
||||
|
||||
} // namespace
|
||||
|
||||
grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetHeaderPrologue(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -108,25 +111,24 @@ grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetHeaderIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetHeaderIncludes(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
auto printer = file->CreatePrinter(&output);
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
|
||||
static const char *headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/async_unary_call.h",
|
||||
"grpcpp/impl/codegen/method_handler.h",
|
||||
"grpcpp/impl/codegen/proto_utils.h",
|
||||
"grpcpp/impl/codegen/rpc_method.h",
|
||||
"grpcpp/impl/codegen/service_type.h",
|
||||
"grpcpp/impl/codegen/status.h",
|
||||
"grpcpp/impl/codegen/stub_options.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h"
|
||||
};
|
||||
static const char* headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/async_unary_call.h",
|
||||
"grpcpp/impl/codegen/method_handler.h",
|
||||
"grpcpp/impl/codegen/proto_utils.h",
|
||||
"grpcpp/impl/codegen/rpc_method.h",
|
||||
"grpcpp/impl/codegen/service_type.h",
|
||||
"grpcpp/impl/codegen/status.h",
|
||||
"grpcpp/impl/codegen/stub_options.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h"};
|
||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||
PrintIncludes(printer.get(), headers, params);
|
||||
printer->Print(vars, "\n");
|
||||
@@ -153,8 +155,8 @@ grpc::string GetHeaderIncludes(grpc_generator::File *file,
|
||||
namespace {
|
||||
|
||||
static void PrintHeaderClientMethodInterfaces(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars, bool is_public) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars, bool is_public) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -163,8 +165,8 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
grpc::string prefix;
|
||||
grpc::string method_params; // extra arguments to method
|
||||
grpc::string raw_args; // extra arguments to raw version of method
|
||||
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
|
||||
{ "PrepareAsync", "", "" } };
|
||||
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
|
||||
{"PrepareAsync", "", ""}};
|
||||
|
||||
if (is_public) {
|
||||
if (method->NoStreaming()) {
|
||||
@@ -174,7 +176,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
"const $Request$& request, $Response$* response) = 0;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
printer->Print(
|
||||
*vars,
|
||||
@@ -207,7 +209,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
printer->Print("}\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -242,7 +244,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
printer->Print("}\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -276,7 +278,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
printer->Print("}\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -300,7 +302,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
if (method->NoStreaming()) {
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
printer->Print(
|
||||
*vars,
|
||||
@@ -317,7 +319,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
"::grpc::ClientContext* context, $Response$* response) = 0;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
printer->Print(
|
||||
@@ -335,7 +337,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
"::grpc::ClientContext* context, const $Request$& request) = 0;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
printer->Print(
|
||||
@@ -352,7 +354,7 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
"$Method$Raw(::grpc::ClientContext* context) = 0;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
printer->Print(
|
||||
@@ -366,9 +368,9 @@ static void PrintHeaderClientMethodInterfaces(
|
||||
}
|
||||
}
|
||||
|
||||
static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars,
|
||||
static void PrintHeaderClientMethod(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars,
|
||||
bool is_public) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
@@ -377,8 +379,8 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
grpc::string prefix;
|
||||
grpc::string method_params; // extra arguments to method
|
||||
grpc::string raw_args; // extra arguments to raw version of method
|
||||
} async_prefixes[] = { { "Async", ", void* tag", ", tag" },
|
||||
{ "PrepareAsync", "", "" } };
|
||||
} async_prefixes[] = {{"Async", ", void* tag", ", tag"},
|
||||
{"PrepareAsync", "", ""}};
|
||||
|
||||
if (is_public) {
|
||||
if (method->NoStreaming()) {
|
||||
@@ -404,7 +406,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
printer->Print(
|
||||
*vars,
|
||||
@@ -432,15 +434,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
"($Method$Raw(context, response));\n");
|
||||
printer->Outdent();
|
||||
printer->Print("}\n");
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
printer->Print(*vars, "// Client streaming callback reactor entry.\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
"void async_$Method$(::grpc::ClientContext* context, $Response$* response, ::grpc::ClientWriteReactor< $Request$ >* reactor);\n");
|
||||
}
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
printer->Print(*vars, "// Client streaming callback reactor entry.\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
"void async_$Method$(::grpc::ClientContext* context, $Response$* "
|
||||
"response, ::grpc::ClientWriteReactor< $Request$ >* reactor);\n");
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -474,11 +477,13 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
printer->Print(*vars, "// Server streaming callback reactor entry.\n");
|
||||
printer->Print(*vars,
|
||||
"void async_$Method$(::grpc::ClientContext* context, const $Request$& request, ::grpc::ClientReadReactor< $Response$ >* reactor);\n");
|
||||
"void async_$Method$(::grpc::ClientContext* context, "
|
||||
"const $Request$& request, ::grpc::ClientReadReactor< "
|
||||
"$Response$ >* reactor);\n");
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -508,15 +513,17 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
"$Method$Raw(context));\n");
|
||||
printer->Outdent();
|
||||
printer->Print("}\n");
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
printer->Print(*vars, "// Bidirectional streaming callback reactor entry.\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
"void async_$Method$(::grpc::ClientContext* context, ::grpc::ClientBidiReactor< $Request$, $Response$ >* reactor);\n");
|
||||
}
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
printer->Print(*vars,
|
||||
"// Bidirectional streaming callback reactor entry.\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
"void async_$Method$(::grpc::ClientContext* context, "
|
||||
"::grpc::ClientBidiReactor< $Request$, $Response$ >* reactor);\n");
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -539,7 +546,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
if (method->NoStreaming()) {
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
printer->Print(
|
||||
*vars,
|
||||
@@ -559,7 +566,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
"override;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -576,7 +583,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
" override;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -592,7 +599,7 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
"$Method$Raw(::grpc::ClientContext* context) override;\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["AsyncRawArgs"] = async_prefix.raw_args;
|
||||
@@ -607,16 +614,16 @@ static void PrintHeaderClientMethod(grpc_generator::Printer *printer,
|
||||
}
|
||||
|
||||
static void PrintHeaderClientMethodData(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
printer->Print(*vars,
|
||||
"const ::grpc::internal::RpcMethod rpcmethod_$Method$_;\n");
|
||||
}
|
||||
|
||||
static void PrintHeaderServerMethodSync(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -649,8 +656,8 @@ static void PrintHeaderServerMethodSync(
|
||||
}
|
||||
|
||||
static void PrintHeaderServerMethodAsync(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -765,8 +772,8 @@ static void PrintHeaderServerMethodAsync(
|
||||
}
|
||||
|
||||
static void PrintHeaderServerMethodStreamedUnary(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -816,8 +823,8 @@ static void PrintHeaderServerMethodStreamedUnary(
|
||||
}
|
||||
|
||||
static void PrintHeaderServerMethodSplitStreaming(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -869,8 +876,8 @@ static void PrintHeaderServerMethodSplitStreaming(
|
||||
}
|
||||
|
||||
static void PrintHeaderServerMethodGeneric(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -939,9 +946,9 @@ static void PrintHeaderServerMethodGeneric(
|
||||
printer->Print(*vars, "};\n");
|
||||
}
|
||||
|
||||
static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Service *service,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
static void PrintHeaderService(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Service* service,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Service"] = service->name();
|
||||
|
||||
printer->Print(service->GetLeadingComments("//").c_str());
|
||||
@@ -1036,7 +1043,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
printer->Print(*vars, "WithAsyncMethod_$method_name$<");
|
||||
}
|
||||
printer->Print("Service");
|
||||
for (int i = 0; i < service->method_count(); ++i) { printer->Print(" >"); }
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
printer->Print(" >");
|
||||
}
|
||||
printer->Print(" AsyncService;\n");
|
||||
|
||||
// Server side - Generic
|
||||
@@ -1061,7 +1070,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
}
|
||||
printer->Print("Service");
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
if (service->method(i)->NoStreaming()) { printer->Print(" >"); }
|
||||
if (service->method(i)->NoStreaming()) {
|
||||
printer->Print(" >");
|
||||
}
|
||||
}
|
||||
printer->Print(" StreamedUnaryService;\n");
|
||||
|
||||
@@ -1083,7 +1094,9 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
printer->Print("Service");
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
auto method = service->method(i);
|
||||
if (ServerOnlyStreaming(method.get())) { printer->Print(" >"); }
|
||||
if (ServerOnlyStreaming(method.get())) {
|
||||
printer->Print(" >");
|
||||
}
|
||||
}
|
||||
printer->Print(" SplitStreamedService;\n");
|
||||
|
||||
@@ -1117,10 +1130,10 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
if ((*vars)["generate_callback_api"] == "1") {
|
||||
(*vars)["Service"] = service->name();
|
||||
printer->Print("\n#if defined(GRPC_CALLBACK_API_NONEXPERIMENTAL)\n");
|
||||
printer->Print(*vars,
|
||||
"class $Service$::CallbackService : public ::grpc::Service "
|
||||
"{\n public:\n CallbackService();\n virtual "
|
||||
"~CallbackService();\n");
|
||||
printer->Print(*vars,
|
||||
"class $Service$::CallbackService : public ::grpc::Service "
|
||||
"{\n public:\n CallbackService();\n virtual "
|
||||
"~CallbackService();\n");
|
||||
printer->Indent();
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
auto m = service->method(i);
|
||||
@@ -1158,8 +1171,8 @@ static void PrintHeaderService(grpc_generator::Printer *printer,
|
||||
|
||||
} // namespace
|
||||
|
||||
grpc::string GetHeaderServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetHeaderServices(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1168,7 +1181,9 @@ grpc::string GetHeaderServices(grpc_generator::File *file,
|
||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||
// method names.
|
||||
vars["Package"] = file->package();
|
||||
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["Package"].append(".");
|
||||
}
|
||||
|
||||
if (!params.services_namespace.empty()) {
|
||||
vars["services_namespace"] = params.services_namespace;
|
||||
@@ -1192,8 +1207,8 @@ grpc::string GetHeaderServices(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetHeaderEpilogue(grpc_generator::File *file,
|
||||
const Parameters & /*params*/) {
|
||||
grpc::string GetHeaderEpilogue(grpc_generator::File* file,
|
||||
const Parameters& /*params*/) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1221,8 +1236,8 @@ grpc::string GetHeaderEpilogue(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetSourcePrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetSourcePrologue(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1247,24 +1262,23 @@ grpc::string GetSourcePrologue(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetSourceIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetSourceIncludes(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
auto printer = file->CreatePrinter(&output);
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
|
||||
static const char *headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/async_unary_call.h",
|
||||
"grpcpp/impl/codegen/channel_interface.h",
|
||||
"grpcpp/impl/codegen/client_unary_call.h",
|
||||
"grpcpp/impl/codegen/method_handler.h",
|
||||
"grpcpp/impl/codegen/rpc_service_method.h",
|
||||
"grpcpp/impl/codegen/service_type.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h"
|
||||
};
|
||||
static const char* headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/async_unary_call.h",
|
||||
"grpcpp/impl/codegen/channel_interface.h",
|
||||
"grpcpp/impl/codegen/client_unary_call.h",
|
||||
"grpcpp/impl/codegen/method_handler.h",
|
||||
"grpcpp/impl/codegen/rpc_service_method.h",
|
||||
"grpcpp/impl/codegen/service_type.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h"};
|
||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||
PrintIncludes(printer.get(), headers, params);
|
||||
|
||||
@@ -1285,8 +1299,8 @@ grpc::string GetSourceIncludes(grpc_generator::File *file,
|
||||
namespace {
|
||||
|
||||
static void PrintSourceClientMethod(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -1295,8 +1309,8 @@ static void PrintSourceClientMethod(
|
||||
grpc::string start; // bool literal expressed as string
|
||||
grpc::string method_params; // extra arguments to method
|
||||
grpc::string create_args; // extra arguments to creator
|
||||
} async_prefixes[] = { { "Async", "true", ", void* tag", ", tag" },
|
||||
{ "PrepareAsync", "false", "", ", nullptr" } };
|
||||
} async_prefixes[] = {{"Async", "true", ", void* tag", ", tag"},
|
||||
{"PrepareAsync", "false", "", ", nullptr"}};
|
||||
if (method->NoStreaming()) {
|
||||
printer->Print(*vars,
|
||||
"::grpc::Status $ns$$Service$::Stub::$Method$("
|
||||
@@ -1312,24 +1326,25 @@ static void PrintSourceClientMethod(
|
||||
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
|
||||
"context, const $Request$& request, $Response$* response, "
|
||||
"std::function<void(::grpc::Status)> on_done) {\n");
|
||||
printer->Print(*vars,
|
||||
" ::grpc::internal::CallbackUnaryCall(channel_.get(), "
|
||||
"rpcmethod_$Method$_, context, &request, response, "
|
||||
"std::move(on_done));\n}\n\n");
|
||||
printer->Print(*vars,
|
||||
" ::grpc::internal::CallbackUnaryCall(channel_.get(), "
|
||||
"rpcmethod_$Method$_, context, &request, response, "
|
||||
"std::move(on_done));\n}\n\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
|
||||
"context, const $Request$& request, $Response$* response, "
|
||||
"::grpc::ClientUnaryReactor* reactor) {\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
" "
|
||||
"::grpc::internal::ClientCallbackUnaryFactory::Create(channel_.get(),"
|
||||
" rpcmethod_$Method$_, context, &request, response, reactor);\n}\n\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
" "
|
||||
"::grpc::internal::ClientCallbackUnaryFactory::Create(channel_.get(),"
|
||||
" rpcmethod_$Method$_, context, &request, response, "
|
||||
"reactor);\n}\n\n");
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncStart"] = async_prefix.start;
|
||||
printer->Print(*vars,
|
||||
@@ -1372,7 +1387,7 @@ static void PrintSourceClientMethod(
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncStart"] = async_prefix.start;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
@@ -1409,14 +1424,15 @@ static void PrintSourceClientMethod(
|
||||
"void $ns$$Service$::Stub::async_$Method$(::grpc::ClientContext* "
|
||||
"context, const $Request$& request, ::grpc::ClientReadReactor< "
|
||||
"$Response$ >* reactor) {\n");
|
||||
printer->Print(*vars,
|
||||
" ::grpc::internal::ClientCallbackReaderFactory< "
|
||||
"$Response$ >::Create(channel_.get(), "
|
||||
"rpcmethod_$Method$_, context, &request, reactor);\n}\n\n");
|
||||
printer->Print(
|
||||
*vars,
|
||||
" ::grpc::internal::ClientCallbackReaderFactory< "
|
||||
"$Response$ >::Create(channel_.get(), "
|
||||
"rpcmethod_$Method$_, context, &request, reactor);\n}\n\n");
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncStart"] = async_prefix.start;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
@@ -1460,7 +1476,7 @@ static void PrintSourceClientMethod(
|
||||
}
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncStart"] = async_prefix.start;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
@@ -1483,8 +1499,8 @@ static void PrintSourceClientMethod(
|
||||
}
|
||||
|
||||
static void PrintSourceServerMethod(
|
||||
grpc_generator::Printer *printer, const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
grpc_generator::Printer* printer, const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -1531,9 +1547,9 @@ static void PrintSourceServerMethod(
|
||||
}
|
||||
}
|
||||
|
||||
static void PrintSourceService(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Service *service,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
static void PrintSourceService(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Service* service,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Service"] = service->name();
|
||||
|
||||
if (service->method_count() > 0) {
|
||||
@@ -1660,47 +1676,54 @@ static void PrintSourceService(grpc_generator::Printer *printer,
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
if (method->NoStreaming()) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
|
||||
" new ::grpc::internal::CallbackUnaryHandler<$Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, const $Request$* req, $Response$* resp) {\n"
|
||||
" return this->$Method$(ctx, req, resp);\n"
|
||||
" })));\n");
|
||||
} else if (ClientOnlyStreaming(method.get())) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
|
||||
" new ::grpc::internal::CallbackClientStreamingHandler<$Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, $Response$* resp) {\n"
|
||||
" return this->$Method$(ctx, resp);\n"
|
||||
" })));\n");
|
||||
} else if (ServerOnlyStreaming(method.get())) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
|
||||
" new ::grpc::internal::CallbackServerStreamingHandler<$Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, const $Request$* req) {\n"
|
||||
" return this->$Method$(ctx, req);\n"
|
||||
" })));\n");
|
||||
} else if (method->BidiStreaming()) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::BIDI_STREAMING,\n"
|
||||
" new ::grpc::internal::CallbackBidiHandler<$Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx) {\n"
|
||||
" return this->$Method$(ctx);\n"
|
||||
" })));\n");
|
||||
}
|
||||
if (method->NoStreaming()) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::NORMAL_RPC,\n"
|
||||
" new ::grpc::internal::CallbackUnaryHandler<$Request$, "
|
||||
"$Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, const $Request$* "
|
||||
"req, $Response$* resp) {\n"
|
||||
" return this->$Method$(ctx, req, resp);\n"
|
||||
" })));\n");
|
||||
} else if (ClientOnlyStreaming(method.get())) {
|
||||
printer->Print(*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::CLIENT_STREAMING,\n"
|
||||
" new "
|
||||
"::grpc::internal::CallbackClientStreamingHandler<$"
|
||||
"Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, "
|
||||
"$Response$* resp) {\n"
|
||||
" return this->$Method$(ctx, resp);\n"
|
||||
" })));\n");
|
||||
} else if (ServerOnlyStreaming(method.get())) {
|
||||
printer->Print(*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::SERVER_STREAMING,\n"
|
||||
" new "
|
||||
"::grpc::internal::CallbackServerStreamingHandler<$"
|
||||
"Request$, $Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx, const "
|
||||
"$Request$* req) {\n"
|
||||
" return this->$Method$(ctx, req);\n"
|
||||
" })));\n");
|
||||
} else if (method->BidiStreaming()) {
|
||||
printer->Print(
|
||||
*vars,
|
||||
"AddMethod(new ::grpc::internal::RpcServiceMethod(\n"
|
||||
" $prefix$$Service$_method_names[$Idx$],\n"
|
||||
" ::grpc::internal::RpcMethod::BIDI_STREAMING,\n"
|
||||
" new ::grpc::internal::CallbackBidiHandler<$Request$, "
|
||||
"$Response$>(\n"
|
||||
" [this](::grpc::CallbackServerContext* ctx) {\n"
|
||||
" return this->$Method$(ctx);\n"
|
||||
" })));\n");
|
||||
}
|
||||
}
|
||||
printer->Outdent();
|
||||
printer->Print("}\n\n");
|
||||
@@ -1751,8 +1774,8 @@ static void PrintSourceService(grpc_generator::Printer *printer,
|
||||
|
||||
} // namespace
|
||||
|
||||
grpc::string GetSourceServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetSourceServices(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1761,7 +1784,9 @@ grpc::string GetSourceServices(grpc_generator::File *file,
|
||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||
// method names.
|
||||
vars["Package"] = file->package();
|
||||
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["Package"].append(".");
|
||||
}
|
||||
if (!params.services_namespace.empty()) {
|
||||
vars["ns"] = params.services_namespace + "::";
|
||||
vars["prefix"] = params.services_namespace;
|
||||
@@ -1779,8 +1804,8 @@ grpc::string GetSourceServices(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetSourceEpilogue(grpc_generator::File *file,
|
||||
const Parameters & /*params*/) {
|
||||
grpc::string GetSourceEpilogue(grpc_generator::File* file,
|
||||
const Parameters& /*params*/) {
|
||||
grpc::string temp;
|
||||
|
||||
if (!file->package().empty()) {
|
||||
@@ -1797,8 +1822,8 @@ grpc::string GetSourceEpilogue(grpc_generator::File *file,
|
||||
return temp;
|
||||
}
|
||||
|
||||
grpc::string GetMockPrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetMockPrologue(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1824,18 +1849,18 @@ grpc::string GetMockPrologue(grpc_generator::File *file,
|
||||
}
|
||||
|
||||
// TODO(mmukhi): Add client-stream and completion-queue headers.
|
||||
grpc::string GetMockIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetMockIncludes(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
auto printer = file->CreatePrinter(&output);
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
|
||||
static const char *headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h",
|
||||
"gmock/gmock.h",
|
||||
static const char* headers_strs[] = {
|
||||
"grpcpp/impl/codegen/async_stream.h",
|
||||
"grpcpp/impl/codegen/sync_stream.h",
|
||||
"gmock/gmock.h",
|
||||
};
|
||||
std::vector<grpc::string> headers(headers_strs, array_end(headers_strs));
|
||||
PrintIncludes(printer.get(), headers, params);
|
||||
@@ -1856,9 +1881,9 @@ grpc::string GetMockIncludes(grpc_generator::File *file,
|
||||
|
||||
namespace {
|
||||
|
||||
static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
static void PrintMockClientMethods(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Method"] = method->name();
|
||||
(*vars)["Request"] = method->input_type_name();
|
||||
(*vars)["Response"] = method->output_type_name();
|
||||
@@ -1867,8 +1892,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
grpc::string prefix;
|
||||
grpc::string method_params; // extra arguments to method
|
||||
int extra_method_param_count;
|
||||
} async_prefixes[] = { { "Async", ", void* tag", 1 },
|
||||
{ "PrepareAsync", "", 0 } };
|
||||
} async_prefixes[] = {{"Async", ", void* tag", 1}, {"PrepareAsync", "", 0}};
|
||||
|
||||
if (method->NoStreaming()) {
|
||||
printer->Print(
|
||||
@@ -1877,7 +1901,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
"const $Request$& request, $Response$* response));\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
printer->Print(
|
||||
*vars,
|
||||
@@ -1894,7 +1918,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
"(::grpc::ClientContext* context, $Response$* response));\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["MockArgs"] =
|
||||
@@ -1913,7 +1937,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
"(::grpc::ClientContext* context, const $Request$& request));\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["MockArgs"] =
|
||||
@@ -1933,7 +1957,7 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
"(::grpc::ClientContext* context));\n");
|
||||
for (size_t i = 0; i < sizeof(async_prefixes) / sizeof(async_prefixes[0]);
|
||||
i++) {
|
||||
auto &async_prefix = async_prefixes[i];
|
||||
auto& async_prefix = async_prefixes[i];
|
||||
(*vars)["AsyncPrefix"] = async_prefix.prefix;
|
||||
(*vars)["AsyncMethodParams"] = async_prefix.method_params;
|
||||
(*vars)["MockArgs"] =
|
||||
@@ -1948,9 +1972,9 @@ static void PrintMockClientMethods(grpc_generator::Printer *printer,
|
||||
}
|
||||
}
|
||||
|
||||
static void PrintMockService(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Service *service,
|
||||
std::map<grpc::string, grpc::string> *vars) {
|
||||
static void PrintMockService(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Service* service,
|
||||
std::map<grpc::string, grpc::string>* vars) {
|
||||
(*vars)["Service"] = service->name();
|
||||
|
||||
printer->Print(*vars,
|
||||
@@ -1966,8 +1990,8 @@ static void PrintMockService(grpc_generator::Printer *printer,
|
||||
|
||||
} // namespace
|
||||
|
||||
grpc::string GetMockServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms) {
|
||||
grpc::string GetMockServices(grpc_generator::File* file,
|
||||
const Parameters& params) {
|
||||
grpc::string output;
|
||||
{
|
||||
// Scope the output stream so it closes and finalizes output to the string.
|
||||
@@ -1976,7 +2000,9 @@ grpc::string GetMockServices(grpc_generator::File *file,
|
||||
// Package string is empty or ends with a dot. It is used to fully qualify
|
||||
// method names.
|
||||
vars["Package"] = file->package();
|
||||
if (!file->package().empty()) { vars["Package"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["Package"].append(".");
|
||||
}
|
||||
|
||||
if (!params.services_namespace.empty()) {
|
||||
vars["services_namespace"] = params.services_namespace;
|
||||
@@ -1995,8 +2021,8 @@ grpc::string GetMockServices(grpc_generator::File *file,
|
||||
return output;
|
||||
}
|
||||
|
||||
grpc::string GetMockEpilogue(grpc_generator::File *file,
|
||||
const Parameters & /*params*/) {
|
||||
grpc::string GetMockEpilogue(grpc_generator::File* file,
|
||||
const Parameters& /*params*/) {
|
||||
grpc::string temp;
|
||||
|
||||
if (!file->package().empty()) {
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
#include "src/compiler/schema_interface.h"
|
||||
|
||||
#ifndef GRPC_CUSTOM_STRING
|
||||
# include <string>
|
||||
# define GRPC_CUSTOM_STRING std::string
|
||||
#include <string>
|
||||
#define GRPC_CUSTOM_STRING std::string
|
||||
#endif
|
||||
|
||||
namespace grpc {
|
||||
@@ -42,68 +42,68 @@ struct Parameters {
|
||||
};
|
||||
|
||||
// Return the prologue of the generated header file.
|
||||
grpc::string GetHeaderPrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetHeaderPrologue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the includes needed for generated header file.
|
||||
grpc::string GetHeaderIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetHeaderIncludes(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the includes needed for generated source file.
|
||||
grpc::string GetSourceIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetSourceIncludes(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the epilogue of the generated header file.
|
||||
grpc::string GetHeaderEpilogue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetHeaderEpilogue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the prologue of the generated source file.
|
||||
grpc::string GetSourcePrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetSourcePrologue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the services for generated header file.
|
||||
grpc::string GetHeaderServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetHeaderServices(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the services for generated source file.
|
||||
grpc::string GetSourceServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetSourceServices(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the epilogue of the generated source file.
|
||||
grpc::string GetSourceEpilogue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetSourceEpilogue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the prologue of the generated mock file.
|
||||
grpc::string GetMockPrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockPrologue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the includes needed for generated mock file.
|
||||
grpc::string GetMockIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockIncludes(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the services for generated mock file.
|
||||
grpc::string GetMockServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockServices(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the epilogue of generated mock file.
|
||||
grpc::string GetMockEpilogue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockEpilogue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the prologue of the generated mock file.
|
||||
grpc::string GetMockPrologue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockPrologue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the includes needed for generated mock file.
|
||||
grpc::string GetMockIncludes(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockIncludes(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the services for generated mock file.
|
||||
grpc::string GetMockServices(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockServices(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
// Return the epilogue of generated mock file.
|
||||
grpc::string GetMockEpilogue(grpc_generator::File *file,
|
||||
const Parameters ¶ms);
|
||||
grpc::string GetMockEpilogue(grpc_generator::File* file,
|
||||
const Parameters& params);
|
||||
|
||||
} // namespace grpc_cpp_generator
|
||||
|
||||
|
||||
@@ -4,17 +4,18 @@
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
|
||||
template<class T> grpc::string as_string(T x) {
|
||||
template <class T>
|
||||
grpc::string as_string(T x) {
|
||||
std::ostringstream out;
|
||||
out << x;
|
||||
return out.str();
|
||||
}
|
||||
|
||||
inline bool ClientOnlyStreaming(const grpc_generator::Method *method) {
|
||||
inline bool ClientOnlyStreaming(const grpc_generator::Method* method) {
|
||||
return method->ClientStreaming() && !method->ServerStreaming();
|
||||
}
|
||||
|
||||
inline bool ServerOnlyStreaming(const grpc_generator::Method *method) {
|
||||
inline bool ServerOnlyStreaming(const grpc_generator::Method* method) {
|
||||
return !method->ClientStreaming() && method->ServerStreaming();
|
||||
}
|
||||
|
||||
@@ -35,9 +36,9 @@ static grpc::string exportName(grpc::string s) {
|
||||
return s;
|
||||
}
|
||||
|
||||
static void GenerateError(grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars,
|
||||
const bool multiple_return = true) {
|
||||
static void GenerateError(grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars,
|
||||
const bool multiple_return = true) {
|
||||
printer->Print(vars, "if $Error_Check$ {\n");
|
||||
printer->Indent();
|
||||
vars["Return"] = multiple_return ? "nil, err" : "err";
|
||||
@@ -47,9 +48,9 @@ static void GenerateError(grpc_generator::Printer *printer,
|
||||
}
|
||||
|
||||
// Generates imports for the service
|
||||
static void GenerateImports(grpc_generator::File *file,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
static void GenerateImports(grpc_generator::File* file,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
vars["filename"] = file->filename();
|
||||
printer->Print("//Generated by gRPC Go plugin\n");
|
||||
printer->Print("//If you make any local changes, they will be lost\n");
|
||||
@@ -67,9 +68,9 @@ static void GenerateImports(grpc_generator::File *file,
|
||||
}
|
||||
|
||||
// Generates Server method signature source
|
||||
static void GenerateServerMethodSignature(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
static void GenerateServerMethodSignature(
|
||||
const grpc_generator::Method* method, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
vars["Method"] = exportName(method->name());
|
||||
vars["Request"] = method->get_input_type_name();
|
||||
vars["Response"] = (vars["CustomMethodIO"] == "")
|
||||
@@ -87,9 +88,9 @@ static void GenerateServerMethodSignature(const grpc_generator::Method *method,
|
||||
}
|
||||
}
|
||||
|
||||
static void GenerateServerMethod(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
static void GenerateServerMethod(const grpc_generator::Method* method,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
vars["Method"] = exportName(method->name());
|
||||
vars["Request"] = method->get_input_type_name();
|
||||
vars["Response"] = (vars["CustomMethodIO"] == "")
|
||||
@@ -160,8 +161,12 @@ static void GenerateServerMethod(const grpc_generator::Method *method,
|
||||
|
||||
printer->Print(vars, "type $Service$_$Method$Server interface {\n");
|
||||
printer->Indent();
|
||||
if (genSend) { printer->Print(vars, "Send(*$Response$) error\n"); }
|
||||
if (genRecv) { printer->Print(vars, "Recv() (*$Request$, error)\n"); }
|
||||
if (genSend) {
|
||||
printer->Print(vars, "Send(*$Response$) error\n");
|
||||
}
|
||||
if (genRecv) {
|
||||
printer->Print(vars, "Recv() (*$Request$, error)\n");
|
||||
}
|
||||
if (genSendAndClose) {
|
||||
printer->Print(vars, "SendAndClose(*$Response$) error\n");
|
||||
}
|
||||
@@ -205,9 +210,9 @@ static void GenerateServerMethod(const grpc_generator::Method *method,
|
||||
}
|
||||
|
||||
// Generates Client method signature source
|
||||
static void GenerateClientMethodSignature(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
static void GenerateClientMethodSignature(
|
||||
const grpc_generator::Method* method, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
vars["Method"] = exportName(method->name());
|
||||
vars["Request"] =
|
||||
", in *" + ((vars["CustomMethodIO"] == "") ? method->get_input_type_name()
|
||||
@@ -226,9 +231,9 @@ static void GenerateClientMethodSignature(const grpc_generator::Method *method,
|
||||
}
|
||||
|
||||
// Generates Client method source
|
||||
static void GenerateClientMethod(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
static void GenerateClientMethod(const grpc_generator::Method* method,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
printer->Print(vars, "func (c *$ServiceUnexported$Client) ");
|
||||
vars["Ending"] = " {\n";
|
||||
GenerateClientMethodSignature(method, printer, vars);
|
||||
@@ -277,8 +282,12 @@ static void GenerateClientMethod(const grpc_generator::Method *method,
|
||||
// Stream interface
|
||||
printer->Print(vars, "type $Service$_$Method$Client interface {\n");
|
||||
printer->Indent();
|
||||
if (genSend) { printer->Print(vars, "Send(*$Request$) error\n"); }
|
||||
if (genRecv) { printer->Print(vars, "Recv() (*$Response$, error)\n"); }
|
||||
if (genSend) {
|
||||
printer->Print(vars, "Send(*$Request$) error\n");
|
||||
}
|
||||
if (genRecv) {
|
||||
printer->Print(vars, "Recv() (*$Response$, error)\n");
|
||||
}
|
||||
if (genCloseAndRecv) {
|
||||
printer->Print(vars, "CloseAndRecv() (*$Response$, error)\n");
|
||||
}
|
||||
@@ -329,8 +338,8 @@ static void GenerateClientMethod(const grpc_generator::Method *method,
|
||||
}
|
||||
|
||||
// Generates client API for the service
|
||||
void GenerateService(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
void GenerateService(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string> vars) {
|
||||
vars["Service"] = exportName(service->name());
|
||||
// Client Interface
|
||||
@@ -484,9 +493,9 @@ void GenerateService(const grpc_generator::Service *service,
|
||||
} // namespace
|
||||
|
||||
// Returns source for the service
|
||||
grpc::string GenerateServiceSource(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
grpc_go_generator::Parameters *parameters) {
|
||||
grpc::string GenerateServiceSource(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
grpc_go_generator::Parameters* parameters) {
|
||||
grpc::string out;
|
||||
auto p = file->CreatePrinter(&out, '\t');
|
||||
p->SetIndentationSize(1);
|
||||
|
||||
@@ -24,9 +24,9 @@ struct Parameters {
|
||||
};
|
||||
|
||||
// Return the source of the generated service file.
|
||||
grpc::string GenerateServiceSource(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
grpc_go_generator::Parameters *parameters);
|
||||
grpc::string GenerateServiceSource(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
grpc_go_generator::Parameters* parameters);
|
||||
|
||||
} // namespace grpc_go_generator
|
||||
|
||||
|
||||
@@ -28,11 +28,11 @@
|
||||
|
||||
// Stringify helpers used solely to cast GRPC_VERSION
|
||||
#ifndef STR
|
||||
# define STR(s) # s
|
||||
#define STR(s) #s
|
||||
#endif
|
||||
|
||||
#ifndef XSTR
|
||||
# define XSTR(s) STR(s)
|
||||
#define XSTR(s) STR(s)
|
||||
#endif
|
||||
|
||||
typedef grpc_generator::Printer Printer;
|
||||
@@ -46,8 +46,8 @@ namespace grpc_java_generator {
|
||||
typedef std::string string;
|
||||
namespace {
|
||||
// Generates imports for the service
|
||||
static void GenerateImports(grpc_generator::File *file,
|
||||
grpc_generator::Printer *printer, VARS &vars) {
|
||||
static void GenerateImports(grpc_generator::File* file,
|
||||
grpc_generator::Printer* printer, VARS& vars) {
|
||||
vars["filename"] = file->filename();
|
||||
printer->Print(vars,
|
||||
"//Generated by flatc compiler (version $flatc_version$)\n");
|
||||
@@ -64,7 +64,7 @@ static void GenerateImports(grpc_generator::File *file,
|
||||
// Adjust a method name prefix identifier to follow the JavaBean spec:
|
||||
// - decapitalize the first letter
|
||||
// - remove embedded underscores & capitalize the following letter
|
||||
static string MixedLower(const string &word) {
|
||||
static string MixedLower(const string& word) {
|
||||
string w;
|
||||
w += static_cast<string::value_type>(tolower(word[0]));
|
||||
bool after_underscore = false;
|
||||
@@ -84,7 +84,7 @@ static string MixedLower(const string &word) {
|
||||
// - An underscore is inserted where a lower case letter is followed by an
|
||||
// upper case letter.
|
||||
// - All letters are converted to upper case
|
||||
static string ToAllUpperCase(const string &word) {
|
||||
static string ToAllUpperCase(const string& word) {
|
||||
string w;
|
||||
for (size_t i = 0; i < word.length(); ++i) {
|
||||
w += static_cast<string::value_type>(toupper(word[i]));
|
||||
@@ -95,49 +95,48 @@ static string ToAllUpperCase(const string &word) {
|
||||
return w;
|
||||
}
|
||||
|
||||
static inline string LowerMethodName(const MethodDescriptor *method) {
|
||||
static inline string LowerMethodName(const MethodDescriptor* method) {
|
||||
return MixedLower(method->name());
|
||||
}
|
||||
|
||||
static inline string MethodPropertiesFieldName(const MethodDescriptor *method) {
|
||||
static inline string MethodPropertiesFieldName(const MethodDescriptor* method) {
|
||||
return "METHOD_" + ToAllUpperCase(method->name());
|
||||
}
|
||||
|
||||
static inline string MethodPropertiesGetterName(
|
||||
const MethodDescriptor *method) {
|
||||
const MethodDescriptor* method) {
|
||||
return MixedLower("get_" + method->name() + "_method");
|
||||
}
|
||||
|
||||
static inline string MethodIdFieldName(const MethodDescriptor *method) {
|
||||
static inline string MethodIdFieldName(const MethodDescriptor* method) {
|
||||
return "METHODID_" + ToAllUpperCase(method->name());
|
||||
}
|
||||
|
||||
static inline string JavaClassName(VARS &vars, const string &name) {
|
||||
static inline string JavaClassName(VARS& vars, const string& name) {
|
||||
// string name = google::protobuf::compiler::java::ClassName(desc);
|
||||
return vars["Package"] + name;
|
||||
}
|
||||
|
||||
static inline string ServiceClassName(const string &service_name) {
|
||||
static inline string ServiceClassName(const string& service_name) {
|
||||
return service_name + "Grpc";
|
||||
}
|
||||
|
||||
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
||||
// distribution.
|
||||
template<typename ITR>
|
||||
static void GrpcSplitStringToIteratorUsing(const string &full,
|
||||
const char *delim, ITR &result) {
|
||||
template <typename ITR>
|
||||
static void GrpcSplitStringToIteratorUsing(const string& full,
|
||||
const char* delim, ITR& result) {
|
||||
// Optimize the common case where delim is a single character.
|
||||
if (delim[0] != '\0' && delim[1] == '\0') {
|
||||
char c = delim[0];
|
||||
const char *p = full.data();
|
||||
const char *end = p + full.size();
|
||||
const char* p = full.data();
|
||||
const char* end = p + full.size();
|
||||
while (p != end) {
|
||||
if (*p == c) {
|
||||
++p;
|
||||
} else {
|
||||
const char *start = p;
|
||||
while (++p != end && *p != c)
|
||||
;
|
||||
const char* start = p;
|
||||
while (++p != end && *p != c);
|
||||
*result++ = string(start, p - start);
|
||||
}
|
||||
}
|
||||
@@ -157,13 +156,13 @@ static void GrpcSplitStringToIteratorUsing(const string &full,
|
||||
}
|
||||
}
|
||||
|
||||
static void GrpcSplitStringUsing(const string &full, const char *delim,
|
||||
std::vector<string> *result) {
|
||||
static void GrpcSplitStringUsing(const string& full, const char* delim,
|
||||
std::vector<string>* result) {
|
||||
std::back_insert_iterator<std::vector<string>> it(*result);
|
||||
GrpcSplitStringToIteratorUsing(full, delim, it);
|
||||
}
|
||||
|
||||
static std::vector<string> GrpcSplit(const string &full, const char *delim) {
|
||||
static std::vector<string> GrpcSplit(const string& full, const char* delim) {
|
||||
std::vector<string> result;
|
||||
GrpcSplitStringUsing(full, delim, &result);
|
||||
return result;
|
||||
@@ -171,7 +170,7 @@ static std::vector<string> GrpcSplit(const string &full, const char *delim) {
|
||||
|
||||
// TODO(nmittler): Remove once protobuf includes javadoc methods in
|
||||
// distribution.
|
||||
static string GrpcEscapeJavadoc(const string &input) {
|
||||
static string GrpcEscapeJavadoc(const string& input) {
|
||||
string result;
|
||||
result.reserve(input.size() * 2);
|
||||
|
||||
@@ -218,7 +217,9 @@ static string GrpcEscapeJavadoc(const string &input) {
|
||||
// Java interprets Unicode escape sequences anywhere!
|
||||
result.append("\");
|
||||
break;
|
||||
default: result.push_back(c); break;
|
||||
default:
|
||||
result.push_back(c);
|
||||
break;
|
||||
}
|
||||
|
||||
prev = c;
|
||||
@@ -227,7 +228,7 @@ static string GrpcEscapeJavadoc(const string &input) {
|
||||
return result;
|
||||
}
|
||||
|
||||
static std::vector<string> GrpcGetDocLines(const string &comments) {
|
||||
static std::vector<string> GrpcGetDocLines(const string& comments) {
|
||||
if (!comments.empty()) {
|
||||
// TODO(kenton): Ideally we should parse the comment text as Markdown and
|
||||
// write it back as HTML, but this requires a Markdown parser. For now
|
||||
@@ -238,23 +239,27 @@ static std::vector<string> GrpcGetDocLines(const string &comments) {
|
||||
string escapedComments = GrpcEscapeJavadoc(comments);
|
||||
|
||||
std::vector<string> lines = GrpcSplit(escapedComments, "\n");
|
||||
while (!lines.empty() && lines.back().empty()) { lines.pop_back(); }
|
||||
while (!lines.empty() && lines.back().empty()) {
|
||||
lines.pop_back();
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
return std::vector<string>();
|
||||
}
|
||||
|
||||
static std::vector<string> GrpcGetDocLinesForDescriptor(
|
||||
const DescriptorType *descriptor) {
|
||||
const DescriptorType* descriptor) {
|
||||
return descriptor->GetAllComments();
|
||||
// return GrpcGetDocLines(descriptor->GetLeadingComments("///"));
|
||||
}
|
||||
|
||||
static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
|
||||
const std::vector<string> &lines,
|
||||
static void GrpcWriteDocCommentBody(Printer* printer, VARS& vars,
|
||||
const std::vector<string>& lines,
|
||||
bool surroundWithPreTag) {
|
||||
if (!lines.empty()) {
|
||||
if (surroundWithPreTag) { printer->Print(" * <pre>\n"); }
|
||||
if (surroundWithPreTag) {
|
||||
printer->Print(" * <pre>\n");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < lines.size(); i++) {
|
||||
// Most lines should start with a space. Watch out for lines that start
|
||||
@@ -268,28 +273,30 @@ static void GrpcWriteDocCommentBody(Printer *printer, VARS &vars,
|
||||
}
|
||||
}
|
||||
|
||||
if (surroundWithPreTag) { printer->Print(" * </pre>\n"); }
|
||||
if (surroundWithPreTag) {
|
||||
printer->Print(" * </pre>\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void GrpcWriteDocComment(Printer *printer, VARS &vars,
|
||||
const string &comments) {
|
||||
static void GrpcWriteDocComment(Printer* printer, VARS& vars,
|
||||
const string& comments) {
|
||||
printer->Print("/**\n");
|
||||
std::vector<string> lines = GrpcGetDocLines(comments);
|
||||
GrpcWriteDocCommentBody(printer, vars, lines, false);
|
||||
printer->Print(" */\n");
|
||||
}
|
||||
|
||||
static void GrpcWriteServiceDocComment(Printer *printer, VARS &vars,
|
||||
const ServiceDescriptor *service) {
|
||||
static void GrpcWriteServiceDocComment(Printer* printer, VARS& vars,
|
||||
const ServiceDescriptor* service) {
|
||||
printer->Print("/**\n");
|
||||
std::vector<string> lines = GrpcGetDocLinesForDescriptor(service);
|
||||
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
||||
printer->Print(" */\n");
|
||||
}
|
||||
|
||||
static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
|
||||
const MethodDescriptor *method) {
|
||||
static void GrpcWriteMethodDocComment(Printer* printer, VARS& vars,
|
||||
const MethodDescriptor* method) {
|
||||
printer->Print("/**\n");
|
||||
std::vector<string> lines = GrpcGetDocLinesForDescriptor(method);
|
||||
GrpcWriteDocCommentBody(printer, vars, lines, true);
|
||||
@@ -298,7 +305,7 @@ static void GrpcWriteMethodDocComment(Printer *printer, VARS &vars,
|
||||
|
||||
// outputs static singleton extractor for type stored in "extr_type" and
|
||||
// "extr_type_name" vars
|
||||
static void PrintTypeExtractor(Printer *p, VARS &vars) {
|
||||
static void PrintTypeExtractor(Printer* p, VARS& vars) {
|
||||
p->Print(vars,
|
||||
"private static volatile FlatbuffersUtils.FBExtactor<$extr_type$> "
|
||||
"extractorOf$extr_type_name$;\n"
|
||||
@@ -320,8 +327,8 @@ static void PrintTypeExtractor(Printer *p, VARS &vars) {
|
||||
" }\n"
|
||||
"}\n\n");
|
||||
}
|
||||
static void PrintMethodFields(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service) {
|
||||
static void PrintMethodFields(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service) {
|
||||
p->Print("// Static method descriptors that strictly reflect the proto.\n");
|
||||
vars["service_name"] = service->name();
|
||||
|
||||
@@ -443,11 +450,11 @@ enum StubType {
|
||||
|
||||
enum CallType { ASYNC_CALL = 0, BLOCKING_CALL = 1, FUTURE_CALL = 2 };
|
||||
|
||||
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service);
|
||||
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service);
|
||||
|
||||
// Prints a client interface or implementation class, or a server interface.
|
||||
static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||
static void PrintStub(Printer* p, VARS& vars, const ServiceDescriptor* service,
|
||||
StubType type) {
|
||||
const string service_name = service->name();
|
||||
vars["service_name"] = service_name;
|
||||
@@ -493,7 +500,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||
vars["client_name"] = client_name;
|
||||
|
||||
// Class head
|
||||
if (!interface) { GrpcWriteServiceDocComment(p, vars, service); }
|
||||
if (!interface) {
|
||||
GrpcWriteServiceDocComment(p, vars, service);
|
||||
}
|
||||
if (impl_base) {
|
||||
p->Print(vars,
|
||||
"public static abstract class $abstract_name$ implements "
|
||||
@@ -555,7 +564,9 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||
p->Print("\n");
|
||||
// TODO(nmittler): Replace with WriteMethodDocComment once included by the
|
||||
// protobuf distro.
|
||||
if (!interface) { GrpcWriteMethodDocComment(p, vars, &*method); }
|
||||
if (!interface) {
|
||||
GrpcWriteMethodDocComment(p, vars, &*method);
|
||||
}
|
||||
p->Print("public ");
|
||||
switch (call_type) {
|
||||
case BLOCKING_CALL:
|
||||
@@ -620,7 +631,8 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||
"responseObserver);\n");
|
||||
}
|
||||
break;
|
||||
default: break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} else if (!interface) {
|
||||
switch (call_type) {
|
||||
@@ -695,15 +707,15 @@ static void PrintStub(Printer *p, VARS &vars, const ServiceDescriptor *service,
|
||||
}
|
||||
|
||||
static bool CompareMethodClientStreaming(
|
||||
const std::unique_ptr<const grpc_generator::Method> &method1,
|
||||
const std::unique_ptr<const grpc_generator::Method> &method2) {
|
||||
const std::unique_ptr<const grpc_generator::Method>& method1,
|
||||
const std::unique_ptr<const grpc_generator::Method>& method2) {
|
||||
return method1->ClientStreaming() < method2->ClientStreaming();
|
||||
}
|
||||
|
||||
// Place all method invocations into a single class to reduce memory footprint
|
||||
// on Android.
|
||||
static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service) {
|
||||
static void PrintMethodHandlerClass(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service) {
|
||||
// Sort method ids based on ClientStreaming() so switch tables are compact.
|
||||
std::vector<std::unique_ptr<const grpc_generator::Method>> sorted_methods(
|
||||
service->method_count());
|
||||
@@ -713,7 +725,7 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||
stable_sort(sorted_methods.begin(), sorted_methods.end(),
|
||||
CompareMethodClientStreaming);
|
||||
for (size_t i = 0; i < sorted_methods.size(); i++) {
|
||||
auto &method = sorted_methods[i];
|
||||
auto& method = sorted_methods[i];
|
||||
vars["method_id"] = to_string(i);
|
||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||
p->Print(vars,
|
||||
@@ -746,7 +758,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
auto method = service->method(i);
|
||||
if (method->ClientStreaming() || method->BidiStreaming()) { continue; }
|
||||
if (method->ClientStreaming() || method->BidiStreaming()) {
|
||||
continue;
|
||||
}
|
||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||
vars["lower_method_name"] = LowerMethodName(&*method);
|
||||
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
||||
@@ -778,7 +792,9 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||
|
||||
for (int i = 0; i < service->method_count(); ++i) {
|
||||
auto method = service->method(i);
|
||||
if (!(method->ClientStreaming() || method->BidiStreaming())) { continue; }
|
||||
if (!(method->ClientStreaming() || method->BidiStreaming())) {
|
||||
continue;
|
||||
}
|
||||
vars["method_id_name"] = MethodIdFieldName(&*method);
|
||||
vars["lower_method_name"] = LowerMethodName(&*method);
|
||||
vars["input_type"] = JavaClassName(vars, method->get_input_type_name());
|
||||
@@ -803,8 +819,8 @@ static void PrintMethodHandlerClass(Printer *p, VARS &vars,
|
||||
p->Print("}\n\n");
|
||||
}
|
||||
|
||||
static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service) {
|
||||
static void PrintGetServiceDescriptorMethod(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service) {
|
||||
vars["service_name"] = service->name();
|
||||
// vars["proto_base_descriptor_supplier"] = service->name() +
|
||||
// "BaseDescriptorSupplier"; vars["proto_file_descriptor_supplier"] =
|
||||
@@ -896,8 +912,8 @@ static void PrintGetServiceDescriptorMethod(Printer *p, VARS &vars,
|
||||
p->Print("}\n");
|
||||
}
|
||||
|
||||
static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service) {
|
||||
static void PrintBindServiceMethodBody(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service) {
|
||||
vars["service_name"] = service->name();
|
||||
p->Indent();
|
||||
p->Print(vars,
|
||||
@@ -949,8 +965,8 @@ static void PrintBindServiceMethodBody(Printer *p, VARS &vars,
|
||||
p->Outdent();
|
||||
}
|
||||
|
||||
static void PrintService(Printer *p, VARS &vars,
|
||||
const ServiceDescriptor *service,
|
||||
static void PrintService(Printer* p, VARS& vars,
|
||||
const ServiceDescriptor* service,
|
||||
bool disable_version) {
|
||||
vars["service_name"] = service->name();
|
||||
vars["service_class_name"] = ServiceClassName(service->name());
|
||||
@@ -1030,7 +1046,7 @@ static void PrintService(Printer *p, VARS &vars,
|
||||
p->Print("}\n");
|
||||
}
|
||||
|
||||
static void PrintStaticImports(Printer *p) {
|
||||
static void PrintStaticImports(Printer* p) {
|
||||
p->Print(
|
||||
"import java.nio.ByteBuffer;\n"
|
||||
"import static "
|
||||
@@ -1063,9 +1079,9 @@ static void PrintStaticImports(Printer *p) {
|
||||
"io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;\n\n");
|
||||
}
|
||||
|
||||
static void GenerateService(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer, VARS &vars,
|
||||
bool disable_version) {
|
||||
static void GenerateService(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer, VARS& vars,
|
||||
bool disable_version) {
|
||||
// All non-generated classes must be referred by fully qualified names to
|
||||
// avoid collision with generated classes.
|
||||
vars["String"] = "java.lang.String";
|
||||
@@ -1098,11 +1114,11 @@ static void GenerateService(const grpc_generator::Service *service,
|
||||
|
||||
PrintService(printer, vars, service, disable_version);
|
||||
}
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
grpc::string GenerateServiceSource(
|
||||
grpc_generator::File *file, const grpc_generator::Service *service,
|
||||
grpc_java_generator::Parameters *parameters) {
|
||||
grpc_generator::File* file, const grpc_generator::Service* service,
|
||||
grpc_java_generator::Parameters* parameters) {
|
||||
grpc::string out;
|
||||
auto printer = file->CreatePrinter(&out);
|
||||
VARS vars;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
#define NET_GRPC_COMPILER_JAVA_GENERATOR_H_
|
||||
|
||||
#include <stdlib.h> // for abort()
|
||||
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
@@ -39,8 +40,8 @@ class LogHelper {
|
||||
LogHelper(std::ostream* os) : os_(os) {}
|
||||
#if defined(_MSC_VER)
|
||||
#pragma warning(push)
|
||||
#pragma warning( \
|
||||
disable : 4722) // the flow of control terminates in a destructor
|
||||
#pragma warning(disable \
|
||||
: 4722) // the flow of control terminates in a destructor
|
||||
// (needed to compile ~LogHelper where destructor emits abort intentionally -
|
||||
// inherited from grpc/java code generator).
|
||||
#endif
|
||||
|
||||
@@ -35,22 +35,22 @@ namespace flatbuffers {
|
||||
namespace python {
|
||||
namespace grpc {
|
||||
namespace {
|
||||
bool ClientStreaming(const RPCCall *method) {
|
||||
const Value *val = method->attributes.Lookup("streaming");
|
||||
bool ClientStreaming(const RPCCall* method) {
|
||||
const Value* val = method->attributes.Lookup("streaming");
|
||||
return val != nullptr &&
|
||||
(val->constant == "client" || val->constant == "bidi");
|
||||
}
|
||||
|
||||
bool ServerStreaming(const RPCCall *method) {
|
||||
const Value *val = method->attributes.Lookup("streaming");
|
||||
bool ServerStreaming(const RPCCall* method) {
|
||||
const Value* val = method->attributes.Lookup("streaming");
|
||||
return val != nullptr &&
|
||||
(val->constant == "server" || val->constant == "bidi");
|
||||
}
|
||||
|
||||
void FormatImports(std::stringstream &ss, const Imports &imports) {
|
||||
void FormatImports(std::stringstream& ss, const Imports& imports) {
|
||||
std::set<std::string> modules;
|
||||
std::map<std::string, std::set<std::string>> names_by_module;
|
||||
for (const Import &import : imports.imports) {
|
||||
for (const Import& import : imports.imports) {
|
||||
if (import.IsLocal()) continue; // skip all local imports
|
||||
if (import.name == "") {
|
||||
modules.insert(import.module);
|
||||
@@ -59,14 +59,14 @@ void FormatImports(std::stringstream &ss, const Imports &imports) {
|
||||
}
|
||||
}
|
||||
|
||||
for (const std::string &module : modules) {
|
||||
for (const std::string& module : modules) {
|
||||
ss << "import " << module << '\n';
|
||||
}
|
||||
ss << '\n';
|
||||
for (const auto &import : names_by_module) {
|
||||
for (const auto& import : names_by_module) {
|
||||
ss << "from " << import.first << " import ";
|
||||
size_t i = 0;
|
||||
for (const std::string &name : import.second) {
|
||||
for (const std::string& name : import.second) {
|
||||
if (i > 0) ss << ", ";
|
||||
ss << name;
|
||||
++i;
|
||||
@@ -76,8 +76,8 @@ void FormatImports(std::stringstream &ss, const Imports &imports) {
|
||||
ss << "\n\n";
|
||||
}
|
||||
|
||||
bool SaveStub(const std::string &filename, const Imports &imports,
|
||||
const std::string &content) {
|
||||
bool SaveStub(const std::string& filename, const Imports& imports,
|
||||
const std::string& content) {
|
||||
std::stringstream ss;
|
||||
ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n"
|
||||
<< '\n'
|
||||
@@ -90,8 +90,8 @@ bool SaveStub(const std::string &filename, const Imports &imports,
|
||||
return flatbuffers::SaveFile(filename.c_str(), ss.str(), false);
|
||||
}
|
||||
|
||||
bool SaveService(const std::string &filename, const Imports &imports,
|
||||
const std::string &content) {
|
||||
bool SaveService(const std::string& filename, const Imports& imports,
|
||||
const std::string& content) {
|
||||
std::stringstream ss;
|
||||
ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" << '\n';
|
||||
FormatImports(ss, imports);
|
||||
@@ -103,32 +103,33 @@ bool SaveService(const std::string &filename, const Imports &imports,
|
||||
|
||||
class BaseGenerator {
|
||||
protected:
|
||||
BaseGenerator(const Parser &parser, const Namer::Config &config,
|
||||
const std::string &path, const Version &version)
|
||||
: parser_{ parser },
|
||||
namer_{ WithFlagOptions(config, parser.opts, path), Keywords(version) },
|
||||
version_{ version },
|
||||
BaseGenerator(const Parser& parser, const Namer::Config& config,
|
||||
const std::string& path, const Version& version)
|
||||
: parser_{parser},
|
||||
namer_{WithFlagOptions(config, parser.opts, path), Keywords(version)},
|
||||
version_{version},
|
||||
path_(path) {}
|
||||
|
||||
protected:
|
||||
std::string ModuleForFile(const std::string &file) const {
|
||||
std::string ModuleForFile(const std::string& file) const {
|
||||
std::string module = parser_.opts.include_prefix + StripExtension(file) +
|
||||
parser_.opts.filename_suffix;
|
||||
std::replace(module.begin(), module.end(), '/', '.');
|
||||
return module;
|
||||
}
|
||||
|
||||
template<typename T> std::string ModuleFor(const T *def) const {
|
||||
template <typename T>
|
||||
std::string ModuleFor(const T* def) const {
|
||||
if (parser_.opts.one_file) return ModuleForFile(def->file);
|
||||
return namer_.NamespacedType(*def);
|
||||
}
|
||||
|
||||
std::string NamespaceDir(const Parser &parser, const std::string &path,
|
||||
const Namespace &ns, const bool dasherize) {
|
||||
std::string NamespaceDir(const Parser& parser, const std::string& path,
|
||||
const Namespace& ns, const bool dasherize) {
|
||||
EnsureDirExists(path);
|
||||
if (parser.opts.one_file) return path;
|
||||
std::string namespace_dir = path; // Either empty or ends in separator.
|
||||
auto &namespaces = ns.components;
|
||||
auto& namespaces = ns.components;
|
||||
for (auto it = namespaces.begin(); it != namespaces.end(); ++it) {
|
||||
namespace_dir +=
|
||||
!dasherize ? *it : ConvertCase(*it, Case::kDasher, Case::kUpperCamel);
|
||||
@@ -138,32 +139,32 @@ class BaseGenerator {
|
||||
return namespace_dir;
|
||||
}
|
||||
|
||||
std::string NamespaceDir(const Namespace &ns, const bool dasherize) {
|
||||
std::string NamespaceDir(const Namespace& ns, const bool dasherize) {
|
||||
return NamespaceDir(parser_, path_, ns, dasherize);
|
||||
}
|
||||
|
||||
const Parser &parser_;
|
||||
const Parser& parser_;
|
||||
const IdlNamer namer_;
|
||||
const Version version_;
|
||||
const std::string &path_;
|
||||
const std::string& path_;
|
||||
};
|
||||
|
||||
class StubGenerator : public BaseGenerator {
|
||||
public:
|
||||
StubGenerator(const Parser &parser, const std::string &path,
|
||||
const Version &version)
|
||||
StubGenerator(const Parser& parser, const std::string& path,
|
||||
const Version& version)
|
||||
: BaseGenerator(parser, kStubConfig, path, version) {}
|
||||
|
||||
bool Generate() {
|
||||
Imports imports;
|
||||
std::stringstream stub;
|
||||
std::string ns_name{};
|
||||
for (const ServiceDef *service : parser_.services_.vec) {
|
||||
for (const ServiceDef* service : parser_.services_.vec) {
|
||||
Generate(stub, service, &imports);
|
||||
ns_name = NamespaceDir(*service->defined_namespace, false);
|
||||
}
|
||||
|
||||
std::string sanitized_suffix{ parser_.opts.grpc_filename_suffix };
|
||||
std::string sanitized_suffix{parser_.opts.grpc_filename_suffix};
|
||||
std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_');
|
||||
std::string filename =
|
||||
ns_name + kPathSeparator +
|
||||
@@ -174,14 +175,14 @@ class StubGenerator : public BaseGenerator {
|
||||
}
|
||||
|
||||
private:
|
||||
void Generate(std::stringstream &ss, const ServiceDef *service,
|
||||
Imports *imports) {
|
||||
void Generate(std::stringstream& ss, const ServiceDef* service,
|
||||
Imports* imports) {
|
||||
imports->Import("grpc");
|
||||
|
||||
ss << "class " << service->name << "Stub(object):\n"
|
||||
<< " def __init__(self, channel: grpc.Channel) -> None: ...\n";
|
||||
|
||||
for (const RPCCall *method : service->calls.vec) {
|
||||
for (const RPCCall* method : service->calls.vec) {
|
||||
std::string request = "bytes";
|
||||
std::string response = "bytes";
|
||||
|
||||
@@ -213,7 +214,7 @@ class StubGenerator : public BaseGenerator {
|
||||
ss << "\n\n";
|
||||
ss << "class " << service->name << "Servicer(object):\n";
|
||||
|
||||
for (const RPCCall *method : service->calls.vec) {
|
||||
for (const RPCCall* method : service->calls.vec) {
|
||||
std::string request = "bytes";
|
||||
std::string response = "bytes";
|
||||
|
||||
@@ -252,8 +253,8 @@ class StubGenerator : public BaseGenerator {
|
||||
|
||||
class ServiceGenerator : public BaseGenerator {
|
||||
public:
|
||||
ServiceGenerator(const Parser &parser, const std::string &path,
|
||||
const Version &version)
|
||||
ServiceGenerator(const Parser& parser, const std::string& path,
|
||||
const Version& version)
|
||||
: BaseGenerator(parser, kConfig, path, version) {}
|
||||
|
||||
bool Generate() {
|
||||
@@ -274,14 +275,14 @@ class ServiceGenerator : public BaseGenerator {
|
||||
}
|
||||
|
||||
std::string ns_name{};
|
||||
for (const ServiceDef *service : parser_.services_.vec) {
|
||||
for (const ServiceDef* service : parser_.services_.vec) {
|
||||
GenerateStub(ss, service, &imports);
|
||||
GenerateServicer(ss, service, &imports);
|
||||
GenerateRegister(ss, service, &imports);
|
||||
ns_name = NamespaceDir(*service->defined_namespace, false);
|
||||
}
|
||||
|
||||
std::string sanitized_suffix{ parser_.opts.grpc_filename_suffix };
|
||||
std::string sanitized_suffix{parser_.opts.grpc_filename_suffix};
|
||||
std::replace(sanitized_suffix.begin(), sanitized_suffix.end(), '.', '_');
|
||||
std::string filename =
|
||||
ns_name + kPathSeparator +
|
||||
@@ -292,8 +293,8 @@ class ServiceGenerator : public BaseGenerator {
|
||||
}
|
||||
|
||||
private:
|
||||
void GenerateStub(std::stringstream &ss, const ServiceDef *service,
|
||||
Imports *imports) {
|
||||
void GenerateStub(std::stringstream& ss, const ServiceDef* service,
|
||||
Imports* imports) {
|
||||
ss << "class " << service->name << "Stub";
|
||||
if (version_.major != 3) ss << "(object)";
|
||||
ss << ":\n"
|
||||
@@ -307,7 +308,7 @@ class ServiceGenerator : public BaseGenerator {
|
||||
<< " '''\n"
|
||||
<< '\n';
|
||||
|
||||
for (const RPCCall *method : service->calls.vec) {
|
||||
for (const RPCCall* method : service->calls.vec) {
|
||||
std::string response = namer_.Type(*method->response);
|
||||
|
||||
imports->Import(ModuleFor(method->response), response);
|
||||
@@ -330,8 +331,8 @@ class ServiceGenerator : public BaseGenerator {
|
||||
ss << '\n';
|
||||
}
|
||||
|
||||
void GenerateServicer(std::stringstream &ss, const ServiceDef *service,
|
||||
Imports *imports) {
|
||||
void GenerateServicer(std::stringstream& ss, const ServiceDef* service,
|
||||
Imports* imports) {
|
||||
imports->Import("grpc");
|
||||
|
||||
ss << "class " << service->name << "Servicer";
|
||||
@@ -340,7 +341,7 @@ class ServiceGenerator : public BaseGenerator {
|
||||
<< " '''Interface exported by the server.'''\n"
|
||||
<< '\n';
|
||||
|
||||
for (const RPCCall *method : service->calls.vec) {
|
||||
for (const RPCCall* method : service->calls.vec) {
|
||||
const std::string request_param =
|
||||
ClientStreaming(method) ? "request_iterator" : "request";
|
||||
ss << " def " << method->name << "(self, " << request_param
|
||||
@@ -354,15 +355,15 @@ class ServiceGenerator : public BaseGenerator {
|
||||
ss << '\n';
|
||||
}
|
||||
|
||||
void GenerateRegister(std::stringstream &ss, const ServiceDef *service,
|
||||
Imports *imports) {
|
||||
void GenerateRegister(std::stringstream& ss, const ServiceDef* service,
|
||||
Imports* imports) {
|
||||
imports->Import("grpc");
|
||||
|
||||
ss << "def add_" << service->name
|
||||
<< "Servicer_to_server(servicer, server):\n"
|
||||
<< " rpc_method_handlers = {\n";
|
||||
|
||||
for (const RPCCall *method : service->calls.vec) {
|
||||
for (const RPCCall* method : service->calls.vec) {
|
||||
std::string request = namer_.Type(*method->request);
|
||||
|
||||
imports->Import(ModuleFor(method->request), request);
|
||||
@@ -393,15 +394,15 @@ class ServiceGenerator : public BaseGenerator {
|
||||
};
|
||||
} // namespace
|
||||
|
||||
bool Generate(const Parser &parser, const std::string &path,
|
||||
const Version &version) {
|
||||
ServiceGenerator generator{ parser, path, version };
|
||||
bool Generate(const Parser& parser, const std::string& path,
|
||||
const Version& version) {
|
||||
ServiceGenerator generator{parser, path, version};
|
||||
return generator.Generate();
|
||||
}
|
||||
|
||||
bool GenerateStub(const Parser &parser, const std::string &path,
|
||||
const Version &version) {
|
||||
StubGenerator generator{ parser, path, version };
|
||||
bool GenerateStub(const Parser& parser, const std::string& path,
|
||||
const Version& version) {
|
||||
StubGenerator generator{parser, path, version};
|
||||
return generator.Generate();
|
||||
}
|
||||
|
||||
|
||||
@@ -27,11 +27,11 @@
|
||||
namespace flatbuffers {
|
||||
namespace python {
|
||||
namespace grpc {
|
||||
bool Generate(const Parser &parser, const std::string &path,
|
||||
const Version &version);
|
||||
bool Generate(const Parser& parser, const std::string& path,
|
||||
const Version& version);
|
||||
|
||||
bool GenerateStub(const Parser &parser, const std::string &path,
|
||||
const Version &version);
|
||||
bool GenerateStub(const Parser& parser, const std::string& path,
|
||||
const Version& version);
|
||||
} // namespace grpc
|
||||
} // namespace python
|
||||
} // namespace flatbuffers
|
||||
|
||||
@@ -20,34 +20,35 @@
|
||||
* please open an issue in the flatbuffers repository. This file should always
|
||||
* be maintained according to the Swift-grpc repository
|
||||
*/
|
||||
#include "src/compiler/swift_generator.h"
|
||||
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
|
||||
#include "flatbuffers/util.h"
|
||||
#include "src/compiler/schema_interface.h"
|
||||
#include "src/compiler/swift_generator.h"
|
||||
|
||||
namespace grpc_swift_generator {
|
||||
namespace {
|
||||
|
||||
static std::string WrapInNameSpace(const std::vector<std::string> &components,
|
||||
const grpc::string &name) {
|
||||
static std::string WrapInNameSpace(const std::vector<std::string>& components,
|
||||
const grpc::string& name) {
|
||||
std::string qualified_name;
|
||||
for (auto it = components.begin(); it != components.end(); ++it)
|
||||
qualified_name += *it + "_";
|
||||
return qualified_name + name;
|
||||
}
|
||||
|
||||
static grpc::string GenerateMessage(const std::vector<std::string> &components,
|
||||
const grpc::string &name) {
|
||||
static grpc::string GenerateMessage(const std::vector<std::string>& components,
|
||||
const grpc::string& name) {
|
||||
return "Message<" + WrapInNameSpace(components, name) + ">";
|
||||
}
|
||||
|
||||
// MARK: - Client
|
||||
|
||||
static void GenerateClientFuncName(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateClientFuncName(
|
||||
const grpc_generator::Method* method, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
if (method->NoStreaming()) {
|
||||
printer->Print(vars,
|
||||
@@ -83,9 +84,9 @@ static void GenerateClientFuncName(const grpc_generator::Method *method,
|
||||
" ) -> BidirectionalStreamingCall<$Input$, $Output$>");
|
||||
}
|
||||
|
||||
static void GenerateClientFuncBody(const grpc_generator::Method *method,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateClientFuncBody(
|
||||
const grpc_generator::Method* method, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
vars["Interceptor"] =
|
||||
"interceptors: self.interceptors?.make$MethodName$Interceptors() ?? []";
|
||||
@@ -133,9 +134,9 @@ static void GenerateClientFuncBody(const grpc_generator::Method *method,
|
||||
" )\n");
|
||||
}
|
||||
|
||||
void GenerateClientProtocol(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
void GenerateClientProtocol(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(
|
||||
vars,
|
||||
@@ -207,8 +208,8 @@ void GenerateClientProtocol(const grpc_generator::Service *service,
|
||||
printer->Print("}\n\n");
|
||||
}
|
||||
|
||||
void GenerateClientClass(grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
void GenerateClientClass(grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars,
|
||||
"$ACCESS$ final class $ServiceQualifiedName$ServiceClient: "
|
||||
@@ -237,7 +238,7 @@ void GenerateClientClass(grpc_generator::Printer *printer,
|
||||
|
||||
// MARK: - Server
|
||||
|
||||
grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
|
||||
grpc::string GenerateServerFuncName(const grpc_generator::Method* method) {
|
||||
if (method->NoStreaming()) {
|
||||
return "func $MethodName$(request: $Input$"
|
||||
", context: StatusOnlyCallContext) -> EventLoopFuture<$Output$>";
|
||||
@@ -258,7 +259,7 @@ grpc::string GenerateServerFuncName(const grpc_generator::Method *method) {
|
||||
"-> EventLoopFuture<(StreamEvent<$Input$>) -> Void>";
|
||||
}
|
||||
|
||||
grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
|
||||
grpc::string GenerateServerExtensionBody(const grpc_generator::Method* method) {
|
||||
grpc::string start = " case \"$MethodName$\":\n ";
|
||||
grpc::string interceptors =
|
||||
" interceptors: self.interceptors?.make$MethodName$Interceptors() "
|
||||
@@ -302,9 +303,9 @@ grpc::string GenerateServerExtensionBody(const grpc_generator::Method *method) {
|
||||
return "";
|
||||
}
|
||||
|
||||
void GenerateServerProtocol(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
void GenerateServerProtocol(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars,
|
||||
"$ACCESS$ protocol $ServiceQualifiedName$Provider: "
|
||||
@@ -373,14 +374,16 @@ void GenerateServerProtocol(const grpc_generator::Service *service,
|
||||
}
|
||||
printer->Print("}");
|
||||
}
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
grpc::string Generate(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service) {
|
||||
grpc::string Generate(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service) {
|
||||
grpc::string output;
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
vars["PATH"] = file->package();
|
||||
if (!file->package().empty()) { vars["PATH"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["PATH"].append(".");
|
||||
}
|
||||
vars["ServiceQualifiedName"] =
|
||||
WrapInNameSpace(service->namespace_parts(), service->name());
|
||||
vars["ServiceName"] = service->name();
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
#include "src/compiler/schema_interface.h"
|
||||
|
||||
#ifndef GRPC_CUSTOM_STRING
|
||||
# include <string>
|
||||
# define GRPC_CUSTOM_STRING std::string
|
||||
#include <string>
|
||||
#define GRPC_CUSTOM_STRING std::string
|
||||
#endif
|
||||
|
||||
namespace grpc {
|
||||
@@ -31,7 +31,7 @@ typedef GRPC_CUSTOM_STRING string;
|
||||
} // namespace grpc
|
||||
|
||||
namespace grpc_swift_generator {
|
||||
grpc::string Generate(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service);
|
||||
grpc::string Generate(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service);
|
||||
grpc::string GenerateHeader();
|
||||
} // namespace grpc_swift_generator
|
||||
|
||||
@@ -33,8 +33,8 @@ namespace grpc_ts_generator {
|
||||
namespace {
|
||||
|
||||
static grpc::string GenerateNamespace(const std::vector<std::string> ns,
|
||||
const std::string filename,
|
||||
const bool include_separator) {
|
||||
const std::string filename,
|
||||
const bool include_separator) {
|
||||
grpc::string path = "";
|
||||
if (include_separator) path += ".";
|
||||
|
||||
@@ -56,10 +56,10 @@ static grpc::string GenerateNamespace(const std::vector<std::string> ns,
|
||||
|
||||
// MARK: - Shared code
|
||||
|
||||
static void GenerateImports(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary,
|
||||
const bool grpc_var_import) {
|
||||
static void GenerateImports(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary,
|
||||
const bool grpc_var_import) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(
|
||||
"// Generated GRPC code for FlatBuffers TS *** DO NOT EDIT ***\n");
|
||||
@@ -105,9 +105,9 @@ static void GenerateImports(const grpc_generator::Service *service,
|
||||
|
||||
// MARK: - Generate Main GRPC Code
|
||||
|
||||
static void GetStreamType(grpc_generator::Printer *printer,
|
||||
const grpc_generator::Method *method,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GetStreamType(grpc_generator::Printer* printer,
|
||||
const grpc_generator::Method* method,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
auto client_streaming = method->ClientStreaming() || method->BidiStreaming();
|
||||
auto server_streaming = method->ServerStreaming() || method->BidiStreaming();
|
||||
@@ -117,8 +117,9 @@ static void GetStreamType(grpc_generator::Printer *printer,
|
||||
printer->Print(vars, "responseStream: $ServerStreaming$,\n");
|
||||
}
|
||||
|
||||
static void GenerateSerializeMethod(grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateSerializeMethod(
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars, "function serialize_$Type$(buffer_args) {\n");
|
||||
printer->Indent();
|
||||
@@ -134,8 +135,8 @@ static void GenerateSerializeMethod(grpc_generator::Printer *printer,
|
||||
}
|
||||
|
||||
static void GenerateDeserializeMethod(
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars, "function deserialize_$Type$(buffer) {\n");
|
||||
printer->Indent();
|
||||
@@ -146,9 +147,9 @@ static void GenerateDeserializeMethod(
|
||||
printer->Print("}\n\n");
|
||||
}
|
||||
|
||||
static void GenerateMethods(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateMethods(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
|
||||
std::set<grpc::string> generated_functions;
|
||||
@@ -178,9 +179,9 @@ static void GenerateMethods(const grpc_generator::Service *service,
|
||||
}
|
||||
}
|
||||
|
||||
static void GenerateService(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateService(const grpc_generator::Service* service,
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
vars["NAME"] = service->name() + "Service";
|
||||
|
||||
@@ -213,17 +214,19 @@ static void GenerateService(const grpc_generator::Service *service,
|
||||
"grpc.makeGenericClientConstructor($NAME$);");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
grpc::string Generate(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
const grpc::string &filename) {
|
||||
grpc::string Generate(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
const grpc::string& filename) {
|
||||
grpc::string output;
|
||||
std::map<grpc::string, grpc::string> vars;
|
||||
|
||||
vars["PATH"] = file->package();
|
||||
|
||||
if (!file->package().empty()) { vars["PATH"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["PATH"].append(".");
|
||||
}
|
||||
|
||||
vars["ServiceName"] = service->name();
|
||||
vars["FBSFile"] = service->name() + "_fbs";
|
||||
@@ -240,8 +243,8 @@ namespace {
|
||||
|
||||
// MARK: - Generate Interface
|
||||
|
||||
static void FillInterface(grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void FillInterface(grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars,
|
||||
"interface I$ServiceName$Service_I$MethodName$ extends "
|
||||
@@ -258,9 +261,9 @@ static void FillInterface(grpc_generator::Printer *printer,
|
||||
printer->Print("}\n");
|
||||
}
|
||||
|
||||
static void GenerateInterfaces(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateInterfaces(
|
||||
const grpc_generator::Service* service, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
for (auto it = 0; it < service->method_count(); it++) {
|
||||
auto method = service->method(it);
|
||||
@@ -281,8 +284,8 @@ static void GenerateInterfaces(const grpc_generator::Service *service,
|
||||
}
|
||||
|
||||
static void GenerateExportedInterface(
|
||||
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
const grpc_generator::Service* service, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars,
|
||||
"export interface I$ServiceName$Server extends "
|
||||
@@ -324,9 +327,9 @@ static void GenerateExportedInterface(
|
||||
printer->Print("}\n");
|
||||
}
|
||||
|
||||
static void GenerateMainInterface(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateMainInterface(
|
||||
const grpc_generator::Service* service, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(
|
||||
vars,
|
||||
@@ -351,11 +354,13 @@ static void GenerateMainInterface(const grpc_generator::Service *service,
|
||||
|
||||
static grpc::string GenerateMetaData() { return "metadata: grpc.Metadata"; }
|
||||
|
||||
static grpc::string GenerateOptions() { return "options: Partial<grpc.CallOptions>"; }
|
||||
static grpc::string GenerateOptions() {
|
||||
return "options: Partial<grpc.CallOptions>";
|
||||
}
|
||||
|
||||
static void GenerateUnaryClientInterface(
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
|
||||
grpc::string callback =
|
||||
@@ -369,8 +374,8 @@ static void GenerateUnaryClientInterface(
|
||||
}
|
||||
|
||||
static void GenerateClientWriteStreamInterface(
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
grpc::string main = "$ISPUBLIC$$MethodName$(";
|
||||
grpc::string callback =
|
||||
@@ -386,8 +391,8 @@ static void GenerateClientWriteStreamInterface(
|
||||
}
|
||||
|
||||
static void GenerateClientReadableStreamInterface(
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
grpc::string main = "$ISPUBLIC$$MethodName$(request: $INPUT$, ";
|
||||
grpc::string end_function = "): grpc.ClientReadableStream<$OUTPUT$>;\n";
|
||||
@@ -398,8 +403,8 @@ static void GenerateClientReadableStreamInterface(
|
||||
}
|
||||
|
||||
static void GenerateDepluxStreamInterface(
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
grpc::string main = "$ISPUBLIC$$MethodName$(";
|
||||
grpc::string end_function =
|
||||
@@ -413,9 +418,9 @@ static void GenerateDepluxStreamInterface(
|
||||
.c_str());
|
||||
}
|
||||
|
||||
static void GenerateClientInterface(const grpc_generator::Service *service,
|
||||
grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
static void GenerateClientInterface(
|
||||
const grpc_generator::Service* service, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars, "export interface I$ServiceName$Client {\n");
|
||||
printer->Indent();
|
||||
@@ -452,8 +457,8 @@ static void GenerateClientInterface(const grpc_generator::Service *service,
|
||||
}
|
||||
|
||||
static void GenerateClientClassInterface(
|
||||
const grpc_generator::Service *service, grpc_generator::Printer *printer,
|
||||
std::map<grpc::string, grpc::string> *dictonary) {
|
||||
const grpc_generator::Service* service, grpc_generator::Printer* printer,
|
||||
std::map<grpc::string, grpc::string>* dictonary) {
|
||||
auto vars = *dictonary;
|
||||
printer->Print(vars,
|
||||
"export class $ServiceName$Client extends grpc.Client "
|
||||
@@ -492,12 +497,11 @@ static void GenerateClientClassInterface(
|
||||
printer->Outdent();
|
||||
printer->Print("}\n");
|
||||
}
|
||||
} // namespace
|
||||
} // namespace
|
||||
|
||||
|
||||
grpc::string GenerateInterface(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
const grpc::string &filename) {
|
||||
grpc::string GenerateInterface(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
const grpc::string& filename) {
|
||||
grpc::string output;
|
||||
|
||||
std::set<grpc::string> generated_functions;
|
||||
@@ -505,7 +509,9 @@ grpc::string GenerateInterface(grpc_generator::File *file,
|
||||
|
||||
vars["PATH"] = file->package();
|
||||
|
||||
if (!file->package().empty()) { vars["PATH"].append("."); }
|
||||
if (!file->package().empty()) {
|
||||
vars["PATH"].append(".");
|
||||
}
|
||||
|
||||
vars["ServiceName"] = service->name();
|
||||
vars["FBSFile"] = service->name() + "_fbs";
|
||||
|
||||
@@ -5,8 +5,8 @@
|
||||
#include "src/compiler/schema_interface.h"
|
||||
|
||||
#ifndef GRPC_CUSTOM_STRING
|
||||
# include <string>
|
||||
# define GRPC_CUSTOM_STRING std::string
|
||||
#include <string>
|
||||
#define GRPC_CUSTOM_STRING std::string
|
||||
#endif
|
||||
|
||||
namespace grpc {
|
||||
@@ -16,11 +16,11 @@ typedef GRPC_CUSTOM_STRING string;
|
||||
} // namespace grpc
|
||||
|
||||
namespace grpc_ts_generator {
|
||||
grpc::string Generate(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
const grpc::string &filename);
|
||||
grpc::string Generate(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
const grpc::string& filename);
|
||||
|
||||
grpc::string GenerateInterface(grpc_generator::File *file,
|
||||
const grpc_generator::Service *service,
|
||||
const grpc::string &filename);
|
||||
grpc::string GenerateInterface(grpc_generator::File* file,
|
||||
const grpc_generator::Service* service,
|
||||
const grpc::string& filename);
|
||||
} // namespace grpc_ts_generator
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import java.nio.ByteBuffer;
|
||||
import MyGame.Example.Monster;
|
||||
import MyGame.Example.Stat;
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import java.nio.ByteBuffer;
|
||||
|
||||
class GameFactory {
|
||||
public static Monster createMonster(String monsterName, short nestedMonsterHp, short nestedMonsterMana) {
|
||||
public static Monster createMonster(
|
||||
String monsterName, short nestedMonsterHp, short nestedMonsterMana) {
|
||||
FlatBufferBuilder builder = new FlatBufferBuilder();
|
||||
|
||||
int name_offset = builder.createString(monsterName);
|
||||
@@ -31,12 +32,11 @@ class GameFactory {
|
||||
return monster;
|
||||
}
|
||||
|
||||
public static Stat createStat(String greeting, long val, int count) {
|
||||
public static Stat createStat(String greeting, long val, int count) {
|
||||
FlatBufferBuilder builder = new FlatBufferBuilder();
|
||||
int statOffset = Stat.createStat(builder, builder.createString(greeting), val, count);
|
||||
builder.finish(statOffset);
|
||||
Stat stat = Stat.getRootAsStat(builder.dataBuffer());
|
||||
return stat;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -17,226 +17,236 @@
|
||||
import MyGame.Example.Monster;
|
||||
import MyGame.Example.MonsterStorageGrpc;
|
||||
import MyGame.Example.Stat;
|
||||
import com.google.flatbuffers.FlatBufferBuilder;
|
||||
import io.grpc.ManagedChannel;
|
||||
import io.grpc.ManagedChannelBuilder;
|
||||
import io.grpc.Server;
|
||||
import io.grpc.ServerBuilder;
|
||||
import io.grpc.stub.StreamObserver;
|
||||
import java.io.IOException;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import org.junit.Assert;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.InterruptedException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
|
||||
|
||||
/**
|
||||
* Demonstrates basic client-server interaction using grpc-java over netty.
|
||||
*/
|
||||
/** Demonstrates basic client-server interaction using grpc-java over netty. */
|
||||
public class JavaGrpcTest {
|
||||
static final String BIG_MONSTER_NAME = "Cyberdemon";
|
||||
static final short nestedMonsterHp = 600;
|
||||
static final short nestedMonsterMana = 1024;
|
||||
static final int numStreamedMsgs = 10;
|
||||
static final int timeoutMs = 3000;
|
||||
static Server server;
|
||||
static ManagedChannel channel;
|
||||
static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub;
|
||||
static MonsterStorageGrpc.MonsterStorageStub asyncStub;
|
||||
static final String BIG_MONSTER_NAME = "Cyberdemon";
|
||||
static final short nestedMonsterHp = 600;
|
||||
static final short nestedMonsterMana = 1024;
|
||||
static final int numStreamedMsgs = 10;
|
||||
static final int timeoutMs = 3000;
|
||||
static Server server;
|
||||
static ManagedChannel channel;
|
||||
static MonsterStorageGrpc.MonsterStorageBlockingStub blockingStub;
|
||||
static MonsterStorageGrpc.MonsterStorageStub asyncStub;
|
||||
|
||||
static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase {
|
||||
@Override
|
||||
public void store(Monster request, io.grpc.stub.StreamObserver<Stat> responseObserver) {
|
||||
Assert.assertEquals(request.name(), BIG_MONSTER_NAME);
|
||||
Assert.assertEquals(request.hp(), nestedMonsterHp);
|
||||
Assert.assertEquals(request.mana(), nestedMonsterMana);
|
||||
System.out.println("Received store request from " + request.name());
|
||||
// Create a response from the incoming request name.
|
||||
Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10);
|
||||
responseObserver.onNext(stat);
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void retrieve(Stat request, io.grpc.stub.StreamObserver<Monster> responseObserver) {
|
||||
// Create 10 monsters for streaming response.
|
||||
for (int i=0; i<numStreamedMsgs; i++) {
|
||||
Monster monster = GameFactory.createMonsterFromStat(request, i);
|
||||
responseObserver.onNext(monster);
|
||||
}
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public StreamObserver<Monster> getMaxHitPoint(final StreamObserver<Stat> responseObserver) {
|
||||
return computeMinMax(responseObserver, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public StreamObserver<Monster> getMinMaxHitPoints(final StreamObserver<Stat> responseObserver) {
|
||||
return computeMinMax(responseObserver, true);
|
||||
}
|
||||
|
||||
private StreamObserver<Monster> computeMinMax(final StreamObserver<Stat> responseObserver, final boolean includeMin) {
|
||||
final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE);
|
||||
final AtomicReference<String> maxHpMonsterName = new AtomicReference<String>();
|
||||
final AtomicInteger maxHpCount = new AtomicInteger();
|
||||
|
||||
final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE);
|
||||
final AtomicReference<String> minHpMonsterName = new AtomicReference<String>();
|
||||
final AtomicInteger minHpCount = new AtomicInteger();
|
||||
|
||||
return new StreamObserver<Monster>() {
|
||||
public void onNext(Monster monster) {
|
||||
if (monster.hp() > maxHp.get()) {
|
||||
// Found a monster of higher hit points.
|
||||
maxHp.set(monster.hp());
|
||||
maxHpMonsterName.set(monster.name());
|
||||
maxHpCount.set(1);
|
||||
}
|
||||
else if (monster.hp() == maxHp.get()) {
|
||||
// Count how many times we saw a monster of current max hit points.
|
||||
maxHpCount.getAndIncrement();
|
||||
}
|
||||
|
||||
if (monster.hp() < minHp.get()) {
|
||||
// Found a monster of a lower hit points.
|
||||
minHp.set(monster.hp());
|
||||
minHpMonsterName.set(monster.name());
|
||||
minHpCount.set(1);
|
||||
}
|
||||
else if (monster.hp() == minHp.get()) {
|
||||
// Count how many times we saw a monster of current min hit points.
|
||||
minHpCount.getAndIncrement();
|
||||
}
|
||||
}
|
||||
public void onCompleted() {
|
||||
Stat maxHpStat = GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get());
|
||||
// Send max hit points first.
|
||||
responseObserver.onNext(maxHpStat);
|
||||
if (includeMin) {
|
||||
// Send min hit points.
|
||||
Stat minHpStat = GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get());
|
||||
responseObserver.onNext(minHpStat);
|
||||
}
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
public void onError(Throwable t) {
|
||||
// Not expected
|
||||
Assert.fail();
|
||||
};
|
||||
};
|
||||
}
|
||||
static class MyService extends MonsterStorageGrpc.MonsterStorageImplBase {
|
||||
@Override
|
||||
public void store(Monster request, io.grpc.stub.StreamObserver<Stat> responseObserver) {
|
||||
Assert.assertEquals(request.name(), BIG_MONSTER_NAME);
|
||||
Assert.assertEquals(request.hp(), nestedMonsterHp);
|
||||
Assert.assertEquals(request.mana(), nestedMonsterMana);
|
||||
System.out.println("Received store request from " + request.name());
|
||||
// Create a response from the incoming request name.
|
||||
Stat stat = GameFactory.createStat("Hello " + request.name(), 100, 10);
|
||||
responseObserver.onNext(stat);
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@org.junit.BeforeClass
|
||||
public static void startServer() throws IOException {
|
||||
server = ServerBuilder.forPort(0).addService(new MyService()).build().start();
|
||||
int port = server.getPort();
|
||||
channel = ManagedChannelBuilder.forAddress("localhost", port)
|
||||
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
|
||||
// needing certificates.
|
||||
.usePlaintext()
|
||||
.directExecutor()
|
||||
.build();
|
||||
blockingStub = MonsterStorageGrpc.newBlockingStub(channel);
|
||||
asyncStub = MonsterStorageGrpc.newStub(channel);
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testUnary() throws IOException {
|
||||
Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
|
||||
Stat stat = blockingStub.store(monsterRequest);
|
||||
Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME);
|
||||
System.out.println("Received stat response from service: " + stat.id());
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testServerStreaming() throws IOException {
|
||||
Monster monsterRequest = GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
|
||||
Stat stat = blockingStub.store(monsterRequest);
|
||||
Iterator<Monster> iterator = blockingStub.retrieve(stat);
|
||||
int counter = 0;
|
||||
while(iterator.hasNext()) {
|
||||
Monster m = iterator.next();
|
||||
System.out.println("Received monster " + m.name());
|
||||
counter ++;
|
||||
}
|
||||
Assert.assertEquals(counter, numStreamedMsgs);
|
||||
System.out.println("FlatBuffers GRPC client/server test: completed successfully");
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testClientStreaming() throws IOException, InterruptedException {
|
||||
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
|
||||
final CountDownLatch streamAlive = new CountDownLatch(1);
|
||||
|
||||
StreamObserver<Stat> statObserver = new StreamObserver<Stat>() {
|
||||
public void onCompleted() {
|
||||
streamAlive.countDown();
|
||||
}
|
||||
public void onError(Throwable ex) { }
|
||||
public void onNext(Stat stat) {
|
||||
maxHitStat.set(stat);
|
||||
}
|
||||
};
|
||||
StreamObserver<Monster> monsterStream = asyncStub.getMaxHitPoint(statObserver);
|
||||
short count = 10;
|
||||
for (short i = 0;i < count; ++i) {
|
||||
Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
|
||||
monsterStream.onNext(monster);
|
||||
@Override
|
||||
public void retrieve(Stat request, io.grpc.stub.StreamObserver<Monster> responseObserver) {
|
||||
// Create 10 monsters for streaming response.
|
||||
for (int i = 0; i < numStreamedMsgs; i++) {
|
||||
Monster monster = GameFactory.createMonsterFromStat(request, i);
|
||||
responseObserver.onNext(monster);
|
||||
}
|
||||
monsterStream.onCompleted();
|
||||
// Wait a little bit for the server to send the stats of the monster with the max hit-points.
|
||||
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().count(), 1);
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testBiDiStreaming() throws IOException, InterruptedException {
|
||||
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
|
||||
final AtomicReference<Stat> minHitStat = new AtomicReference<Stat>();
|
||||
final CountDownLatch streamAlive = new CountDownLatch(1);
|
||||
@Override
|
||||
public StreamObserver<Monster> getMaxHitPoint(final StreamObserver<Stat> responseObserver) {
|
||||
return computeMinMax(responseObserver, false);
|
||||
}
|
||||
|
||||
StreamObserver<Stat> statObserver = new StreamObserver<Stat>() {
|
||||
public void onCompleted() {
|
||||
streamAlive.countDown();
|
||||
@Override
|
||||
public StreamObserver<Monster> getMinMaxHitPoints(final StreamObserver<Stat> responseObserver) {
|
||||
return computeMinMax(responseObserver, true);
|
||||
}
|
||||
|
||||
private StreamObserver<Monster> computeMinMax(
|
||||
final StreamObserver<Stat> responseObserver, final boolean includeMin) {
|
||||
final AtomicInteger maxHp = new AtomicInteger(Integer.MIN_VALUE);
|
||||
final AtomicReference<String> maxHpMonsterName = new AtomicReference<String>();
|
||||
final AtomicInteger maxHpCount = new AtomicInteger();
|
||||
|
||||
final AtomicInteger minHp = new AtomicInteger(Integer.MAX_VALUE);
|
||||
final AtomicReference<String> minHpMonsterName = new AtomicReference<String>();
|
||||
final AtomicInteger minHpCount = new AtomicInteger();
|
||||
|
||||
return new StreamObserver<Monster>() {
|
||||
public void onNext(Monster monster) {
|
||||
if (monster.hp() > maxHp.get()) {
|
||||
// Found a monster of higher hit points.
|
||||
maxHp.set(monster.hp());
|
||||
maxHpMonsterName.set(monster.name());
|
||||
maxHpCount.set(1);
|
||||
} else if (monster.hp() == maxHp.get()) {
|
||||
// Count how many times we saw a monster of current max hit points.
|
||||
maxHpCount.getAndIncrement();
|
||||
}
|
||||
|
||||
if (monster.hp() < minHp.get()) {
|
||||
// Found a monster of a lower hit points.
|
||||
minHp.set(monster.hp());
|
||||
minHpMonsterName.set(monster.name());
|
||||
minHpCount.set(1);
|
||||
} else if (monster.hp() == minHp.get()) {
|
||||
// Count how many times we saw a monster of current min hit points.
|
||||
minHpCount.getAndIncrement();
|
||||
}
|
||||
}
|
||||
public void onError(Throwable ex) { }
|
||||
public void onNext(Stat stat) {
|
||||
// We expect the server to send the max stat first and then the min stat.
|
||||
if (maxHitStat.get() == null) {
|
||||
|
||||
public void onCompleted() {
|
||||
Stat maxHpStat =
|
||||
GameFactory.createStat(maxHpMonsterName.get(), maxHp.get(), maxHpCount.get());
|
||||
// Send max hit points first.
|
||||
responseObserver.onNext(maxHpStat);
|
||||
if (includeMin) {
|
||||
// Send min hit points.
|
||||
Stat minHpStat =
|
||||
GameFactory.createStat(minHpMonsterName.get(), minHp.get(), minHpCount.get());
|
||||
responseObserver.onNext(minHpStat);
|
||||
}
|
||||
responseObserver.onCompleted();
|
||||
}
|
||||
|
||||
public void onError(Throwable t) {
|
||||
// Not expected
|
||||
Assert.fail();
|
||||
}
|
||||
;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@org.junit.BeforeClass
|
||||
public static void startServer() throws IOException {
|
||||
server = ServerBuilder.forPort(0).addService(new MyService()).build().start();
|
||||
int port = server.getPort();
|
||||
channel =
|
||||
ManagedChannelBuilder.forAddress("localhost", port)
|
||||
// Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
|
||||
// needing certificates.
|
||||
.usePlaintext()
|
||||
.directExecutor()
|
||||
.build();
|
||||
blockingStub = MonsterStorageGrpc.newBlockingStub(channel);
|
||||
asyncStub = MonsterStorageGrpc.newStub(channel);
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testUnary() throws IOException {
|
||||
Monster monsterRequest =
|
||||
GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
|
||||
Stat stat = blockingStub.store(monsterRequest);
|
||||
Assert.assertEquals(stat.id(), "Hello " + BIG_MONSTER_NAME);
|
||||
System.out.println("Received stat response from service: " + stat.id());
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testServerStreaming() throws IOException {
|
||||
Monster monsterRequest =
|
||||
GameFactory.createMonster(BIG_MONSTER_NAME, nestedMonsterHp, nestedMonsterMana);
|
||||
Stat stat = blockingStub.store(monsterRequest);
|
||||
Iterator<Monster> iterator = blockingStub.retrieve(stat);
|
||||
int counter = 0;
|
||||
while (iterator.hasNext()) {
|
||||
Monster m = iterator.next();
|
||||
System.out.println("Received monster " + m.name());
|
||||
counter++;
|
||||
}
|
||||
Assert.assertEquals(counter, numStreamedMsgs);
|
||||
System.out.println("FlatBuffers GRPC client/server test: completed successfully");
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testClientStreaming() throws IOException, InterruptedException {
|
||||
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
|
||||
final CountDownLatch streamAlive = new CountDownLatch(1);
|
||||
|
||||
StreamObserver<Stat> statObserver =
|
||||
new StreamObserver<Stat>() {
|
||||
public void onCompleted() {
|
||||
streamAlive.countDown();
|
||||
}
|
||||
|
||||
public void onError(Throwable ex) {}
|
||||
|
||||
public void onNext(Stat stat) {
|
||||
maxHitStat.set(stat);
|
||||
}
|
||||
else {
|
||||
minHitStat.set(stat);
|
||||
}
|
||||
}
|
||||
};
|
||||
StreamObserver<Monster> monsterStream = asyncStub.getMinMaxHitPoints(statObserver);
|
||||
short count = 10;
|
||||
for (short i = 0;i < count; ++i) {
|
||||
Monster monster = GameFactory.createMonster(BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
|
||||
monsterStream.onNext(monster);
|
||||
}
|
||||
monsterStream.onCompleted();
|
||||
|
||||
// Wait a little bit for the server to send the stats of the monster with the max and min hit-points.
|
||||
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
|
||||
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().count(), 1);
|
||||
|
||||
Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0);
|
||||
Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0);
|
||||
Assert.assertEquals(minHitStat.get().count(), 1);
|
||||
};
|
||||
StreamObserver<Monster> monsterStream = asyncStub.getMaxHitPoint(statObserver);
|
||||
short count = 10;
|
||||
for (short i = 0; i < count; ++i) {
|
||||
Monster monster =
|
||||
GameFactory.createMonster(
|
||||
BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
|
||||
monsterStream.onNext(monster);
|
||||
}
|
||||
monsterStream.onCompleted();
|
||||
// Wait a little bit for the server to send the stats of the monster with the max hit-points.
|
||||
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().count(), 1);
|
||||
}
|
||||
|
||||
@org.junit.Test
|
||||
public void testBiDiStreaming() throws IOException, InterruptedException {
|
||||
final AtomicReference<Stat> maxHitStat = new AtomicReference<Stat>();
|
||||
final AtomicReference<Stat> minHitStat = new AtomicReference<Stat>();
|
||||
final CountDownLatch streamAlive = new CountDownLatch(1);
|
||||
|
||||
StreamObserver<Stat> statObserver =
|
||||
new StreamObserver<Stat>() {
|
||||
public void onCompleted() {
|
||||
streamAlive.countDown();
|
||||
}
|
||||
|
||||
public void onError(Throwable ex) {}
|
||||
|
||||
public void onNext(Stat stat) {
|
||||
// We expect the server to send the max stat first and then the min stat.
|
||||
if (maxHitStat.get() == null) {
|
||||
maxHitStat.set(stat);
|
||||
} else {
|
||||
minHitStat.set(stat);
|
||||
}
|
||||
}
|
||||
};
|
||||
StreamObserver<Monster> monsterStream = asyncStub.getMinMaxHitPoints(statObserver);
|
||||
short count = 10;
|
||||
for (short i = 0; i < count; ++i) {
|
||||
Monster monster =
|
||||
GameFactory.createMonster(
|
||||
BIG_MONSTER_NAME + i, (short) (nestedMonsterHp * i), nestedMonsterMana);
|
||||
monsterStream.onNext(monster);
|
||||
}
|
||||
monsterStream.onCompleted();
|
||||
|
||||
// Wait a little bit for the server to send the stats of the monster with the max and min
|
||||
// hit-points.
|
||||
streamAlive.await(timeoutMs, TimeUnit.MILLISECONDS);
|
||||
|
||||
Assert.assertEquals(maxHitStat.get().id(), BIG_MONSTER_NAME + (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().val(), nestedMonsterHp * (count - 1));
|
||||
Assert.assertEquals(maxHitStat.get().count(), 1);
|
||||
|
||||
Assert.assertEquals(minHitStat.get().id(), BIG_MONSTER_NAME + 0);
|
||||
Assert.assertEquals(minHitStat.get().val(), nestedMonsterHp * 0);
|
||||
Assert.assertEquals(minHitStat.get().count(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
from __future__ import print_function
|
||||
|
||||
from concurrent import futures
|
||||
import os
|
||||
import sys
|
||||
import grpc
|
||||
|
||||
import flatbuffers
|
||||
import grpc
|
||||
|
||||
from concurrent import futures
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'tests'))
|
||||
sys.path.append(os.path.join(os.path.dirname(__file__), "..", "..", "tests"))
|
||||
import MyGame.Example.Monster as Monster
|
||||
import MyGame.Example.Stat as Stat
|
||||
import MyGame.Example.Vec3 as Vec3
|
||||
@@ -39,136 +39,138 @@ test_no_of_monsters = 2
|
||||
|
||||
class MonsterStorage(monster_grpc_fb.MonsterStorageServicer):
|
||||
|
||||
def Store(self, request, context):
|
||||
def Store(self, request, context):
|
||||
|
||||
m = Monster.Monster().GetRootAsMonster(request, 0)
|
||||
m = Monster.Monster().GetRootAsMonster(request, 0)
|
||||
|
||||
assert m.Name().decode("utf-8") == test_monster_name1
|
||||
assert m.Name().decode("utf-8") == test_monster_name1
|
||||
|
||||
assert m.Pos().X() == test_X
|
||||
assert m.Pos().Y() == test_Y
|
||||
assert m.Pos().Z() == test_Z
|
||||
assert m.Pos().Test1() == test_test1
|
||||
assert m.Pos().Test2() == test_color
|
||||
test3 = Test.Test()
|
||||
assert m.Pos().Test3(test3).A() == test_a
|
||||
assert m.Pos().Test3(test3).B() == test_b
|
||||
assert m.Pos().X() == test_X
|
||||
assert m.Pos().Y() == test_Y
|
||||
assert m.Pos().Z() == test_Z
|
||||
assert m.Pos().Test1() == test_test1
|
||||
assert m.Pos().Test2() == test_color
|
||||
test3 = Test.Test()
|
||||
assert m.Pos().Test3(test3).A() == test_a
|
||||
assert m.Pos().Test3(test3).B() == test_b
|
||||
|
||||
assert m.Hp() == test_hp
|
||||
assert m.Hp() == test_hp
|
||||
|
||||
assert m.Color() == test_color
|
||||
assert m.Color() == test_color
|
||||
|
||||
assert m.InventoryLength() == len(test_inventory)
|
||||
for i in range(0, len(test_inventory)):
|
||||
assert m.Inventory(i) == test_inventory[len(test_inventory)-i -1]
|
||||
assert m.InventoryLength() == len(test_inventory)
|
||||
for i in range(0, len(test_inventory)):
|
||||
assert m.Inventory(i) == test_inventory[len(test_inventory) - i - 1]
|
||||
|
||||
assert m.TestType() == test_testtype
|
||||
assert m.TestType() == test_testtype
|
||||
|
||||
assert m.Test() is not None
|
||||
table = m.Test()
|
||||
assert m.Test() is not None
|
||||
table = m.Test()
|
||||
|
||||
m2 = Monster.Monster()
|
||||
m2.Init(table.Bytes, table.Pos)
|
||||
assert m2.Name().decode("utf-8") == test_monster_name2
|
||||
m2 = Monster.Monster()
|
||||
m2.Init(table.Bytes, table.Pos)
|
||||
assert m2.Name().decode("utf-8") == test_monster_name2
|
||||
|
||||
m3 = m.Enemy()
|
||||
assert m3.Name().decode("utf-8") == test_monster_name2
|
||||
m3 = m.Enemy()
|
||||
assert m3.Name().decode("utf-8") == test_monster_name2
|
||||
|
||||
assert m.Testarrayofstring(0).decode("utf-8") == test_string
|
||||
assert m.Testarrayofstring(0).decode("utf-8") == test_string
|
||||
|
||||
b = flatbuffers.Builder(0)
|
||||
i = b.CreateString(test_stat_id)
|
||||
Stat.StatStart(b)
|
||||
Stat.StatAddId(b, i)
|
||||
Stat.StatAddVal(b, test_stat_val)
|
||||
Stat.StatAddCount(b, test_stat_count)
|
||||
b.Finish(Stat.StatEnd(b))
|
||||
return bytes(b.Output())
|
||||
b = flatbuffers.Builder(0)
|
||||
i = b.CreateString(test_stat_id)
|
||||
Stat.StatStart(b)
|
||||
Stat.StatAddId(b, i)
|
||||
Stat.StatAddVal(b, test_stat_val)
|
||||
Stat.StatAddCount(b, test_stat_count)
|
||||
b.Finish(Stat.StatEnd(b))
|
||||
return bytes(b.Output())
|
||||
|
||||
def Retrieve(self, request, context):
|
||||
def Retrieve(self, request, context):
|
||||
|
||||
s = Stat.Stat().GetRootAsStat(request, 0)
|
||||
s = Stat.Stat().GetRootAsStat(request, 0)
|
||||
|
||||
no_of_monsters = test_no_of_monsters
|
||||
for i in range(0, no_of_monsters):
|
||||
b = flatbuffers.Builder(0)
|
||||
i = b.CreateString(test_monsters_name_retrieve[i])
|
||||
Monster.MonsterStart(b)
|
||||
Monster.MonsterAddName(b, i)
|
||||
b.Finish(Monster.MonsterEnd(b))
|
||||
yield bytes(b.Output())
|
||||
no_of_monsters = test_no_of_monsters
|
||||
for i in range(0, no_of_monsters):
|
||||
b = flatbuffers.Builder(0)
|
||||
i = b.CreateString(test_monsters_name_retrieve[i])
|
||||
Monster.MonsterStart(b)
|
||||
Monster.MonsterAddName(b, i)
|
||||
b.Finish(Monster.MonsterEnd(b))
|
||||
yield bytes(b.Output())
|
||||
|
||||
|
||||
def serve():
|
||||
|
||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
|
||||
monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server)
|
||||
server.add_insecure_port('[::]:50051')
|
||||
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
|
||||
monster_grpc_fb.add_MonsterStorageServicer_to_server(MonsterStorage(), server)
|
||||
server.add_insecure_port("[::]:50051")
|
||||
|
||||
server.start()
|
||||
server.start()
|
||||
|
||||
run()
|
||||
run()
|
||||
|
||||
|
||||
def run():
|
||||
|
||||
channel = grpc.insecure_channel('127.0.0.1:50051')
|
||||
stub = monster_grpc_fb.MonsterStorageStub(channel)
|
||||
channel = grpc.insecure_channel("127.0.0.1:50051")
|
||||
stub = monster_grpc_fb.MonsterStorageStub(channel)
|
||||
|
||||
b = flatbuffers.Builder(0)
|
||||
name2 = b.CreateString(test_monster_name2)
|
||||
name1 = b.CreateString(test_monster_name1)
|
||||
Monster.MonsterStart(b)
|
||||
Monster.MonsterAddName(b, name2)
|
||||
monster2 = Monster.MonsterEnd(b)
|
||||
test1 = b.CreateString(test_string)
|
||||
b = flatbuffers.Builder(0)
|
||||
name2 = b.CreateString(test_monster_name2)
|
||||
name1 = b.CreateString(test_monster_name1)
|
||||
Monster.MonsterStart(b)
|
||||
Monster.MonsterAddName(b, name2)
|
||||
monster2 = Monster.MonsterEnd(b)
|
||||
test1 = b.CreateString(test_string)
|
||||
|
||||
Monster.MonsterStartInventoryVector(b, len(test_inventory))
|
||||
for i in range(0, len(test_inventory)):
|
||||
b.PrependByte(test_inventory[i])
|
||||
inv = b.EndVector()
|
||||
Monster.MonsterStartInventoryVector(b, len(test_inventory))
|
||||
for i in range(0, len(test_inventory)):
|
||||
b.PrependByte(test_inventory[i])
|
||||
inv = b.EndVector()
|
||||
|
||||
Monster.MonsterStartTest4Vector(b, 2)
|
||||
Test.CreateTest(b, 10, 20)
|
||||
Test.CreateTest(b, 30, 40)
|
||||
test4 = b.EndVector()
|
||||
Monster.MonsterStartTest4Vector(b, 2)
|
||||
Test.CreateTest(b, 10, 20)
|
||||
Test.CreateTest(b, 30, 40)
|
||||
test4 = b.EndVector()
|
||||
|
||||
Monster.MonsterStartTestarrayofstringVector(b, 1)
|
||||
b.PrependUOffsetTRelative(test1)
|
||||
test_array_of_string = b.EndVector()
|
||||
Monster.MonsterStartTestarrayofstringVector(b, 1)
|
||||
b.PrependUOffsetTRelative(test1)
|
||||
test_array_of_string = b.EndVector()
|
||||
|
||||
Monster.MonsterStart(b)
|
||||
Monster.MonsterStart(b)
|
||||
|
||||
Monster.MonsterAddHp(b, test_hp)
|
||||
Monster.MonsterAddName(b, name1)
|
||||
Monster.MonsterAddColor(b, test_color)
|
||||
pos = Vec3.CreateVec3(b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b)
|
||||
Monster.MonsterAddPos(b, pos)
|
||||
Monster.MonsterAddInventory(b, inv)
|
||||
Monster.MonsterAddTestType(b, test_testtype)
|
||||
Monster.MonsterAddTest(b, monster2)
|
||||
Monster.MonsterAddTest4(b, test4)
|
||||
Monster.MonsterAddEnemy(b, monster2)
|
||||
Monster.MonsterAddTestarrayofstring(b, test_array_of_string)
|
||||
monster = Monster.MonsterEnd(b)
|
||||
Monster.MonsterAddHp(b, test_hp)
|
||||
Monster.MonsterAddName(b, name1)
|
||||
Monster.MonsterAddColor(b, test_color)
|
||||
pos = Vec3.CreateVec3(
|
||||
b, test_X, test_Y, test_Z, test_test1, test_color, test_a, test_b
|
||||
)
|
||||
Monster.MonsterAddPos(b, pos)
|
||||
Monster.MonsterAddInventory(b, inv)
|
||||
Monster.MonsterAddTestType(b, test_testtype)
|
||||
Monster.MonsterAddTest(b, monster2)
|
||||
Monster.MonsterAddTest4(b, test4)
|
||||
Monster.MonsterAddEnemy(b, monster2)
|
||||
Monster.MonsterAddTestarrayofstring(b, test_array_of_string)
|
||||
monster = Monster.MonsterEnd(b)
|
||||
|
||||
b.Finish(monster)
|
||||
b.Finish(monster)
|
||||
|
||||
stat_response = stub.Store(bytes(b.Output()))
|
||||
stat_response = stub.Store(bytes(b.Output()))
|
||||
|
||||
s = Stat.Stat().GetRootAsStat(stat_response, 0)
|
||||
s = Stat.Stat().GetRootAsStat(stat_response, 0)
|
||||
|
||||
assert s.Id().decode("utf-8") == test_stat_id
|
||||
assert s.Val() == test_stat_val
|
||||
assert s.Count() == test_stat_count
|
||||
assert s.Id().decode("utf-8") == test_stat_id
|
||||
assert s.Val() == test_stat_val
|
||||
assert s.Count() == test_stat_count
|
||||
|
||||
monster_reponses = stub.Retrieve(stat_response)
|
||||
count = 0
|
||||
for monster_reponse in monster_reponses:
|
||||
m = Monster.Monster().GetRootAsMonster(monster_reponse, 0)
|
||||
assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count]
|
||||
count = count + 1
|
||||
monster_reponses = stub.Retrieve(stat_response)
|
||||
count = 0
|
||||
for monster_reponse in monster_reponses:
|
||||
m = Monster.Monster().GetRootAsMonster(monster_reponse, 0)
|
||||
assert m.Name().decode("utf-8") == test_monsters_name_retrieve[count]
|
||||
count = count + 1
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
serve()
|
||||
if __name__ == "__main__":
|
||||
serve()
|
||||
|
||||
Reference in New Issue
Block a user